blob: e9478d603a5241299b8b61bde44054458cd5c42b [file] [log] [blame]
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001//===- Lexer.cpp - C Language Family Lexer --------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000013
14#include "clang/Lex/Lexer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "UnicodeCharSets.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000016#include "clang/Basic/CharInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceLocation.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000020#include "clang/Basic/SourceManager.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000021#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Richard Smith2a988622013-09-24 04:06:10 +000023#include "clang/Lex/LiteralSupport.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000024#include "clang/Lex/MultipleIncludeOpt.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
Alex Lorenzfb7654a2017-06-16 20:13:39 +000026#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000027#include "clang/Lex/Token.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/TokenKinds.h"
31#include "llvm/ADT/None.h"
32#include "llvm/ADT/Optional.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000033#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000035#include "llvm/ADT/StringRef.h"
Chris Lattner619c1742007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000039#include "llvm/Support/MemoryBuffer.h"
Richard Smith77091b12017-12-14 13:15:08 +000040#include "llvm/Support/NativeFormatting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "llvm/Support/UnicodeCharRanges.h"
42#include <algorithm>
43#include <cassert>
44#include <cstddef>
45#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000046#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include <string>
48#include <tuple>
49#include <utility>
50
Chris Lattner22eb9722006-06-18 05:43:12 +000051using namespace clang;
52
Chris Lattner4894f482007-10-07 08:47:24 +000053//===----------------------------------------------------------------------===//
54// Token Class Implementation
55//===----------------------------------------------------------------------===//
56
Mike Stump11289f42009-09-09 15:08:12 +000057/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000058bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Alex Lorenzd4754662017-05-17 11:08:36 +000059 if (isAnnotation())
60 return false;
Douglas Gregor90abb6d2008-12-01 21:46:47 +000061 if (IdentifierInfo *II = getIdentifierInfo())
62 return II->getObjCKeywordID() == objcKey;
63 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000064}
65
66/// getObjCKeywordID - Return the ObjC keyword kind.
67tok::ObjCKeywordKind Token::getObjCKeywordID() const {
Alex Lorenzd4754662017-05-17 11:08:36 +000068 if (isAnnotation())
69 return tok::objc_not_keyword;
Chris Lattner4894f482007-10-07 08:47:24 +000070 IdentifierInfo *specId = getIdentifierInfo();
71 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
72}
73
74//===----------------------------------------------------------------------===//
75// Lexer Class Implementation
76//===----------------------------------------------------------------------===//
77
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000078void Lexer::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +000079
Mike Stump11289f42009-09-09 15:08:12 +000080void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000081 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000082 BufferStart = BufStart;
83 BufferPtr = BufPtr;
84 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerf76b9202009-01-17 06:55:17 +000086 assert(BufEnd[0] == 0 &&
87 "We assume that the input buffer has a null character at the end"
88 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000089
Eric Christopher7f36a792011-04-09 00:01:04 +000090 // Check whether we have a BOM in the beginning of the buffer. If yes - act
91 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
92 // skip the UTF-8 BOM if it's present.
93 if (BufferStart == BufferPtr) {
94 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000095 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000096 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000097 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
98 .Default(0);
99
100 // Skip the BOM.
101 BufferPtr += BOMLength;
102 }
103
Chris Lattnerf76b9202009-01-17 06:55:17 +0000104 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +0000105 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +0000106
Chris Lattnerf76b9202009-01-17 06:55:17 +0000107 // Start of the file is a start of line.
108 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000109 IsAtPhysicalStartOfLine = true;
110
111 HasLeadingSpace = false;
112 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerf76b9202009-01-17 06:55:17 +0000114 // We are not after parsing a #.
115 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerf76b9202009-01-17 06:55:17 +0000117 // We are not after parsing #include.
118 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattnerf76b9202009-01-17 06:55:17 +0000120 // We are not in raw mode. Raw mode disables diagnostics and interpretation
121 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
122 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
123 // or otherwise skipping over tokens.
124 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chris Lattnerf76b9202009-01-17 06:55:17 +0000126 // Default to not keeping comments.
127 ExtendedTokenMode = 0;
128}
129
Chris Lattner5965a282009-01-17 07:56:59 +0000130/// Lexer constructor - Create a new lexer object for the specified buffer
131/// with the specified preprocessor managing the lexing process. This lexer
132/// assumes that the associated file buffer and Preprocessor objects will
133/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000134Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000135 : PreprocessorLexer(&PP, FID),
136 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
137 LangOpts(PP.getLangOpts()) {
Chris Lattner5965a282009-01-17 07:56:59 +0000138 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
139 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000140
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000141 resetExtendedTokenMode();
142}
143
Chris Lattner02b436a2007-10-17 20:41:00 +0000144/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000145/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000146/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000147Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000148 const char *BufStart, const char *BufPtr, const char *BufEnd)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000149 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000150 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000151
Chris Lattner02b436a2007-10-17 20:41:00 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000154}
155
Chris Lattner08354fe2009-01-17 07:35:14 +0000156/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000157/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000158/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000159Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000160 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000161 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
162 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000163
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000164void Lexer::resetExtendedTokenMode() {
165 assert(PP && "Cannot reset token mode without a preprocessor");
166 if (LangOpts.TraditionalCPP)
167 SetKeepWhitespaceMode(true);
168 else
169 SetCommentRetentionState(PP->getCommentRetentionState());
170}
171
Chris Lattner757169b2009-01-17 08:27:52 +0000172/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
173/// _Pragma expansion. This has a variety of magic semantics that this method
174/// sets up. It returns a new'd Lexer that must be delete'd when done.
175///
176/// On entrance to this routine, TokStartLoc is a macro location which has a
177/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000178/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000179/// "expanded from".
180///
Alp Toker7755aff2014-05-18 18:37:59 +0000181/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000182/// normal lexer that remaps tokens as they fly by. This would require making
183/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
184/// interface that could handle this stuff. This would pull GetMappedTokenLoc
185/// out of the critical path of the lexer!
186///
Mike Stump11289f42009-09-09 15:08:12 +0000187Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000188 SourceLocation ExpansionLocStart,
189 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000190 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000191 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000192
193 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000194 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000195 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
196 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner757169b2009-01-17 08:27:52 +0000198 // Now that the lexer is created, change the start/end locations so that we
199 // just lex the subsection of the file that we want. This is lexing from a
200 // scratch buffer.
201 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner757169b2009-01-17 08:27:52 +0000203 L->BufferPtr = StrData;
204 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000205 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000206
207 // Set the SourceLocation with the remapping information. This ensures that
208 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000209 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
210 ExpansionLocStart,
211 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner757169b2009-01-17 08:27:52 +0000213 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000214 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000215 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner757169b2009-01-17 08:27:52 +0000217 // This lexer really is for _Pragma.
218 L->Is_PragmaLexer = true;
219 return L;
220}
221
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000222template <typename T> static void StringifyImpl(T &Str, char Quote) {
Taewook Ohcebac482017-12-06 17:00:53 +0000223 typename T::size_type i = 0, e = Str.size();
224 while (i < e) {
225 if (Str[i] == '\\' || Str[i] == Quote) {
226 Str.insert(Str.begin() + i, '\\');
227 i += 2;
228 ++e;
229 } else if (Str[i] == '\n' || Str[i] == '\r') {
230 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
231 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
232 Str[i] != Str[i + 1]) {
233 Str[i] = '\\';
234 Str[i + 1] = 'n';
235 } else {
236 // Replace '\n' and '\r' to '\\' followed by 'n'.
237 Str[i] = '\\';
238 Str.insert(Str.begin() + i + 1, 'n');
239 ++e;
240 }
241 i += 2;
242 } else
243 ++i;
244 }
245}
246
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000247std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000248 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000249 char Quote = Charify ? '\'' : '"';
Taewook Ohcebac482017-12-06 17:00:53 +0000250 StringifyImpl(Result, Quote);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000251 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000252}
253
Taewook Ohcebac482017-12-06 17:00:53 +0000254void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
Chris Lattner4c4a2452007-07-24 06:57:14 +0000255
Chris Lattner39720112010-11-17 07:26:20 +0000256//===----------------------------------------------------------------------===//
257// Token Spelling
258//===----------------------------------------------------------------------===//
259
Richard Smith9a67f472012-11-28 07:29:00 +0000260/// \brief Slow case of getSpelling. Extract the characters comprising the
261/// spelling of this token from the provided input buffer.
262static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
263 const LangOptions &LangOpts, char *Spelling) {
264 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
265
266 size_t Length = 0;
267 const char *BufEnd = BufPtr + Tok.getLength();
268
Craig Toppera6324c92015-10-22 15:35:21 +0000269 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000270 // Munch the encoding-prefix and opening double-quote.
271 while (BufPtr < BufEnd) {
272 unsigned Size;
273 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
274 BufPtr += Size;
275
276 if (Spelling[Length - 1] == '"')
277 break;
278 }
279
280 // Raw string literals need special handling; trigraph expansion and line
281 // splicing do not occur within their d-char-sequence nor within their
282 // r-char-sequence.
283 if (Length >= 2 &&
284 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
285 // Search backwards from the end of the token to find the matching closing
286 // quote.
287 const char *RawEnd = BufEnd;
288 do --RawEnd; while (*RawEnd != '"');
289 size_t RawLength = RawEnd - BufPtr + 1;
290
291 // Everything between the quotes is included verbatim in the spelling.
292 memcpy(Spelling + Length, BufPtr, RawLength);
293 Length += RawLength;
294 BufPtr += RawLength;
295
296 // The rest of the token is lexed normally.
297 }
298 }
299
300 while (BufPtr < BufEnd) {
301 unsigned Size;
302 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
303 BufPtr += Size;
304 }
305
306 assert(Length < Tok.getLength() &&
307 "NeedsCleaning flag set on token that didn't need cleaning!");
308 return Length;
309}
310
Chris Lattner39720112010-11-17 07:26:20 +0000311/// getSpelling() - Return the 'spelling' of this token. The spelling of a
312/// token are the characters used to represent the token in the source file
313/// after trigraph expansion and escaped-newline folding. In particular, this
314/// wants to get the true, uncanonicalized, spelling of things like digraphs
315/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000317 SmallVectorImpl<char> &buffer,
318 const SourceManager &SM,
319 const LangOptions &options,
320 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000321 // Break down the source location.
322 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
323
324 // Try to the load the file buffer.
325 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000327 if (invalidTemp) {
328 if (invalid) *invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000329 return {};
John McCall462c0552011-03-08 07:59:04 +0000330 }
331
332 const char *tokenBegin = file.data() + locInfo.second;
333
334 // Lex from the start of the given location.
335 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
336 file.begin(), tokenBegin, file.end());
337 Token token;
338 lexer.LexFromRawLexer(token);
339
340 unsigned length = token.getLength();
341
342 // Common case: no need for cleaning.
343 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000345
Richard Smith9a67f472012-11-28 07:29:00 +0000346 // Hard case, we need to relex the characters into the string.
347 buffer.resize(length);
348 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000350}
351
352/// getSpelling() - Return the 'spelling' of this token. The spelling of a
353/// token are the characters used to represent the token in the source file
354/// after trigraph expansion and escaped-newline folding. In particular, this
355/// wants to get the true, uncanonicalized, spelling of things like digraphs
356/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000357std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000358 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000359 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000360
Chris Lattner39720112010-11-17 07:26:20 +0000361 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000362 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000363 &CharDataInvalid);
364 if (Invalid)
365 *Invalid = CharDataInvalid;
366 if (CharDataInvalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000367 return {};
Richard Smith9a67f472012-11-28 07:29:00 +0000368
369 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000370 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000371 return std::string(TokStart, TokStart + Tok.getLength());
372
Chris Lattner39720112010-11-17 07:26:20 +0000373 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000374 Result.resize(Tok.getLength());
375 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000376 return Result;
377}
378
379/// getSpelling - This method is used to get the spelling of a token into a
380/// preallocated buffer, instead of as an std::string. The caller is required
381/// to allocate enough space for the token, which is guaranteed to be at least
382/// Tok.getLength() bytes long. The actual length of the token is returned.
383///
384/// Note that this method may do two possible things: it may either fill in
385/// the buffer specified with characters, or it may *change the input pointer*
386/// to point to a constant buffer with the data already in it (avoiding a
387/// copy). The caller is not allowed to modify the returned buffer pointer
388/// if an internal buffer is returned.
Taewook Ohcebac482017-12-06 17:00:53 +0000389unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
Chris Lattner39720112010-11-17 07:26:20 +0000390 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000391 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000392 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000393
Craig Topperd2d442c2014-05-17 23:10:59 +0000394 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000395 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
396 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000397 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000398 else if (!Tok.hasUCN()) {
399 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
400 // Just return the string from the identifier table, which is very quick.
401 Buffer = II->getNameStart();
402 return II->getLength();
403 }
Chris Lattner39720112010-11-17 07:26:20 +0000404 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000405
406 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000407 if (Tok.isLiteral())
408 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000409
Craig Topperd2d442c2014-05-17 23:10:59 +0000410 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000411 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000412 bool CharDataInvalid = false;
413 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
414 if (Invalid)
415 *Invalid = CharDataInvalid;
416 if (CharDataInvalid) {
417 Buffer = "";
418 return 0;
419 }
420 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000421
Chris Lattner39720112010-11-17 07:26:20 +0000422 // If this token contains nothing interesting, return it directly.
423 if (!Tok.needsCleaning()) {
424 Buffer = TokStart;
425 return Tok.getLength();
426 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000427
Chris Lattner39720112010-11-17 07:26:20 +0000428 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000429 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000430}
431
Chris Lattner8e129c22007-10-17 21:18:47 +0000432/// MeasureTokenLength - Relex the token at the specified location and return
433/// its length in bytes in the input file. If the token needs cleaning (e.g.
434/// includes a trigraph or an escaped newline) then this count includes bytes
435/// that are part of that.
436unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000437 const SourceManager &SM,
438 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000439 Token TheTok;
440 if (getRawToken(Loc, TheTok, SM, LangOpts))
441 return 0;
442 return TheTok.getLength();
443}
444
445/// \brief Relex the token at the specified location.
446/// \returns true if there was a failure, false on success.
447bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
448 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000449 const LangOptions &LangOpts,
450 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000451 // TODO: this could be special cased for common tokens like identifiers, ')',
452 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000453 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000454 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
455 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000456
457 // If this comes from a macro expansion, we really do want the macro name, not
458 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000459 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000460 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000461 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000463 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000464 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000465
466 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000467
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000468 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000469 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000470
Chris Lattner8e129c22007-10-17 21:18:47 +0000471 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000472 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
473 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000474 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000475 TheLexer.LexFromRawLexer(Result);
476 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000477}
478
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000479/// Returns the pointer that points to the beginning of line that contains
480/// the given offset, or null if the offset if invalid.
481static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
482 const char *BufStart = Buffer.data();
483 if (Offset >= Buffer.size())
484 return nullptr;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000485
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000486 const char *LexStart = BufStart + Offset;
487 for (; LexStart != BufStart; --LexStart) {
488 if (isVerticalWhitespace(LexStart[0]) &&
489 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
490 // LexStart should point at first character of logical line.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000491 ++LexStart;
492 break;
493 }
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000494 }
495 return LexStart;
496}
497
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000498static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
499 const SourceManager &SM,
500 const LangOptions &LangOpts) {
501 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000502 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000503 if (LocInfo.first.isInvalid())
504 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000505
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000506 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000508 if (Invalid)
509 return Loc;
510
511 // Back up from the current location until we hit the beginning of a line
512 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000513 const char *StrData = Buffer.data() + LocInfo.second;
514 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
515 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000516 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000517
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000518 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000519 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000520 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
521 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000522 TheLexer.SetCommentRetentionState(true);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000523
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000524 // Lex tokens until we find the token that contains the source location.
525 Token TheTok;
526 do {
527 TheLexer.LexFromRawLexer(TheTok);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000528
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000529 if (TheLexer.getBufferLocation() > StrData) {
530 // Lexing this token has taken the lexer past the source location we're
531 // looking for. If the current token encompasses our source location,
532 // return the beginning of that token.
533 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
534 return TheTok.getLocation();
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000535
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000536 // We ended up skipping over the source location entirely, which means
537 // that it points into whitespace. We're done here.
538 break;
539 }
540 } while (TheTok.getKind() != tok::eof);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000541
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000542 // We've passed our source location; just return the original source location.
543 return Loc;
544}
545
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000546SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
547 const SourceManager &SM,
548 const LangOptions &LangOpts) {
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000549 if (Loc.isFileID())
550 return getBeginningOfFileToken(Loc, SM, LangOpts);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000551
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000552 if (!SM.isMacroArgExpansion(Loc))
553 return Loc;
554
555 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
556 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
557 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
558 std::pair<FileID, unsigned> BeginFileLocInfo =
559 SM.getDecomposedLoc(BeginFileLoc);
560 assert(FileLocInfo.first == BeginFileLocInfo.first &&
561 FileLocInfo.second >= BeginFileLocInfo.second);
562 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000563}
564
Douglas Gregoraf82e352010-07-20 20:18:03 +0000565namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000566
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000567enum PreambleDirectiveKind {
568 PDK_Skipped,
569 PDK_Unknown
570};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000571
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000572} // namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000573
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000574PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
575 const LangOptions &LangOpts,
576 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000577 // Create a lexer starting at the beginning of the file. Note that we use a
578 // "fake" file source location at offset 1 so that the lexer will track our
579 // position within the file.
580 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000581 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000582 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
583 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000584 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000585
Douglas Gregoraf82e352010-07-20 20:18:03 +0000586 bool InPreprocessorDirective = false;
587 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000588 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000589
590 unsigned MaxLineOffset = 0;
591 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000592 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000593 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000594 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000595 char ch = *CurPtr++;
596 if (ch == '\n') {
597 ++CurLine;
598 if (CurLine == MaxLines)
599 break;
600 }
601 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000602 if (CurPtr != Buffer.end())
603 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000604 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000605
Douglas Gregoraf82e352010-07-20 20:18:03 +0000606 do {
607 TheLexer.LexFromRawLexer(TheTok);
608
609 if (InPreprocessorDirective) {
610 // If we've hit the end of the file, we're done.
611 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000612 break;
613 }
Taewook Ohcebac482017-12-06 17:00:53 +0000614
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615 // If we haven't hit the end of the preprocessor directive, skip this
616 // token.
617 if (!TheTok.isAtStartOfLine())
618 continue;
Taewook Ohcebac482017-12-06 17:00:53 +0000619
Douglas Gregoraf82e352010-07-20 20:18:03 +0000620 // We've passed the end of the preprocessor directive, and will look
621 // at this token again below.
622 InPreprocessorDirective = false;
623 }
Taewook Ohcebac482017-12-06 17:00:53 +0000624
Douglas Gregor028d3e42010-08-09 20:45:32 +0000625 // Keep track of the # of lines in the preamble.
626 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000627 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000628
629 // If we were asked to limit the number of lines in the preamble,
630 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000631 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000632 break;
633 }
634
Douglas Gregoraf82e352010-07-20 20:18:03 +0000635 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000636 if (TheTok.getKind() == tok::comment) {
637 if (ActiveCommentLoc.isInvalid())
638 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000639 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000640 }
Taewook Ohcebac482017-12-06 17:00:53 +0000641
Douglas Gregoraf82e352010-07-20 20:18:03 +0000642 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
Taewook Ohcebac482017-12-06 17:00:53 +0000643 // This is the start of a preprocessor directive.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000644 Token HashTok = TheTok;
645 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000646 ActiveCommentLoc = SourceLocation();
Taewook Ohcebac482017-12-06 17:00:53 +0000647
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000648 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000649 // we don't have an identifier table available. Instead, just look at
650 // the raw identifier to recognize and categorize preprocessor directives.
651 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000652 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000653 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000654 PreambleDirectiveKind PDK
655 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
656 .Case("include", PDK_Skipped)
657 .Case("__include_macros", PDK_Skipped)
658 .Case("define", PDK_Skipped)
659 .Case("undef", PDK_Skipped)
660 .Case("line", PDK_Skipped)
661 .Case("error", PDK_Skipped)
662 .Case("pragma", PDK_Skipped)
663 .Case("import", PDK_Skipped)
664 .Case("include_next", PDK_Skipped)
665 .Case("warning", PDK_Skipped)
666 .Case("ident", PDK_Skipped)
667 .Case("sccs", PDK_Skipped)
668 .Case("assert", PDK_Skipped)
669 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000670 .Case("if", PDK_Skipped)
671 .Case("ifdef", PDK_Skipped)
672 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000673 .Case("elif", PDK_Skipped)
674 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000675 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000676 .Default(PDK_Unknown);
677
678 switch (PDK) {
679 case PDK_Skipped:
680 continue;
681
Douglas Gregoraf82e352010-07-20 20:18:03 +0000682 case PDK_Unknown:
683 // We don't know what this directive is; stop at the '#'.
684 break;
685 }
686 }
Taewook Ohcebac482017-12-06 17:00:53 +0000687
Douglas Gregoraf82e352010-07-20 20:18:03 +0000688 // We only end up here if we didn't recognize the preprocessor
689 // directive or it was one that can't occur in the preamble at this
690 // point. Roll back the current token to the location of the '#'.
691 InPreprocessorDirective = false;
692 TheTok = HashTok;
693 }
694
Douglas Gregor028d3e42010-08-09 20:45:32 +0000695 // We hit a token that we don't recognize as being in the
696 // "preprocessing only" part of the file, so we're no longer in
697 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000698 break;
699 } while (true);
Taewook Ohcebac482017-12-06 17:00:53 +0000700
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000701 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000702 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000703 End = ActiveCommentLoc; // don't truncate a decl comment.
704 else
705 End = TheTok.getLocation();
706
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000707 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000708 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000709}
710
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
756/// \brief Computes the source location just past the end of the
757/// 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
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000791/// \brief 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
813/// \brief 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
1259/// \brief Checks that the given token is the first token that occurs after the
1260/// 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
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001412/// \brief Routine that indiscriminately sets the offset into the source file.
1413void 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[] = {
1513 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1514 {U'\u037e', ';'}, // GREEK QUESTION MARK
1515 {U'\u2212', '-'}, // MINUS SIGN
1516 {U'\u2215', '/'}, // DIVISION SLASH
1517 {U'\u2216', '\\'}, // SET MINUS
1518 {U'\u2217', '*'}, // ASTERISK OPERATOR
1519 {U'\u2223', '|'}, // DIVIDES
1520 {U'\u2227', '^'}, // LOGICAL AND
1521 {U'\u2236', ':'}, // RATIO
1522 {U'\u223c', '~'}, // TILDE OPERATOR
1523 {U'\ua789', ':'}, // MODIFIER LETTER COLON
1524 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1525 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1526 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1527 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1528 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1529 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1530 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1531 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1532 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1533 {U'\uff0c', ','}, // FULLWIDTH COMMA
1534 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1535 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1536 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1537 {U'\uff1a', ':'}, // FULLWIDTH COLON
1538 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1539 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1540 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1541 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1542 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1543 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1544 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1545 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1546 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1547 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1548 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1549 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1550 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1551 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1552 {0, 0}
1553 };
1554 auto Homoglyph =
1555 std::lower_bound(std::begin(SortedHomoglyphs),
1556 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1557 if (Homoglyph->Character == C) {
1558 llvm::SmallString<5> CharBuf;
1559 {
1560 llvm::raw_svector_ostream CharOS(CharBuf);
1561 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1562 }
1563 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1564 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1565 << Range << CharBuf << LooksLikeStr;
1566 }
1567}
1568
Richard Smith8b7258b2014-02-17 21:52:30 +00001569bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1570 Token &Result) {
1571 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001572 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001573 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1574 return false;
1575
1576 if (!isLexingRawMode())
1577 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1578 makeCharRange(*this, CurPtr, UCNPtr),
1579 /*IsFirst=*/false);
1580
1581 Result.setFlag(Token::HasUCN);
1582 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1583 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1584 CurPtr = UCNPtr;
1585 else
1586 while (CurPtr != UCNPtr)
1587 (void)getAndAdvanceChar(CurPtr, Result);
1588 return true;
1589}
1590
1591bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1592 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001593 llvm::UTF32 CodePoint;
1594 llvm::ConversionResult Result =
1595 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1596 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001597 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001598 llvm::strictConversion);
1599 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001600 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1601 return false;
1602
Richard Smith77091b12017-12-14 13:15:08 +00001603 if (!isLexingRawMode()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001604 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1605 makeCharRange(*this, CurPtr, UnicodePtr),
1606 /*IsFirst=*/false);
Richard Smith77091b12017-12-14 13:15:08 +00001607 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1608 makeCharRange(*this, CurPtr, UnicodePtr));
1609 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001610
1611 CurPtr = UnicodePtr;
1612 return true;
1613}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001614
Eli Friedman0834a4b2013-09-19 00:41:32 +00001615bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001616 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1617 unsigned Size;
1618 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001619 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001620 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001621
Chris Lattner22eb9722006-06-18 05:43:12 +00001622 --CurPtr; // Back up over the skipped character.
1623
1624 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1625 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001626 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001627 // TODO: Could merge these checks into an InfoTable flag to make the
1628 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001629 if (isASCII(C) && C != '\\' && C != '?' &&
1630 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001631FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001632 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001633 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1634 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattner0f1f5052006-07-20 04:16:23 +00001636 // If we are in raw mode, return this identifier raw. There is no need to
1637 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001638 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001639 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001640
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001641 // Fill in Result.IdentifierInfo and update the token kind,
1642 // looking up the identifier in the identifier table.
1643 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Ilya Biryukovb3510c42018-04-24 13:48:53 +00001644 // Note that we have to call PP->LookUpIdentifierInfo() even for code
1645 // completion, it writes IdentifierInfo into Result, and callers rely on it.
1646
1647 // If the completion point is at the end of an identifier, we want to treat
1648 // the identifier as incomplete even if it resolves to a macro or a keyword.
1649 // This allows e.g. 'class^' to complete to 'classifier'.
1650 if (isCodeCompletionPoint(CurPtr)) {
1651 // Return the code-completion token.
1652 Result.setKind(tok::code_completion);
Ilya Biryukovef4ece72018-04-25 15:13:34 +00001653 // Skip the code-completion char and all immediate identifier characters.
1654 // This ensures we get consistent behavior when completing at any point in
1655 // an identifier (i.e. at the start, in the middle, at the end). Note that
1656 // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1657 // simpler.
1658 assert(*CurPtr == 0 && "Completion character must be 0");
1659 ++CurPtr;
1660 // Note that code completion token is not added as a separate character
1661 // when the completion point is at the end of the buffer. Therefore, we need
1662 // to check if the buffer has ended.
1663 if (CurPtr < BufferEnd) {
1664 while (isIdentifierBody(*CurPtr))
1665 ++CurPtr;
1666 }
1667 BufferPtr = CurPtr;
Ilya Biryukovb3510c42018-04-24 13:48:53 +00001668 return true;
1669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattnerc5a00062006-06-18 16:41:01 +00001671 // Finally, now that we know we have an identifier, pass this off to the
1672 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001673 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001674 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001675
Eli Friedman0834a4b2013-09-19 00:41:32 +00001676 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 }
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattner22eb9722006-06-18 05:43:12 +00001679 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattner22eb9722006-06-18 05:43:12 +00001681 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001682 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001683 if (C == '$') {
1684 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001685 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001686
Chris Lattner22eb9722006-06-18 05:43:12 +00001687 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001688 if (!isLexingRawMode())
1689 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001690 CurPtr = ConsumeChar(CurPtr, Size, Result);
1691 C = getCharAndSize(CurPtr, Size);
1692 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001693 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001694 C = getCharAndSize(CurPtr, Size);
1695 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001696 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001697 C = getCharAndSize(CurPtr, Size);
1698 continue;
1699 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001700 goto FinishIdentifier;
1701 }
1702
1703 // Otherwise, this character is good, consume it.
1704 CurPtr = ConsumeChar(CurPtr, Size, Result);
1705
1706 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001707 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001708 CurPtr = ConsumeChar(CurPtr, Size, Result);
1709 C = getCharAndSize(CurPtr, Size);
1710 }
1711 }
1712}
1713
Douglas Gregor759ef232010-08-30 14:50:47 +00001714/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001715/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001716bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001717 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001718 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001719 if (C1 != '0')
1720 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001721 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001722 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001723}
Chris Lattner22eb9722006-06-18 05:43:12 +00001724
Nate Begeman5eee9332008-04-14 02:26:39 +00001725/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001726/// constant. From[-1] is the first character lexed. Return the end of the
1727/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001728bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001729 unsigned Size;
1730 char C = getCharAndSize(CurPtr, Size);
1731 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001732 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001733 CurPtr = ConsumeChar(CurPtr, Size, Result);
1734 PrevCh = C;
1735 C = getCharAndSize(CurPtr, Size);
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Chris Lattner22eb9722006-06-18 05:43:12 +00001738 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001739 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1740 // If we are in Microsoft mode, don't continue if the constant is hex.
1741 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001742 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001743 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1744 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001745
1746 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001747 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001748 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001749 // not-quite-conforming extension. Only do so if this looks like it's
1750 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1751 bool IsHexFloat = true;
1752 if (!LangOpts.C99) {
1753 if (!isHexaLiteral(BufferPtr, LangOpts))
1754 IsHexFloat = false;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001755 else if (!getLangOpts().CPlusPlus17 &&
Richard Smith560a3572016-03-04 22:32:06 +00001756 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001757 IsHexFloat = false;
1758 }
1759 if (IsHexFloat)
1760 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1761 }
Mike Stump11289f42009-09-09 15:08:12 +00001762
Richard Smithfde94852013-09-26 03:33:06 +00001763 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001764 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001765 unsigned NextSize;
1766 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001767 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001768 if (!isLexingRawMode())
1769 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1770 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001771 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001772 return LexNumericConstant(Result, CurPtr);
1773 }
1774 }
1775
Richard Smith8b7258b2014-02-17 21:52:30 +00001776 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1777 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1778 return LexNumericConstant(Result, CurPtr);
1779 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1780 return LexNumericConstant(Result, CurPtr);
1781
Chris Lattnerd01e2912006-06-18 16:22:51 +00001782 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001783 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001784 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001785 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001786 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001787}
1788
Richard Smithe18f0fa2012-03-05 04:02:15 +00001789/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001790/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001791const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1792 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001793 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001794
Richard Smith8b7258b2014-02-17 21:52:30 +00001795 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001796 unsigned Size;
1797 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001798 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001799
Richard Smith8b7258b2014-02-17 21:52:30 +00001800 if (!isIdentifierHead(C)) {
1801 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1802 Consumed = true;
1803 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1804 Consumed = true;
1805 else
1806 return CurPtr;
1807 }
1808
1809 if (!getLangOpts().CPlusPlus11) {
1810 if (!isLexingRawMode())
1811 Diag(CurPtr,
1812 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1813 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1814 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1815 return CurPtr;
1816 }
1817
1818 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1819 // that does not start with an underscore is ill-formed. As a conforming
1820 // extension, we treat all such suffixes as if they had whitespace before
1821 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1822 // likely to be a ud-suffix than a macro, however, and accept that.
1823 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001824 bool IsUDSuffix = false;
1825 if (C == '_')
1826 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001827 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001828 // In C++1y, we need to look ahead a few characters to see if this is a
1829 // valid suffix for a string literal or a numeric literal (this could be
1830 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001831 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001832 char Buffer[MaxStandardSuffixLength] = { C };
1833 unsigned Consumed = Size;
1834 unsigned Chars = 1;
1835 while (true) {
1836 unsigned NextSize;
1837 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1838 getLangOpts());
1839 if (!isIdentifierBody(Next)) {
1840 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001841 const StringRef CompleteSuffix(Buffer, Chars);
1842 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1843 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001844 break;
1845 }
1846
1847 if (Chars == MaxStandardSuffixLength)
1848 // Too long: can't be a standard suffix.
1849 break;
1850
1851 Buffer[Chars++] = Next;
1852 Consumed += NextSize;
1853 }
Richard Smithf4198b72013-07-23 08:14:48 +00001854 }
1855
1856 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001857 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001858 Diag(CurPtr, getLangOpts().MSVCCompat
1859 ? diag::ext_ms_reserved_user_defined_literal
1860 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001861 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001862 return CurPtr;
1863 }
1864
Richard Smith8b7258b2014-02-17 21:52:30 +00001865 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001866 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001867
1868 Result.setFlag(Token::HasUDSuffix);
1869 while (true) {
1870 C = getCharAndSize(CurPtr, Size);
1871 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1872 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1873 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1874 else break;
1875 }
1876
Richard Smithe18f0fa2012-03-05 04:02:15 +00001877 return CurPtr;
1878}
1879
Chris Lattner22eb9722006-06-18 05:43:12 +00001880/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001881/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001882bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001883 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001884 // Does this string contain the \0 character?
1885 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001886
Richard Smithacd4d3d2011-10-15 01:18:56 +00001887 if (!isLexingRawMode() &&
1888 (Kind == tok::utf8_string_literal ||
1889 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001890 Kind == tok::utf32_string_literal))
1891 Diag(BufferPtr, getLangOpts().CPlusPlus
1892 ? diag::warn_cxx98_compat_unicode_literal
1893 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001894
Chris Lattner22eb9722006-06-18 05:43:12 +00001895 char C = getAndAdvanceChar(CurPtr, Result);
1896 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001897 // Skip escaped characters. Escaped newlines will already be processed by
1898 // getAndAdvanceChar.
1899 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001900 C = getAndAdvanceChar(CurPtr, Result);
Taewook Ohcebac482017-12-06 17:00:53 +00001901
Chris Lattner52d96ac2010-05-30 23:27:38 +00001902 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001903 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001904 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001905 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001906 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001907 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 }
Taewook Ohcebac482017-12-06 17:00:53 +00001909
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001910 if (C == 0) {
1911 if (isCodeCompletionPoint(CurPtr-1)) {
1912 PP->CodeCompleteNaturalLanguage();
1913 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001914 cutOffLexing();
1915 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001916 }
1917
Chris Lattner52d96ac2010-05-30 23:27:38 +00001918 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001919 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001920 C = getAndAdvanceChar(CurPtr, Result);
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Richard Smithe18f0fa2012-03-05 04:02:15 +00001923 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001924 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001925 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001926
Chris Lattner5a78a022006-07-20 06:02:19 +00001927 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001928 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001929 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001930
Chris Lattnerd01e2912006-06-18 16:22:51 +00001931 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001932 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001933 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001934 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001935 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001936}
1937
Craig Topper54edcca2011-08-11 04:06:15 +00001938/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1939/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001940bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001941 tok::TokenKind Kind) {
1942 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1943 // Between the initial and final double quote characters of the raw string,
1944 // any transformations performed in phases 1 and 2 (trigraphs,
1945 // universal-character-names, and line splicing) are reverted.
1946
Richard Smithacd4d3d2011-10-15 01:18:56 +00001947 if (!isLexingRawMode())
1948 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1949
Craig Topper54edcca2011-08-11 04:06:15 +00001950 unsigned PrefixLen = 0;
1951
1952 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1953 ++PrefixLen;
1954
1955 // If the last character was not a '(', then we didn't lex a valid delimiter.
1956 if (CurPtr[PrefixLen] != '(') {
1957 if (!isLexingRawMode()) {
1958 const char *PrefixEnd = &CurPtr[PrefixLen];
1959 if (PrefixLen == 16) {
1960 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1961 } else {
1962 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1963 << StringRef(PrefixEnd, 1);
1964 }
1965 }
1966
1967 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1968 // it's possible the '"' was intended to be part of the raw string, but
1969 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001970 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001971 char C = *CurPtr++;
1972
1973 if (C == '"')
1974 break;
1975 if (C == 0 && CurPtr-1 == BufferEnd) {
1976 --CurPtr;
1977 break;
1978 }
1979 }
1980
1981 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001982 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001983 }
1984
1985 // Save prefix and move CurPtr past it
1986 const char *Prefix = CurPtr;
1987 CurPtr += PrefixLen + 1; // skip over prefix and '('
1988
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 // Check for prefix match and closing quote.
1994 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1995 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1996 break;
1997 }
1998 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1999 if (!isLexingRawMode())
2000 Diag(BufferPtr, diag::err_unterminated_raw_string)
2001 << StringRef(Prefix, PrefixLen);
2002 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002003 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002004 }
2005 }
2006
Richard Smithe18f0fa2012-03-05 04:02:15 +00002007 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002008 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002009 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002010
Craig Topper54edcca2011-08-11 04:06:15 +00002011 // Update the location of token as well as BufferPtr.
2012 const char *TokStart = BufferPtr;
2013 FormTokenWithChars(Result, CurPtr, Kind);
2014 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002015 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002016}
2017
Chris Lattner22eb9722006-06-18 05:43:12 +00002018/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2019/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002020bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002021 // Does this string contain the \0 character?
2022 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00002023 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 char C = getAndAdvanceChar(CurPtr, Result);
2025 while (C != '>') {
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002026 // Skip escaped characters. Escaped newlines will already be processed by
2027 // getAndAdvanceChar.
2028 if (C == '\\')
2029 C = getAndAdvanceChar(CurPtr, Result);
2030
2031 if (C == '\n' || C == '\r' || // Newline.
2032 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
2033 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00002034 // If the filename is unterminated, then it must just be a lone <
2035 // character. Return this as such.
2036 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002037 return true;
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002038 }
2039
2040 if (C == 0) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002041 NulCharacter = CurPtr-1;
2042 }
2043 C = getAndAdvanceChar(CurPtr, Result);
2044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
Chris Lattner5a78a022006-07-20 06:02:19 +00002046 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002047 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002048 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattnerd01e2912006-06-18 16:22:51 +00002050 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002051 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002052 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002053 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002054 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002055}
2056
Chris Lattner22eb9722006-06-18 05:43:12 +00002057/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00002058/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002059bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00002060 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002061 // Does this character contain the \0 character?
2062 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002063
Richard Smith3e3a7052014-11-08 06:08:42 +00002064 if (!isLexingRawMode()) {
2065 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2066 Diag(BufferPtr, getLangOpts().CPlusPlus
2067 ? diag::warn_cxx98_compat_unicode_literal
2068 : diag::warn_c99_compat_unicode_literal);
2069 else if (Kind == tok::utf8_char_constant)
2070 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2071 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00002072
Chris Lattner22eb9722006-06-18 05:43:12 +00002073 char C = getAndAdvanceChar(CurPtr, Result);
2074 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002075 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00002076 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002077 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002078 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00002079 }
2080
2081 while (C != '\'') {
2082 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00002083 if (C == '\\')
2084 C = getAndAdvanceChar(CurPtr, Result);
2085
2086 if (C == '\n' || C == '\r' || // Newline.
2087 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002088 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00002089 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00002090 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002091 return true;
Nico Weber4e270382012-11-17 20:25:54 +00002092 }
2093
2094 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002095 if (isCodeCompletionPoint(CurPtr-1)) {
2096 PP->CodeCompleteNaturalLanguage();
2097 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002098 cutOffLexing();
2099 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002100 }
2101
Chris Lattner86851b82010-07-07 23:24:27 +00002102 NulCharacter = CurPtr-1;
2103 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002104 C = getAndAdvanceChar(CurPtr, Result);
2105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Richard Smithe18f0fa2012-03-05 04:02:15 +00002107 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002108 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002109 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002110
Chris Lattner86851b82010-07-07 23:24:27 +00002111 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002112 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002113 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002114
Chris Lattnerd01e2912006-06-18 16:22:51 +00002115 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002116 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002117 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002118 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002119 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002120}
2121
2122/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2123/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002124///
2125/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002126bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2127 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002128 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002129 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2130
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002131 unsigned char Char = *CurPtr;
2132
2133 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002134 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 // Skip horizontal whitespace very aggressively.
2136 while (isHorizontalWhitespace(Char))
2137 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002138
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002139 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002140 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002141 break;
Mike Stump11289f42009-09-09 15:08:12 +00002142
Chris Lattner22eb9722006-06-18 05:43:12 +00002143 if (ParsingPreprocessorDirective) {
2144 // End of preprocessor directive line, let LexTokenInternal handle this.
2145 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002146 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002149 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002150 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002151 Char = *++CurPtr;
2152 }
2153
Chris Lattner4d963442008-10-12 04:05:48 +00002154 // If the client wants us to return whitespace, return it now.
2155 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002156 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002157 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002158 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002159 IsAtPhysicalStartOfLine = true;
2160 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002161 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002162 return true;
2163 }
Mike Stump11289f42009-09-09 15:08:12 +00002164
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002165 // If this isn't immediately after a newline, there is leading space.
2166 char PrevChar = CurPtr[-1];
2167 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2168
2169 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002170 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002171 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002172 TokAtPhysicalStartOfLine = true;
2173 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002174
Chris Lattner22eb9722006-06-18 05:43:12 +00002175 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002176 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002177}
2178
Nico Weber158a31a2012-11-11 07:02:14 +00002179/// We have just read the // characters from input. Skip until we find the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002180/// newline character that terminates the comment. Then update BufferPtr and
Nico Weber158a31a2012-11-11 07:02:14 +00002181/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002182///
2183/// If we're in KeepCommentMode or any CommentHandler has inserted
2184/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002185bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2186 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002187 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002188 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002189 if (!LangOpts.LineComment && !isLexingRawMode()) {
2190 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002191
Chris Lattner22eb9722006-06-18 05:43:12 +00002192 // Mark them enabled so we only emit one warning for this translation
2193 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002194 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 // Scan over the body of the comment. The common case, when scanning, is that
2198 // the comment contains normal ascii characters with nothing interesting in
2199 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002200 //
2201 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2202 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002203 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002204 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002205 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002206 // Skip over characters in the fast loop.
2207 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002208 C != '\n' && C != '\r') // Newline or DOS-style newline.
2209 C = *++CurPtr;
2210
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002211 const char *NextLine = CurPtr;
2212 if (C != 0) {
2213 // We found a newline, see if it's escaped.
2214 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002215 bool HasSpace = false;
2216 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002217 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002218 HasSpace = true;
2219 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002220
Richard Smith4c132e52017-04-18 21:45:04 +00002221 if (*EscapePtr == '\\')
2222 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002223 CurPtr = EscapePtr;
2224 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002225 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2226 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002227 CurPtr = EscapePtr-2;
2228 else
2229 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002230
2231 // If there was space between the backslash and newline, warn about it.
2232 if (HasSpace && !isLexingRawMode())
2233 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattner22eb9722006-06-18 05:43:12 +00002236 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002237 // properly decode the character. Read it in raw mode to avoid emitting
2238 // diagnostics about things like trigraphs. If we see an escaped newline,
2239 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002241 bool OldRawMode = isLexingRawMode();
2242 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002243 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002244 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002245
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002246 // If we only read only one character, then no special handling is needed.
2247 // We're done and can skip forward to the newline.
2248 if (C != 0 && CurPtr == OldPtr+1) {
2249 CurPtr = NextLine;
2250 break;
2251 }
2252
Chris Lattner22eb9722006-06-18 05:43:12 +00002253 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002254 // \n, then we had an escaped newline within the comment. Emit diagnostic
2255 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002256 if (CurPtr != OldPtr + 1 && C != '/' &&
2257 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 for (; OldPtr != CurPtr; ++OldPtr)
2259 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002260 // Okay, we found a // comment that ends in a newline, if the next
2261 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002262 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002263 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002264 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002265 ++ForwardPtr;
2266 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2267 break;
2268 }
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattner6d27a162008-11-22 02:02:22 +00002270 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002271 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002272 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002273 }
2274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
Richard Smith1d2ae942017-04-17 23:44:51 +00002276 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2277 --CurPtr;
2278 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002279 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002280
2281 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2282 PP->CodeCompleteNaturalLanguage();
2283 cutOffLexing();
2284 return false;
2285 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002286 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002287
Chris Lattner93ddf802010-02-03 21:06:21 +00002288 // Found but did not consume the newline. Notify comment handlers about the
2289 // comment unless we're in a #if 0 block.
2290 if (PP && !isLexingRawMode() &&
2291 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2292 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002293 BufferPtr = CurPtr;
2294 return true; // A token has to be returned.
2295 }
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattner457fc152006-07-29 06:30:25 +00002297 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002298 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002299 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002300
2301 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002302 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002303 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002304 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002305 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 }
Mike Stump11289f42009-09-09 15:08:12 +00002307
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002309 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002310 // contribute to another token), it isn't needed for correctness. Note that
2311 // this is ok even in KeepWhitespaceMode, because we would have returned the
2312 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002313 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattner22eb9722006-06-18 05:43:12 +00002315 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002316 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002317 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002319 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002320 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002321 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002322}
Chris Lattner22eb9722006-06-18 05:43:12 +00002323
Nico Weber158a31a2012-11-11 07:02:14 +00002324/// If in save-comment mode, package up this Line comment in an appropriate
2325/// way and return it.
2326bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002327 // If we're not in a preprocessor directive, just return the // comment
2328 // directly.
2329 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002330
David Blaikied5321242012-06-06 18:52:13 +00002331 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002332 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002333
Nico Weber158a31a2012-11-11 07:02:14 +00002334 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002335 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002336 bool Invalid = false;
2337 std::string Spelling = PP->getSpelling(Result, &Invalid);
2338 if (Invalid)
2339 return true;
Taewook Ohcebac482017-12-06 17:00:53 +00002340
Nico Weber158a31a2012-11-11 07:02:14 +00002341 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002342 Spelling[1] = '*'; // Change prefix to "/*".
2343 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattnerb11c3232008-10-12 04:51:35 +00002345 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002346 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002347 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002348 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002349}
2350
Chris Lattnercb283342006-06-18 06:48:37 +00002351/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002352/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2353/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002354static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002355 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002356 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002357
Chris Lattner22eb9722006-06-18 05:43:12 +00002358 // Back up off the newline.
2359 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Chris Lattner22eb9722006-06-18 05:43:12 +00002361 // If this is a two-character newline sequence, skip the other character.
2362 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2363 // \n\n or \r\r -> not escaped newline.
2364 if (CurPtr[0] == CurPtr[1])
2365 return false;
2366 // \n\r or \r\n -> skip the newline.
2367 --CurPtr;
2368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattner22eb9722006-06-18 05:43:12 +00002370 // If we have horizontal whitespace, skip over it. We allow whitespace
2371 // between the slash and newline.
2372 bool HasSpace = false;
2373 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2374 --CurPtr;
2375 HasSpace = true;
2376 }
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 // If we have a slash, we know this is an escaped newline.
2379 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002380 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002381 } else {
2382 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002383 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2384 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002385 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Chris Lattnercb283342006-06-18 06:48:37 +00002387 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002388 CurPtr -= 2;
2389
2390 // If no trigraphs are enabled, warn that we ignored this trigraph and
2391 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002392 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002393 if (!L->isLexingRawMode())
2394 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002395 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002396 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002397 if (!L->isLexingRawMode())
2398 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002399 }
Mike Stump11289f42009-09-09 15:08:12 +00002400
Chris Lattner22eb9722006-06-18 05:43:12 +00002401 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002402 if (!L->isLexingRawMode())
2403 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Chris Lattner22eb9722006-06-18 05:43:12 +00002405 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002406 if (HasSpace && !L->isLexingRawMode())
2407 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002408
Chris Lattnercb283342006-06-18 06:48:37 +00002409 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002410}
2411
Chris Lattneraded4a92006-10-27 04:42:31 +00002412#ifdef __SSE2__
2413#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002414#elif __ALTIVEC__
2415#include <altivec.h>
2416#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002417#endif
2418
James Dennettf442d242012-06-17 03:40:43 +00002419/// We have just read from input the / and * characters that started a comment.
2420/// Read until we find the * and / characters that terminate the comment.
2421/// Note that we don't bother decoding trigraphs or escaped newlines in block
2422/// comments, because they cannot cause the comment to end. The only thing
2423/// that can happen is the comment could end with an escaped newline between
2424/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002425///
Chris Lattner87d02082010-01-18 22:35:47 +00002426/// If we're in KeepCommentMode or any CommentHandler has inserted
2427/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002428bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2429 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002430 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002431 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002432 // optimization helps people who like to put a lot of * characters in their
2433 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002434
2435 // The first character we get with newlines and trigraphs skipped to handle
2436 // the degenerate /*/ case below correctly if the * has an escaped newline
2437 // after it.
2438 unsigned CharSize;
2439 unsigned char C = getCharAndSize(CurPtr, CharSize);
2440 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002441 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002442 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002443 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002444 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002445
Chris Lattner99e7d232008-10-12 04:19:49 +00002446 // KeepWhitespaceMode should return this broken comment as a token. Since
2447 // it isn't a well formed comment, just return it as an 'unknown' token.
2448 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002449 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002450 return true;
2451 }
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattner99e7d232008-10-12 04:19:49 +00002453 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002454 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattnerc850ad62007-07-21 23:43:37 +00002457 // Check to see if the first character after the '/*' is another /. If so,
2458 // then this slash does not end the block comment, it is part of it.
2459 if (C == '/')
2460 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002461
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002462 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002463 // Skip over all non-interesting characters until we find end of buffer or a
2464 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002465 if (CurPtr + 24 < BufferEnd &&
2466 // If there is a code-completion point avoid the fast scan because it
2467 // doesn't check for '\0'.
2468 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002469 // While not aligned to a 16-byte boundary.
2470 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2471 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002472
Chris Lattner6cc3e362006-10-27 04:12:35 +00002473 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002474
2475#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002476 __m128i Slashes = _mm_set1_epi8('/');
2477 while (CurPtr+16 <= BufferEnd) {
2478 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2479 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002480 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002481 // Adjust the pointer to point directly after the first slash. It's
2482 // not necessary to set C here, it will be overwritten at the end of
2483 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002484 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002485 goto FoundSlash;
2486 }
Roman Divacky61509902014-04-03 18:04:52 +00002487 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002488 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002489#elif __ALTIVEC__
2490 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002491 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002492 '/', '/', '/', '/', '/', '/', '/', '/'
2493 };
2494 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002495 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002496 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002497#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002498 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002499 while (CurPtr[0] != '/' &&
2500 CurPtr[1] != '/' &&
2501 CurPtr[2] != '/' &&
2502 CurPtr[3] != '/' &&
2503 CurPtr+4 < BufferEnd) {
2504 CurPtr += 4;
2505 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002506#endif
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattneraded4a92006-10-27 04:42:31 +00002508 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002509 C = *CurPtr++;
2510 }
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattneraded4a92006-10-27 04:42:31 +00002512 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002513 while (C != '/' && C != '\0')
2514 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Chris Lattner22eb9722006-06-18 05:43:12 +00002516 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002517 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002518 if (CurPtr[-2] == '*') // We found the final */. We're done!
2519 break;
Mike Stump11289f42009-09-09 15:08:12 +00002520
Chris Lattner22eb9722006-06-18 05:43:12 +00002521 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002522 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002523 // We found the final */, though it had an escaped newline between the
2524 // * and /. We're done!
2525 break;
2526 }
2527 }
2528 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2529 // If this is a /* inside of the comment, emit a warning. Don't do this
2530 // if this is a /*/, which will end the comment. This misses cases with
2531 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002532 if (!isLexingRawMode())
2533 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002534 }
2535 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002536 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002537 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002538 // Note: the user probably forgot a */. We could continue immediately
2539 // after the /*, but this would involve lexing a lot of what really is the
2540 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002541 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002542
Chris Lattner99e7d232008-10-12 04:19:49 +00002543 // KeepWhitespaceMode should return this broken comment as a token. Since
2544 // it isn't a well formed comment, just return it as an 'unknown' token.
2545 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002546 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002547 return true;
2548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
Chris Lattner99e7d232008-10-12 04:19:49 +00002550 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002551 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002552 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2553 PP->CodeCompleteNaturalLanguage();
2554 cutOffLexing();
2555 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002556 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002557
Chris Lattner22eb9722006-06-18 05:43:12 +00002558 C = *CurPtr++;
2559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Chris Lattner93ddf802010-02-03 21:06:21 +00002561 // Notify comment handlers about the comment unless we're in a #if 0 block.
2562 if (PP && !isLexingRawMode() &&
2563 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2564 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002565 BufferPtr = CurPtr;
2566 return true; // A token has to be returned.
2567 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002568
Chris Lattner457fc152006-07-29 06:30:25 +00002569 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002570 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002571 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002572 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002573 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002574
2575 // It is common for the tokens immediately after a /**/ comment to be
2576 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002577 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2578 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002579 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002580 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002581 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002582 }
2583
2584 // Otherwise, just return so that the next character will be lexed as a token.
2585 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002586 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002587 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002588}
2589
2590//===----------------------------------------------------------------------===//
2591// Primary Lexing Entry Points
2592//===----------------------------------------------------------------------===//
2593
Chris Lattner22eb9722006-06-18 05:43:12 +00002594/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2595/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002596void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002597 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2598 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002599 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002600
2601 // CurPtr - Cache BufferPtr in an automatic variable.
2602 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002603 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002604 char Char = getAndAdvanceChar(CurPtr, Tmp);
2605 switch (Char) {
2606 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002607 if (Result)
2608 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002609 break;
2610 case 0: // Null.
2611 // Found end of file?
2612 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002613 if (isCodeCompletionPoint(CurPtr-1)) {
2614 PP->CodeCompleteNaturalLanguage();
2615 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002616 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002617 }
2618
Chris Lattner22eb9722006-06-18 05:43:12 +00002619 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002620 if (Result)
2621 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002622 break;
2623 }
2624 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002625 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002626 case '\r':
2627 case '\n':
2628 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2629 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2630 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002631
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002632 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002633 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002634 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002635 if (PP)
2636 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002637 Lex(Tmp);
2638 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002639 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002640
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002641 // Finally, we're done;
2642 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002643 }
2644 }
2645}
2646
2647/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2648/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002649/// This returns true if Result contains a token, false if PP.Lex should be
2650/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002651bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002652 // If we hit the end of the file while parsing a preprocessor directive,
2653 // end the preprocessor directive first. The next token returned will
2654 // then be the end of file.
2655 if (ParsingPreprocessorDirective) {
2656 // Done parsing the "line".
2657 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002658 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002659 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner457fc152006-07-29 06:30:25 +00002661 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002662 if (PP)
2663 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002664 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002665 }
Taewook Ohcebac482017-12-06 17:00:53 +00002666
Chris Lattner30a2fa12006-07-19 06:31:49 +00002667 // If we are in raw mode, return this event as an EOF token. Let the caller
2668 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002669 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002670 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002671 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002672 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002673 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002674 }
Taewook Ohcebac482017-12-06 17:00:53 +00002675
Erik Verbruggen795eee92017-07-05 09:44:07 +00002676 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002677 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2678 ConditionalStack.clear();
2679 }
2680
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002681 // Issue diagnostics for unterminated #if and missing newline.
2682
Chris Lattner30a2fa12006-07-19 06:31:49 +00002683 // If we are in a #if directive, emit an error.
2684 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002685 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002686 PP->Diag(ConditionalStack.back().IfLoc,
2687 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002688 ConditionalStack.pop_back();
2689 }
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattner8f96d042008-04-12 05:54:25 +00002691 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2692 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002693 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2694 DiagnosticsEngine &Diags = PP->getDiagnostics();
2695 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2696 unsigned DiagID;
2697
2698 if (LangOpts.CPlusPlus11) {
2699 // C++11 [lex.phases] 2.2 p2
2700 // Prefer the C++98 pedantic compatibility warning over the generic,
2701 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002702 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002703 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2704 } else {
2705 DiagID = diag::warn_no_newline_eof;
2706 }
2707 } else {
2708 DiagID = diag::ext_no_newline_eof;
2709 }
2710
2711 Diag(BufferEnd, DiagID)
2712 << FixItHint::CreateInsertion(EndLoc, "\n");
2713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
Chris Lattner22eb9722006-06-18 05:43:12 +00002715 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002716
2717 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002718 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002719}
2720
Chris Lattner678c8802006-07-11 05:46:12 +00002721/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2722/// the specified lexer will return a tok::l_paren token, 0 if it is something
2723/// else and 2 if there are no more tokens in the buffer controlled by the
2724/// lexer.
2725unsigned Lexer::isNextPPTokenLParen() {
2726 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002727
Chris Lattner678c8802006-07-11 05:46:12 +00002728 // Switch to 'skipping' mode. This will ensure that we can lex a token
2729 // without emitting diagnostics, disables macro expansion, and will cause EOF
2730 // to return an EOF token instead of popping the include stack.
2731 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002732
Chris Lattner678c8802006-07-11 05:46:12 +00002733 // Save state that can be changed while lexing so that we can restore it.
2734 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002735 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002736 bool atStartOfLine = IsAtStartOfLine;
2737 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2738 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002739
Chris Lattner146762e2007-07-20 16:59:19 +00002740 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002741 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002742
Chris Lattner678c8802006-07-11 05:46:12 +00002743 // Restore state that may have changed.
2744 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002745 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002746 HasLeadingSpace = leadingSpace;
2747 IsAtStartOfLine = atStartOfLine;
2748 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Chris Lattner678c8802006-07-11 05:46:12 +00002750 // Restore the lexer back to non-skipping mode.
2751 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002753 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002754 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002755 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002756}
2757
James Dennettf442d242012-06-17 03:40:43 +00002758/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002759static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2760 ConflictMarkerKind CMK) {
2761 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2762 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002763 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002764 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002765 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002766 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002767 if (Pos == 0 ||
2768 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002769 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2770 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002771 continue;
2772 }
2773 return RestOfBuffer.data()+Pos;
2774 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002775 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002776}
2777
2778/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2779/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2780/// and recover nicely. This returns true if it is a conflict marker and false
2781/// if not.
2782bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2783 // Only a conflict marker if it starts at the beginning of a line.
2784 if (CurPtr != BufferStart &&
2785 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2786 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002787
Richard Smitha9e33d42011-10-12 00:37:51 +00002788 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002789 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2790 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002791 return false;
2792
2793 // If we have a situation where we don't care about conflict markers, ignore
2794 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002795 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002796 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002797
Richard Smitha9e33d42011-10-12 00:37:51 +00002798 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2799
2800 // Check to see if there is an ending marker somewhere in the buffer at the
2801 // start of a line to terminate this conflict marker.
2802 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002803 // We found a match. We are really in a conflict marker.
2804 // Diagnose this, and ignore to the end of line.
2805 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002806 CurrentConflictMarkerState = Kind;
Taewook Ohcebac482017-12-06 17:00:53 +00002807
Chris Lattner7c027ee2009-12-14 06:16:57 +00002808 // Skip ahead to the end of line. We know this exists because the
2809 // end-of-conflict marker starts with \r or \n.
2810 while (*CurPtr != '\r' && *CurPtr != '\n') {
2811 assert(CurPtr != BufferEnd && "Didn't find end of line");
2812 ++CurPtr;
2813 }
2814 BufferPtr = CurPtr;
2815 return true;
2816 }
Taewook Ohcebac482017-12-06 17:00:53 +00002817
Chris Lattner7c027ee2009-12-14 06:16:57 +00002818 // No end of conflict marker found.
2819 return false;
2820}
2821
Richard Smitha9e33d42011-10-12 00:37:51 +00002822/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2823/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2824/// is the end of a conflict marker. Handle it by ignoring up until the end of
2825/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002826bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2827 // Only a conflict marker if it starts at the beginning of a line.
2828 if (CurPtr != BufferStart &&
2829 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2830 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002831
Chris Lattner7c027ee2009-12-14 06:16:57 +00002832 // If we have a situation where we don't care about conflict markers, ignore
2833 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002834 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002835 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002836
Richard Smitha9e33d42011-10-12 00:37:51 +00002837 // Check to see if we have the marker (4 characters in a row).
2838 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002839 if (CurPtr[i] != CurPtr[0])
2840 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002841
Chris Lattner7c027ee2009-12-14 06:16:57 +00002842 // If we do have it, search for the end of the conflict marker. This could
2843 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2844 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002845 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2846 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002847 CurPtr = End;
Taewook Ohcebac482017-12-06 17:00:53 +00002848
Chris Lattner7c027ee2009-12-14 06:16:57 +00002849 // Skip ahead to the end of line.
2850 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2851 ++CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002852
Chris Lattner7c027ee2009-12-14 06:16:57 +00002853 BufferPtr = CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002854
Chris Lattner7c027ee2009-12-14 06:16:57 +00002855 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002856 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002857 return true;
2858 }
Taewook Ohcebac482017-12-06 17:00:53 +00002859
Chris Lattner7c027ee2009-12-14 06:16:57 +00002860 return false;
2861}
2862
Alex Lorenz1be800c52017-04-19 08:58:56 +00002863static const char *findPlaceholderEnd(const char *CurPtr,
2864 const char *BufferEnd) {
2865 if (CurPtr == BufferEnd)
2866 return nullptr;
2867 BufferEnd -= 1; // Scan until the second last character.
2868 for (; CurPtr != BufferEnd; ++CurPtr) {
2869 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2870 return CurPtr + 2;
2871 }
2872 return nullptr;
2873}
2874
2875bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2876 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002877 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002878 return false;
2879 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2880 if (!End)
2881 return false;
2882 const char *Start = CurPtr - 1;
2883 if (!LangOpts.AllowEditorPlaceholders)
2884 Diag(Start, diag::err_placeholder_in_source);
2885 Result.startToken();
2886 FormTokenWithChars(Result, End, tok::raw_identifier);
2887 Result.setRawIdentifierData(Start);
2888 PP->LookUpIdentifierInfo(Result);
2889 Result.setFlag(Token::IsEditorPlaceholder);
2890 BufferPtr = End;
2891 return true;
2892}
2893
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002894bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2895 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002896 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002897 return Loc == PP->getCodeCompletionLoc();
2898 }
2899
2900 return false;
2901}
2902
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002903uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2904 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002905 unsigned CharSize;
2906 char Kind = getCharAndSize(StartPtr, CharSize);
2907
2908 unsigned NumHexDigits;
2909 if (Kind == 'u')
2910 NumHexDigits = 4;
2911 else if (Kind == 'U')
2912 NumHexDigits = 8;
2913 else
2914 return 0;
2915
Jordan Rosec0cba272013-01-27 20:12:04 +00002916 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002917 if (Result && !isLexingRawMode())
2918 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002919 return 0;
2920 }
2921
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002922 const char *CurPtr = StartPtr + CharSize;
2923 const char *KindLoc = &CurPtr[-1];
2924
2925 uint32_t CodePoint = 0;
2926 for (unsigned i = 0; i < NumHexDigits; ++i) {
2927 char C = getCharAndSize(CurPtr, CharSize);
2928
2929 unsigned Value = llvm::hexDigitValue(C);
2930 if (Value == -1U) {
2931 if (Result && !isLexingRawMode()) {
2932 if (i == 0) {
2933 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2934 << StringRef(KindLoc, 1);
2935 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002936 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002937
2938 // If the user wrote \U1234, suggest a fixit to \u.
2939 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002940 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002941 Diag(KindLoc, diag::note_ucn_four_not_eight)
2942 << FixItHint::CreateReplacement(URange, "u");
2943 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002944 }
2945 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002946
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002947 return 0;
2948 }
2949
2950 CodePoint <<= 4;
2951 CodePoint += Value;
2952
2953 CurPtr += CharSize;
2954 }
2955
2956 if (Result) {
2957 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002958 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002959 StartPtr = CurPtr;
2960 else
2961 while (StartPtr != CurPtr)
2962 (void)getAndAdvanceChar(StartPtr, *Result);
2963 } else {
2964 StartPtr = CurPtr;
2965 }
2966
Justin Bogner53535132013-10-21 05:02:28 +00002967 // Don't apply C family restrictions to UCNs in assembly mode
2968 if (LangOpts.AsmPreprocessor)
2969 return CodePoint;
2970
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002971 // C99 6.4.3p2: A universal character name shall not specify a character whose
2972 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2973 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2974 // C++11 [lex.charset]p2: If the hexadecimal value for a
2975 // universal-character-name corresponds to a surrogate code point (in the
2976 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2977 // if the hexadecimal value for a universal-character-name outside the
2978 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2979 // string literal corresponds to a control character (in either of the
2980 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2981 // basic source character set, the program is ill-formed.
2982 if (CodePoint < 0xA0) {
2983 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2984 return CodePoint;
2985
2986 // We don't use isLexingRawMode() here because we need to warn about bad
2987 // UCNs even when skipping preprocessing tokens in a #if block.
2988 if (Result && PP) {
2989 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2990 Diag(BufferPtr, diag::err_ucn_control_character);
2991 else {
2992 char C = static_cast<char>(CodePoint);
2993 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2994 }
2995 }
2996
2997 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002998 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002999 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00003000 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003001 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00003002 if (Result && PP) {
3003 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3004 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3005 else
3006 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3007 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003008 return 0;
3009 }
3010
3011 return CodePoint;
3012}
3013
Eli Friedman0834a4b2013-09-19 00:41:32 +00003014bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3015 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003016 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3017 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00003018 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003019 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00003020 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00003021 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00003022
3023 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003024 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00003025 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003026 return false;
3027}
Jordan Rose4246ae02013-01-24 20:50:50 +00003028
Eli Friedman0834a4b2013-09-19 00:41:32 +00003029bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00003030 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3031 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3032 !PP->isPreprocessedOutput()) {
3033 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3034 makeCharRange(*this, BufferPtr, CurPtr),
3035 /*IsFirst=*/true);
3036 }
3037
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003038 MIOpt.ReadToken();
3039 return LexIdentifier(Result, CurPtr);
3040 }
3041
Jordan Rosecc538342013-01-31 19:48:48 +00003042 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3043 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00003044 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003045 // Non-ASCII characters tend to creep into source code unintentionally.
3046 // Instead of letting the parser complain about the unknown token,
3047 // just drop the character.
3048 // Note that we can /only/ do this when the non-ASCII character is actually
3049 // spelled as Unicode, not written as a UCN. The standard requires that
3050 // we not throw away any possible preprocessor tokens, but there's a
3051 // loophole in the mapping of Unicode characters to basic character set
3052 // characters that allows us to map these particular characters to, say,
3053 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00003054 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00003055 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003056
3057 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003058 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003059 }
3060
3061 // Otherwise, we have an explicit UCN or a character that's unlikely to show
3062 // up by accident.
3063 MIOpt.ReadToken();
3064 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003065 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003066}
3067
Eli Friedman0834a4b2013-09-19 00:41:32 +00003068void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3069 IsAtStartOfLine = Result.isAtStartOfLine();
3070 HasLeadingSpace = Result.hasLeadingSpace();
3071 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3072 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3073}
3074
3075bool Lexer::Lex(Token &Result) {
3076 // Start a new token.
3077 Result.startToken();
3078
3079 // Set up misc whitespace flags for LexTokenInternal.
3080 if (IsAtStartOfLine) {
3081 Result.setFlag(Token::StartOfLine);
3082 IsAtStartOfLine = false;
3083 }
3084
3085 if (HasLeadingSpace) {
3086 Result.setFlag(Token::LeadingSpace);
3087 HasLeadingSpace = false;
3088 }
3089
3090 if (HasLeadingEmptyMacro) {
3091 Result.setFlag(Token::LeadingEmptyMacro);
3092 HasLeadingEmptyMacro = false;
3093 }
3094
3095 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3096 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00003097 bool isRawLex = isLexingRawMode();
3098 (void) isRawLex;
3099 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3100 // (After the LexTokenInternal call, the lexer might be destroyed.)
3101 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3102 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003103}
Chris Lattner22eb9722006-06-18 05:43:12 +00003104
3105/// LexTokenInternal - This implements a simple C family lexer. It is an
3106/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003107/// has a null character at the end of the file. This returns a preprocessing
3108/// token, not a normal token, as such, it is an internal interface. It assumes
3109/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003110bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003111LexNextToken:
3112 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003113 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003114 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003115
Chris Lattner22eb9722006-06-18 05:43:12 +00003116 // CurPtr - Cache BufferPtr in an automatic variable.
3117 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003118
Chris Lattnereb54b592006-07-10 06:34:27 +00003119 // Small amounts of horizontal whitespace is very common between tokens.
3120 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3121 ++CurPtr;
3122 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3123 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003124
Chris Lattner4d963442008-10-12 04:05:48 +00003125 // If we are keeping whitespace and other tokens, just return what we just
3126 // skipped. The next lexer invocation will return the token after the
3127 // whitespace.
3128 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003129 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003130 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003131 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattnereb54b592006-07-10 06:34:27 +00003134 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003135 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003136 }
Mike Stump11289f42009-09-09 15:08:12 +00003137
Chris Lattner22eb9722006-06-18 05:43:12 +00003138 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003139
Chris Lattner22eb9722006-06-18 05:43:12 +00003140 // Read a character, advancing over it.
3141 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003142 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003143
Chris Lattner22eb9722006-06-18 05:43:12 +00003144 switch (Char) {
3145 case 0: // Null.
3146 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003147 if (CurPtr-1 == BufferEnd)
3148 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003149
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003150 // Check if we are performing code completion.
3151 if (isCodeCompletionPoint(CurPtr-1)) {
3152 // Return the code-completion token.
3153 Result.startToken();
3154 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003155 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003156 }
3157
Chris Lattner6d27a162008-11-22 02:02:22 +00003158 if (!isLexingRawMode())
3159 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003160 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003161 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3162 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003163
Eli Friedman0834a4b2013-09-19 00:41:32 +00003164 // We know the lexer hasn't changed, so just try again with this lexer.
3165 // (We manually eliminate the tail call to avoid recursion.)
3166 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003167
Chris Lattner3dfff972009-12-17 05:29:40 +00003168 case 26: // DOS & CP/M EOF: "^Z".
3169 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003170 if (LangOpts.MicrosoftExt) {
3171 if (!isLexingRawMode())
3172 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003173 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003174 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003175
Chris Lattner3dfff972009-12-17 05:29:40 +00003176 // If Microsoft extensions are disabled, this is just random garbage.
3177 Kind = tok::unknown;
3178 break;
Taewook Ohcebac482017-12-06 17:00:53 +00003179
Chris Lattner22eb9722006-06-18 05:43:12 +00003180 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003181 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003182 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003183 LLVM_FALLTHROUGH;
3184 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003185 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003186 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 if (ParsingPreprocessorDirective) {
3188 // Done parsing the "line".
3189 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003190
Chris Lattner457fc152006-07-29 06:30:25 +00003191 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003192 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003193 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003194
Chris Lattner22eb9722006-06-18 05:43:12 +00003195 // Since we consumed a newline, we are back at the start of a line.
3196 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003197 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003198
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003199 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 break;
3201 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003202
Chris Lattner22eb9722006-06-18 05:43:12 +00003203 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003204 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003205
Eli Friedman0834a4b2013-09-19 00:41:32 +00003206 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3207 return true; // KeepWhitespaceMode
3208
3209 // We only saw whitespace, so just try again with this lexer.
3210 // (We manually eliminate the tail call to avoid recursion.)
3211 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003212 case ' ':
3213 case '\t':
3214 case '\f':
3215 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003216 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003217 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003218 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3219 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003220
3221 SkipIgnoredUnits:
3222 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003223
Chris Lattnerb9b85972007-07-22 06:29:05 +00003224 // If the next token is obviously a // or /* */ comment, skip it efficiently
3225 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003226 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003227 LangOpts.LineComment &&
3228 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003229 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3230 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003231 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003232 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003233 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3234 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003235 goto SkipIgnoredUnits;
3236 } else if (isHorizontalWhitespace(*CurPtr)) {
3237 goto SkipHorizontalWhitespace;
3238 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003239 // We only saw whitespace, so just try again with this lexer.
3240 // (We manually eliminate the tail call to avoid recursion.)
3241 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003242
Chris Lattner2b15cf72008-01-03 17:58:54 +00003243 // C99 6.4.4.1: Integer Constants.
3244 // C99 6.4.4.2: Floating Constants.
3245 case '0': case '1': case '2': case '3': case '4':
3246 case '5': case '6': case '7': case '8': case '9':
3247 // Notify MIOpt that we read a non-whitespace/non-comment token.
3248 MIOpt.ReadToken();
3249 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003250
Richard Smith9b362092013-03-09 23:56:02 +00003251 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003252 // Notify MIOpt that we read a non-whitespace/non-comment token.
3253 MIOpt.ReadToken();
3254
Richard Smith9b362092013-03-09 23:56:02 +00003255 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003256 Char = getCharAndSize(CurPtr, SizeTmp);
3257
3258 // UTF-16 string literal
3259 if (Char == '"')
3260 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3261 tok::utf16_string_literal);
3262
3263 // UTF-16 character constant
3264 if (Char == '\'')
3265 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3266 tok::utf16_char_constant);
3267
Craig Topper54edcca2011-08-11 04:06:15 +00003268 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003269 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3270 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003271 return LexRawStringLiteral(Result,
3272 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3273 SizeTmp2, Result),
3274 tok::utf16_string_literal);
3275
3276 if (Char == '8') {
3277 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3278
3279 // UTF-8 string literal
3280 if (Char2 == '"')
3281 return LexStringLiteral(Result,
3282 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3283 SizeTmp2, Result),
3284 tok::utf8_string_literal);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003285 if (Char2 == '\'' && LangOpts.CPlusPlus17)
Richard Smith3e3a7052014-11-08 06:08:42 +00003286 return LexCharConstant(
3287 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3288 SizeTmp2, Result),
3289 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003290
Richard Smith9b362092013-03-09 23:56:02 +00003291 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003292 unsigned SizeTmp3;
3293 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3294 // UTF-8 raw string literal
3295 if (Char3 == '"') {
3296 return LexRawStringLiteral(Result,
3297 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3298 SizeTmp2, Result),
3299 SizeTmp3, Result),
3300 tok::utf8_string_literal);
3301 }
3302 }
3303 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003304 }
3305
3306 // treat u like the start of an identifier.
3307 return LexIdentifier(Result, CurPtr);
3308
Richard Smith9b362092013-03-09 23:56:02 +00003309 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003310 // Notify MIOpt that we read a non-whitespace/non-comment token.
3311 MIOpt.ReadToken();
3312
Richard Smith9b362092013-03-09 23:56:02 +00003313 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003314 Char = getCharAndSize(CurPtr, SizeTmp);
3315
3316 // UTF-32 string literal
3317 if (Char == '"')
3318 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3319 tok::utf32_string_literal);
3320
3321 // UTF-32 character constant
3322 if (Char == '\'')
3323 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3324 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003325
3326 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003327 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3328 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003329 return LexRawStringLiteral(Result,
3330 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3331 SizeTmp2, Result),
3332 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003333 }
3334
3335 // treat U like the start of an identifier.
3336 return LexIdentifier(Result, CurPtr);
3337
Craig Topper54edcca2011-08-11 04:06:15 +00003338 case 'R': // Identifier or C++0x raw string literal
3339 // Notify MIOpt that we read a non-whitespace/non-comment token.
3340 MIOpt.ReadToken();
3341
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003342 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003343 Char = getCharAndSize(CurPtr, SizeTmp);
3344
3345 if (Char == '"')
3346 return LexRawStringLiteral(Result,
3347 ConsumeChar(CurPtr, SizeTmp, Result),
3348 tok::string_literal);
3349 }
3350
3351 // treat R like the start of an identifier.
3352 return LexIdentifier(Result, CurPtr);
3353
Chris Lattner2b15cf72008-01-03 17:58:54 +00003354 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003355 // Notify MIOpt that we read a non-whitespace/non-comment token.
3356 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003357 Char = getCharAndSize(CurPtr, SizeTmp);
3358
3359 // Wide string literal.
3360 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003361 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003362 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003363
Craig Topper54edcca2011-08-11 04:06:15 +00003364 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003365 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003366 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3367 return LexRawStringLiteral(Result,
3368 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3369 SizeTmp2, Result),
3370 tok::wide_string_literal);
3371
Chris Lattner22eb9722006-06-18 05:43:12 +00003372 // Wide character constant.
3373 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003374 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3375 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003376 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003377 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003378
Chris Lattner22eb9722006-06-18 05:43:12 +00003379 // C99 6.4.2: Identifiers.
3380 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3381 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003382 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003383 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3384 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3385 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003386 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003387 case 'v': case 'w': case 'x': case 'y': case 'z':
3388 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003389 // Notify MIOpt that we read a non-whitespace/non-comment token.
3390 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003392
3393 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003394 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003395 if (!isLexingRawMode())
3396 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003397 // Notify MIOpt that we read a non-whitespace/non-comment token.
3398 MIOpt.ReadToken();
3399 return LexIdentifier(Result, CurPtr);
3400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Chris Lattnerb11c3232008-10-12 04:51:35 +00003402 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003403 break;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattner22eb9722006-06-18 05:43:12 +00003405 // C99 6.4.4: Character Constants.
3406 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003407 // Notify MIOpt that we read a non-whitespace/non-comment token.
3408 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003409 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003410
3411 // C99 6.4.5: String Literals.
3412 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003413 // Notify MIOpt that we read a non-whitespace/non-comment token.
3414 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003415 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003416
3417 // C99 6.4.6: Punctuators.
3418 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003419 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003420 break;
3421 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003422 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003423 break;
3424 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003425 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 break;
3427 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003428 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003429 break;
3430 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003431 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003432 break;
3433 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003434 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003435 break;
3436 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003437 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003438 break;
3439 case '.':
3440 Char = getCharAndSize(CurPtr, SizeTmp);
3441 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003442 // Notify MIOpt that we read a non-whitespace/non-comment token.
3443 MIOpt.ReadToken();
3444
Chris Lattner22eb9722006-06-18 05:43:12 +00003445 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003446 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003447 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003448 CurPtr += SizeTmp;
3449 } else if (Char == '.' &&
3450 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003451 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003452 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3453 SizeTmp2, Result);
3454 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003455 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003456 }
3457 break;
3458 case '&':
3459 Char = getCharAndSize(CurPtr, SizeTmp);
3460 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003461 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003462 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3463 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003464 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003465 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3466 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003467 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003468 }
3469 break;
Mike Stump11289f42009-09-09 15:08:12 +00003470 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003471 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003472 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3474 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 }
3477 break;
3478 case '+':
3479 Char = getCharAndSize(CurPtr, SizeTmp);
3480 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003481 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003482 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003483 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003485 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003486 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003487 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003488 }
3489 break;
3490 case '-':
3491 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003492 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003493 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003494 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003495 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003496 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003497 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3498 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003499 Kind = tok::arrowstar;
3500 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003501 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003502 Kind = tok::arrow;
3503 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003504 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003505 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003506 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003507 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003508 }
3509 break;
3510 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003511 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003512 break;
3513 case '!':
3514 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003515 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3517 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003518 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003519 }
3520 break;
3521 case '/':
3522 // 6.4.9: Comments
3523 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003524 if (Char == '/') { // Line comment.
3525 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003526 // want to lex this as a comment. There is one problem with this though,
3527 // that in one particular corner case, this can change the behavior of the
3528 // resultant program. For example, In "foo //**/ bar", C89 would lex
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003529 // this as "foo / bar" and languages with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003530 // "foo". Check to see if the character after the second slash is a '*'.
3531 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003532 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003533 bool TreatAsComment = LangOpts.LineComment &&
3534 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003535 if (!TreatAsComment)
3536 if (!(PP && PP->isPreprocessedOutput()))
3537 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3538
3539 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003540 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3541 TokAtPhysicalStartOfLine))
3542 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003543
Chris Lattner58827712009-01-16 22:39:25 +00003544 // It is common for the tokens immediately after a // comment to be
3545 // whitespace (indentation for the next line). Instead of going through
3546 // the big switch, handle it efficiently now.
3547 goto SkipIgnoredUnits;
3548 }
3549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Chris Lattner58827712009-01-16 22:39:25 +00003551 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003552 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3553 TokAtPhysicalStartOfLine))
3554 return true; // There is a token to return.
3555
3556 // We only saw whitespace, so just try again with this lexer.
3557 // (We manually eliminate the tail call to avoid recursion.)
3558 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003559 }
Mike Stump11289f42009-09-09 15:08:12 +00003560
Chris Lattner58827712009-01-16 22:39:25 +00003561 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003563 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003564 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003565 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003566 }
3567 break;
3568 case '%':
3569 Char = getCharAndSize(CurPtr, SizeTmp);
3570 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003571 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003574 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003575 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003577 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003578 Char = getCharAndSize(CurPtr, SizeTmp);
3579 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003580 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003581 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3582 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003583 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003584 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003585 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003586 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003587 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003588 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003589 // We parsed a # character. If this occurs at the start of the line,
3590 // it's actually the start of a preprocessing directive. Callback to
3591 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003592 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003593 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003594 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattner2534324a2009-03-18 20:58:27 +00003596 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003597 }
3598 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003599 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003600 }
3601 break;
3602 case '<':
3603 Char = getCharAndSize(CurPtr, SizeTmp);
3604 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003605 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003606 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003607 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3608 if (After == '=') {
3609 Kind = tok::lesslessequal;
3610 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3611 SizeTmp2, Result);
3612 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3613 // If this is actually a '<<<<<<<' version control conflict marker,
3614 // recognize it as such and recover nicely.
3615 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003616 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3617 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3618 // ignore it.
3619 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003620 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003621 Kind = tok::lesslessless;
3622 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3623 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003624 } else {
3625 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3626 Kind = tok::lessless;
3627 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003628 } else if (Char == '=') {
Richard Smithedbf5972017-12-01 01:07:10 +00003629 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3630 if (After == '>') {
3631 if (getLangOpts().CPlusPlus2a) {
3632 if (!isLexingRawMode())
3633 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3634 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3635 SizeTmp2, Result);
3636 Kind = tok::spaceship;
3637 break;
3638 }
3639 // Suggest adding a space between the '<=' and the '>' to avoid a
3640 // change in semantics if this turns up in C++ <=17 mode.
3641 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3642 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3643 << FixItHint::CreateInsertion(
3644 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3645 }
3646 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003647 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003648 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003649 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003650 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003651 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3652 // C++0x [lex.pptoken]p3:
3653 // Otherwise, if the next three characters are <:: and the subsequent
3654 // character is neither : nor >, the < is treated as a preprocessor
3655 // token by itself and not as the first character of the alternative
3656 // token <:.
3657 unsigned SizeTmp3;
3658 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3659 if (After != ':' && After != '>') {
3660 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003661 if (!isLexingRawMode())
3662 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003663 break;
3664 }
3665 }
3666
Chris Lattner22eb9722006-06-18 05:43:12 +00003667 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003668 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003669 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003670 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003671 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003672 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3673 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003674 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003675 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003676 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003677 }
3678 break;
3679 case '>':
3680 Char = getCharAndSize(CurPtr, SizeTmp);
3681 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003682 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003683 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003684 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003685 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3686 if (After == '=') {
3687 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3688 SizeTmp2, Result);
3689 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003690 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3691 // If this is actually a '>>>>' conflict marker, recognize it as such
3692 // and recover nicely.
3693 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003694 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3695 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3696 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003697 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003698 Kind = tok::greatergreatergreater;
3699 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3700 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003701 } else {
3702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3703 Kind = tok::greatergreater;
3704 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003705 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003706 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003707 }
3708 break;
3709 case '^':
3710 Char = getCharAndSize(CurPtr, SizeTmp);
3711 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003712 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003713 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003714 } else if (LangOpts.OpenCL && Char == '^') {
3715 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3716 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003717 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003718 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003719 }
3720 break;
3721 case '|':
3722 Char = getCharAndSize(CurPtr, SizeTmp);
3723 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003724 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003725 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3726 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003727 // If this is '|||||||' and we're in a conflict marker, ignore it.
3728 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3729 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003730 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003731 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3732 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003733 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003734 }
3735 break;
3736 case ':':
3737 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003738 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003739 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003740 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Aaron Ballman606093a2017-10-15 15:01:42 +00003741 } else if ((LangOpts.CPlusPlus ||
3742 LangOpts.DoubleSquareBracketAttributes) &&
3743 Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003744 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003745 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003746 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003747 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003748 }
3749 break;
3750 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003751 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003752 break;
3753 case '=':
3754 Char = getCharAndSize(CurPtr, SizeTmp);
3755 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003756 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003757 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3758 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003759
Chris Lattnerb11c3232008-10-12 04:51:35 +00003760 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003761 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003762 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003763 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003764 }
3765 break;
3766 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003767 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003768 break;
3769 case '#':
3770 Char = getCharAndSize(CurPtr, SizeTmp);
3771 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003772 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003773 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003774 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003775 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003776 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003777 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003778 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003779 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003780 // We parsed a # character. If this occurs at the start of the line,
3781 // it's actually the start of a preprocessing directive. Callback to
3782 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003783 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003784 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003785 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003786
Chris Lattner2534324a2009-03-18 20:58:27 +00003787 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003788 }
3789 break;
3790
Chris Lattner2b15cf72008-01-03 17:58:54 +00003791 case '@':
3792 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003793 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003794 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003795 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003796 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003797 break;
Mike Stump11289f42009-09-09 15:08:12 +00003798
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003799 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003800 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003801 if (!LangOpts.AsmPreprocessor) {
3802 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3803 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3804 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3805 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003806
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003807 // We only saw whitespace, so just try again with this lexer.
3808 // (We manually eliminate the tail call to avoid recursion.)
3809 goto LexNextToken;
3810 }
3811
3812 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003813 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003814 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003815
Chris Lattnerb11c3232008-10-12 04:51:35 +00003816 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003817 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003818
3819 default: {
3820 if (isASCII(Char)) {
3821 Kind = tok::unknown;
3822 break;
3823 }
3824
Justin Lebar90910552016-09-30 00:38:45 +00003825 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003826
3827 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3828 // an escaped newline.
3829 --CurPtr;
Richard Smith77091b12017-12-14 13:15:08 +00003830 const char *UTF8StartPtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003831 llvm::ConversionResult Status =
3832 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3833 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003834 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003835 llvm::strictConversion);
3836 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003837 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3838 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3839 return true; // KeepWhitespaceMode
3840
3841 // We only saw whitespace, so just try again with this lexer.
3842 // (We manually eliminate the tail call to avoid recursion.)
3843 goto LexNextToken;
3844 }
Richard Smith77091b12017-12-14 13:15:08 +00003845 if (!isLexingRawMode())
3846 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
3847 makeCharRange(*this, UTF8StartPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003848 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003849 }
Taewook Ohcebac482017-12-06 17:00:53 +00003850
Jordan Rosecc538342013-01-31 19:48:48 +00003851 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3852 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003853 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003854 Kind = tok::unknown;
3855 break;
3856 }
3857
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003858 // Non-ASCII characters tend to creep into source code unintentionally.
3859 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003860 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003861 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003862
3863 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003864 // We're pretending the character didn't exist, so just try again with
3865 // this lexer.
3866 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003867 goto LexNextToken;
3868 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003869 }
Mike Stump11289f42009-09-09 15:08:12 +00003870
Chris Lattner371ac8a2006-07-04 07:11:10 +00003871 // Notify MIOpt that we read a non-whitespace/non-comment token.
3872 MIOpt.ReadToken();
3873
Chris Lattnerd01e2912006-06-18 16:22:51 +00003874 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003875 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003876 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003877
3878HandleDirective:
3879 // We parsed a # character and it's the start of a preprocessing directive.
3880
3881 FormTokenWithChars(Result, CurPtr, tok::hash);
3882 PP->HandleDirective(Result);
3883
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003884 if (PP->hadModuleLoaderFatalFailure()) {
3885 // With a fatal failure in the module loader, we abort parsing.
3886 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003887 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003888 }
3889
Eli Friedman0834a4b2013-09-19 00:41:32 +00003890 // We parsed the directive; lex a token with the new state.
3891 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003892}