blob: a929da4e233dc76007de7012a58f3d0655def9b0 [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000260/// Slow case of getSpelling. Extract the characters comprising the
Richard Smith9a67f472012-11-28 07:29:00 +0000261/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445/// Relex the token at the specified location.
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000446/// \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
Richard Smithb5f81712018-04-30 05:25:48 +0000711unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
712 const SourceManager &SM,
713 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000714 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000715 // character is. This needs to take into consideration newlines and
716 // trigraphs.
717 bool Invalid = false;
718 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
Taewook Ohcebac482017-12-06 17:00:53 +0000719
Chris Lattner2a6ee912010-11-17 07:05:50 +0000720 // If they request the first char of the token, we're trivially done.
721 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
Richard Smithb5f81712018-04-30 05:25:48 +0000722 return 0;
Taewook Ohcebac482017-12-06 17:00:53 +0000723
Chris Lattner2a6ee912010-11-17 07:05:50 +0000724 unsigned PhysOffset = 0;
Taewook Ohcebac482017-12-06 17:00:53 +0000725
Chris Lattner2a6ee912010-11-17 07:05:50 +0000726 // The usual case is that tokens don't contain anything interesting. Skip
727 // over the uninteresting characters. If a token only consists of simple
728 // chars, this method is extremely fast.
729 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
730 if (CharNo == 0)
Richard Smithb5f81712018-04-30 05:25:48 +0000731 return PhysOffset;
Richard Trieucc3949d2016-02-18 22:34:54 +0000732 ++TokPtr;
733 --CharNo;
734 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000735 }
Taewook Ohcebac482017-12-06 17:00:53 +0000736
Chris Lattner2a6ee912010-11-17 07:05:50 +0000737 // If we have a character that may be a trigraph or escaped newline, use a
738 // lexer to parse it correctly.
739 for (; CharNo; --CharNo) {
740 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000742 TokPtr += Size;
743 PhysOffset += Size;
744 }
Taewook Ohcebac482017-12-06 17:00:53 +0000745
Chris Lattner2a6ee912010-11-17 07:05:50 +0000746 // Final detail: if we end up on an escaped newline, we want to return the
747 // location of the actual byte of the token. For example foo\<newline>bar
748 // advanced by 3 should return the location of b, not of \\. One compounding
749 // detail of this is that the escape may be made by a trigraph.
750 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
751 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
Taewook Ohcebac482017-12-06 17:00:53 +0000752
Richard Smithb5f81712018-04-30 05:25:48 +0000753 return PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000754}
755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000756/// Computes the source location just past the end of the
Chris Lattner2a6ee912010-11-17 07:05:50 +0000757/// token at this source location.
758///
759/// This routine can be used to produce a source location that
760/// points just past the end of the token referenced by \p Loc, and
761/// is generally used when a diagnostic needs to point just after a
762/// token where it expected something different that it received. If
763/// the returned source location would not be meaningful (e.g., if
764/// it points into a macro), this routine returns an invalid
765/// source location.
766///
767/// \param Offset an offset from the end of the token, where the source
768/// location should refer to. The default offset (0) produces a source
769/// location pointing just past the end of the token; an offset of 1 produces
770/// a source location pointing to the last character in the token, etc.
771SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
772 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000773 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000774 if (Loc.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000775 return {};
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000776
777 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000778 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000779 return {}; // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000780 }
781
David Blaikiebbafb8a2012-03-11 07:00:24 +0000782 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000783 if (Len > Offset)
784 Len = Len - Offset;
785 else
786 return Loc;
Taewook Ohcebac482017-12-06 17:00:53 +0000787
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000788 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000789}
790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000791/// Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000792/// token of the macro expansion.
793bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000794 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000795 const LangOptions &LangOpts,
796 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000797 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
798
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000799 SourceLocation expansionLoc;
800 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
801 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000802
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000803 if (expansionLoc.isFileID()) {
804 // No other macro expansions, this is the first.
805 if (MacroBegin)
806 *MacroBegin = expansionLoc;
807 return true;
808 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000809
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000810 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000811}
812
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000813/// Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000814/// token of the macro expansion.
815bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000816 const SourceManager &SM,
817 const LangOptions &LangOpts,
818 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000819 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
820
821 SourceLocation spellLoc = SM.getSpellingLoc(loc);
822 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
823 if (tokLen == 0)
824 return false;
825
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000826 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
827 SourceLocation expansionLoc;
828 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
829 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000830
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000831 if (expansionLoc.isFileID()) {
832 // No other macro expansions.
833 if (MacroEnd)
834 *MacroEnd = expansionLoc;
835 return true;
836 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000837
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000838 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000839}
840
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000841static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000842 const SourceManager &SM,
843 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000844 SourceLocation Begin = Range.getBegin();
845 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000846 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000847 if (Range.isTokenRange()) {
848 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
849 if (End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000850 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000851 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000852
853 // Break down the source locations.
854 FileID FID;
855 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000856 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000857 if (FID.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000858 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000859
860 unsigned EndOffs;
861 if (!SM.isInFileID(End, FID, &EndOffs) ||
862 BeginOffs > EndOffs)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000863 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000864
865 return CharSourceRange::getCharRange(Begin, End);
866}
867
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000868CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000869 const SourceManager &SM,
870 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871 SourceLocation Begin = Range.getBegin();
872 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000873 if (Begin.isInvalid() || End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000874 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000875
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000877 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000878
879 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000880 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000881 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000882 Range.setBegin(Begin);
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000885
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000887 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
888 &End)) ||
889 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
890 &End)))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000891 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000892 Range.setEnd(End);
893 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000894 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000895
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000896 assert(Begin.isMacroID() && End.isMacroID());
897 SourceLocation MacroBegin, MacroEnd;
898 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000899 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
900 &MacroEnd)) ||
901 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
902 &MacroEnd)))) {
903 Range.setBegin(MacroBegin);
904 Range.setEnd(MacroEnd);
905 return makeRangeFromFileLocs(Range, SM, LangOpts);
906 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000907
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000908 bool Invalid = false;
909 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
910 &Invalid);
911 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000912 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000913
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000914 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
915 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
916 &Invalid);
917 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000918 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000919
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000920 if (EndEntry.getExpansion().isMacroArgExpansion() &&
921 BeginEntry.getExpansion().getExpansionLocStart() ==
922 EndEntry.getExpansion().getExpansionLocStart()) {
923 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
924 Range.setEnd(SM.getImmediateSpellingLoc(End));
925 return makeFileCharRange(Range, SM, LangOpts);
926 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000927 }
928
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000929 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000930}
931
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000932StringRef Lexer::getSourceText(CharSourceRange Range,
933 const SourceManager &SM,
934 const LangOptions &LangOpts,
935 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000936 Range = makeFileCharRange(Range, SM, LangOpts);
937 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000938 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000939 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000940 }
941
942 // Break down the source location.
943 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
944 if (beginInfo.first.isInvalid()) {
945 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000946 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000947 }
948
949 unsigned EndOffs;
950 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
951 beginInfo.second > EndOffs) {
952 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000953 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000954 }
955
956 // Try to the load the file buffer.
957 bool invalidTemp = false;
958 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
959 if (invalidTemp) {
960 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000961 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000962 }
963
964 if (Invalid) *Invalid = false;
965 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
966}
967
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000968StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
969 const SourceManager &SM,
970 const LangOptions &LangOpts) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000971 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000972
973 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000974 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000975 FileID FID = SM.getFileID(Loc);
976 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
977 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
978 Loc = Expansion.getExpansionLocStart();
979 if (!Expansion.isMacroArgExpansion())
980 break;
981
982 // For macro arguments we need to check that the argument did not come
983 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
Taewook Ohcebac482017-12-06 17:00:53 +0000984
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000985 // Loc points to the argument id of the macro definition, move to the
986 // macro expansion.
Richard Smithb5f81712018-04-30 05:25:48 +0000987 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000988 SourceLocation SpellLoc = Expansion.getSpellingLoc();
989 if (SpellLoc.isFileID())
990 break; // No inner macro.
991
992 // If spelling location resides in the same FileID as macro expansion
993 // location, it means there is no inner macro.
994 FileID MacroFID = SM.getFileID(Loc);
995 if (SM.isInFileID(SpellLoc, MacroFID))
996 break;
997
998 // Argument came from inner macro.
999 Loc = SpellLoc;
1000 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001001
1002 // Find the spelling location of the start of the non-argument expansion
1003 // range. This is where the macro name was spelled in order to begin
1004 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001005 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001006
1007 // Dig out the buffer where the macro name was spelled and the extents of the
1008 // name so that we can render it into the expansion note.
1009 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1010 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1011 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1012 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1013}
1014
Richard Trieu3a5c9582016-01-26 02:51:55 +00001015StringRef Lexer::getImmediateMacroNameForDiagnostics(
1016 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001017 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
Richard Trieu3a5c9582016-01-26 02:51:55 +00001018 // Walk past macro argument expanions.
1019 while (SM.isMacroArgExpansion(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +00001020 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu3a5c9582016-01-26 02:51:55 +00001021
1022 // If the macro's spelling has no FileID, then it's actually a token paste
1023 // or stringization (or similar) and not a macro at all.
1024 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001025 return {};
Richard Trieu3a5c9582016-01-26 02:51:55 +00001026
1027 // Find the spelling location of the start of the non-argument expansion
1028 // range. This is where the macro name was spelled in order to begin
1029 // expanding this macro.
Richard Smithb5f81712018-04-30 05:25:48 +00001030 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
Richard Trieu3a5c9582016-01-26 02:51:55 +00001031
1032 // Dig out the buffer where the macro name was spelled and the extents of the
1033 // name so that we can render it into the expansion note.
1034 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1035 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1036 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1037 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1038}
1039
Jordan Rose288c4212012-06-07 01:10:31 +00001040bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001041 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001042}
1043
Alexander Kornienkocf007a72017-08-10 10:06:16 +00001044bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1045 assert(isVerticalWhitespace(Str[0]));
1046 if (Str - 1 < BufferStart)
1047 return false;
1048
1049 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1050 (Str[0] == '\r' && Str[-1] == '\n')) {
1051 if (Str - 2 < BufferStart)
1052 return false;
1053 --Str;
1054 }
1055 --Str;
1056
1057 // Rewind to first non-space character:
1058 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1059 --Str;
1060
1061 return *Str == '\\';
1062}
1063
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001064StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1065 const SourceManager &SM) {
1066 if (Loc.isInvalid() || Loc.isMacroID())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001067 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001068 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1069 if (LocInfo.first.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001070 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001071 bool Invalid = false;
1072 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1073 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001074 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001075 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1076 if (!Line)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001077 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001078 StringRef Rest = Buffer.substr(Line - Buffer.data());
1079 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1080 return NumWhitespaceChars == StringRef::npos
1081 ? ""
1082 : Rest.take_front(NumWhitespaceChars);
1083}
1084
Chris Lattner22eb9722006-06-18 05:43:12 +00001085//===----------------------------------------------------------------------===//
1086// Diagnostics forwarding code.
1087//===----------------------------------------------------------------------===//
1088
Chris Lattner619c1742007-07-22 18:38:25 +00001089/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001090/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001091/// This is currently only used for _Pragma implementation, so it is the slow
1092/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001093static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1094 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001095static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1096 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001097 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001098 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001099
Chris Lattner619c1742007-07-22 18:38:25 +00001100 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001101 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001102 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001103 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001105 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001106 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001107 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001108 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001109
Chris Lattner9dc9c202009-02-15 20:52:18 +00001110 // Figure out the expansion loc range, which is the range covered by the
1111 // original _Pragma(...) sequence.
Richard Smithb5f81712018-04-30 05:25:48 +00001112 CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001113
Richard Smithb5f81712018-04-30 05:25:48 +00001114 return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001115}
1116
Chris Lattner22eb9722006-06-18 05:43:12 +00001117/// getSourceLocation - Return a source location identifier for the specified
1118/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001119SourceLocation Lexer::getSourceLocation(const char *Loc,
1120 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001121 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001122 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001123
1124 // In the normal case, we're just lexing from a simple file buffer, return
1125 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001126 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001127 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001128 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattnerd32480d2009-01-17 06:22:33 +00001130 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1131 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001132 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001133 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001134}
1135
Chris Lattner22eb9722006-06-18 05:43:12 +00001136/// Diag - Forwarding function for diagnostics. This translate a source
1137/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001138DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001139 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001140}
1141
1142//===----------------------------------------------------------------------===//
1143// Trigraph and Escaped Newline Handling Code.
1144//===----------------------------------------------------------------------===//
1145
1146/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1147/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1148static char GetTrigraphCharForLetter(char Letter) {
1149 switch (Letter) {
1150 default: return 0;
1151 case '=': return '#';
1152 case ')': return ']';
1153 case '(': return '[';
1154 case '!': return '|';
1155 case '\'': return '^';
1156 case '>': return '}';
1157 case '/': return '\\';
1158 case '<': return '{';
1159 case '-': return '~';
1160 }
1161}
1162
1163/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1164/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1165/// return the result character. Finally, emit a warning about trigraph use
1166/// whether trigraphs are enabled or not.
1167static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1168 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001169 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001170
David Blaikiebbafb8a2012-03-11 07:00:24 +00001171 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001172 if (!L->isLexingRawMode())
1173 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001174 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001175 }
Mike Stump11289f42009-09-09 15:08:12 +00001176
Chris Lattner6d27a162008-11-22 02:02:22 +00001177 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001178 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 return Res;
1180}
1181
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001182/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1183/// 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 +00001184/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001185unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1186 unsigned Size = 0;
1187 while (isWhitespace(Ptr[Size])) {
1188 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001190 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1191 continue;
1192
1193 // If this is a \r\n or \n\r, skip the other half.
1194 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1195 Ptr[Size-1] != Ptr[Size])
1196 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001198 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001199 }
1200
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001201 // Not an escaped newline, must be a \t or something else.
1202 return 0;
1203}
1204
Chris Lattner38b2cde2009-04-18 22:27:02 +00001205/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1206/// them), skip over them and return the first non-escaped-newline found,
1207/// otherwise return P.
1208const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001209 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001210 const char *AfterEscape;
1211 if (*P == '\\') {
1212 AfterEscape = P+1;
1213 } else if (*P == '?') {
1214 // If not a trigraph for escape, bail out.
1215 if (P[1] != '?' || P[2] != '/')
1216 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001217 // FIXME: Take LangOpts into account; the language might not
1218 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001219 AfterEscape = P+3;
1220 } else {
1221 return P;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Chris Lattner38b2cde2009-04-18 22:27:02 +00001224 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1225 if (NewLineSize == 0) return P;
1226 P = AfterEscape+NewLineSize;
1227 }
1228}
1229
Alex Lorenzebbbb812017-11-03 18:11:22 +00001230Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1231 const SourceManager &SM,
1232 const LangOptions &LangOpts) {
Anna Zaks59a3c802011-07-27 21:43:43 +00001233 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001234 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Alex Lorenzebbbb812017-11-03 18:11:22 +00001235 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001236 }
1237 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1238
1239 // Break down the source location.
1240 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1241
1242 // Try to load the file buffer.
1243 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001244 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001245 if (InvalidTemp)
Alex Lorenzebbbb812017-11-03 18:11:22 +00001246 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001247
1248 const char *TokenBegin = File.data() + LocInfo.second;
1249
1250 // Lex from the start of the given location.
1251 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1252 TokenBegin, File.end());
1253 // Find the token.
1254 Token Tok;
1255 lexer.LexFromRawLexer(Tok);
Alex Lorenzebbbb812017-11-03 18:11:22 +00001256 return Tok;
1257}
1258
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001259/// Checks that the given token is the first token that occurs after the
Alex Lorenzebbbb812017-11-03 18:11:22 +00001260/// given location (this excludes comments and whitespace). Returns the location
1261/// immediately after the specified token. If the token is not found or the
1262/// location is inside a macro, the returned source location will be invalid.
1263SourceLocation Lexer::findLocationAfterToken(
1264 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1265 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1266 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1267 if (!Tok || Tok->isNot(TKind))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001268 return {};
Alex Lorenzebbbb812017-11-03 18:11:22 +00001269 SourceLocation TokenLoc = Tok->getLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001270
1271 // Calculate how much whitespace needs to be skipped if any.
1272 unsigned NumWhitespaceChars = 0;
1273 if (SkipTrailingWhitespaceAndNewLine) {
Alex Lorenzebbbb812017-11-03 18:11:22 +00001274 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
Anna Zaks59a3c802011-07-27 21:43:43 +00001275 unsigned char C = *TokenEnd;
1276 while (isHorizontalWhitespace(C)) {
1277 C = *(++TokenEnd);
1278 NumWhitespaceChars++;
1279 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001280
1281 // Skip \r, \n, \r\n, or \n\r
1282 if (C == '\n' || C == '\r') {
1283 char PrevC = C;
1284 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001285 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001286 if ((C == '\n' || C == '\r') && C != PrevC)
1287 NumWhitespaceChars++;
1288 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001289 }
1290
Alex Lorenzebbbb812017-11-03 18:11:22 +00001291 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001292}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001293
Chris Lattner22eb9722006-06-18 05:43:12 +00001294/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1295/// get its size, and return it. This is tricky in several cases:
1296/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1297/// then either return the trigraph (skipping 3 chars) or the '?',
1298/// depending on whether trigraphs are enabled or not.
1299/// 2. If this is an escaped newline (potentially with whitespace between
1300/// the backslash and newline), implicitly skip the newline and return
1301/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001302///
1303/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1304/// know that we can accumulate into Size, and that we have already incremented
1305/// Ptr by Size bytes.
1306///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001307/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1308/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001309char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001310 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001311 // If we have a slash, look for an escaped newline.
1312 if (Ptr[0] == '\\') {
1313 ++Size;
1314 ++Ptr;
1315Slash:
1316 // Common case, backslash-char where the char is not whitespace.
1317 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattnerc1835952009-06-23 05:15:06 +00001319 // See if we have optional whitespace characters between the slash and
1320 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001321 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1322 // Remember that this token needs to be cleaned.
1323 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001324
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001325 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001326 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001327 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001329 // Found backslash<whitespace><newline>. Parse the char after it.
1330 Size += EscapedNewLineSize;
1331 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001332
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001333 // Use slow version to accumulate a correct size field.
1334 return getCharAndSizeSlow(Ptr, Size, Tok);
1335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 // Otherwise, this is not an escaped newline, just return the slash.
1338 return '\\';
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // If this is a trigraph, process it.
1342 if (Ptr[0] == '?' && Ptr[1] == '?') {
1343 // If this is actually a legal trigraph (not something like "??x"), emit
1344 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001345 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001347 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001348
1349 Ptr += 3;
1350 Size += 3;
1351 if (C == '\\') goto Slash;
1352 return C;
1353 }
1354 }
Mike Stump11289f42009-09-09 15:08:12 +00001355
Chris Lattner22eb9722006-06-18 05:43:12 +00001356 // If this is neither, return a single character.
1357 ++Size;
1358 return *Ptr;
1359}
1360
1361/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1362/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1363/// and that we have already incremented Ptr by Size bytes.
1364///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001365/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1366/// be updated to match.
1367char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001368 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 // If we have a slash, look for an escaped newline.
1370 if (Ptr[0] == '\\') {
1371 ++Size;
1372 ++Ptr;
1373Slash:
1374 // Common case, backslash-char where the char is not whitespace.
1375 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001378 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1379 // Found backslash<whitespace><newline>. Parse the char after it.
1380 Size += EscapedNewLineSize;
1381 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001382
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001383 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattner22eb9722006-06-18 05:43:12 +00001387 // Otherwise, this is not an escaped newline, just return the slash.
1388 return '\\';
1389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001392 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 // If this is actually a legal trigraph (not something like "??x"), return
1394 // it.
1395 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1396 Ptr += 3;
1397 Size += 3;
1398 if (C == '\\') goto Slash;
1399 return C;
1400 }
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Chris Lattner22eb9722006-06-18 05:43:12 +00001403 // If this is neither, return a single character.
1404 ++Size;
1405 return *Ptr;
1406}
1407
Chris Lattner22eb9722006-06-18 05:43:12 +00001408//===----------------------------------------------------------------------===//
1409// Helper methods for lexing.
1410//===----------------------------------------------------------------------===//
1411
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001412/// Routine that indiscriminately sets the offset into the source file.
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001413void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1414 BufferPtr = BufferStart + Offset;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001415 if (BufferPtr > BufferEnd)
1416 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001417 // FIXME: What exactly does the StartOfLine bit mean? There are two
1418 // possible meanings for the "start" of the line: the first token on the
1419 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001420 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001421 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001422}
1423
Jordan Rose58c61e02013-02-09 01:10:25 +00001424static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001425 if (LangOpts.AsmPreprocessor) {
1426 return false;
1427 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001428 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1429 C11AllowedIDCharRanges);
1430 return C11AllowedIDChars.contains(C);
1431 } else if (LangOpts.CPlusPlus) {
1432 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1433 CXX03AllowedIDCharRanges);
1434 return CXX03AllowedIDChars.contains(C);
1435 } else {
1436 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1437 C99AllowedIDCharRanges);
1438 return C99AllowedIDChars.contains(C);
1439 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001440}
1441
Jordan Rose58c61e02013-02-09 01:10:25 +00001442static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1443 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001444 if (LangOpts.AsmPreprocessor) {
1445 return false;
1446 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001447 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1448 C11DisallowedInitialIDCharRanges);
1449 return !C11DisallowedInitialIDChars.contains(C);
1450 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001451 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001452 } else {
1453 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1454 C99DisallowedInitialIDCharRanges);
1455 return !C99DisallowedInitialIDChars.contains(C);
1456 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001457}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001458
Jordan Rose58c61e02013-02-09 01:10:25 +00001459static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1460 const char *End) {
1461 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1462 L.getSourceLocation(End));
1463}
1464
1465static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1466 CharSourceRange Range, bool IsFirst) {
1467 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001468 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001469 enum {
1470 CannotAppearInIdentifier = 0,
1471 CannotStartIdentifier
1472 };
1473
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001474 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1475 C99AllowedIDCharRanges);
1476 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1477 C99DisallowedInitialIDCharRanges);
1478 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001479 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1480 << Range
1481 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001482 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001483 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1484 << Range
1485 << CannotStartIdentifier;
1486 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001487 }
1488
Jordan Rose58c61e02013-02-09 01:10:25 +00001489 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001490 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001491 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1492 CXX03AllowedIDCharRanges);
1493 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001494 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1495 << Range;
1496 }
1497 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001498}
1499
Richard Smith77091b12017-12-14 13:15:08 +00001500/// After encountering UTF-8 character C and interpreting it as an identifier
1501/// character, check whether it's a homoglyph for a common non-identifier
1502/// source character that is unlikely to be an intentional identifier
1503/// character and warn if so.
1504static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1505 CharSourceRange Range) {
1506 // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1507 struct HomoglyphPair {
1508 uint32_t Character;
1509 char LooksLike;
1510 bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1511 };
1512 static constexpr HomoglyphPair SortedHomoglyphs[] = {
Richard Smith8ed77762018-09-07 19:25:39 +00001513 {U'\u00ad', 0}, // SOFT HYPHEN
Richard Smith77091b12017-12-14 13:15:08 +00001514 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1515 {U'\u037e', ';'}, // GREEK QUESTION MARK
Richard Smith8ed77762018-09-07 19:25:39 +00001516 {U'\u200b', 0}, // ZERO WIDTH SPACE
1517 {U'\u200c', 0}, // ZERO WIDTH NON-JOINER
1518 {U'\u200d', 0}, // ZERO WIDTH JOINER
1519 {U'\u2060', 0}, // WORD JOINER
1520 {U'\u2061', 0}, // FUNCTION APPLICATION
1521 {U'\u2062', 0}, // INVISIBLE TIMES
1522 {U'\u2063', 0}, // INVISIBLE SEPARATOR
1523 {U'\u2064', 0}, // INVISIBLE PLUS
Richard Smith77091b12017-12-14 13:15:08 +00001524 {U'\u2212', '-'}, // MINUS SIGN
1525 {U'\u2215', '/'}, // DIVISION SLASH
1526 {U'\u2216', '\\'}, // SET MINUS
1527 {U'\u2217', '*'}, // ASTERISK OPERATOR
1528 {U'\u2223', '|'}, // DIVIDES
1529 {U'\u2227', '^'}, // LOGICAL AND
1530 {U'\u2236', ':'}, // RATIO
1531 {U'\u223c', '~'}, // TILDE OPERATOR
1532 {U'\ua789', ':'}, // MODIFIER LETTER COLON
Richard Smith8ed77762018-09-07 19:25:39 +00001533 {U'\ufeff', 0}, // ZERO WIDTH NO-BREAK SPACE
Richard Smith77091b12017-12-14 13:15:08 +00001534 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1535 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1536 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1537 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1538 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1539 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1540 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1541 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1542 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1543 {U'\uff0c', ','}, // FULLWIDTH COMMA
1544 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1545 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1546 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1547 {U'\uff1a', ':'}, // FULLWIDTH COLON
1548 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1549 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1550 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1551 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1552 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1553 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1554 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1555 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1556 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1557 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1558 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1559 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1560 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1561 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1562 {0, 0}
1563 };
1564 auto Homoglyph =
1565 std::lower_bound(std::begin(SortedHomoglyphs),
1566 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1567 if (Homoglyph->Character == C) {
1568 llvm::SmallString<5> CharBuf;
1569 {
1570 llvm::raw_svector_ostream CharOS(CharBuf);
1571 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1572 }
Richard Smith8ed77762018-09-07 19:25:39 +00001573 if (Homoglyph->LooksLike) {
1574 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1575 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1576 << Range << CharBuf << LooksLikeStr;
1577 } else {
1578 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
1579 << Range << CharBuf;
1580 }
Richard Smith77091b12017-12-14 13:15:08 +00001581 }
1582}
1583
Richard Smith8b7258b2014-02-17 21:52:30 +00001584bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1585 Token &Result) {
1586 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001587 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001588 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1589 return false;
1590
1591 if (!isLexingRawMode())
1592 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1593 makeCharRange(*this, CurPtr, UCNPtr),
1594 /*IsFirst=*/false);
1595
1596 Result.setFlag(Token::HasUCN);
1597 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1598 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1599 CurPtr = UCNPtr;
1600 else
1601 while (CurPtr != UCNPtr)
1602 (void)getAndAdvanceChar(CurPtr, Result);
1603 return true;
1604}
1605
1606bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1607 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001608 llvm::UTF32 CodePoint;
1609 llvm::ConversionResult Result =
1610 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1611 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001612 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001613 llvm::strictConversion);
1614 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001615 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1616 return false;
1617
Richard Smith77091b12017-12-14 13:15:08 +00001618 if (!isLexingRawMode()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001619 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1620 makeCharRange(*this, CurPtr, UnicodePtr),
1621 /*IsFirst=*/false);
Richard Smith77091b12017-12-14 13:15:08 +00001622 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1623 makeCharRange(*this, CurPtr, UnicodePtr));
1624 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001625
1626 CurPtr = UnicodePtr;
1627 return true;
1628}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001629
Eli Friedman0834a4b2013-09-19 00:41:32 +00001630bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001631 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1632 unsigned Size;
1633 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001634 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001635 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001636
Chris Lattner22eb9722006-06-18 05:43:12 +00001637 --CurPtr; // Back up over the skipped character.
1638
1639 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1640 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001641 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001642 // TODO: Could merge these checks into an InfoTable flag to make the
1643 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001644 if (isASCII(C) && C != '\\' && C != '?' &&
1645 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001646FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001647 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001648 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1649 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattner0f1f5052006-07-20 04:16:23 +00001651 // If we are in raw mode, return this identifier raw. There is no need to
1652 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001653 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001654 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001655
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001656 // Fill in Result.IdentifierInfo and update the token kind,
1657 // looking up the identifier in the identifier table.
1658 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Ilya Biryukovb3510c42018-04-24 13:48:53 +00001659 // Note that we have to call PP->LookUpIdentifierInfo() even for code
1660 // completion, it writes IdentifierInfo into Result, and callers rely on it.
1661
1662 // If the completion point is at the end of an identifier, we want to treat
1663 // the identifier as incomplete even if it resolves to a macro or a keyword.
1664 // This allows e.g. 'class^' to complete to 'classifier'.
1665 if (isCodeCompletionPoint(CurPtr)) {
1666 // Return the code-completion token.
1667 Result.setKind(tok::code_completion);
Ilya Biryukovef4ece72018-04-25 15:13:34 +00001668 // Skip the code-completion char and all immediate identifier characters.
1669 // This ensures we get consistent behavior when completing at any point in
1670 // an identifier (i.e. at the start, in the middle, at the end). Note that
1671 // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1672 // simpler.
1673 assert(*CurPtr == 0 && "Completion character must be 0");
1674 ++CurPtr;
1675 // Note that code completion token is not added as a separate character
1676 // when the completion point is at the end of the buffer. Therefore, we need
1677 // to check if the buffer has ended.
1678 if (CurPtr < BufferEnd) {
1679 while (isIdentifierBody(*CurPtr))
1680 ++CurPtr;
1681 }
1682 BufferPtr = CurPtr;
Ilya Biryukovb3510c42018-04-24 13:48:53 +00001683 return true;
1684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnerc5a00062006-06-18 16:41:01 +00001686 // Finally, now that we know we have an identifier, pass this off to the
1687 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001688 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001689 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001690
Eli Friedman0834a4b2013-09-19 00:41:32 +00001691 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001692 }
Mike Stump11289f42009-09-09 15:08:12 +00001693
Chris Lattner22eb9722006-06-18 05:43:12 +00001694 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattner22eb9722006-06-18 05:43:12 +00001696 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001697 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 if (C == '$') {
1699 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001701
Chris Lattner22eb9722006-06-18 05:43:12 +00001702 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001703 if (!isLexingRawMode())
1704 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001705 CurPtr = ConsumeChar(CurPtr, Size, Result);
1706 C = getCharAndSize(CurPtr, Size);
1707 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001708 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001709 C = getCharAndSize(CurPtr, Size);
1710 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001711 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001712 C = getCharAndSize(CurPtr, Size);
1713 continue;
1714 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001715 goto FinishIdentifier;
1716 }
1717
1718 // Otherwise, this character is good, consume it.
1719 CurPtr = ConsumeChar(CurPtr, Size, Result);
1720
1721 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001722 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001723 CurPtr = ConsumeChar(CurPtr, Size, Result);
1724 C = getCharAndSize(CurPtr, Size);
1725 }
1726 }
1727}
1728
Douglas Gregor759ef232010-08-30 14:50:47 +00001729/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001730/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001731bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001732 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001733 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001734 if (C1 != '0')
1735 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001736 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001737 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001738}
Chris Lattner22eb9722006-06-18 05:43:12 +00001739
Nate Begeman5eee9332008-04-14 02:26:39 +00001740/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001741/// constant. From[-1] is the first character lexed. Return the end of the
1742/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001743bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001744 unsigned Size;
1745 char C = getCharAndSize(CurPtr, Size);
1746 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001747 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001748 CurPtr = ConsumeChar(CurPtr, Size, Result);
1749 PrevCh = C;
1750 C = getCharAndSize(CurPtr, Size);
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Chris Lattner22eb9722006-06-18 05:43:12 +00001753 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001754 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1755 // If we are in Microsoft mode, don't continue if the constant is hex.
1756 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001757 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001758 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1759 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001760
1761 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001762 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001763 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001764 // not-quite-conforming extension. Only do so if this looks like it's
1765 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1766 bool IsHexFloat = true;
1767 if (!LangOpts.C99) {
1768 if (!isHexaLiteral(BufferPtr, LangOpts))
1769 IsHexFloat = false;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001770 else if (!getLangOpts().CPlusPlus17 &&
Richard Smith560a3572016-03-04 22:32:06 +00001771 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001772 IsHexFloat = false;
1773 }
1774 if (IsHexFloat)
1775 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
Richard Smithfde94852013-09-26 03:33:06 +00001778 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001779 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001780 unsigned NextSize;
1781 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001782 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001783 if (!isLexingRawMode())
1784 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1785 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001786 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001787 return LexNumericConstant(Result, CurPtr);
1788 }
1789 }
1790
Richard Smith8b7258b2014-02-17 21:52:30 +00001791 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1792 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1793 return LexNumericConstant(Result, CurPtr);
1794 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1795 return LexNumericConstant(Result, CurPtr);
1796
Chris Lattnerd01e2912006-06-18 16:22:51 +00001797 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001798 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001799 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001800 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001801 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001802}
1803
Richard Smithe18f0fa2012-03-05 04:02:15 +00001804/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001805/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001806const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1807 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001808 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001809
Richard Smith8b7258b2014-02-17 21:52:30 +00001810 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001811 unsigned Size;
1812 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001813 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001814
Richard Smith8b7258b2014-02-17 21:52:30 +00001815 if (!isIdentifierHead(C)) {
1816 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1817 Consumed = true;
1818 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1819 Consumed = true;
1820 else
1821 return CurPtr;
1822 }
1823
1824 if (!getLangOpts().CPlusPlus11) {
1825 if (!isLexingRawMode())
1826 Diag(CurPtr,
1827 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1828 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1829 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1830 return CurPtr;
1831 }
1832
1833 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1834 // that does not start with an underscore is ill-formed. As a conforming
1835 // extension, we treat all such suffixes as if they had whitespace before
1836 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1837 // likely to be a ud-suffix than a macro, however, and accept that.
1838 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001839 bool IsUDSuffix = false;
1840 if (C == '_')
1841 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001842 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001843 // In C++1y, we need to look ahead a few characters to see if this is a
1844 // valid suffix for a string literal or a numeric literal (this could be
1845 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001846 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001847 char Buffer[MaxStandardSuffixLength] = { C };
1848 unsigned Consumed = Size;
1849 unsigned Chars = 1;
1850 while (true) {
1851 unsigned NextSize;
1852 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1853 getLangOpts());
1854 if (!isIdentifierBody(Next)) {
1855 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001856 const StringRef CompleteSuffix(Buffer, Chars);
1857 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1858 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001859 break;
1860 }
1861
1862 if (Chars == MaxStandardSuffixLength)
1863 // Too long: can't be a standard suffix.
1864 break;
1865
1866 Buffer[Chars++] = Next;
1867 Consumed += NextSize;
1868 }
Richard Smithf4198b72013-07-23 08:14:48 +00001869 }
1870
1871 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001872 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001873 Diag(CurPtr, getLangOpts().MSVCCompat
1874 ? diag::ext_ms_reserved_user_defined_literal
1875 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001876 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001877 return CurPtr;
1878 }
1879
Richard Smith8b7258b2014-02-17 21:52:30 +00001880 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001881 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001882
1883 Result.setFlag(Token::HasUDSuffix);
1884 while (true) {
1885 C = getCharAndSize(CurPtr, Size);
1886 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1887 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1888 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1889 else break;
1890 }
1891
Richard Smithe18f0fa2012-03-05 04:02:15 +00001892 return CurPtr;
1893}
1894
Chris Lattner22eb9722006-06-18 05:43:12 +00001895/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001896/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001897bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001898 tok::TokenKind Kind) {
Sam McCall3d8051a2018-09-18 08:40:41 +00001899 const char *AfterQuote = CurPtr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001900 // Does this string contain the \0 character?
1901 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Richard Smithacd4d3d2011-10-15 01:18:56 +00001903 if (!isLexingRawMode() &&
1904 (Kind == tok::utf8_string_literal ||
1905 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001906 Kind == tok::utf32_string_literal))
1907 Diag(BufferPtr, getLangOpts().CPlusPlus
1908 ? diag::warn_cxx98_compat_unicode_literal
1909 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001910
Chris Lattner22eb9722006-06-18 05:43:12 +00001911 char C = getAndAdvanceChar(CurPtr, Result);
1912 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001913 // Skip escaped characters. Escaped newlines will already be processed by
1914 // getAndAdvanceChar.
1915 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 C = getAndAdvanceChar(CurPtr, Result);
Taewook Ohcebac482017-12-06 17:00:53 +00001917
Chris Lattner52d96ac2010-05-30 23:27:38 +00001918 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001919 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001920 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001921 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001922 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001923 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001924 }
Taewook Ohcebac482017-12-06 17:00:53 +00001925
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001926 if (C == 0) {
1927 if (isCodeCompletionPoint(CurPtr-1)) {
Sam McCall3d8051a2018-09-18 08:40:41 +00001928 if (ParsingFilename)
1929 codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
1930 else
1931 PP->CodeCompleteNaturalLanguage();
1932 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001933 cutOffLexing();
1934 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001935 }
1936
Chris Lattner52d96ac2010-05-30 23:27:38 +00001937 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001938 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001939 C = getAndAdvanceChar(CurPtr, Result);
1940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Richard Smithe18f0fa2012-03-05 04:02:15 +00001942 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001943 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001944 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001945
Chris Lattner5a78a022006-07-20 06:02:19 +00001946 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001947 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001948 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001949
Chris Lattnerd01e2912006-06-18 16:22:51 +00001950 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001951 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001952 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001953 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001954 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001955}
1956
Craig Topper54edcca2011-08-11 04:06:15 +00001957/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1958/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001959bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001960 tok::TokenKind Kind) {
1961 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1962 // Between the initial and final double quote characters of the raw string,
1963 // any transformations performed in phases 1 and 2 (trigraphs,
1964 // universal-character-names, and line splicing) are reverted.
1965
Richard Smithacd4d3d2011-10-15 01:18:56 +00001966 if (!isLexingRawMode())
1967 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1968
Craig Topper54edcca2011-08-11 04:06:15 +00001969 unsigned PrefixLen = 0;
1970
1971 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1972 ++PrefixLen;
1973
1974 // If the last character was not a '(', then we didn't lex a valid delimiter.
1975 if (CurPtr[PrefixLen] != '(') {
1976 if (!isLexingRawMode()) {
1977 const char *PrefixEnd = &CurPtr[PrefixLen];
1978 if (PrefixLen == 16) {
1979 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1980 } else {
1981 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1982 << StringRef(PrefixEnd, 1);
1983 }
1984 }
1985
1986 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1987 // it's possible the '"' was intended to be part of the raw string, but
1988 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001989 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001990 char C = *CurPtr++;
1991
1992 if (C == '"')
1993 break;
1994 if (C == 0 && CurPtr-1 == BufferEnd) {
1995 --CurPtr;
1996 break;
1997 }
1998 }
1999
2000 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002001 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002002 }
2003
2004 // Save prefix and move CurPtr past it
2005 const char *Prefix = CurPtr;
2006 CurPtr += PrefixLen + 1; // skip over prefix and '('
2007
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002008 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00002009 char C = *CurPtr++;
2010
2011 if (C == ')') {
2012 // Check for prefix match and closing quote.
2013 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
2014 CurPtr += PrefixLen + 1; // skip over prefix and '"'
2015 break;
2016 }
2017 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
2018 if (!isLexingRawMode())
2019 Diag(BufferPtr, diag::err_unterminated_raw_string)
2020 << StringRef(Prefix, PrefixLen);
2021 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002022 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002023 }
2024 }
2025
Richard Smithe18f0fa2012-03-05 04:02:15 +00002026 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002027 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002028 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002029
Craig Topper54edcca2011-08-11 04:06:15 +00002030 // Update the location of token as well as BufferPtr.
2031 const char *TokStart = BufferPtr;
2032 FormTokenWithChars(Result, CurPtr, Kind);
2033 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002034 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002035}
2036
Chris Lattner22eb9722006-06-18 05:43:12 +00002037/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2038/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002039bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002040 // Does this string contain the \0 character?
2041 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00002042 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 char C = getAndAdvanceChar(CurPtr, Result);
2044 while (C != '>') {
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002045 // Skip escaped characters. Escaped newlines will already be processed by
2046 // getAndAdvanceChar.
2047 if (C == '\\')
2048 C = getAndAdvanceChar(CurPtr, Result);
2049
Sam McCall3d8051a2018-09-18 08:40:41 +00002050 if (C == '\n' || C == '\r' || // Newline.
2051 (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
Chris Lattnerb40289b2009-04-17 23:56:52 +00002052 // If the filename is unterminated, then it must just be a lone <
2053 // character. Return this as such.
2054 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002055 return true;
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002056 }
2057
2058 if (C == 0) {
Sam McCall3d8051a2018-09-18 08:40:41 +00002059 if (isCodeCompletionPoint(CurPtr - 1)) {
2060 codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
2061 cutOffLexing();
2062 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2063 return true;
2064 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 NulCharacter = CurPtr-1;
2066 }
2067 C = getAndAdvanceChar(CurPtr, Result);
2068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
Chris Lattner5a78a022006-07-20 06:02:19 +00002070 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002071 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002072 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattnerd01e2912006-06-18 16:22:51 +00002074 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002075 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002076 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002077 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002078 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002079}
2080
Sam McCall3d8051a2018-09-18 08:40:41 +00002081void Lexer::codeCompleteIncludedFile(const char *PathStart,
2082 const char *CompletionPoint,
2083 bool IsAngled) {
2084 // Completion only applies to the filename, after the last slash.
2085 StringRef PartialPath(PathStart, CompletionPoint - PathStart);
2086 auto Slash = PartialPath.find_last_of(LangOpts.MSVCCompat ? "/\\" : "/");
2087 StringRef Dir =
2088 (Slash == StringRef::npos) ? "" : PartialPath.take_front(Slash);
2089 const char *StartOfFilename =
2090 (Slash == StringRef::npos) ? PathStart : PathStart + Slash + 1;
2091 // Code completion filter range is the filename only, up to completion point.
2092 PP->setCodeCompletionIdentifierInfo(&PP->getIdentifierTable().get(
2093 StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
2094 // We should replace the characters up to the closing quote, if any.
2095 while (CompletionPoint < BufferEnd) {
2096 char Next = *(CompletionPoint + 1);
2097 if (Next == 0 || Next == '\r' || Next == '\n')
2098 break;
2099 ++CompletionPoint;
2100 if (Next == (IsAngled ? '>' : '"'))
2101 break;
2102 }
2103 PP->setCodeCompletionTokenRange(
2104 FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
2105 FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
2106 PP->CodeCompleteIncludedFile(Dir, IsAngled);
2107}
2108
Chris Lattner22eb9722006-06-18 05:43:12 +00002109/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00002110/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002111bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00002112 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002113 // Does this character contain the \0 character?
2114 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002115
Richard Smith3e3a7052014-11-08 06:08:42 +00002116 if (!isLexingRawMode()) {
2117 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2118 Diag(BufferPtr, getLangOpts().CPlusPlus
2119 ? diag::warn_cxx98_compat_unicode_literal
2120 : diag::warn_c99_compat_unicode_literal);
2121 else if (Kind == tok::utf8_char_constant)
2122 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2123 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00002124
Chris Lattner22eb9722006-06-18 05:43:12 +00002125 char C = getAndAdvanceChar(CurPtr, Result);
2126 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00002128 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002129 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002130 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00002131 }
2132
2133 while (C != '\'') {
2134 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00002135 if (C == '\\')
2136 C = getAndAdvanceChar(CurPtr, Result);
2137
2138 if (C == '\n' || C == '\r' || // Newline.
2139 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002140 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00002141 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00002142 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002143 return true;
Nico Weber4e270382012-11-17 20:25:54 +00002144 }
2145
2146 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002147 if (isCodeCompletionPoint(CurPtr-1)) {
2148 PP->CodeCompleteNaturalLanguage();
2149 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002150 cutOffLexing();
2151 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002152 }
2153
Chris Lattner86851b82010-07-07 23:24:27 +00002154 NulCharacter = CurPtr-1;
2155 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002156 C = getAndAdvanceChar(CurPtr, Result);
2157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Richard Smithe18f0fa2012-03-05 04:02:15 +00002159 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002160 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002161 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002162
Chris Lattner86851b82010-07-07 23:24:27 +00002163 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002164 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002165 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002166
Chris Lattnerd01e2912006-06-18 16:22:51 +00002167 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002168 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002169 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002170 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002171 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002172}
2173
2174/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2175/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002176///
2177/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002178bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2179 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002181 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2182
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002183 unsigned char Char = *CurPtr;
2184
2185 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002186 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002187 // Skip horizontal whitespace very aggressively.
2188 while (isHorizontalWhitespace(Char))
2189 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002191 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002192 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002193 break;
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 if (ParsingPreprocessorDirective) {
2196 // End of preprocessor directive line, let LexTokenInternal handle this.
2197 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002198 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002201 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002202 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002203 Char = *++CurPtr;
2204 }
2205
Chris Lattner4d963442008-10-12 04:05:48 +00002206 // If the client wants us to return whitespace, return it now.
2207 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002208 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002209 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002210 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002211 IsAtPhysicalStartOfLine = true;
2212 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002213 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002214 return true;
2215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002217 // If this isn't immediately after a newline, there is leading space.
2218 char PrevChar = CurPtr[-1];
2219 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2220
2221 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002222 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002223 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002224 TokAtPhysicalStartOfLine = true;
2225 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002226
Chris Lattner22eb9722006-06-18 05:43:12 +00002227 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002228 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002229}
2230
Nico Weber158a31a2012-11-11 07:02:14 +00002231/// We have just read the // characters from input. Skip until we find the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002232/// newline character that terminates the comment. Then update BufferPtr and
Nico Weber158a31a2012-11-11 07:02:14 +00002233/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002234///
2235/// If we're in KeepCommentMode or any CommentHandler has inserted
2236/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002237bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2238 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002239 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002241 if (!LangOpts.LineComment && !isLexingRawMode()) {
2242 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002243
Chris Lattner22eb9722006-06-18 05:43:12 +00002244 // Mark them enabled so we only emit one warning for this translation
2245 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002246 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Chris Lattner22eb9722006-06-18 05:43:12 +00002249 // Scan over the body of the comment. The common case, when scanning, is that
2250 // the comment contains normal ascii characters with nothing interesting in
2251 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002252 //
2253 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2254 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002255 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002256 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002257 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 // Skip over characters in the fast loop.
2259 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002260 C != '\n' && C != '\r') // Newline or DOS-style newline.
2261 C = *++CurPtr;
2262
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002263 const char *NextLine = CurPtr;
2264 if (C != 0) {
2265 // We found a newline, see if it's escaped.
2266 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002267 bool HasSpace = false;
2268 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002269 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002270 HasSpace = true;
2271 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002272
Richard Smith4c132e52017-04-18 21:45:04 +00002273 if (*EscapePtr == '\\')
2274 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002275 CurPtr = EscapePtr;
2276 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002277 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2278 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002279 CurPtr = EscapePtr-2;
2280 else
2281 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002282
2283 // If there was space between the backslash and newline, warn about it.
2284 if (HasSpace && !isLexingRawMode())
2285 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattner22eb9722006-06-18 05:43:12 +00002288 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002289 // properly decode the character. Read it in raw mode to avoid emitting
2290 // diagnostics about things like trigraphs. If we see an escaped newline,
2291 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002292 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002293 bool OldRawMode = isLexingRawMode();
2294 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002295 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002296 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002297
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002298 // If we only read only one character, then no special handling is needed.
2299 // We're done and can skip forward to the newline.
2300 if (C != 0 && CurPtr == OldPtr+1) {
2301 CurPtr = NextLine;
2302 break;
2303 }
2304
Chris Lattner22eb9722006-06-18 05:43:12 +00002305 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002306 // \n, then we had an escaped newline within the comment. Emit diagnostic
2307 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002308 if (CurPtr != OldPtr + 1 && C != '/' &&
2309 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002310 for (; OldPtr != CurPtr; ++OldPtr)
2311 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002312 // Okay, we found a // comment that ends in a newline, if the next
2313 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002314 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002315 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002316 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002317 ++ForwardPtr;
2318 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2319 break;
2320 }
Mike Stump11289f42009-09-09 15:08:12 +00002321
Chris Lattner6d27a162008-11-22 02:02:22 +00002322 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002323 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002324 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002325 }
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Richard Smith1d2ae942017-04-17 23:44:51 +00002328 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2329 --CurPtr;
2330 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002331 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002332
2333 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2334 PP->CodeCompleteNaturalLanguage();
2335 cutOffLexing();
2336 return false;
2337 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002338 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002339
Chris Lattner93ddf802010-02-03 21:06:21 +00002340 // Found but did not consume the newline. Notify comment handlers about the
2341 // comment unless we're in a #if 0 block.
2342 if (PP && !isLexingRawMode() &&
2343 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2344 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002345 BufferPtr = CurPtr;
2346 return true; // A token has to be returned.
2347 }
Mike Stump11289f42009-09-09 15:08:12 +00002348
Chris Lattner457fc152006-07-29 06:30:25 +00002349 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002350 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002351 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002352
2353 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002354 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002355 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002356 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002357 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002358 }
Mike Stump11289f42009-09-09 15:08:12 +00002359
Chris Lattner22eb9722006-06-18 05:43:12 +00002360 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002361 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002362 // contribute to another token), it isn't needed for correctness. Note that
2363 // this is ok even in KeepWhitespaceMode, because we would have returned the
2364 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002365 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Chris Lattner22eb9722006-06-18 05:43:12 +00002367 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002368 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002369 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002370 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002371 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002372 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002373 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002374}
Chris Lattner22eb9722006-06-18 05:43:12 +00002375
Nico Weber158a31a2012-11-11 07:02:14 +00002376/// If in save-comment mode, package up this Line comment in an appropriate
2377/// way and return it.
2378bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002379 // If we're not in a preprocessor directive, just return the // comment
2380 // directly.
2381 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002382
David Blaikied5321242012-06-06 18:52:13 +00002383 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002384 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002385
Nico Weber158a31a2012-11-11 07:02:14 +00002386 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002387 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002388 bool Invalid = false;
2389 std::string Spelling = PP->getSpelling(Result, &Invalid);
2390 if (Invalid)
2391 return true;
Taewook Ohcebac482017-12-06 17:00:53 +00002392
Nico Weber158a31a2012-11-11 07:02:14 +00002393 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002394 Spelling[1] = '*'; // Change prefix to "/*".
2395 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattnerb11c3232008-10-12 04:51:35 +00002397 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002398 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002399 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002400 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002401}
2402
Chris Lattnercb283342006-06-18 06:48:37 +00002403/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002404/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2405/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002406static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002407 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002408 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chris Lattner22eb9722006-06-18 05:43:12 +00002410 // Back up off the newline.
2411 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Chris Lattner22eb9722006-06-18 05:43:12 +00002413 // If this is a two-character newline sequence, skip the other character.
2414 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2415 // \n\n or \r\r -> not escaped newline.
2416 if (CurPtr[0] == CurPtr[1])
2417 return false;
2418 // \n\r or \r\n -> skip the newline.
2419 --CurPtr;
2420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Chris Lattner22eb9722006-06-18 05:43:12 +00002422 // If we have horizontal whitespace, skip over it. We allow whitespace
2423 // between the slash and newline.
2424 bool HasSpace = false;
2425 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2426 --CurPtr;
2427 HasSpace = true;
2428 }
Mike Stump11289f42009-09-09 15:08:12 +00002429
Chris Lattner22eb9722006-06-18 05:43:12 +00002430 // If we have a slash, we know this is an escaped newline.
2431 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002432 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002433 } else {
2434 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002435 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2436 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002437 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattnercb283342006-06-18 06:48:37 +00002439 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002440 CurPtr -= 2;
2441
2442 // If no trigraphs are enabled, warn that we ignored this trigraph and
2443 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002444 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002445 if (!L->isLexingRawMode())
2446 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002447 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002448 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002449 if (!L->isLexingRawMode())
2450 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattner22eb9722006-06-18 05:43:12 +00002453 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002454 if (!L->isLexingRawMode())
2455 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattner22eb9722006-06-18 05:43:12 +00002457 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002458 if (HasSpace && !L->isLexingRawMode())
2459 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Chris Lattnercb283342006-06-18 06:48:37 +00002461 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002462}
2463
Chris Lattneraded4a92006-10-27 04:42:31 +00002464#ifdef __SSE2__
2465#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002466#elif __ALTIVEC__
2467#include <altivec.h>
2468#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002469#endif
2470
James Dennettf442d242012-06-17 03:40:43 +00002471/// We have just read from input the / and * characters that started a comment.
2472/// Read until we find the * and / characters that terminate the comment.
2473/// Note that we don't bother decoding trigraphs or escaped newlines in block
2474/// comments, because they cannot cause the comment to end. The only thing
2475/// that can happen is the comment could end with an escaped newline between
2476/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002477///
Chris Lattner87d02082010-01-18 22:35:47 +00002478/// If we're in KeepCommentMode or any CommentHandler has inserted
2479/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002480bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2481 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002482 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002483 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002484 // optimization helps people who like to put a lot of * characters in their
2485 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002486
2487 // The first character we get with newlines and trigraphs skipped to handle
2488 // the degenerate /*/ case below correctly if the * has an escaped newline
2489 // after it.
2490 unsigned CharSize;
2491 unsigned char C = getCharAndSize(CurPtr, CharSize);
2492 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002493 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002494 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002495 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002496 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Chris Lattner99e7d232008-10-12 04:19:49 +00002498 // KeepWhitespaceMode should return this broken comment as a token. Since
2499 // it isn't a well formed comment, just return it as an 'unknown' token.
2500 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002501 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002502 return true;
2503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattner99e7d232008-10-12 04:19:49 +00002505 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002506 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattnerc850ad62007-07-21 23:43:37 +00002509 // Check to see if the first character after the '/*' is another /. If so,
2510 // then this slash does not end the block comment, it is part of it.
2511 if (C == '/')
2512 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002513
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002514 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002515 // Skip over all non-interesting characters until we find end of buffer or a
2516 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002517 if (CurPtr + 24 < BufferEnd &&
2518 // If there is a code-completion point avoid the fast scan because it
2519 // doesn't check for '\0'.
2520 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002521 // While not aligned to a 16-byte boundary.
2522 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2523 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002524
Chris Lattner6cc3e362006-10-27 04:12:35 +00002525 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002526
2527#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002528 __m128i Slashes = _mm_set1_epi8('/');
2529 while (CurPtr+16 <= BufferEnd) {
2530 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2531 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002532 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002533 // Adjust the pointer to point directly after the first slash. It's
2534 // not necessary to set C here, it will be overwritten at the end of
2535 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002536 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002537 goto FoundSlash;
2538 }
Roman Divacky61509902014-04-03 18:04:52 +00002539 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002540 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002541#elif __ALTIVEC__
2542 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002543 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002544 '/', '/', '/', '/', '/', '/', '/', '/'
2545 };
2546 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002547 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002548 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002549#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002550 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002551 while (CurPtr[0] != '/' &&
2552 CurPtr[1] != '/' &&
2553 CurPtr[2] != '/' &&
2554 CurPtr[3] != '/' &&
2555 CurPtr+4 < BufferEnd) {
2556 CurPtr += 4;
2557 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002558#endif
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chris Lattneraded4a92006-10-27 04:42:31 +00002560 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002561 C = *CurPtr++;
2562 }
Mike Stump11289f42009-09-09 15:08:12 +00002563
Chris Lattneraded4a92006-10-27 04:42:31 +00002564 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002565 while (C != '/' && C != '\0')
2566 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002567
Chris Lattner22eb9722006-06-18 05:43:12 +00002568 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002569 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002570 if (CurPtr[-2] == '*') // We found the final */. We're done!
2571 break;
Mike Stump11289f42009-09-09 15:08:12 +00002572
Chris Lattner22eb9722006-06-18 05:43:12 +00002573 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002574 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002575 // We found the final */, though it had an escaped newline between the
2576 // * and /. We're done!
2577 break;
2578 }
2579 }
2580 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2581 // If this is a /* inside of the comment, emit a warning. Don't do this
2582 // if this is a /*/, which will end the comment. This misses cases with
2583 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002584 if (!isLexingRawMode())
2585 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002586 }
2587 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002588 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002589 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002590 // Note: the user probably forgot a */. We could continue immediately
2591 // after the /*, but this would involve lexing a lot of what really is the
2592 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002593 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002594
Chris Lattner99e7d232008-10-12 04:19:49 +00002595 // KeepWhitespaceMode should return this broken comment as a token. Since
2596 // it isn't a well formed comment, just return it as an 'unknown' token.
2597 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002598 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002599 return true;
2600 }
Mike Stump11289f42009-09-09 15:08:12 +00002601
Chris Lattner99e7d232008-10-12 04:19:49 +00002602 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002603 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002604 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2605 PP->CodeCompleteNaturalLanguage();
2606 cutOffLexing();
2607 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002608 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002609
Chris Lattner22eb9722006-06-18 05:43:12 +00002610 C = *CurPtr++;
2611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612
Chris Lattner93ddf802010-02-03 21:06:21 +00002613 // Notify comment handlers about the comment unless we're in a #if 0 block.
2614 if (PP && !isLexingRawMode() &&
2615 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2616 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002617 BufferPtr = CurPtr;
2618 return true; // A token has to be returned.
2619 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002620
Chris Lattner457fc152006-07-29 06:30:25 +00002621 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002622 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002623 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002624 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002625 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002626
2627 // It is common for the tokens immediately after a /**/ comment to be
2628 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002629 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2630 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002631 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002632 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002633 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002634 }
2635
2636 // Otherwise, just return so that the next character will be lexed as a token.
2637 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002638 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002639 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002640}
2641
2642//===----------------------------------------------------------------------===//
2643// Primary Lexing Entry Points
2644//===----------------------------------------------------------------------===//
2645
Chris Lattner22eb9722006-06-18 05:43:12 +00002646/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2647/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002648void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002649 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2650 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002651 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002652
2653 // CurPtr - Cache BufferPtr in an automatic variable.
2654 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002655 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002656 char Char = getAndAdvanceChar(CurPtr, Tmp);
2657 switch (Char) {
2658 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002659 if (Result)
2660 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002661 break;
2662 case 0: // Null.
2663 // Found end of file?
2664 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002665 if (isCodeCompletionPoint(CurPtr-1)) {
2666 PP->CodeCompleteNaturalLanguage();
2667 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002668 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002669 }
2670
Chris Lattner22eb9722006-06-18 05:43:12 +00002671 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002672 if (Result)
2673 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002674 break;
2675 }
2676 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002677 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002678 case '\r':
2679 case '\n':
2680 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2681 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2682 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002683
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002684 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002685 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002686 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002687 if (PP)
2688 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002689 Lex(Tmp);
2690 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002691 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002692
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002693 // Finally, we're done;
2694 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002695 }
2696 }
2697}
2698
2699/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2700/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002701/// This returns true if Result contains a token, false if PP.Lex should be
2702/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002703bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002704 // If we hit the end of the file while parsing a preprocessor directive,
2705 // end the preprocessor directive first. The next token returned will
2706 // then be the end of file.
2707 if (ParsingPreprocessorDirective) {
2708 // Done parsing the "line".
2709 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002710 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002711 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002712
Chris Lattner457fc152006-07-29 06:30:25 +00002713 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002714 if (PP)
2715 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002716 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002717 }
Taewook Ohcebac482017-12-06 17:00:53 +00002718
Chris Lattner30a2fa12006-07-19 06:31:49 +00002719 // If we are in raw mode, return this event as an EOF token. Let the caller
2720 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002721 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002722 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002723 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002724 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002725 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002726 }
Taewook Ohcebac482017-12-06 17:00:53 +00002727
Erik Verbruggen795eee92017-07-05 09:44:07 +00002728 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002729 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2730 ConditionalStack.clear();
2731 }
2732
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002733 // Issue diagnostics for unterminated #if and missing newline.
2734
Chris Lattner30a2fa12006-07-19 06:31:49 +00002735 // If we are in a #if directive, emit an error.
2736 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002737 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002738 PP->Diag(ConditionalStack.back().IfLoc,
2739 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002740 ConditionalStack.pop_back();
2741 }
Mike Stump11289f42009-09-09 15:08:12 +00002742
Chris Lattner8f96d042008-04-12 05:54:25 +00002743 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2744 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002745 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2746 DiagnosticsEngine &Diags = PP->getDiagnostics();
2747 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2748 unsigned DiagID;
2749
2750 if (LangOpts.CPlusPlus11) {
2751 // C++11 [lex.phases] 2.2 p2
2752 // Prefer the C++98 pedantic compatibility warning over the generic,
2753 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002754 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002755 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2756 } else {
2757 DiagID = diag::warn_no_newline_eof;
2758 }
2759 } else {
2760 DiagID = diag::ext_no_newline_eof;
2761 }
2762
2763 Diag(BufferEnd, DiagID)
2764 << FixItHint::CreateInsertion(EndLoc, "\n");
2765 }
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner22eb9722006-06-18 05:43:12 +00002767 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002768
2769 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002770 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002771}
2772
Chris Lattner678c8802006-07-11 05:46:12 +00002773/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2774/// the specified lexer will return a tok::l_paren token, 0 if it is something
2775/// else and 2 if there are no more tokens in the buffer controlled by the
2776/// lexer.
2777unsigned Lexer::isNextPPTokenLParen() {
2778 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002779
Chris Lattner678c8802006-07-11 05:46:12 +00002780 // Switch to 'skipping' mode. This will ensure that we can lex a token
2781 // without emitting diagnostics, disables macro expansion, and will cause EOF
2782 // to return an EOF token instead of popping the include stack.
2783 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002784
Chris Lattner678c8802006-07-11 05:46:12 +00002785 // Save state that can be changed while lexing so that we can restore it.
2786 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002787 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002788 bool atStartOfLine = IsAtStartOfLine;
2789 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2790 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Chris Lattner146762e2007-07-20 16:59:19 +00002792 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002793 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002794
Chris Lattner678c8802006-07-11 05:46:12 +00002795 // Restore state that may have changed.
2796 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002797 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002798 HasLeadingSpace = leadingSpace;
2799 IsAtStartOfLine = atStartOfLine;
2800 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002801
Chris Lattner678c8802006-07-11 05:46:12 +00002802 // Restore the lexer back to non-skipping mode.
2803 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002804
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002805 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002806 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002807 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002808}
2809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002810/// Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002811static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2812 ConflictMarkerKind CMK) {
2813 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2814 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002815 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002816 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002817 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002818 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002819 if (Pos == 0 ||
2820 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002821 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2822 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002823 continue;
2824 }
2825 return RestOfBuffer.data()+Pos;
2826 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002827 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002828}
2829
2830/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2831/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2832/// and recover nicely. This returns true if it is a conflict marker and false
2833/// if not.
2834bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2835 // Only a conflict marker if it starts at the beginning of a line.
2836 if (CurPtr != BufferStart &&
2837 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2838 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002839
Richard Smitha9e33d42011-10-12 00:37:51 +00002840 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002841 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2842 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002843 return false;
2844
2845 // If we have a situation where we don't care about conflict markers, ignore
2846 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002847 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002848 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002849
Richard Smitha9e33d42011-10-12 00:37:51 +00002850 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2851
2852 // Check to see if there is an ending marker somewhere in the buffer at the
2853 // start of a line to terminate this conflict marker.
2854 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002855 // We found a match. We are really in a conflict marker.
2856 // Diagnose this, and ignore to the end of line.
2857 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002858 CurrentConflictMarkerState = Kind;
Taewook Ohcebac482017-12-06 17:00:53 +00002859
Chris Lattner7c027ee2009-12-14 06:16:57 +00002860 // Skip ahead to the end of line. We know this exists because the
2861 // end-of-conflict marker starts with \r or \n.
2862 while (*CurPtr != '\r' && *CurPtr != '\n') {
2863 assert(CurPtr != BufferEnd && "Didn't find end of line");
2864 ++CurPtr;
2865 }
2866 BufferPtr = CurPtr;
2867 return true;
2868 }
Taewook Ohcebac482017-12-06 17:00:53 +00002869
Chris Lattner7c027ee2009-12-14 06:16:57 +00002870 // No end of conflict marker found.
2871 return false;
2872}
2873
Richard Smitha9e33d42011-10-12 00:37:51 +00002874/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2875/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2876/// is the end of a conflict marker. Handle it by ignoring up until the end of
2877/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002878bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2879 // Only a conflict marker if it starts at the beginning of a line.
2880 if (CurPtr != BufferStart &&
2881 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2882 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002883
Chris Lattner7c027ee2009-12-14 06:16:57 +00002884 // If we have a situation where we don't care about conflict markers, ignore
2885 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002886 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002887 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002888
Richard Smitha9e33d42011-10-12 00:37:51 +00002889 // Check to see if we have the marker (4 characters in a row).
2890 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002891 if (CurPtr[i] != CurPtr[0])
2892 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002893
Chris Lattner7c027ee2009-12-14 06:16:57 +00002894 // If we do have it, search for the end of the conflict marker. This could
2895 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2896 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002897 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2898 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002899 CurPtr = End;
Taewook Ohcebac482017-12-06 17:00:53 +00002900
Chris Lattner7c027ee2009-12-14 06:16:57 +00002901 // Skip ahead to the end of line.
2902 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2903 ++CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002904
Chris Lattner7c027ee2009-12-14 06:16:57 +00002905 BufferPtr = CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002906
Chris Lattner7c027ee2009-12-14 06:16:57 +00002907 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002908 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002909 return true;
2910 }
Taewook Ohcebac482017-12-06 17:00:53 +00002911
Chris Lattner7c027ee2009-12-14 06:16:57 +00002912 return false;
2913}
2914
Alex Lorenz1be800c52017-04-19 08:58:56 +00002915static const char *findPlaceholderEnd(const char *CurPtr,
2916 const char *BufferEnd) {
2917 if (CurPtr == BufferEnd)
2918 return nullptr;
2919 BufferEnd -= 1; // Scan until the second last character.
2920 for (; CurPtr != BufferEnd; ++CurPtr) {
2921 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2922 return CurPtr + 2;
2923 }
2924 return nullptr;
2925}
2926
2927bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2928 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002929 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002930 return false;
2931 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2932 if (!End)
2933 return false;
2934 const char *Start = CurPtr - 1;
2935 if (!LangOpts.AllowEditorPlaceholders)
2936 Diag(Start, diag::err_placeholder_in_source);
2937 Result.startToken();
2938 FormTokenWithChars(Result, End, tok::raw_identifier);
2939 Result.setRawIdentifierData(Start);
2940 PP->LookUpIdentifierInfo(Result);
2941 Result.setFlag(Token::IsEditorPlaceholder);
2942 BufferPtr = End;
2943 return true;
2944}
2945
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002946bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2947 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002948 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002949 return Loc == PP->getCodeCompletionLoc();
2950 }
2951
2952 return false;
2953}
2954
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002955uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2956 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002957 unsigned CharSize;
2958 char Kind = getCharAndSize(StartPtr, CharSize);
2959
2960 unsigned NumHexDigits;
2961 if (Kind == 'u')
2962 NumHexDigits = 4;
2963 else if (Kind == 'U')
2964 NumHexDigits = 8;
2965 else
2966 return 0;
2967
Jordan Rosec0cba272013-01-27 20:12:04 +00002968 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002969 if (Result && !isLexingRawMode())
2970 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002971 return 0;
2972 }
2973
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002974 const char *CurPtr = StartPtr + CharSize;
2975 const char *KindLoc = &CurPtr[-1];
2976
2977 uint32_t CodePoint = 0;
2978 for (unsigned i = 0; i < NumHexDigits; ++i) {
2979 char C = getCharAndSize(CurPtr, CharSize);
2980
2981 unsigned Value = llvm::hexDigitValue(C);
2982 if (Value == -1U) {
2983 if (Result && !isLexingRawMode()) {
2984 if (i == 0) {
2985 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2986 << StringRef(KindLoc, 1);
2987 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002988 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002989
2990 // If the user wrote \U1234, suggest a fixit to \u.
2991 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002992 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002993 Diag(KindLoc, diag::note_ucn_four_not_eight)
2994 << FixItHint::CreateReplacement(URange, "u");
2995 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002996 }
2997 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002998
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002999 return 0;
3000 }
3001
3002 CodePoint <<= 4;
3003 CodePoint += Value;
3004
3005 CurPtr += CharSize;
3006 }
3007
3008 if (Result) {
3009 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00003010 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003011 StartPtr = CurPtr;
3012 else
3013 while (StartPtr != CurPtr)
3014 (void)getAndAdvanceChar(StartPtr, *Result);
3015 } else {
3016 StartPtr = CurPtr;
3017 }
3018
Justin Bogner53535132013-10-21 05:02:28 +00003019 // Don't apply C family restrictions to UCNs in assembly mode
3020 if (LangOpts.AsmPreprocessor)
3021 return CodePoint;
3022
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003023 // C99 6.4.3p2: A universal character name shall not specify a character whose
3024 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
3025 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
3026 // C++11 [lex.charset]p2: If the hexadecimal value for a
3027 // universal-character-name corresponds to a surrogate code point (in the
3028 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3029 // if the hexadecimal value for a universal-character-name outside the
3030 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3031 // string literal corresponds to a control character (in either of the
3032 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3033 // basic source character set, the program is ill-formed.
3034 if (CodePoint < 0xA0) {
3035 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
3036 return CodePoint;
3037
3038 // We don't use isLexingRawMode() here because we need to warn about bad
3039 // UCNs even when skipping preprocessing tokens in a #if block.
3040 if (Result && PP) {
3041 if (CodePoint < 0x20 || CodePoint >= 0x7F)
3042 Diag(BufferPtr, diag::err_ucn_control_character);
3043 else {
3044 char C = static_cast<char>(CodePoint);
3045 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3046 }
3047 }
3048
3049 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00003050 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003051 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00003052 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003053 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00003054 if (Result && PP) {
3055 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3056 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3057 else
3058 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3059 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003060 return 0;
3061 }
3062
3063 return CodePoint;
3064}
3065
Eli Friedman0834a4b2013-09-19 00:41:32 +00003066bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3067 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003068 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3069 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00003070 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003071 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00003072 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00003073 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00003074
3075 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003076 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00003077 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003078 return false;
3079}
Jordan Rose4246ae02013-01-24 20:50:50 +00003080
Eli Friedman0834a4b2013-09-19 00:41:32 +00003081bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00003082 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3083 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3084 !PP->isPreprocessedOutput()) {
3085 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3086 makeCharRange(*this, BufferPtr, CurPtr),
3087 /*IsFirst=*/true);
Richard Smith4e966e82018-09-25 22:34:45 +00003088 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
3089 makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose58c61e02013-02-09 01:10:25 +00003090 }
3091
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003092 MIOpt.ReadToken();
3093 return LexIdentifier(Result, CurPtr);
3094 }
3095
Jordan Rosecc538342013-01-31 19:48:48 +00003096 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3097 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00003098 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003099 // Non-ASCII characters tend to creep into source code unintentionally.
3100 // Instead of letting the parser complain about the unknown token,
3101 // just drop the character.
3102 // Note that we can /only/ do this when the non-ASCII character is actually
3103 // spelled as Unicode, not written as a UCN. The standard requires that
3104 // we not throw away any possible preprocessor tokens, but there's a
3105 // loophole in the mapping of Unicode characters to basic character set
3106 // characters that allows us to map these particular characters to, say,
3107 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00003108 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00003109 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003110
3111 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003112 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003113 }
3114
3115 // Otherwise, we have an explicit UCN or a character that's unlikely to show
3116 // up by accident.
3117 MIOpt.ReadToken();
3118 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003119 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003120}
3121
Eli Friedman0834a4b2013-09-19 00:41:32 +00003122void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3123 IsAtStartOfLine = Result.isAtStartOfLine();
3124 HasLeadingSpace = Result.hasLeadingSpace();
3125 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3126 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3127}
3128
3129bool Lexer::Lex(Token &Result) {
3130 // Start a new token.
3131 Result.startToken();
3132
3133 // Set up misc whitespace flags for LexTokenInternal.
3134 if (IsAtStartOfLine) {
3135 Result.setFlag(Token::StartOfLine);
3136 IsAtStartOfLine = false;
3137 }
3138
3139 if (HasLeadingSpace) {
3140 Result.setFlag(Token::LeadingSpace);
3141 HasLeadingSpace = false;
3142 }
3143
3144 if (HasLeadingEmptyMacro) {
3145 Result.setFlag(Token::LeadingEmptyMacro);
3146 HasLeadingEmptyMacro = false;
3147 }
3148
3149 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3150 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00003151 bool isRawLex = isLexingRawMode();
3152 (void) isRawLex;
3153 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3154 // (After the LexTokenInternal call, the lexer might be destroyed.)
3155 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3156 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003157}
Chris Lattner22eb9722006-06-18 05:43:12 +00003158
3159/// LexTokenInternal - This implements a simple C family lexer. It is an
3160/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003161/// has a null character at the end of the file. This returns a preprocessing
3162/// token, not a normal token, as such, it is an internal interface. It assumes
3163/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003164bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003165LexNextToken:
3166 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003167 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003168 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003169
Chris Lattner22eb9722006-06-18 05:43:12 +00003170 // CurPtr - Cache BufferPtr in an automatic variable.
3171 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003172
Chris Lattnereb54b592006-07-10 06:34:27 +00003173 // Small amounts of horizontal whitespace is very common between tokens.
3174 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3175 ++CurPtr;
3176 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3177 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003178
Chris Lattner4d963442008-10-12 04:05:48 +00003179 // If we are keeping whitespace and other tokens, just return what we just
3180 // skipped. The next lexer invocation will return the token after the
3181 // whitespace.
3182 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003183 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003184 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003185 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003186 }
Mike Stump11289f42009-09-09 15:08:12 +00003187
Chris Lattnereb54b592006-07-10 06:34:27 +00003188 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003189 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Chris Lattner22eb9722006-06-18 05:43:12 +00003192 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003193
Chris Lattner22eb9722006-06-18 05:43:12 +00003194 // Read a character, advancing over it.
3195 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003196 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003197
Chris Lattner22eb9722006-06-18 05:43:12 +00003198 switch (Char) {
3199 case 0: // Null.
3200 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003201 if (CurPtr-1 == BufferEnd)
3202 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003203
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003204 // Check if we are performing code completion.
3205 if (isCodeCompletionPoint(CurPtr-1)) {
3206 // Return the code-completion token.
3207 Result.startToken();
3208 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003209 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003210 }
3211
Chris Lattner6d27a162008-11-22 02:02:22 +00003212 if (!isLexingRawMode())
3213 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003214 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003215 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3216 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003217
Eli Friedman0834a4b2013-09-19 00:41:32 +00003218 // We know the lexer hasn't changed, so just try again with this lexer.
3219 // (We manually eliminate the tail call to avoid recursion.)
3220 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003221
Chris Lattner3dfff972009-12-17 05:29:40 +00003222 case 26: // DOS & CP/M EOF: "^Z".
3223 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003224 if (LangOpts.MicrosoftExt) {
3225 if (!isLexingRawMode())
3226 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003227 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003228 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003229
Chris Lattner3dfff972009-12-17 05:29:40 +00003230 // If Microsoft extensions are disabled, this is just random garbage.
3231 Kind = tok::unknown;
3232 break;
Taewook Ohcebac482017-12-06 17:00:53 +00003233
Chris Lattner22eb9722006-06-18 05:43:12 +00003234 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003235 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003236 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003237 LLVM_FALLTHROUGH;
3238 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003239 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003240 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003241 if (ParsingPreprocessorDirective) {
3242 // Done parsing the "line".
3243 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003244
Chris Lattner457fc152006-07-29 06:30:25 +00003245 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003246 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003247 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003248
Chris Lattner22eb9722006-06-18 05:43:12 +00003249 // Since we consumed a newline, we are back at the start of a line.
3250 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003251 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003252
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003253 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003254 break;
3255 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003256
Chris Lattner22eb9722006-06-18 05:43:12 +00003257 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003258 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003259
Eli Friedman0834a4b2013-09-19 00:41:32 +00003260 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3261 return true; // KeepWhitespaceMode
3262
3263 // We only saw whitespace, so just try again with this lexer.
3264 // (We manually eliminate the tail call to avoid recursion.)
3265 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 case ' ':
3267 case '\t':
3268 case '\f':
3269 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003270 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003271 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003272 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3273 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003274
3275 SkipIgnoredUnits:
3276 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003277
Chris Lattnerb9b85972007-07-22 06:29:05 +00003278 // If the next token is obviously a // or /* */ comment, skip it efficiently
3279 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003280 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003281 LangOpts.LineComment &&
3282 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003283 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3284 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003285 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003286 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003287 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3288 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003289 goto SkipIgnoredUnits;
3290 } else if (isHorizontalWhitespace(*CurPtr)) {
3291 goto SkipHorizontalWhitespace;
3292 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003293 // We only saw whitespace, so just try again with this lexer.
3294 // (We manually eliminate the tail call to avoid recursion.)
3295 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003296
Chris Lattner2b15cf72008-01-03 17:58:54 +00003297 // C99 6.4.4.1: Integer Constants.
3298 // C99 6.4.4.2: Floating Constants.
3299 case '0': case '1': case '2': case '3': case '4':
3300 case '5': case '6': case '7': case '8': case '9':
3301 // Notify MIOpt that we read a non-whitespace/non-comment token.
3302 MIOpt.ReadToken();
3303 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003304
Richard Smith9b362092013-03-09 23:56:02 +00003305 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003306 // Notify MIOpt that we read a non-whitespace/non-comment token.
3307 MIOpt.ReadToken();
3308
Richard Smith9b362092013-03-09 23:56:02 +00003309 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003310 Char = getCharAndSize(CurPtr, SizeTmp);
3311
3312 // UTF-16 string literal
3313 if (Char == '"')
3314 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3315 tok::utf16_string_literal);
3316
3317 // UTF-16 character constant
3318 if (Char == '\'')
3319 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3320 tok::utf16_char_constant);
3321
Craig Topper54edcca2011-08-11 04:06:15 +00003322 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003323 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3324 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003325 return LexRawStringLiteral(Result,
3326 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3327 SizeTmp2, Result),
3328 tok::utf16_string_literal);
3329
3330 if (Char == '8') {
3331 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3332
3333 // UTF-8 string literal
3334 if (Char2 == '"')
3335 return LexStringLiteral(Result,
3336 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3337 SizeTmp2, Result),
3338 tok::utf8_string_literal);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003339 if (Char2 == '\'' && LangOpts.CPlusPlus17)
Richard Smith3e3a7052014-11-08 06:08:42 +00003340 return LexCharConstant(
3341 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3342 SizeTmp2, Result),
3343 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003344
Richard Smith9b362092013-03-09 23:56:02 +00003345 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003346 unsigned SizeTmp3;
3347 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3348 // UTF-8 raw string literal
3349 if (Char3 == '"') {
3350 return LexRawStringLiteral(Result,
3351 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3352 SizeTmp2, Result),
3353 SizeTmp3, Result),
3354 tok::utf8_string_literal);
3355 }
3356 }
3357 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003358 }
3359
3360 // treat u like the start of an identifier.
3361 return LexIdentifier(Result, CurPtr);
3362
Richard Smith9b362092013-03-09 23:56:02 +00003363 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003364 // Notify MIOpt that we read a non-whitespace/non-comment token.
3365 MIOpt.ReadToken();
3366
Richard Smith9b362092013-03-09 23:56:02 +00003367 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003368 Char = getCharAndSize(CurPtr, SizeTmp);
3369
3370 // UTF-32 string literal
3371 if (Char == '"')
3372 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3373 tok::utf32_string_literal);
3374
3375 // UTF-32 character constant
3376 if (Char == '\'')
3377 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3378 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003379
3380 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003381 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3382 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003383 return LexRawStringLiteral(Result,
3384 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3385 SizeTmp2, Result),
3386 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003387 }
3388
3389 // treat U like the start of an identifier.
3390 return LexIdentifier(Result, CurPtr);
3391
Craig Topper54edcca2011-08-11 04:06:15 +00003392 case 'R': // Identifier or C++0x raw string literal
3393 // Notify MIOpt that we read a non-whitespace/non-comment token.
3394 MIOpt.ReadToken();
3395
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003396 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003397 Char = getCharAndSize(CurPtr, SizeTmp);
3398
3399 if (Char == '"')
3400 return LexRawStringLiteral(Result,
3401 ConsumeChar(CurPtr, SizeTmp, Result),
3402 tok::string_literal);
3403 }
3404
3405 // treat R like the start of an identifier.
3406 return LexIdentifier(Result, CurPtr);
3407
Chris Lattner2b15cf72008-01-03 17:58:54 +00003408 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003409 // Notify MIOpt that we read a non-whitespace/non-comment token.
3410 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 Char = getCharAndSize(CurPtr, SizeTmp);
3412
3413 // Wide string literal.
3414 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003415 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003416 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003417
Craig Topper54edcca2011-08-11 04:06:15 +00003418 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003419 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003420 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3421 return LexRawStringLiteral(Result,
3422 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3423 SizeTmp2, Result),
3424 tok::wide_string_literal);
3425
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 // Wide character constant.
3427 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003428 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3429 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003430 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003431 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003432
Chris Lattner22eb9722006-06-18 05:43:12 +00003433 // C99 6.4.2: Identifiers.
3434 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3435 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003436 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003437 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3438 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3439 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003440 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003441 case 'v': case 'w': case 'x': case 'y': case 'z':
3442 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003443 // Notify MIOpt that we read a non-whitespace/non-comment token.
3444 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003445 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003446
3447 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003448 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003449 if (!isLexingRawMode())
3450 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003451 // Notify MIOpt that we read a non-whitespace/non-comment token.
3452 MIOpt.ReadToken();
3453 return LexIdentifier(Result, CurPtr);
3454 }
Mike Stump11289f42009-09-09 15:08:12 +00003455
Chris Lattnerb11c3232008-10-12 04:51:35 +00003456 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003457 break;
Mike Stump11289f42009-09-09 15:08:12 +00003458
Chris Lattner22eb9722006-06-18 05:43:12 +00003459 // C99 6.4.4: Character Constants.
3460 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003461 // Notify MIOpt that we read a non-whitespace/non-comment token.
3462 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003463 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003464
3465 // C99 6.4.5: String Literals.
3466 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003467 // Notify MIOpt that we read a non-whitespace/non-comment token.
3468 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003469 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003470
3471 // C99 6.4.6: Punctuators.
3472 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003473 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 break;
3475 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003476 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003477 break;
3478 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003479 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003480 break;
3481 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003482 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003483 break;
3484 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003485 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003486 break;
3487 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003488 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003489 break;
3490 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003491 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003492 break;
3493 case '.':
3494 Char = getCharAndSize(CurPtr, SizeTmp);
3495 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003496 // Notify MIOpt that we read a non-whitespace/non-comment token.
3497 MIOpt.ReadToken();
3498
Chris Lattner22eb9722006-06-18 05:43:12 +00003499 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003500 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003501 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 CurPtr += SizeTmp;
3503 } else if (Char == '.' &&
3504 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003505 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3507 SizeTmp2, Result);
3508 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003509 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003510 }
3511 break;
3512 case '&':
3513 Char = getCharAndSize(CurPtr, SizeTmp);
3514 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003515 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3517 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003518 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003519 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3520 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003521 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003522 }
3523 break;
Mike Stump11289f42009-09-09 15:08:12 +00003524 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003525 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003526 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003527 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3528 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003529 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003530 }
3531 break;
3532 case '+':
3533 Char = getCharAndSize(CurPtr, SizeTmp);
3534 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003536 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003537 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003539 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003540 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003541 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003542 }
3543 break;
3544 case '-':
3545 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003546 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003547 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003548 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003549 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003550 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003551 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3552 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003553 Kind = tok::arrowstar;
3554 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003556 Kind = tok::arrow;
3557 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003558 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003559 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003560 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003561 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003562 }
3563 break;
3564 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003565 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003566 break;
3567 case '!':
3568 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003569 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003570 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3571 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003572 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003573 }
3574 break;
3575 case '/':
3576 // 6.4.9: Comments
3577 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003578 if (Char == '/') { // Line comment.
3579 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003580 // want to lex this as a comment. There is one problem with this though,
3581 // that in one particular corner case, this can change the behavior of the
3582 // resultant program. For example, In "foo //**/ bar", C89 would lex
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003583 // this as "foo / bar" and languages with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003584 // "foo". Check to see if the character after the second slash is a '*'.
3585 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003586 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003587 bool TreatAsComment = LangOpts.LineComment &&
3588 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003589 if (!TreatAsComment)
3590 if (!(PP && PP->isPreprocessedOutput()))
3591 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3592
3593 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003594 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3595 TokAtPhysicalStartOfLine))
3596 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003597
Chris Lattner58827712009-01-16 22:39:25 +00003598 // It is common for the tokens immediately after a // comment to be
3599 // whitespace (indentation for the next line). Instead of going through
3600 // the big switch, handle it efficiently now.
3601 goto SkipIgnoredUnits;
3602 }
3603 }
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattner58827712009-01-16 22:39:25 +00003605 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003606 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3607 TokAtPhysicalStartOfLine))
3608 return true; // There is a token to return.
3609
3610 // We only saw whitespace, so just try again with this lexer.
3611 // (We manually eliminate the tail call to avoid recursion.)
3612 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003613 }
Mike Stump11289f42009-09-09 15:08:12 +00003614
Chris Lattner58827712009-01-16 22:39:25 +00003615 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003616 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003617 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003618 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003619 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003620 }
3621 break;
3622 case '%':
3623 Char = getCharAndSize(CurPtr, SizeTmp);
3624 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003625 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003626 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003627 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003628 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003630 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003631 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003632 Char = getCharAndSize(CurPtr, SizeTmp);
3633 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003634 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003635 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3636 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003637 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003638 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003639 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003640 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003641 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003642 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003643 // We parsed a # character. If this occurs at the start of the line,
3644 // it's actually the start of a preprocessing directive. Callback to
3645 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003646 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003647 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003648 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003649
Chris Lattner2534324a2009-03-18 20:58:27 +00003650 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003651 }
3652 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003653 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003654 }
3655 break;
3656 case '<':
3657 Char = getCharAndSize(CurPtr, SizeTmp);
3658 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003659 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003660 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003661 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3662 if (After == '=') {
3663 Kind = tok::lesslessequal;
3664 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3665 SizeTmp2, Result);
3666 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3667 // If this is actually a '<<<<<<<' version control conflict marker,
3668 // recognize it as such and recover nicely.
3669 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003670 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3671 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3672 // ignore it.
3673 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003674 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003675 Kind = tok::lesslessless;
3676 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3677 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003678 } else {
3679 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3680 Kind = tok::lessless;
3681 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003682 } else if (Char == '=') {
Richard Smithedbf5972017-12-01 01:07:10 +00003683 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3684 if (After == '>') {
3685 if (getLangOpts().CPlusPlus2a) {
3686 if (!isLexingRawMode())
3687 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3688 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3689 SizeTmp2, Result);
3690 Kind = tok::spaceship;
3691 break;
3692 }
3693 // Suggest adding a space between the '<=' and the '>' to avoid a
3694 // change in semantics if this turns up in C++ <=17 mode.
3695 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3696 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3697 << FixItHint::CreateInsertion(
3698 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3699 }
3700 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003701 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003702 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003703 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003704 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003705 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3706 // C++0x [lex.pptoken]p3:
3707 // Otherwise, if the next three characters are <:: and the subsequent
3708 // character is neither : nor >, the < is treated as a preprocessor
3709 // token by itself and not as the first character of the alternative
3710 // token <:.
3711 unsigned SizeTmp3;
3712 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3713 if (After != ':' && After != '>') {
3714 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003715 if (!isLexingRawMode())
3716 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003717 break;
3718 }
3719 }
3720
Chris Lattner22eb9722006-06-18 05:43:12 +00003721 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003722 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003723 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003724 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003725 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003726 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3727 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003728 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003729 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003730 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003731 }
3732 break;
3733 case '>':
3734 Char = getCharAndSize(CurPtr, SizeTmp);
3735 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003736 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003737 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003738 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003739 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3740 if (After == '=') {
3741 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3742 SizeTmp2, Result);
3743 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003744 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3745 // If this is actually a '>>>>' conflict marker, recognize it as such
3746 // and recover nicely.
3747 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003748 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3749 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3750 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003751 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003752 Kind = tok::greatergreatergreater;
3753 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3754 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003755 } else {
3756 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3757 Kind = tok::greatergreater;
3758 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003759 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003760 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003761 }
3762 break;
3763 case '^':
3764 Char = getCharAndSize(CurPtr, SizeTmp);
3765 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003766 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003767 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003768 } else if (LangOpts.OpenCL && Char == '^') {
3769 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3770 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003771 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003772 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003773 }
3774 break;
3775 case '|':
3776 Char = getCharAndSize(CurPtr, SizeTmp);
3777 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003778 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003779 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3780 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003781 // If this is '|||||||' and we're in a conflict marker, ignore it.
3782 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3783 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003784 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003785 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3786 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003787 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003788 }
3789 break;
3790 case ':':
3791 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003792 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003793 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003794 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Aaron Ballman606093a2017-10-15 15:01:42 +00003795 } else if ((LangOpts.CPlusPlus ||
3796 LangOpts.DoubleSquareBracketAttributes) &&
3797 Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003798 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003799 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003800 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003801 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003802 }
3803 break;
3804 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003805 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003806 break;
3807 case '=':
3808 Char = getCharAndSize(CurPtr, SizeTmp);
3809 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003810 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003811 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3812 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003813
Chris Lattnerb11c3232008-10-12 04:51:35 +00003814 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003815 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003816 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003817 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003818 }
3819 break;
3820 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003821 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003822 break;
3823 case '#':
3824 Char = getCharAndSize(CurPtr, SizeTmp);
3825 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003826 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003827 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003828 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003829 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003830 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003831 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003832 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003833 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003834 // We parsed a # character. If this occurs at the start of the line,
3835 // it's actually the start of a preprocessing directive. Callback to
3836 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003837 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003838 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003839 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003840
Chris Lattner2534324a2009-03-18 20:58:27 +00003841 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003842 }
3843 break;
3844
Chris Lattner2b15cf72008-01-03 17:58:54 +00003845 case '@':
3846 // Objective C support.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003847 if (CurPtr[-1] == '@' && LangOpts.ObjC)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003848 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003849 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003850 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003851 break;
Mike Stump11289f42009-09-09 15:08:12 +00003852
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003853 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003854 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003855 if (!LangOpts.AsmPreprocessor) {
3856 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3857 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3858 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3859 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003860
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003861 // We only saw whitespace, so just try again with this lexer.
3862 // (We manually eliminate the tail call to avoid recursion.)
3863 goto LexNextToken;
3864 }
3865
3866 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003867 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003868 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003869
Chris Lattnerb11c3232008-10-12 04:51:35 +00003870 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003871 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003872
3873 default: {
3874 if (isASCII(Char)) {
3875 Kind = tok::unknown;
3876 break;
3877 }
3878
Justin Lebar90910552016-09-30 00:38:45 +00003879 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003880
3881 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3882 // an escaped newline.
3883 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003884 llvm::ConversionResult Status =
3885 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3886 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003887 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003888 llvm::strictConversion);
3889 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003890 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3891 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3892 return true; // KeepWhitespaceMode
3893
3894 // We only saw whitespace, so just try again with this lexer.
3895 // (We manually eliminate the tail call to avoid recursion.)
3896 goto LexNextToken;
3897 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003898 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003899 }
Taewook Ohcebac482017-12-06 17:00:53 +00003900
Jordan Rosecc538342013-01-31 19:48:48 +00003901 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3902 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003903 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003904 Kind = tok::unknown;
3905 break;
3906 }
3907
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003908 // Non-ASCII characters tend to creep into source code unintentionally.
3909 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003910 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003911 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003912
3913 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003914 // We're pretending the character didn't exist, so just try again with
3915 // this lexer.
3916 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003917 goto LexNextToken;
3918 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003919 }
Mike Stump11289f42009-09-09 15:08:12 +00003920
Chris Lattner371ac8a2006-07-04 07:11:10 +00003921 // Notify MIOpt that we read a non-whitespace/non-comment token.
3922 MIOpt.ReadToken();
3923
Chris Lattnerd01e2912006-06-18 16:22:51 +00003924 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003925 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003926 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003927
3928HandleDirective:
3929 // We parsed a # character and it's the start of a preprocessing directive.
3930
3931 FormTokenWithChars(Result, CurPtr, tok::hash);
3932 PP->HandleDirective(Result);
3933
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003934 if (PP->hadModuleLoaderFatalFailure()) {
3935 // With a fatal failure in the module loader, we abort parsing.
3936 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003937 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003938 }
3939
Eli Friedman0834a4b2013-09-19 00:41:32 +00003940 // We parsed the directive; lex a token with the new state.
3941 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003942}