blob: aeb123a36037b87712b2bde768d2091f207a3b91 [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/Support/UnicodeCharRanges.h"
41#include <algorithm>
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000045#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include <string>
47#include <tuple>
48#include <utility>
49
Chris Lattner22eb9722006-06-18 05:43:12 +000050using namespace clang;
51
Chris Lattner4894f482007-10-07 08:47:24 +000052//===----------------------------------------------------------------------===//
53// Token Class Implementation
54//===----------------------------------------------------------------------===//
55
Mike Stump11289f42009-09-09 15:08:12 +000056/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000057bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Alex Lorenzd4754662017-05-17 11:08:36 +000058 if (isAnnotation())
59 return false;
Douglas Gregor90abb6d2008-12-01 21:46:47 +000060 if (IdentifierInfo *II = getIdentifierInfo())
61 return II->getObjCKeywordID() == objcKey;
62 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000063}
64
65/// getObjCKeywordID - Return the ObjC keyword kind.
66tok::ObjCKeywordKind Token::getObjCKeywordID() const {
Alex Lorenzd4754662017-05-17 11:08:36 +000067 if (isAnnotation())
68 return tok::objc_not_keyword;
Chris Lattner4894f482007-10-07 08:47:24 +000069 IdentifierInfo *specId = getIdentifierInfo();
70 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
71}
72
73//===----------------------------------------------------------------------===//
74// Lexer Class Implementation
75//===----------------------------------------------------------------------===//
76
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000077void Lexer::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +000078
Mike Stump11289f42009-09-09 15:08:12 +000079void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000080 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000081 BufferStart = BufStart;
82 BufferPtr = BufPtr;
83 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000084
Chris Lattnerf76b9202009-01-17 06:55:17 +000085 assert(BufEnd[0] == 0 &&
86 "We assume that the input buffer has a null character at the end"
87 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000088
Eric Christopher7f36a792011-04-09 00:01:04 +000089 // Check whether we have a BOM in the beginning of the buffer. If yes - act
90 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
91 // skip the UTF-8 BOM if it's present.
92 if (BufferStart == BufferPtr) {
93 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000094 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000095 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000096 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
97 .Default(0);
98
99 // Skip the BOM.
100 BufferPtr += BOMLength;
101 }
102
Chris Lattnerf76b9202009-01-17 06:55:17 +0000103 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +0000104 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +0000105
Chris Lattnerf76b9202009-01-17 06:55:17 +0000106 // Start of the file is a start of line.
107 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000108 IsAtPhysicalStartOfLine = true;
109
110 HasLeadingSpace = false;
111 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattnerf76b9202009-01-17 06:55:17 +0000113 // We are not after parsing a #.
114 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattnerf76b9202009-01-17 06:55:17 +0000116 // We are not after parsing #include.
117 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000118
Chris Lattnerf76b9202009-01-17 06:55:17 +0000119 // We are not in raw mode. Raw mode disables diagnostics and interpretation
120 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
121 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
122 // or otherwise skipping over tokens.
123 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000124
Chris Lattnerf76b9202009-01-17 06:55:17 +0000125 // Default to not keeping comments.
126 ExtendedTokenMode = 0;
127}
128
Chris Lattner5965a282009-01-17 07:56:59 +0000129/// Lexer constructor - Create a new lexer object for the specified buffer
130/// with the specified preprocessor managing the lexing process. This lexer
131/// assumes that the associated file buffer and Preprocessor objects will
132/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000133Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000134 : PreprocessorLexer(&PP, FID),
135 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
136 LangOpts(PP.getLangOpts()) {
Chris Lattner5965a282009-01-17 07:56:59 +0000137 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
138 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000139
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000140 resetExtendedTokenMode();
141}
142
Chris Lattner02b436a2007-10-17 20:41:00 +0000143/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000144/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000145/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000147 const char *BufStart, const char *BufPtr, const char *BufEnd)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000148 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000149 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000150
Chris Lattner02b436a2007-10-17 20:41:00 +0000151 // We *are* in raw mode.
152 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000153}
154
Chris Lattner08354fe2009-01-17 07:35:14 +0000155/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000156/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000157/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000158Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000159 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000160 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
161 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000162
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000163void Lexer::resetExtendedTokenMode() {
164 assert(PP && "Cannot reset token mode without a preprocessor");
165 if (LangOpts.TraditionalCPP)
166 SetKeepWhitespaceMode(true);
167 else
168 SetCommentRetentionState(PP->getCommentRetentionState());
169}
170
Chris Lattner757169b2009-01-17 08:27:52 +0000171/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
172/// _Pragma expansion. This has a variety of magic semantics that this method
173/// sets up. It returns a new'd Lexer that must be delete'd when done.
174///
175/// On entrance to this routine, TokStartLoc is a macro location which has a
176/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000177/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000178/// "expanded from".
179///
Alp Toker7755aff2014-05-18 18:37:59 +0000180/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000181/// normal lexer that remaps tokens as they fly by. This would require making
182/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
183/// interface that could handle this stuff. This would pull GetMappedTokenLoc
184/// out of the critical path of the lexer!
185///
Mike Stump11289f42009-09-09 15:08:12 +0000186Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000187 SourceLocation ExpansionLocStart,
188 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000189 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000190 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000191
192 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000193 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000194 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
195 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattner757169b2009-01-17 08:27:52 +0000197 // Now that the lexer is created, change the start/end locations so that we
198 // just lex the subsection of the file that we want. This is lexing from a
199 // scratch buffer.
200 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattner757169b2009-01-17 08:27:52 +0000202 L->BufferPtr = StrData;
203 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000204 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000205
206 // Set the SourceLocation with the remapping information. This ensures that
207 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000208 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
209 ExpansionLocStart,
210 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner757169b2009-01-17 08:27:52 +0000212 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000213 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000214 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000215
Chris Lattner757169b2009-01-17 08:27:52 +0000216 // This lexer really is for _Pragma.
217 L->Is_PragmaLexer = true;
218 return L;
219}
220
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000221template <typename T> static void StringifyImpl(T &Str, char Quote) {
Taewook Ohcebac482017-12-06 17:00:53 +0000222 typename T::size_type i = 0, e = Str.size();
223 while (i < e) {
224 if (Str[i] == '\\' || Str[i] == Quote) {
225 Str.insert(Str.begin() + i, '\\');
226 i += 2;
227 ++e;
228 } else if (Str[i] == '\n' || Str[i] == '\r') {
229 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
230 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
231 Str[i] != Str[i + 1]) {
232 Str[i] = '\\';
233 Str[i + 1] = 'n';
234 } else {
235 // Replace '\n' and '\r' to '\\' followed by 'n'.
236 Str[i] = '\\';
237 Str.insert(Str.begin() + i + 1, 'n');
238 ++e;
239 }
240 i += 2;
241 } else
242 ++i;
243 }
244}
245
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000246std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000247 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000248 char Quote = Charify ? '\'' : '"';
Taewook Ohcebac482017-12-06 17:00:53 +0000249 StringifyImpl(Result, Quote);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000250 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000251}
252
Taewook Ohcebac482017-12-06 17:00:53 +0000253void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
Chris Lattner4c4a2452007-07-24 06:57:14 +0000254
Chris Lattner39720112010-11-17 07:26:20 +0000255//===----------------------------------------------------------------------===//
256// Token Spelling
257//===----------------------------------------------------------------------===//
258
Richard Smith9a67f472012-11-28 07:29:00 +0000259/// \brief Slow case of getSpelling. Extract the characters comprising the
260/// spelling of this token from the provided input buffer.
261static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
262 const LangOptions &LangOpts, char *Spelling) {
263 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
264
265 size_t Length = 0;
266 const char *BufEnd = BufPtr + Tok.getLength();
267
Craig Toppera6324c92015-10-22 15:35:21 +0000268 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000269 // Munch the encoding-prefix and opening double-quote.
270 while (BufPtr < BufEnd) {
271 unsigned Size;
272 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
273 BufPtr += Size;
274
275 if (Spelling[Length - 1] == '"')
276 break;
277 }
278
279 // Raw string literals need special handling; trigraph expansion and line
280 // splicing do not occur within their d-char-sequence nor within their
281 // r-char-sequence.
282 if (Length >= 2 &&
283 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
284 // Search backwards from the end of the token to find the matching closing
285 // quote.
286 const char *RawEnd = BufEnd;
287 do --RawEnd; while (*RawEnd != '"');
288 size_t RawLength = RawEnd - BufPtr + 1;
289
290 // Everything between the quotes is included verbatim in the spelling.
291 memcpy(Spelling + Length, BufPtr, RawLength);
292 Length += RawLength;
293 BufPtr += RawLength;
294
295 // The rest of the token is lexed normally.
296 }
297 }
298
299 while (BufPtr < BufEnd) {
300 unsigned Size;
301 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
302 BufPtr += Size;
303 }
304
305 assert(Length < Tok.getLength() &&
306 "NeedsCleaning flag set on token that didn't need cleaning!");
307 return Length;
308}
309
Chris Lattner39720112010-11-17 07:26:20 +0000310/// getSpelling() - Return the 'spelling' of this token. The spelling of a
311/// token are the characters used to represent the token in the source file
312/// after trigraph expansion and escaped-newline folding. In particular, this
313/// wants to get the true, uncanonicalized, spelling of things like digraphs
314/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000315StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000316 SmallVectorImpl<char> &buffer,
317 const SourceManager &SM,
318 const LangOptions &options,
319 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000320 // Break down the source location.
321 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
322
323 // Try to the load the file buffer.
324 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000326 if (invalidTemp) {
327 if (invalid) *invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000328 return {};
John McCall462c0552011-03-08 07:59:04 +0000329 }
330
331 const char *tokenBegin = file.data() + locInfo.second;
332
333 // Lex from the start of the given location.
334 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
335 file.begin(), tokenBegin, file.end());
336 Token token;
337 lexer.LexFromRawLexer(token);
338
339 unsigned length = token.getLength();
340
341 // Common case: no need for cleaning.
342 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000343 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000344
Richard Smith9a67f472012-11-28 07:29:00 +0000345 // Hard case, we need to relex the characters into the string.
346 buffer.resize(length);
347 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000349}
350
351/// getSpelling() - Return the 'spelling' of this token. The spelling of a
352/// token are the characters used to represent the token in the source file
353/// after trigraph expansion and escaped-newline folding. In particular, this
354/// wants to get the true, uncanonicalized, spelling of things like digraphs
355/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000356std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000357 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000358 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000359
Chris Lattner39720112010-11-17 07:26:20 +0000360 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000361 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000362 &CharDataInvalid);
363 if (Invalid)
364 *Invalid = CharDataInvalid;
365 if (CharDataInvalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000366 return {};
Richard Smith9a67f472012-11-28 07:29:00 +0000367
368 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000369 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000370 return std::string(TokStart, TokStart + Tok.getLength());
371
Chris Lattner39720112010-11-17 07:26:20 +0000372 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000373 Result.resize(Tok.getLength());
374 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000375 return Result;
376}
377
378/// getSpelling - This method is used to get the spelling of a token into a
379/// preallocated buffer, instead of as an std::string. The caller is required
380/// to allocate enough space for the token, which is guaranteed to be at least
381/// Tok.getLength() bytes long. The actual length of the token is returned.
382///
383/// Note that this method may do two possible things: it may either fill in
384/// the buffer specified with characters, or it may *change the input pointer*
385/// to point to a constant buffer with the data already in it (avoiding a
386/// copy). The caller is not allowed to modify the returned buffer pointer
387/// if an internal buffer is returned.
Taewook Ohcebac482017-12-06 17:00:53 +0000388unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
Chris Lattner39720112010-11-17 07:26:20 +0000389 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000390 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000391 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392
Craig Topperd2d442c2014-05-17 23:10:59 +0000393 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000394 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
395 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000396 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000397 else if (!Tok.hasUCN()) {
398 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
399 // Just return the string from the identifier table, which is very quick.
400 Buffer = II->getNameStart();
401 return II->getLength();
402 }
Chris Lattner39720112010-11-17 07:26:20 +0000403 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000404
405 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000406 if (Tok.isLiteral())
407 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000408
Craig Topperd2d442c2014-05-17 23:10:59 +0000409 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000410 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000411 bool CharDataInvalid = false;
412 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
413 if (Invalid)
414 *Invalid = CharDataInvalid;
415 if (CharDataInvalid) {
416 Buffer = "";
417 return 0;
418 }
419 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000420
Chris Lattner39720112010-11-17 07:26:20 +0000421 // If this token contains nothing interesting, return it directly.
422 if (!Tok.needsCleaning()) {
423 Buffer = TokStart;
424 return Tok.getLength();
425 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000426
Chris Lattner39720112010-11-17 07:26:20 +0000427 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000428 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000429}
430
Chris Lattner8e129c22007-10-17 21:18:47 +0000431/// MeasureTokenLength - Relex the token at the specified location and return
432/// its length in bytes in the input file. If the token needs cleaning (e.g.
433/// includes a trigraph or an escaped newline) then this count includes bytes
434/// that are part of that.
435unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000436 const SourceManager &SM,
437 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000438 Token TheTok;
439 if (getRawToken(Loc, TheTok, SM, LangOpts))
440 return 0;
441 return TheTok.getLength();
442}
443
444/// \brief Relex the token at the specified location.
445/// \returns true if there was a failure, false on success.
446bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
447 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000448 const LangOptions &LangOpts,
449 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000450 // TODO: this could be special cased for common tokens like identifiers, ')',
451 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000452 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000453 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
454 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000455
456 // If this comes from a macro expansion, we really do want the macro name, not
457 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000458 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000460 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000461 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000462 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000463 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000464
465 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000466
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000467 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000468 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000469
Chris Lattner8e129c22007-10-17 21:18:47 +0000470 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000471 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
472 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000473 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000474 TheLexer.LexFromRawLexer(Result);
475 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000476}
477
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000478/// Returns the pointer that points to the beginning of line that contains
479/// the given offset, or null if the offset if invalid.
480static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
481 const char *BufStart = Buffer.data();
482 if (Offset >= Buffer.size())
483 return nullptr;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000484
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000485 const char *LexStart = BufStart + Offset;
486 for (; LexStart != BufStart; --LexStart) {
487 if (isVerticalWhitespace(LexStart[0]) &&
488 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
489 // LexStart should point at first character of logical line.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000490 ++LexStart;
491 break;
492 }
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000493 }
494 return LexStart;
495}
496
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000497static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
498 const SourceManager &SM,
499 const LangOptions &LangOpts) {
500 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000501 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000502 if (LocInfo.first.isInvalid())
503 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000504
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000505 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000506 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000507 if (Invalid)
508 return Loc;
509
510 // Back up from the current location until we hit the beginning of a line
511 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000512 const char *StrData = Buffer.data() + LocInfo.second;
513 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
514 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000515 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000516
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000517 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000518 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000519 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
520 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000521 TheLexer.SetCommentRetentionState(true);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000522
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000523 // Lex tokens until we find the token that contains the source location.
524 Token TheTok;
525 do {
526 TheLexer.LexFromRawLexer(TheTok);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000527
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000528 if (TheLexer.getBufferLocation() > StrData) {
529 // Lexing this token has taken the lexer past the source location we're
530 // looking for. If the current token encompasses our source location,
531 // return the beginning of that token.
532 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
533 return TheTok.getLocation();
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000534
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000535 // We ended up skipping over the source location entirely, which means
536 // that it points into whitespace. We're done here.
537 break;
538 }
539 } while (TheTok.getKind() != tok::eof);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000540
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000541 // We've passed our source location; just return the original source location.
542 return Loc;
543}
544
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000545SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
546 const SourceManager &SM,
547 const LangOptions &LangOpts) {
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000548 if (Loc.isFileID())
549 return getBeginningOfFileToken(Loc, SM, LangOpts);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000550
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000551 if (!SM.isMacroArgExpansion(Loc))
552 return Loc;
553
554 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
555 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
556 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
557 std::pair<FileID, unsigned> BeginFileLocInfo =
558 SM.getDecomposedLoc(BeginFileLoc);
559 assert(FileLocInfo.first == BeginFileLocInfo.first &&
560 FileLocInfo.second >= BeginFileLocInfo.second);
561 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000562}
563
Douglas Gregoraf82e352010-07-20 20:18:03 +0000564namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000565
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000566enum PreambleDirectiveKind {
567 PDK_Skipped,
568 PDK_Unknown
569};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000570
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000571} // namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000572
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000573PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
574 const LangOptions &LangOpts,
575 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000576 // Create a lexer starting at the beginning of the file. Note that we use a
577 // "fake" file source location at offset 1 so that the lexer will track our
578 // position within the file.
579 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000580 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000581 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
582 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000583 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000584
Douglas Gregoraf82e352010-07-20 20:18:03 +0000585 bool InPreprocessorDirective = false;
586 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000587 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000588
589 unsigned MaxLineOffset = 0;
590 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000591 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000592 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000593 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000594 char ch = *CurPtr++;
595 if (ch == '\n') {
596 ++CurLine;
597 if (CurLine == MaxLines)
598 break;
599 }
600 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000601 if (CurPtr != Buffer.end())
602 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000603 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000604
Douglas Gregoraf82e352010-07-20 20:18:03 +0000605 do {
606 TheLexer.LexFromRawLexer(TheTok);
607
608 if (InPreprocessorDirective) {
609 // If we've hit the end of the file, we're done.
610 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000611 break;
612 }
Taewook Ohcebac482017-12-06 17:00:53 +0000613
Douglas Gregoraf82e352010-07-20 20:18:03 +0000614 // If we haven't hit the end of the preprocessor directive, skip this
615 // token.
616 if (!TheTok.isAtStartOfLine())
617 continue;
Taewook Ohcebac482017-12-06 17:00:53 +0000618
Douglas Gregoraf82e352010-07-20 20:18:03 +0000619 // We've passed the end of the preprocessor directive, and will look
620 // at this token again below.
621 InPreprocessorDirective = false;
622 }
Taewook Ohcebac482017-12-06 17:00:53 +0000623
Douglas Gregor028d3e42010-08-09 20:45:32 +0000624 // Keep track of the # of lines in the preamble.
625 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000626 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000627
628 // If we were asked to limit the number of lines in the preamble,
629 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000630 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000631 break;
632 }
633
Douglas Gregoraf82e352010-07-20 20:18:03 +0000634 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000635 if (TheTok.getKind() == tok::comment) {
636 if (ActiveCommentLoc.isInvalid())
637 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000638 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000639 }
Taewook Ohcebac482017-12-06 17:00:53 +0000640
Douglas Gregoraf82e352010-07-20 20:18:03 +0000641 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
Taewook Ohcebac482017-12-06 17:00:53 +0000642 // This is the start of a preprocessor directive.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000643 Token HashTok = TheTok;
644 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000645 ActiveCommentLoc = SourceLocation();
Taewook Ohcebac482017-12-06 17:00:53 +0000646
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000647 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000648 // we don't have an identifier table available. Instead, just look at
649 // the raw identifier to recognize and categorize preprocessor directives.
650 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000651 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000652 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000653 PreambleDirectiveKind PDK
654 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
655 .Case("include", PDK_Skipped)
656 .Case("__include_macros", PDK_Skipped)
657 .Case("define", PDK_Skipped)
658 .Case("undef", PDK_Skipped)
659 .Case("line", PDK_Skipped)
660 .Case("error", PDK_Skipped)
661 .Case("pragma", PDK_Skipped)
662 .Case("import", PDK_Skipped)
663 .Case("include_next", PDK_Skipped)
664 .Case("warning", PDK_Skipped)
665 .Case("ident", PDK_Skipped)
666 .Case("sccs", PDK_Skipped)
667 .Case("assert", PDK_Skipped)
668 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000669 .Case("if", PDK_Skipped)
670 .Case("ifdef", PDK_Skipped)
671 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000672 .Case("elif", PDK_Skipped)
673 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000674 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000675 .Default(PDK_Unknown);
676
677 switch (PDK) {
678 case PDK_Skipped:
679 continue;
680
Douglas Gregoraf82e352010-07-20 20:18:03 +0000681 case PDK_Unknown:
682 // We don't know what this directive is; stop at the '#'.
683 break;
684 }
685 }
Taewook Ohcebac482017-12-06 17:00:53 +0000686
Douglas Gregoraf82e352010-07-20 20:18:03 +0000687 // We only end up here if we didn't recognize the preprocessor
688 // directive or it was one that can't occur in the preamble at this
689 // point. Roll back the current token to the location of the '#'.
690 InPreprocessorDirective = false;
691 TheTok = HashTok;
692 }
693
Douglas Gregor028d3e42010-08-09 20:45:32 +0000694 // We hit a token that we don't recognize as being in the
695 // "preprocessing only" part of the file, so we're no longer in
696 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000697 break;
698 } while (true);
Taewook Ohcebac482017-12-06 17:00:53 +0000699
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000700 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000701 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000702 End = ActiveCommentLoc; // don't truncate a decl comment.
703 else
704 End = TheTok.getLocation();
705
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000706 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000707 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000708}
709
Chris Lattner2a6ee912010-11-17 07:05:50 +0000710/// AdvanceToTokenCharacter - Given a location that specifies the start of a
711/// token, return a new location that specifies a character within the token.
712SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
713 unsigned CharNo,
714 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000715 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000716 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000717 // character is. This needs to take into consideration newlines and
718 // trigraphs.
719 bool Invalid = false;
720 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
Taewook Ohcebac482017-12-06 17:00:53 +0000721
Chris Lattner2a6ee912010-11-17 07:05:50 +0000722 // If they request the first char of the token, we're trivially done.
723 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
724 return TokStart;
Taewook Ohcebac482017-12-06 17:00:53 +0000725
Chris Lattner2a6ee912010-11-17 07:05:50 +0000726 unsigned PhysOffset = 0;
Taewook Ohcebac482017-12-06 17:00:53 +0000727
Chris Lattner2a6ee912010-11-17 07:05:50 +0000728 // The usual case is that tokens don't contain anything interesting. Skip
729 // over the uninteresting characters. If a token only consists of simple
730 // chars, this method is extremely fast.
731 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
732 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000733 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000734 ++TokPtr;
735 --CharNo;
736 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000737 }
Taewook Ohcebac482017-12-06 17:00:53 +0000738
Chris Lattner2a6ee912010-11-17 07:05:50 +0000739 // If we have a character that may be a trigraph or escaped newline, use a
740 // lexer to parse it correctly.
741 for (; CharNo; --CharNo) {
742 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000743 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000744 TokPtr += Size;
745 PhysOffset += Size;
746 }
Taewook Ohcebac482017-12-06 17:00:53 +0000747
Chris Lattner2a6ee912010-11-17 07:05:50 +0000748 // Final detail: if we end up on an escaped newline, we want to return the
749 // location of the actual byte of the token. For example foo\<newline>bar
750 // advanced by 3 should return the location of b, not of \\. One compounding
751 // detail of this is that the escape may be made by a trigraph.
752 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
753 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
Taewook Ohcebac482017-12-06 17:00:53 +0000754
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000755 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000756}
757
758/// \brief Computes the source location just past the end of the
759/// token at this source location.
760///
761/// This routine can be used to produce a source location that
762/// points just past the end of the token referenced by \p Loc, and
763/// is generally used when a diagnostic needs to point just after a
764/// token where it expected something different that it received. If
765/// the returned source location would not be meaningful (e.g., if
766/// it points into a macro), this routine returns an invalid
767/// source location.
768///
769/// \param Offset an offset from the end of the token, where the source
770/// location should refer to. The default offset (0) produces a source
771/// location pointing just past the end of the token; an offset of 1 produces
772/// a source location pointing to the last character in the token, etc.
773SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
774 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000776 if (Loc.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000777 return {};
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000778
779 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000781 return {}; // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000782 }
783
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000785 if (Len > Offset)
786 Len = Len - Offset;
787 else
788 return Loc;
Taewook Ohcebac482017-12-06 17:00:53 +0000789
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000790 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000791}
792
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000793/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000794/// token of the macro expansion.
795bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000796 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000797 const LangOptions &LangOpts,
798 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
800
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000801 SourceLocation expansionLoc;
802 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
803 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000804
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000805 if (expansionLoc.isFileID()) {
806 // No other macro expansions, this is the first.
807 if (MacroBegin)
808 *MacroBegin = expansionLoc;
809 return true;
810 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000811
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000812 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000813}
814
815/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000816/// token of the macro expansion.
817bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000818 const SourceManager &SM,
819 const LangOptions &LangOpts,
820 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000821 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
822
823 SourceLocation spellLoc = SM.getSpellingLoc(loc);
824 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
825 if (tokLen == 0)
826 return false;
827
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000828 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
829 SourceLocation expansionLoc;
830 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
831 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000832
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000833 if (expansionLoc.isFileID()) {
834 // No other macro expansions.
835 if (MacroEnd)
836 *MacroEnd = expansionLoc;
837 return true;
838 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000839
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000840 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000841}
842
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000843static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000844 const SourceManager &SM,
845 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000846 SourceLocation Begin = Range.getBegin();
847 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000848 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000849 if (Range.isTokenRange()) {
850 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
851 if (End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000852 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000853 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000854
855 // Break down the source locations.
856 FileID FID;
857 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000858 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000859 if (FID.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000860 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000861
862 unsigned EndOffs;
863 if (!SM.isInFileID(End, FID, &EndOffs) ||
864 BeginOffs > EndOffs)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000865 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000866
867 return CharSourceRange::getCharRange(Begin, End);
868}
869
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000870CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000871 const SourceManager &SM,
872 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000873 SourceLocation Begin = Range.getBegin();
874 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000875 if (Begin.isInvalid() || End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000876 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000877
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000878 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000879 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000880
881 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000882 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000883 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000884 Range.setBegin(Begin);
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000887
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000888 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
890 &End)) ||
891 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
892 &End)))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000893 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000894 Range.setEnd(End);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000896 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000897
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000898 assert(Begin.isMacroID() && End.isMacroID());
899 SourceLocation MacroBegin, MacroEnd;
900 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000901 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
902 &MacroEnd)) ||
903 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
904 &MacroEnd)))) {
905 Range.setBegin(MacroBegin);
906 Range.setEnd(MacroEnd);
907 return makeRangeFromFileLocs(Range, SM, LangOpts);
908 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000909
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000910 bool Invalid = false;
911 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
912 &Invalid);
913 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000914 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000915
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000916 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
917 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
918 &Invalid);
919 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000920 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000921
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000922 if (EndEntry.getExpansion().isMacroArgExpansion() &&
923 BeginEntry.getExpansion().getExpansionLocStart() ==
924 EndEntry.getExpansion().getExpansionLocStart()) {
925 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
926 Range.setEnd(SM.getImmediateSpellingLoc(End));
927 return makeFileCharRange(Range, SM, LangOpts);
928 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000929 }
930
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000931 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000932}
933
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000934StringRef Lexer::getSourceText(CharSourceRange Range,
935 const SourceManager &SM,
936 const LangOptions &LangOpts,
937 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000938 Range = makeFileCharRange(Range, SM, LangOpts);
939 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000940 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000941 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000942 }
943
944 // Break down the source location.
945 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
946 if (beginInfo.first.isInvalid()) {
947 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000948 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000949 }
950
951 unsigned EndOffs;
952 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
953 beginInfo.second > EndOffs) {
954 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000955 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000956 }
957
958 // Try to the load the file buffer.
959 bool invalidTemp = false;
960 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
961 if (invalidTemp) {
962 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000963 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000964 }
965
966 if (Invalid) *Invalid = false;
967 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
968}
969
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000970StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
971 const SourceManager &SM,
972 const LangOptions &LangOpts) {
973 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000974
975 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000976 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000977 FileID FID = SM.getFileID(Loc);
978 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
979 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
980 Loc = Expansion.getExpansionLocStart();
981 if (!Expansion.isMacroArgExpansion())
982 break;
983
984 // For macro arguments we need to check that the argument did not come
985 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
Taewook Ohcebac482017-12-06 17:00:53 +0000986
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000987 // Loc points to the argument id of the macro definition, move to the
988 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000989 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000990 SourceLocation SpellLoc = Expansion.getSpellingLoc();
991 if (SpellLoc.isFileID())
992 break; // No inner macro.
993
994 // If spelling location resides in the same FileID as macro expansion
995 // location, it means there is no inner macro.
996 FileID MacroFID = SM.getFileID(Loc);
997 if (SM.isInFileID(SpellLoc, MacroFID))
998 break;
999
1000 // Argument came from inner macro.
1001 Loc = SpellLoc;
1002 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001003
1004 // Find the spelling location of the start of the non-argument expansion
1005 // range. This is where the macro name was spelled in order to begin
1006 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001007 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001008
1009 // Dig out the buffer where the macro name was spelled and the extents of the
1010 // name so that we can render it into the expansion note.
1011 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1012 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1013 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1014 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1015}
1016
Richard Trieu3a5c9582016-01-26 02:51:55 +00001017StringRef Lexer::getImmediateMacroNameForDiagnostics(
1018 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1019 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1020 // Walk past macro argument expanions.
1021 while (SM.isMacroArgExpansion(Loc))
1022 Loc = SM.getImmediateExpansionRange(Loc).first;
1023
1024 // If the macro's spelling has no FileID, then it's actually a token paste
1025 // or stringization (or similar) and not a macro at all.
1026 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001027 return {};
Richard Trieu3a5c9582016-01-26 02:51:55 +00001028
1029 // Find the spelling location of the start of the non-argument expansion
1030 // range. This is where the macro name was spelled in order to begin
1031 // expanding this macro.
1032 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1033
1034 // Dig out the buffer where the macro name was spelled and the extents of the
1035 // name so that we can render it into the expansion note.
1036 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1037 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1038 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1039 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1040}
1041
Jordan Rose288c4212012-06-07 01:10:31 +00001042bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001043 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001044}
1045
Alexander Kornienkocf007a72017-08-10 10:06:16 +00001046bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1047 assert(isVerticalWhitespace(Str[0]));
1048 if (Str - 1 < BufferStart)
1049 return false;
1050
1051 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1052 (Str[0] == '\r' && Str[-1] == '\n')) {
1053 if (Str - 2 < BufferStart)
1054 return false;
1055 --Str;
1056 }
1057 --Str;
1058
1059 // Rewind to first non-space character:
1060 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1061 --Str;
1062
1063 return *Str == '\\';
1064}
1065
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001066StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1067 const SourceManager &SM) {
1068 if (Loc.isInvalid() || Loc.isMacroID())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001069 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001070 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1071 if (LocInfo.first.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001072 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001073 bool Invalid = false;
1074 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1075 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001076 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001077 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1078 if (!Line)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001079 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001080 StringRef Rest = Buffer.substr(Line - Buffer.data());
1081 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1082 return NumWhitespaceChars == StringRef::npos
1083 ? ""
1084 : Rest.take_front(NumWhitespaceChars);
1085}
1086
Chris Lattner22eb9722006-06-18 05:43:12 +00001087//===----------------------------------------------------------------------===//
1088// Diagnostics forwarding code.
1089//===----------------------------------------------------------------------===//
1090
Chris Lattner619c1742007-07-22 18:38:25 +00001091/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001092/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001093/// This is currently only used for _Pragma implementation, so it is the slow
1094/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001095static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1096 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001097static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1098 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001099 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001100 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner619c1742007-07-22 18:38:25 +00001102 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001103 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001104 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001105 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001107 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001108 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001109 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001110 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattner9dc9c202009-02-15 20:52:18 +00001112 // Figure out the expansion loc range, which is the range covered by the
1113 // original _Pragma(...) sequence.
1114 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001115 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001116
Chandler Carruth115b0772011-07-26 03:03:05 +00001117 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001118}
1119
Chris Lattner22eb9722006-06-18 05:43:12 +00001120/// getSourceLocation - Return a source location identifier for the specified
1121/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001122SourceLocation Lexer::getSourceLocation(const char *Loc,
1123 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001124 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001125 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001126
1127 // In the normal case, we're just lexing from a simple file buffer, return
1128 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001129 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001130 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001131 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Chris Lattnerd32480d2009-01-17 06:22:33 +00001133 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1134 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001135 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001136 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001137}
1138
Chris Lattner22eb9722006-06-18 05:43:12 +00001139/// Diag - Forwarding function for diagnostics. This translate a source
1140/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001141DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001142 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001143}
1144
1145//===----------------------------------------------------------------------===//
1146// Trigraph and Escaped Newline Handling Code.
1147//===----------------------------------------------------------------------===//
1148
1149/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1150/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1151static char GetTrigraphCharForLetter(char Letter) {
1152 switch (Letter) {
1153 default: return 0;
1154 case '=': return '#';
1155 case ')': return ']';
1156 case '(': return '[';
1157 case '!': return '|';
1158 case '\'': return '^';
1159 case '>': return '}';
1160 case '/': return '\\';
1161 case '<': return '{';
1162 case '-': return '~';
1163 }
1164}
1165
1166/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1167/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1168/// return the result character. Finally, emit a warning about trigraph use
1169/// whether trigraphs are enabled or not.
1170static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1171 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001172 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001173
David Blaikiebbafb8a2012-03-11 07:00:24 +00001174 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001175 if (!L->isLexingRawMode())
1176 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001177 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattner6d27a162008-11-22 02:02:22 +00001180 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001181 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001182 return Res;
1183}
1184
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001185/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1186/// 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 +00001187/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001188unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1189 unsigned Size = 0;
1190 while (isWhitespace(Ptr[Size])) {
1191 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001193 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1194 continue;
1195
1196 // If this is a \r\n or \n\r, skip the other half.
1197 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1198 Ptr[Size-1] != Ptr[Size])
1199 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001201 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001202 }
1203
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001204 // Not an escaped newline, must be a \t or something else.
1205 return 0;
1206}
1207
Chris Lattner38b2cde2009-04-18 22:27:02 +00001208/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1209/// them), skip over them and return the first non-escaped-newline found,
1210/// otherwise return P.
1211const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001212 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001213 const char *AfterEscape;
1214 if (*P == '\\') {
1215 AfterEscape = P+1;
1216 } else if (*P == '?') {
1217 // If not a trigraph for escape, bail out.
1218 if (P[1] != '?' || P[2] != '/')
1219 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001220 // FIXME: Take LangOpts into account; the language might not
1221 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001222 AfterEscape = P+3;
1223 } else {
1224 return P;
1225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
Chris Lattner38b2cde2009-04-18 22:27:02 +00001227 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1228 if (NewLineSize == 0) return P;
1229 P = AfterEscape+NewLineSize;
1230 }
1231}
1232
Alex Lorenzebbbb812017-11-03 18:11:22 +00001233Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1234 const SourceManager &SM,
1235 const LangOptions &LangOpts) {
Anna Zaks59a3c802011-07-27 21:43:43 +00001236 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001237 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Alex Lorenzebbbb812017-11-03 18:11:22 +00001238 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001239 }
1240 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1241
1242 // Break down the source location.
1243 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1244
1245 // Try to load the file buffer.
1246 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001247 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001248 if (InvalidTemp)
Alex Lorenzebbbb812017-11-03 18:11:22 +00001249 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001250
1251 const char *TokenBegin = File.data() + LocInfo.second;
1252
1253 // Lex from the start of the given location.
1254 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1255 TokenBegin, File.end());
1256 // Find the token.
1257 Token Tok;
1258 lexer.LexFromRawLexer(Tok);
Alex Lorenzebbbb812017-11-03 18:11:22 +00001259 return Tok;
1260}
1261
1262/// \brief Checks that the given token is the first token that occurs after the
1263/// given location (this excludes comments and whitespace). Returns the location
1264/// immediately after the specified token. If the token is not found or the
1265/// location is inside a macro, the returned source location will be invalid.
1266SourceLocation Lexer::findLocationAfterToken(
1267 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1268 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1269 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1270 if (!Tok || Tok->isNot(TKind))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001271 return {};
Alex Lorenzebbbb812017-11-03 18:11:22 +00001272 SourceLocation TokenLoc = Tok->getLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001273
1274 // Calculate how much whitespace needs to be skipped if any.
1275 unsigned NumWhitespaceChars = 0;
1276 if (SkipTrailingWhitespaceAndNewLine) {
Alex Lorenzebbbb812017-11-03 18:11:22 +00001277 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
Anna Zaks59a3c802011-07-27 21:43:43 +00001278 unsigned char C = *TokenEnd;
1279 while (isHorizontalWhitespace(C)) {
1280 C = *(++TokenEnd);
1281 NumWhitespaceChars++;
1282 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001283
1284 // Skip \r, \n, \r\n, or \n\r
1285 if (C == '\n' || C == '\r') {
1286 char PrevC = C;
1287 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001288 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001289 if ((C == '\n' || C == '\r') && C != PrevC)
1290 NumWhitespaceChars++;
1291 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001292 }
1293
Alex Lorenzebbbb812017-11-03 18:11:22 +00001294 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001295}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001296
Chris Lattner22eb9722006-06-18 05:43:12 +00001297/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1298/// get its size, and return it. This is tricky in several cases:
1299/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1300/// then either return the trigraph (skipping 3 chars) or the '?',
1301/// depending on whether trigraphs are enabled or not.
1302/// 2. If this is an escaped newline (potentially with whitespace between
1303/// the backslash and newline), implicitly skip the newline and return
1304/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001305///
1306/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1307/// know that we can accumulate into Size, and that we have already incremented
1308/// Ptr by Size bytes.
1309///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001310/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1311/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001312char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001313 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 // If we have a slash, look for an escaped newline.
1315 if (Ptr[0] == '\\') {
1316 ++Size;
1317 ++Ptr;
1318Slash:
1319 // Common case, backslash-char where the char is not whitespace.
1320 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattnerc1835952009-06-23 05:15:06 +00001322 // See if we have optional whitespace characters between the slash and
1323 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001324 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1325 // Remember that this token needs to be cleaned.
1326 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001327
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001328 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001329 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001330 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001332 // Found backslash<whitespace><newline>. Parse the char after it.
1333 Size += EscapedNewLineSize;
1334 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001335
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001336 // Use slow version to accumulate a correct size field.
1337 return getCharAndSizeSlow(Ptr, Size, Tok);
1338 }
Mike Stump11289f42009-09-09 15:08:12 +00001339
Chris Lattner22eb9722006-06-18 05:43:12 +00001340 // Otherwise, this is not an escaped newline, just return the slash.
1341 return '\\';
1342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 // If this is a trigraph, process it.
1345 if (Ptr[0] == '?' && Ptr[1] == '?') {
1346 // If this is actually a legal trigraph (not something like "??x"), emit
1347 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001348 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001350 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001351
1352 Ptr += 3;
1353 Size += 3;
1354 if (C == '\\') goto Slash;
1355 return C;
1356 }
1357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // If this is neither, return a single character.
1360 ++Size;
1361 return *Ptr;
1362}
1363
1364/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1365/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1366/// and that we have already incremented Ptr by Size bytes.
1367///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001368/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1369/// be updated to match.
1370char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001371 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001372 // If we have a slash, look for an escaped newline.
1373 if (Ptr[0] == '\\') {
1374 ++Size;
1375 ++Ptr;
1376Slash:
1377 // Common case, backslash-char where the char is not whitespace.
1378 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattner22eb9722006-06-18 05:43:12 +00001380 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001381 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1382 // Found backslash<whitespace><newline>. Parse the char after it.
1383 Size += EscapedNewLineSize;
1384 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001385
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001386 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001387 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattner22eb9722006-06-18 05:43:12 +00001390 // Otherwise, this is not an escaped newline, just return the slash.
1391 return '\\';
1392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Chris Lattner22eb9722006-06-18 05:43:12 +00001394 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001395 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001396 // If this is actually a legal trigraph (not something like "??x"), return
1397 // it.
1398 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1399 Ptr += 3;
1400 Size += 3;
1401 if (C == '\\') goto Slash;
1402 return C;
1403 }
1404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
Chris Lattner22eb9722006-06-18 05:43:12 +00001406 // If this is neither, return a single character.
1407 ++Size;
1408 return *Ptr;
1409}
1410
Chris Lattner22eb9722006-06-18 05:43:12 +00001411//===----------------------------------------------------------------------===//
1412// Helper methods for lexing.
1413//===----------------------------------------------------------------------===//
1414
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001415/// \brief Routine that indiscriminately sets the offset into the source file.
1416void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1417 BufferPtr = BufferStart + Offset;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001418 if (BufferPtr > BufferEnd)
1419 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001420 // FIXME: What exactly does the StartOfLine bit mean? There are two
1421 // possible meanings for the "start" of the line: the first token on the
1422 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001423 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001424 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001425}
1426
Jordan Rose58c61e02013-02-09 01:10:25 +00001427static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001428 if (LangOpts.AsmPreprocessor) {
1429 return false;
1430 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001431 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1432 C11AllowedIDCharRanges);
1433 return C11AllowedIDChars.contains(C);
1434 } else if (LangOpts.CPlusPlus) {
1435 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1436 CXX03AllowedIDCharRanges);
1437 return CXX03AllowedIDChars.contains(C);
1438 } else {
1439 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1440 C99AllowedIDCharRanges);
1441 return C99AllowedIDChars.contains(C);
1442 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001443}
1444
Jordan Rose58c61e02013-02-09 01:10:25 +00001445static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1446 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001447 if (LangOpts.AsmPreprocessor) {
1448 return false;
1449 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001450 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1451 C11DisallowedInitialIDCharRanges);
1452 return !C11DisallowedInitialIDChars.contains(C);
1453 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001454 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001455 } else {
1456 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1457 C99DisallowedInitialIDCharRanges);
1458 return !C99DisallowedInitialIDChars.contains(C);
1459 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001460}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001461
Jordan Rose58c61e02013-02-09 01:10:25 +00001462static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1463 const char *End) {
1464 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1465 L.getSourceLocation(End));
1466}
1467
1468static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1469 CharSourceRange Range, bool IsFirst) {
1470 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001471 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001472 enum {
1473 CannotAppearInIdentifier = 0,
1474 CannotStartIdentifier
1475 };
1476
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001477 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1478 C99AllowedIDCharRanges);
1479 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1480 C99DisallowedInitialIDCharRanges);
1481 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001482 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1483 << Range
1484 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001485 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001486 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1487 << Range
1488 << CannotStartIdentifier;
1489 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001490 }
1491
Jordan Rose58c61e02013-02-09 01:10:25 +00001492 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001493 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001494 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1495 CXX03AllowedIDCharRanges);
1496 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001497 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1498 << Range;
1499 }
1500 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001501}
1502
1503bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1504 Token &Result) {
1505 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001506 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001507 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1508 return false;
1509
1510 if (!isLexingRawMode())
1511 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1512 makeCharRange(*this, CurPtr, UCNPtr),
1513 /*IsFirst=*/false);
1514
1515 Result.setFlag(Token::HasUCN);
1516 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1517 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1518 CurPtr = UCNPtr;
1519 else
1520 while (CurPtr != UCNPtr)
1521 (void)getAndAdvanceChar(CurPtr, Result);
1522 return true;
1523}
1524
1525bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1526 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001527 llvm::UTF32 CodePoint;
1528 llvm::ConversionResult Result =
1529 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1530 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001531 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001532 llvm::strictConversion);
1533 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001534 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1535 return false;
1536
1537 if (!isLexingRawMode())
1538 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1539 makeCharRange(*this, CurPtr, UnicodePtr),
1540 /*IsFirst=*/false);
1541
1542 CurPtr = UnicodePtr;
1543 return true;
1544}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001545
Eli Friedman0834a4b2013-09-19 00:41:32 +00001546bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001547 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1548 unsigned Size;
1549 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001550 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001551 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001552
Chris Lattner22eb9722006-06-18 05:43:12 +00001553 --CurPtr; // Back up over the skipped character.
1554
1555 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1556 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001557 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001558 // TODO: Could merge these checks into an InfoTable flag to make the
1559 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001560 if (isASCII(C) && C != '\\' && C != '?' &&
1561 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001562FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001563 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001564 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1565 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner0f1f5052006-07-20 04:16:23 +00001567 // If we are in raw mode, return this identifier raw. There is no need to
1568 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001569 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001570 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001571
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001572 // Fill in Result.IdentifierInfo and update the token kind,
1573 // looking up the identifier in the identifier table.
1574 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattnerc5a00062006-06-18 16:41:01 +00001576 // Finally, now that we know we have an identifier, pass this off to the
1577 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001578 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001579 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001580
1581 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1582 && II->getPPKeywordID() == tok::pp_not_keyword
1583 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1584 // Return the code-completion token.
1585 Result.setKind(tok::code_completion);
1586 cutOffLexing();
1587 return true;
1588 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001589 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
Chris Lattner22eb9722006-06-18 05:43:12 +00001592 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001593
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001595 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001596 if (C == '$') {
1597 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattner22eb9722006-06-18 05:43:12 +00001600 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001601 if (!isLexingRawMode())
1602 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001603 CurPtr = ConsumeChar(CurPtr, Size, Result);
1604 C = getCharAndSize(CurPtr, Size);
1605 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001606 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001607 C = getCharAndSize(CurPtr, Size);
1608 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001609 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001610 C = getCharAndSize(CurPtr, Size);
1611 continue;
1612 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001613 goto FinishIdentifier;
1614 }
1615
1616 // Otherwise, this character is good, consume it.
1617 CurPtr = ConsumeChar(CurPtr, Size, Result);
1618
1619 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001620 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001621 CurPtr = ConsumeChar(CurPtr, Size, Result);
1622 C = getCharAndSize(CurPtr, Size);
1623 }
1624 }
1625}
1626
Douglas Gregor759ef232010-08-30 14:50:47 +00001627/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001628/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001629bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001630 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001631 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001632 if (C1 != '0')
1633 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001634 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001635 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001636}
Chris Lattner22eb9722006-06-18 05:43:12 +00001637
Nate Begeman5eee9332008-04-14 02:26:39 +00001638/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001639/// constant. From[-1] is the first character lexed. Return the end of the
1640/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001641bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001642 unsigned Size;
1643 char C = getCharAndSize(CurPtr, Size);
1644 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001645 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001646 CurPtr = ConsumeChar(CurPtr, Size, Result);
1647 PrevCh = C;
1648 C = getCharAndSize(CurPtr, Size);
1649 }
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattner22eb9722006-06-18 05:43:12 +00001651 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001652 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1653 // If we are in Microsoft mode, don't continue if the constant is hex.
1654 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001655 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001656 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1657 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001658
1659 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001660 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001661 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001662 // not-quite-conforming extension. Only do so if this looks like it's
1663 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1664 bool IsHexFloat = true;
1665 if (!LangOpts.C99) {
1666 if (!isHexaLiteral(BufferPtr, LangOpts))
1667 IsHexFloat = false;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001668 else if (!getLangOpts().CPlusPlus17 &&
Richard Smith560a3572016-03-04 22:32:06 +00001669 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001670 IsHexFloat = false;
1671 }
1672 if (IsHexFloat)
1673 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1674 }
Mike Stump11289f42009-09-09 15:08:12 +00001675
Richard Smithfde94852013-09-26 03:33:06 +00001676 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001677 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001678 unsigned NextSize;
1679 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001680 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001681 if (!isLexingRawMode())
1682 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1683 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001684 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001685 return LexNumericConstant(Result, CurPtr);
1686 }
1687 }
1688
Richard Smith8b7258b2014-02-17 21:52:30 +00001689 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1690 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1691 return LexNumericConstant(Result, CurPtr);
1692 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1693 return LexNumericConstant(Result, CurPtr);
1694
Chris Lattnerd01e2912006-06-18 16:22:51 +00001695 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001696 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001697 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001698 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001699 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001700}
1701
Richard Smithe18f0fa2012-03-05 04:02:15 +00001702/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001703/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001704const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1705 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001706 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001707
Richard Smith8b7258b2014-02-17 21:52:30 +00001708 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001709 unsigned Size;
1710 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001711 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001712
Richard Smith8b7258b2014-02-17 21:52:30 +00001713 if (!isIdentifierHead(C)) {
1714 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1715 Consumed = true;
1716 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1717 Consumed = true;
1718 else
1719 return CurPtr;
1720 }
1721
1722 if (!getLangOpts().CPlusPlus11) {
1723 if (!isLexingRawMode())
1724 Diag(CurPtr,
1725 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1726 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1727 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1728 return CurPtr;
1729 }
1730
1731 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1732 // that does not start with an underscore is ill-formed. As a conforming
1733 // extension, we treat all such suffixes as if they had whitespace before
1734 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1735 // likely to be a ud-suffix than a macro, however, and accept that.
1736 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001737 bool IsUDSuffix = false;
1738 if (C == '_')
1739 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001740 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001741 // In C++1y, we need to look ahead a few characters to see if this is a
1742 // valid suffix for a string literal or a numeric literal (this could be
1743 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001744 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001745 char Buffer[MaxStandardSuffixLength] = { C };
1746 unsigned Consumed = Size;
1747 unsigned Chars = 1;
1748 while (true) {
1749 unsigned NextSize;
1750 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1751 getLangOpts());
1752 if (!isIdentifierBody(Next)) {
1753 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001754 const StringRef CompleteSuffix(Buffer, Chars);
1755 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1756 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001757 break;
1758 }
1759
1760 if (Chars == MaxStandardSuffixLength)
1761 // Too long: can't be a standard suffix.
1762 break;
1763
1764 Buffer[Chars++] = Next;
1765 Consumed += NextSize;
1766 }
Richard Smithf4198b72013-07-23 08:14:48 +00001767 }
1768
1769 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001770 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001771 Diag(CurPtr, getLangOpts().MSVCCompat
1772 ? diag::ext_ms_reserved_user_defined_literal
1773 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001774 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001775 return CurPtr;
1776 }
1777
Richard Smith8b7258b2014-02-17 21:52:30 +00001778 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001779 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001780
1781 Result.setFlag(Token::HasUDSuffix);
1782 while (true) {
1783 C = getCharAndSize(CurPtr, Size);
1784 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1785 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1786 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1787 else break;
1788 }
1789
Richard Smithe18f0fa2012-03-05 04:02:15 +00001790 return CurPtr;
1791}
1792
Chris Lattner22eb9722006-06-18 05:43:12 +00001793/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001794/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001795bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001796 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001797 // Does this string contain the \0 character?
1798 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001799
Richard Smithacd4d3d2011-10-15 01:18:56 +00001800 if (!isLexingRawMode() &&
1801 (Kind == tok::utf8_string_literal ||
1802 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001803 Kind == tok::utf32_string_literal))
1804 Diag(BufferPtr, getLangOpts().CPlusPlus
1805 ? diag::warn_cxx98_compat_unicode_literal
1806 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001807
Chris Lattner22eb9722006-06-18 05:43:12 +00001808 char C = getAndAdvanceChar(CurPtr, Result);
1809 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001810 // Skip escaped characters. Escaped newlines will already be processed by
1811 // getAndAdvanceChar.
1812 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001813 C = getAndAdvanceChar(CurPtr, Result);
Taewook Ohcebac482017-12-06 17:00:53 +00001814
Chris Lattner52d96ac2010-05-30 23:27:38 +00001815 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001816 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001818 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001819 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001820 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001821 }
Taewook Ohcebac482017-12-06 17:00:53 +00001822
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001823 if (C == 0) {
1824 if (isCodeCompletionPoint(CurPtr-1)) {
1825 PP->CodeCompleteNaturalLanguage();
1826 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001827 cutOffLexing();
1828 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001829 }
1830
Chris Lattner52d96ac2010-05-30 23:27:38 +00001831 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001832 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001833 C = getAndAdvanceChar(CurPtr, Result);
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Richard Smithe18f0fa2012-03-05 04:02:15 +00001836 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001837 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001838 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001839
Chris Lattner5a78a022006-07-20 06:02:19 +00001840 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001841 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001842 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001843
Chris Lattnerd01e2912006-06-18 16:22:51 +00001844 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001845 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001846 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001847 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001848 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001849}
1850
Craig Topper54edcca2011-08-11 04:06:15 +00001851/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1852/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001853bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001854 tok::TokenKind Kind) {
1855 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1856 // Between the initial and final double quote characters of the raw string,
1857 // any transformations performed in phases 1 and 2 (trigraphs,
1858 // universal-character-names, and line splicing) are reverted.
1859
Richard Smithacd4d3d2011-10-15 01:18:56 +00001860 if (!isLexingRawMode())
1861 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1862
Craig Topper54edcca2011-08-11 04:06:15 +00001863 unsigned PrefixLen = 0;
1864
1865 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1866 ++PrefixLen;
1867
1868 // If the last character was not a '(', then we didn't lex a valid delimiter.
1869 if (CurPtr[PrefixLen] != '(') {
1870 if (!isLexingRawMode()) {
1871 const char *PrefixEnd = &CurPtr[PrefixLen];
1872 if (PrefixLen == 16) {
1873 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1874 } else {
1875 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1876 << StringRef(PrefixEnd, 1);
1877 }
1878 }
1879
1880 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1881 // it's possible the '"' was intended to be part of the raw string, but
1882 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001883 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001884 char C = *CurPtr++;
1885
1886 if (C == '"')
1887 break;
1888 if (C == 0 && CurPtr-1 == BufferEnd) {
1889 --CurPtr;
1890 break;
1891 }
1892 }
1893
1894 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001895 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001896 }
1897
1898 // Save prefix and move CurPtr past it
1899 const char *Prefix = CurPtr;
1900 CurPtr += PrefixLen + 1; // skip over prefix and '('
1901
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001902 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001903 char C = *CurPtr++;
1904
1905 if (C == ')') {
1906 // Check for prefix match and closing quote.
1907 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1908 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1909 break;
1910 }
1911 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1912 if (!isLexingRawMode())
1913 Diag(BufferPtr, diag::err_unterminated_raw_string)
1914 << StringRef(Prefix, PrefixLen);
1915 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001916 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001917 }
1918 }
1919
Richard Smithe18f0fa2012-03-05 04:02:15 +00001920 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001921 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001922 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001923
Craig Topper54edcca2011-08-11 04:06:15 +00001924 // Update the location of token as well as BufferPtr.
1925 const char *TokStart = BufferPtr;
1926 FormTokenWithChars(Result, CurPtr, Kind);
1927 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001928 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001929}
1930
Chris Lattner22eb9722006-06-18 05:43:12 +00001931/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1932/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001933bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001934 // Does this string contain the \0 character?
1935 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001936 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001937 char C = getAndAdvanceChar(CurPtr, Result);
1938 while (C != '>') {
1939 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001940 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001941 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001942 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001944 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1945 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001946 // If the filename is unterminated, then it must just be a lone <
1947 // character. Return this as such.
1948 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001949 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 } else if (C == 0) {
1951 NulCharacter = CurPtr-1;
1952 }
1953 C = getAndAdvanceChar(CurPtr, Result);
1954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattner5a78a022006-07-20 06:02:19 +00001956 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001957 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001958 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001959
Chris Lattnerd01e2912006-06-18 16:22:51 +00001960 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001961 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001962 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001963 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001964 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001965}
1966
Chris Lattner22eb9722006-06-18 05:43:12 +00001967/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001968/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001969bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001970 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001971 // Does this character contain the \0 character?
1972 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001973
Richard Smith3e3a7052014-11-08 06:08:42 +00001974 if (!isLexingRawMode()) {
1975 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1976 Diag(BufferPtr, getLangOpts().CPlusPlus
1977 ? diag::warn_cxx98_compat_unicode_literal
1978 : diag::warn_c99_compat_unicode_literal);
1979 else if (Kind == tok::utf8_char_constant)
1980 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1981 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001982
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 char C = getAndAdvanceChar(CurPtr, Result);
1984 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001985 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001986 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001987 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001988 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001989 }
1990
1991 while (C != '\'') {
1992 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001993 if (C == '\\')
1994 C = getAndAdvanceChar(CurPtr, Result);
1995
1996 if (C == '\n' || C == '\r' || // Newline.
1997 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001998 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001999 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00002000 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002001 return true;
Nico Weber4e270382012-11-17 20:25:54 +00002002 }
2003
2004 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002005 if (isCodeCompletionPoint(CurPtr-1)) {
2006 PP->CodeCompleteNaturalLanguage();
2007 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002008 cutOffLexing();
2009 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002010 }
2011
Chris Lattner86851b82010-07-07 23:24:27 +00002012 NulCharacter = CurPtr-1;
2013 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 C = getAndAdvanceChar(CurPtr, Result);
2015 }
Mike Stump11289f42009-09-09 15:08:12 +00002016
Richard Smithe18f0fa2012-03-05 04:02:15 +00002017 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002019 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002020
Chris Lattner86851b82010-07-07 23:24:27 +00002021 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002022 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002023 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002024
Chris Lattnerd01e2912006-06-18 16:22:51 +00002025 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002026 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002027 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002028 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002029 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002030}
2031
2032/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2033/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002034///
2035/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002036bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2037 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002038 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002039 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2040
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002041 unsigned char Char = *CurPtr;
2042
2043 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002044 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002045 // Skip horizontal whitespace very aggressively.
2046 while (isHorizontalWhitespace(Char))
2047 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002048
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002049 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002050 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002051 break;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 if (ParsingPreprocessorDirective) {
2054 // End of preprocessor directive line, let LexTokenInternal handle this.
2055 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002056 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002059 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002060 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 Char = *++CurPtr;
2062 }
2063
Chris Lattner4d963442008-10-12 04:05:48 +00002064 // If the client wants us to return whitespace, return it now.
2065 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002066 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002067 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002068 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002069 IsAtPhysicalStartOfLine = true;
2070 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002071 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002072 return true;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002075 // If this isn't immediately after a newline, there is leading space.
2076 char PrevChar = CurPtr[-1];
2077 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2078
2079 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002080 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002081 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002082 TokAtPhysicalStartOfLine = true;
2083 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002084
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002086 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002087}
2088
Nico Weber158a31a2012-11-11 07:02:14 +00002089/// We have just read the // characters from input. Skip until we find the
2090/// newline character thats terminate the comment. Then update BufferPtr and
2091/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002092///
2093/// If we're in KeepCommentMode or any CommentHandler has inserted
2094/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002095bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2096 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002097 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002099 if (!LangOpts.LineComment && !isLexingRawMode()) {
2100 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002101
Chris Lattner22eb9722006-06-18 05:43:12 +00002102 // Mark them enabled so we only emit one warning for this translation
2103 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002104 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner22eb9722006-06-18 05:43:12 +00002107 // Scan over the body of the comment. The common case, when scanning, is that
2108 // the comment contains normal ascii characters with nothing interesting in
2109 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002110 //
2111 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2112 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002114 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 // Skip over characters in the fast loop.
2117 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002118 C != '\n' && C != '\r') // Newline or DOS-style newline.
2119 C = *++CurPtr;
2120
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002121 const char *NextLine = CurPtr;
2122 if (C != 0) {
2123 // We found a newline, see if it's escaped.
2124 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002125 bool HasSpace = false;
2126 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002127 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002128 HasSpace = true;
2129 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002130
Richard Smith4c132e52017-04-18 21:45:04 +00002131 if (*EscapePtr == '\\')
2132 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002133 CurPtr = EscapePtr;
2134 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002135 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2136 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002137 CurPtr = EscapePtr-2;
2138 else
2139 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002140
2141 // If there was space between the backslash and newline, warn about it.
2142 if (HasSpace && !isLexingRawMode())
2143 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner22eb9722006-06-18 05:43:12 +00002146 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002147 // properly decode the character. Read it in raw mode to avoid emitting
2148 // diagnostics about things like trigraphs. If we see an escaped newline,
2149 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002150 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002151 bool OldRawMode = isLexingRawMode();
2152 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002153 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002154 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002155
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002156 // If we only read only one character, then no special handling is needed.
2157 // We're done and can skip forward to the newline.
2158 if (C != 0 && CurPtr == OldPtr+1) {
2159 CurPtr = NextLine;
2160 break;
2161 }
2162
Chris Lattner22eb9722006-06-18 05:43:12 +00002163 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002164 // \n, then we had an escaped newline within the comment. Emit diagnostic
2165 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002166 if (CurPtr != OldPtr + 1 && C != '/' &&
2167 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 for (; OldPtr != CurPtr; ++OldPtr)
2169 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002170 // Okay, we found a // comment that ends in a newline, if the next
2171 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002172 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002173 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002174 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002175 ++ForwardPtr;
2176 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2177 break;
2178 }
Mike Stump11289f42009-09-09 15:08:12 +00002179
Chris Lattner6d27a162008-11-22 02:02:22 +00002180 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002181 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002182 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 }
2184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Richard Smith1d2ae942017-04-17 23:44:51 +00002186 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2187 --CurPtr;
2188 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002189 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002190
2191 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2192 PP->CodeCompleteNaturalLanguage();
2193 cutOffLexing();
2194 return false;
2195 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002196 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002197
Chris Lattner93ddf802010-02-03 21:06:21 +00002198 // Found but did not consume the newline. Notify comment handlers about the
2199 // comment unless we're in a #if 0 block.
2200 if (PP && !isLexingRawMode() &&
2201 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2202 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002203 BufferPtr = CurPtr;
2204 return true; // A token has to be returned.
2205 }
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattner457fc152006-07-29 06:30:25 +00002207 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002208 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002209 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002210
2211 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002212 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002213 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002214 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002215 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
Chris Lattner22eb9722006-06-18 05:43:12 +00002218 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002219 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002220 // contribute to another token), it isn't needed for correctness. Note that
2221 // this is ok even in KeepWhitespaceMode, because we would have returned the
2222 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattner22eb9722006-06-18 05:43:12 +00002225 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002226 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002227 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002228 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002229 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002230 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002231 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002232}
Chris Lattner22eb9722006-06-18 05:43:12 +00002233
Nico Weber158a31a2012-11-11 07:02:14 +00002234/// If in save-comment mode, package up this Line comment in an appropriate
2235/// way and return it.
2236bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002237 // If we're not in a preprocessor directive, just return the // comment
2238 // directly.
2239 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002240
David Blaikied5321242012-06-06 18:52:13 +00002241 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002242 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002243
Nico Weber158a31a2012-11-11 07:02:14 +00002244 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002245 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002246 bool Invalid = false;
2247 std::string Spelling = PP->getSpelling(Result, &Invalid);
2248 if (Invalid)
2249 return true;
Taewook Ohcebac482017-12-06 17:00:53 +00002250
Nico Weber158a31a2012-11-11 07:02:14 +00002251 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002252 Spelling[1] = '*'; // Change prefix to "/*".
2253 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002254
Chris Lattnerb11c3232008-10-12 04:51:35 +00002255 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002256 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002257 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002258 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002259}
2260
Chris Lattnercb283342006-06-18 06:48:37 +00002261/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002262/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2263/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002264static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002265 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002266 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattner22eb9722006-06-18 05:43:12 +00002268 // Back up off the newline.
2269 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chris Lattner22eb9722006-06-18 05:43:12 +00002271 // If this is a two-character newline sequence, skip the other character.
2272 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2273 // \n\n or \r\r -> not escaped newline.
2274 if (CurPtr[0] == CurPtr[1])
2275 return false;
2276 // \n\r or \r\n -> skip the newline.
2277 --CurPtr;
2278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattner22eb9722006-06-18 05:43:12 +00002280 // If we have horizontal whitespace, skip over it. We allow whitespace
2281 // between the slash and newline.
2282 bool HasSpace = false;
2283 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2284 --CurPtr;
2285 HasSpace = true;
2286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattner22eb9722006-06-18 05:43:12 +00002288 // If we have a slash, we know this is an escaped newline.
2289 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002290 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002291 } else {
2292 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002293 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2294 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002295 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnercb283342006-06-18 06:48:37 +00002297 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002298 CurPtr -= 2;
2299
2300 // If no trigraphs are enabled, warn that we ignored this trigraph and
2301 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002302 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002303 if (!L->isLexingRawMode())
2304 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002305 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002307 if (!L->isLexingRawMode())
2308 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner22eb9722006-06-18 05:43:12 +00002311 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002312 if (!L->isLexingRawMode())
2313 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattner22eb9722006-06-18 05:43:12 +00002315 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002316 if (HasSpace && !L->isLexingRawMode())
2317 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Chris Lattnercb283342006-06-18 06:48:37 +00002319 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002320}
2321
Chris Lattneraded4a92006-10-27 04:42:31 +00002322#ifdef __SSE2__
2323#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002324#elif __ALTIVEC__
2325#include <altivec.h>
2326#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002327#endif
2328
James Dennettf442d242012-06-17 03:40:43 +00002329/// We have just read from input the / and * characters that started a comment.
2330/// Read until we find the * and / characters that terminate the comment.
2331/// Note that we don't bother decoding trigraphs or escaped newlines in block
2332/// comments, because they cannot cause the comment to end. The only thing
2333/// that can happen is the comment could end with an escaped newline between
2334/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002335///
Chris Lattner87d02082010-01-18 22:35:47 +00002336/// If we're in KeepCommentMode or any CommentHandler has inserted
2337/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002338bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2339 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002340 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002341 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002342 // optimization helps people who like to put a lot of * characters in their
2343 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002344
2345 // The first character we get with newlines and trigraphs skipped to handle
2346 // the degenerate /*/ case below correctly if the * has an escaped newline
2347 // after it.
2348 unsigned CharSize;
2349 unsigned char C = getCharAndSize(CurPtr, CharSize);
2350 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002351 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002352 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002353 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002354 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002355
Chris Lattner99e7d232008-10-12 04:19:49 +00002356 // KeepWhitespaceMode should return this broken comment as a token. Since
2357 // it isn't a well formed comment, just return it as an 'unknown' token.
2358 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002359 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002360 return true;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner99e7d232008-10-12 04:19:49 +00002363 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002364 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002365 }
Mike Stump11289f42009-09-09 15:08:12 +00002366
Chris Lattnerc850ad62007-07-21 23:43:37 +00002367 // Check to see if the first character after the '/*' is another /. If so,
2368 // then this slash does not end the block comment, it is part of it.
2369 if (C == '/')
2370 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002371
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002372 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002373 // Skip over all non-interesting characters until we find end of buffer or a
2374 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002375 if (CurPtr + 24 < BufferEnd &&
2376 // If there is a code-completion point avoid the fast scan because it
2377 // doesn't check for '\0'.
2378 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002379 // While not aligned to a 16-byte boundary.
2380 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2381 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Chris Lattner6cc3e362006-10-27 04:12:35 +00002383 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002384
2385#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002386 __m128i Slashes = _mm_set1_epi8('/');
2387 while (CurPtr+16 <= BufferEnd) {
2388 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2389 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002390 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002391 // Adjust the pointer to point directly after the first slash. It's
2392 // not necessary to set C here, it will be overwritten at the end of
2393 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002394 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002395 goto FoundSlash;
2396 }
Roman Divacky61509902014-04-03 18:04:52 +00002397 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002398 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002399#elif __ALTIVEC__
2400 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002401 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002402 '/', '/', '/', '/', '/', '/', '/', '/'
2403 };
2404 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002405 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002406 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002407#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002408 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002409 while (CurPtr[0] != '/' &&
2410 CurPtr[1] != '/' &&
2411 CurPtr[2] != '/' &&
2412 CurPtr[3] != '/' &&
2413 CurPtr+4 < BufferEnd) {
2414 CurPtr += 4;
2415 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002416#endif
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattneraded4a92006-10-27 04:42:31 +00002418 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002419 C = *CurPtr++;
2420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Chris Lattneraded4a92006-10-27 04:42:31 +00002422 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002423 while (C != '/' && C != '\0')
2424 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002425
Chris Lattner22eb9722006-06-18 05:43:12 +00002426 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002427 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002428 if (CurPtr[-2] == '*') // We found the final */. We're done!
2429 break;
Mike Stump11289f42009-09-09 15:08:12 +00002430
Chris Lattner22eb9722006-06-18 05:43:12 +00002431 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002432 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002433 // We found the final */, though it had an escaped newline between the
2434 // * and /. We're done!
2435 break;
2436 }
2437 }
2438 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2439 // If this is a /* inside of the comment, emit a warning. Don't do this
2440 // if this is a /*/, which will end the comment. This misses cases with
2441 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002442 if (!isLexingRawMode())
2443 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002444 }
2445 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002446 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002447 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002448 // Note: the user probably forgot a */. We could continue immediately
2449 // after the /*, but this would involve lexing a lot of what really is the
2450 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002451 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002452
Chris Lattner99e7d232008-10-12 04:19:49 +00002453 // KeepWhitespaceMode should return this broken comment as a token. Since
2454 // it isn't a well formed comment, just return it as an 'unknown' token.
2455 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002456 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002457 return true;
2458 }
Mike Stump11289f42009-09-09 15:08:12 +00002459
Chris Lattner99e7d232008-10-12 04:19:49 +00002460 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002461 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002462 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2463 PP->CodeCompleteNaturalLanguage();
2464 cutOffLexing();
2465 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002466 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002467
Chris Lattner22eb9722006-06-18 05:43:12 +00002468 C = *CurPtr++;
2469 }
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattner93ddf802010-02-03 21:06:21 +00002471 // Notify comment handlers about the comment unless we're in a #if 0 block.
2472 if (PP && !isLexingRawMode() &&
2473 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2474 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002475 BufferPtr = CurPtr;
2476 return true; // A token has to be returned.
2477 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002478
Chris Lattner457fc152006-07-29 06:30:25 +00002479 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002480 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002481 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002482 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002483 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002484
2485 // It is common for the tokens immediately after a /**/ comment to be
2486 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002487 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2488 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002489 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002490 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002491 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002492 }
2493
2494 // Otherwise, just return so that the next character will be lexed as a token.
2495 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002496 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002497 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002498}
2499
2500//===----------------------------------------------------------------------===//
2501// Primary Lexing Entry Points
2502//===----------------------------------------------------------------------===//
2503
Chris Lattner22eb9722006-06-18 05:43:12 +00002504/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2505/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002506void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002507 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2508 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002509 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002510
2511 // CurPtr - Cache BufferPtr in an automatic variable.
2512 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002513 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002514 char Char = getAndAdvanceChar(CurPtr, Tmp);
2515 switch (Char) {
2516 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002517 if (Result)
2518 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002519 break;
2520 case 0: // Null.
2521 // Found end of file?
2522 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002523 if (isCodeCompletionPoint(CurPtr-1)) {
2524 PP->CodeCompleteNaturalLanguage();
2525 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002526 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002527 }
2528
Chris Lattner22eb9722006-06-18 05:43:12 +00002529 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002530 if (Result)
2531 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002532 break;
2533 }
2534 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002535 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002536 case '\r':
2537 case '\n':
2538 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2539 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2540 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002541
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002542 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002543 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002544 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002545 if (PP)
2546 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002547 Lex(Tmp);
2548 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002549 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002550
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002551 // Finally, we're done;
2552 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002553 }
2554 }
2555}
2556
2557/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2558/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002559/// This returns true if Result contains a token, false if PP.Lex should be
2560/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002561bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002562 // If we hit the end of the file while parsing a preprocessor directive,
2563 // end the preprocessor directive first. The next token returned will
2564 // then be the end of file.
2565 if (ParsingPreprocessorDirective) {
2566 // Done parsing the "line".
2567 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002568 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002569 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner457fc152006-07-29 06:30:25 +00002571 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002572 if (PP)
2573 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002574 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002575 }
Taewook Ohcebac482017-12-06 17:00:53 +00002576
Chris Lattner30a2fa12006-07-19 06:31:49 +00002577 // If we are in raw mode, return this event as an EOF token. Let the caller
2578 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002579 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002580 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002581 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002582 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002583 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002584 }
Taewook Ohcebac482017-12-06 17:00:53 +00002585
Erik Verbruggen795eee92017-07-05 09:44:07 +00002586 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002587 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2588 ConditionalStack.clear();
2589 }
2590
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002591 // Issue diagnostics for unterminated #if and missing newline.
2592
Chris Lattner30a2fa12006-07-19 06:31:49 +00002593 // If we are in a #if directive, emit an error.
2594 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002595 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002596 PP->Diag(ConditionalStack.back().IfLoc,
2597 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002598 ConditionalStack.pop_back();
2599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Chris Lattner8f96d042008-04-12 05:54:25 +00002601 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2602 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002603 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2604 DiagnosticsEngine &Diags = PP->getDiagnostics();
2605 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2606 unsigned DiagID;
2607
2608 if (LangOpts.CPlusPlus11) {
2609 // C++11 [lex.phases] 2.2 p2
2610 // Prefer the C++98 pedantic compatibility warning over the generic,
2611 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002612 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002613 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2614 } else {
2615 DiagID = diag::warn_no_newline_eof;
2616 }
2617 } else {
2618 DiagID = diag::ext_no_newline_eof;
2619 }
2620
2621 Diag(BufferEnd, DiagID)
2622 << FixItHint::CreateInsertion(EndLoc, "\n");
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattner22eb9722006-06-18 05:43:12 +00002625 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002626
2627 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002628 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002629}
2630
Chris Lattner678c8802006-07-11 05:46:12 +00002631/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2632/// the specified lexer will return a tok::l_paren token, 0 if it is something
2633/// else and 2 if there are no more tokens in the buffer controlled by the
2634/// lexer.
2635unsigned Lexer::isNextPPTokenLParen() {
2636 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002637
Chris Lattner678c8802006-07-11 05:46:12 +00002638 // Switch to 'skipping' mode. This will ensure that we can lex a token
2639 // without emitting diagnostics, disables macro expansion, and will cause EOF
2640 // to return an EOF token instead of popping the include stack.
2641 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002642
Chris Lattner678c8802006-07-11 05:46:12 +00002643 // Save state that can be changed while lexing so that we can restore it.
2644 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002645 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002646 bool atStartOfLine = IsAtStartOfLine;
2647 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2648 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002649
Chris Lattner146762e2007-07-20 16:59:19 +00002650 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002651 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002652
Chris Lattner678c8802006-07-11 05:46:12 +00002653 // Restore state that may have changed.
2654 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002655 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002656 HasLeadingSpace = leadingSpace;
2657 IsAtStartOfLine = atStartOfLine;
2658 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Chris Lattner678c8802006-07-11 05:46:12 +00002660 // Restore the lexer back to non-skipping mode.
2661 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002662
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002663 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002664 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002665 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002666}
2667
James Dennettf442d242012-06-17 03:40:43 +00002668/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002669static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2670 ConflictMarkerKind CMK) {
2671 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2672 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002673 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002674 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002675 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002676 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002677 if (Pos == 0 ||
2678 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002679 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2680 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002681 continue;
2682 }
2683 return RestOfBuffer.data()+Pos;
2684 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002685 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002686}
2687
2688/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2689/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2690/// and recover nicely. This returns true if it is a conflict marker and false
2691/// if not.
2692bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2693 // Only a conflict marker if it starts at the beginning of a line.
2694 if (CurPtr != BufferStart &&
2695 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2696 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002697
Richard Smitha9e33d42011-10-12 00:37:51 +00002698 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002699 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2700 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002701 return false;
2702
2703 // If we have a situation where we don't care about conflict markers, ignore
2704 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002705 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002706 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002707
Richard Smitha9e33d42011-10-12 00:37:51 +00002708 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2709
2710 // Check to see if there is an ending marker somewhere in the buffer at the
2711 // start of a line to terminate this conflict marker.
2712 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002713 // We found a match. We are really in a conflict marker.
2714 // Diagnose this, and ignore to the end of line.
2715 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002716 CurrentConflictMarkerState = Kind;
Taewook Ohcebac482017-12-06 17:00:53 +00002717
Chris Lattner7c027ee2009-12-14 06:16:57 +00002718 // Skip ahead to the end of line. We know this exists because the
2719 // end-of-conflict marker starts with \r or \n.
2720 while (*CurPtr != '\r' && *CurPtr != '\n') {
2721 assert(CurPtr != BufferEnd && "Didn't find end of line");
2722 ++CurPtr;
2723 }
2724 BufferPtr = CurPtr;
2725 return true;
2726 }
Taewook Ohcebac482017-12-06 17:00:53 +00002727
Chris Lattner7c027ee2009-12-14 06:16:57 +00002728 // No end of conflict marker found.
2729 return false;
2730}
2731
Richard Smitha9e33d42011-10-12 00:37:51 +00002732/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2733/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2734/// is the end of a conflict marker. Handle it by ignoring up until the end of
2735/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002736bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2737 // Only a conflict marker if it starts at the beginning of a line.
2738 if (CurPtr != BufferStart &&
2739 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2740 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002741
Chris Lattner7c027ee2009-12-14 06:16:57 +00002742 // If we have a situation where we don't care about conflict markers, ignore
2743 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002744 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002745 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002746
Richard Smitha9e33d42011-10-12 00:37:51 +00002747 // Check to see if we have the marker (4 characters in a row).
2748 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002749 if (CurPtr[i] != CurPtr[0])
2750 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002751
Chris Lattner7c027ee2009-12-14 06:16:57 +00002752 // If we do have it, search for the end of the conflict marker. This could
2753 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2754 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002755 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2756 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002757 CurPtr = End;
Taewook Ohcebac482017-12-06 17:00:53 +00002758
Chris Lattner7c027ee2009-12-14 06:16:57 +00002759 // Skip ahead to the end of line.
2760 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2761 ++CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002762
Chris Lattner7c027ee2009-12-14 06:16:57 +00002763 BufferPtr = CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002764
Chris Lattner7c027ee2009-12-14 06:16:57 +00002765 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002766 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002767 return true;
2768 }
Taewook Ohcebac482017-12-06 17:00:53 +00002769
Chris Lattner7c027ee2009-12-14 06:16:57 +00002770 return false;
2771}
2772
Alex Lorenz1be800c52017-04-19 08:58:56 +00002773static const char *findPlaceholderEnd(const char *CurPtr,
2774 const char *BufferEnd) {
2775 if (CurPtr == BufferEnd)
2776 return nullptr;
2777 BufferEnd -= 1; // Scan until the second last character.
2778 for (; CurPtr != BufferEnd; ++CurPtr) {
2779 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2780 return CurPtr + 2;
2781 }
2782 return nullptr;
2783}
2784
2785bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2786 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002787 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002788 return false;
2789 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2790 if (!End)
2791 return false;
2792 const char *Start = CurPtr - 1;
2793 if (!LangOpts.AllowEditorPlaceholders)
2794 Diag(Start, diag::err_placeholder_in_source);
2795 Result.startToken();
2796 FormTokenWithChars(Result, End, tok::raw_identifier);
2797 Result.setRawIdentifierData(Start);
2798 PP->LookUpIdentifierInfo(Result);
2799 Result.setFlag(Token::IsEditorPlaceholder);
2800 BufferPtr = End;
2801 return true;
2802}
2803
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002804bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2805 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002806 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002807 return Loc == PP->getCodeCompletionLoc();
2808 }
2809
2810 return false;
2811}
2812
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002813uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2814 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002815 unsigned CharSize;
2816 char Kind = getCharAndSize(StartPtr, CharSize);
2817
2818 unsigned NumHexDigits;
2819 if (Kind == 'u')
2820 NumHexDigits = 4;
2821 else if (Kind == 'U')
2822 NumHexDigits = 8;
2823 else
2824 return 0;
2825
Jordan Rosec0cba272013-01-27 20:12:04 +00002826 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002827 if (Result && !isLexingRawMode())
2828 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002829 return 0;
2830 }
2831
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002832 const char *CurPtr = StartPtr + CharSize;
2833 const char *KindLoc = &CurPtr[-1];
2834
2835 uint32_t CodePoint = 0;
2836 for (unsigned i = 0; i < NumHexDigits; ++i) {
2837 char C = getCharAndSize(CurPtr, CharSize);
2838
2839 unsigned Value = llvm::hexDigitValue(C);
2840 if (Value == -1U) {
2841 if (Result && !isLexingRawMode()) {
2842 if (i == 0) {
2843 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2844 << StringRef(KindLoc, 1);
2845 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002846 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002847
2848 // If the user wrote \U1234, suggest a fixit to \u.
2849 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002850 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002851 Diag(KindLoc, diag::note_ucn_four_not_eight)
2852 << FixItHint::CreateReplacement(URange, "u");
2853 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002854 }
2855 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002856
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002857 return 0;
2858 }
2859
2860 CodePoint <<= 4;
2861 CodePoint += Value;
2862
2863 CurPtr += CharSize;
2864 }
2865
2866 if (Result) {
2867 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002868 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002869 StartPtr = CurPtr;
2870 else
2871 while (StartPtr != CurPtr)
2872 (void)getAndAdvanceChar(StartPtr, *Result);
2873 } else {
2874 StartPtr = CurPtr;
2875 }
2876
Justin Bogner53535132013-10-21 05:02:28 +00002877 // Don't apply C family restrictions to UCNs in assembly mode
2878 if (LangOpts.AsmPreprocessor)
2879 return CodePoint;
2880
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002881 // C99 6.4.3p2: A universal character name shall not specify a character whose
2882 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2883 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2884 // C++11 [lex.charset]p2: If the hexadecimal value for a
2885 // universal-character-name corresponds to a surrogate code point (in the
2886 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2887 // if the hexadecimal value for a universal-character-name outside the
2888 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2889 // string literal corresponds to a control character (in either of the
2890 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2891 // basic source character set, the program is ill-formed.
2892 if (CodePoint < 0xA0) {
2893 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2894 return CodePoint;
2895
2896 // We don't use isLexingRawMode() here because we need to warn about bad
2897 // UCNs even when skipping preprocessing tokens in a #if block.
2898 if (Result && PP) {
2899 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2900 Diag(BufferPtr, diag::err_ucn_control_character);
2901 else {
2902 char C = static_cast<char>(CodePoint);
2903 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2904 }
2905 }
2906
2907 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002908 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002909 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002910 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002911 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002912 if (Result && PP) {
2913 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2914 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2915 else
2916 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2917 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002918 return 0;
2919 }
2920
2921 return CodePoint;
2922}
2923
Eli Friedman0834a4b2013-09-19 00:41:32 +00002924bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2925 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002926 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2927 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002928 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002929 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002930 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002931 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002932
2933 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002934 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002935 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002936 return false;
2937}
Jordan Rose4246ae02013-01-24 20:50:50 +00002938
Eli Friedman0834a4b2013-09-19 00:41:32 +00002939bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002940 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2941 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2942 !PP->isPreprocessedOutput()) {
2943 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2944 makeCharRange(*this, BufferPtr, CurPtr),
2945 /*IsFirst=*/true);
2946 }
2947
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002948 MIOpt.ReadToken();
2949 return LexIdentifier(Result, CurPtr);
2950 }
2951
Jordan Rosecc538342013-01-31 19:48:48 +00002952 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2953 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002954 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002955 // Non-ASCII characters tend to creep into source code unintentionally.
2956 // Instead of letting the parser complain about the unknown token,
2957 // just drop the character.
2958 // Note that we can /only/ do this when the non-ASCII character is actually
2959 // spelled as Unicode, not written as a UCN. The standard requires that
2960 // we not throw away any possible preprocessor tokens, but there's a
2961 // loophole in the mapping of Unicode characters to basic character set
2962 // characters that allows us to map these particular characters to, say,
2963 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002964 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002965 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002966
2967 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002968 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002969 }
2970
2971 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2972 // up by accident.
2973 MIOpt.ReadToken();
2974 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002975 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002976}
2977
Eli Friedman0834a4b2013-09-19 00:41:32 +00002978void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2979 IsAtStartOfLine = Result.isAtStartOfLine();
2980 HasLeadingSpace = Result.hasLeadingSpace();
2981 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2982 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2983}
2984
2985bool Lexer::Lex(Token &Result) {
2986 // Start a new token.
2987 Result.startToken();
2988
2989 // Set up misc whitespace flags for LexTokenInternal.
2990 if (IsAtStartOfLine) {
2991 Result.setFlag(Token::StartOfLine);
2992 IsAtStartOfLine = false;
2993 }
2994
2995 if (HasLeadingSpace) {
2996 Result.setFlag(Token::LeadingSpace);
2997 HasLeadingSpace = false;
2998 }
2999
3000 if (HasLeadingEmptyMacro) {
3001 Result.setFlag(Token::LeadingEmptyMacro);
3002 HasLeadingEmptyMacro = false;
3003 }
3004
3005 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3006 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00003007 bool isRawLex = isLexingRawMode();
3008 (void) isRawLex;
3009 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3010 // (After the LexTokenInternal call, the lexer might be destroyed.)
3011 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3012 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003013}
Chris Lattner22eb9722006-06-18 05:43:12 +00003014
3015/// LexTokenInternal - This implements a simple C family lexer. It is an
3016/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003017/// has a null character at the end of the file. This returns a preprocessing
3018/// token, not a normal token, as such, it is an internal interface. It assumes
3019/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003020bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003021LexNextToken:
3022 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003023 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003024 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattner22eb9722006-06-18 05:43:12 +00003026 // CurPtr - Cache BufferPtr in an automatic variable.
3027 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003028
Chris Lattnereb54b592006-07-10 06:34:27 +00003029 // Small amounts of horizontal whitespace is very common between tokens.
3030 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3031 ++CurPtr;
3032 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3033 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003034
Chris Lattner4d963442008-10-12 04:05:48 +00003035 // If we are keeping whitespace and other tokens, just return what we just
3036 // skipped. The next lexer invocation will return the token after the
3037 // whitespace.
3038 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003039 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003040 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003041 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043
Chris Lattnereb54b592006-07-10 06:34:27 +00003044 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003045 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003046 }
Mike Stump11289f42009-09-09 15:08:12 +00003047
Chris Lattner22eb9722006-06-18 05:43:12 +00003048 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003049
Chris Lattner22eb9722006-06-18 05:43:12 +00003050 // Read a character, advancing over it.
3051 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003052 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003053
Chris Lattner22eb9722006-06-18 05:43:12 +00003054 switch (Char) {
3055 case 0: // Null.
3056 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003057 if (CurPtr-1 == BufferEnd)
3058 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003059
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003060 // Check if we are performing code completion.
3061 if (isCodeCompletionPoint(CurPtr-1)) {
3062 // Return the code-completion token.
3063 Result.startToken();
3064 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003065 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003066 }
3067
Chris Lattner6d27a162008-11-22 02:02:22 +00003068 if (!isLexingRawMode())
3069 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003070 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003071 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3072 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003073
Eli Friedman0834a4b2013-09-19 00:41:32 +00003074 // We know the lexer hasn't changed, so just try again with this lexer.
3075 // (We manually eliminate the tail call to avoid recursion.)
3076 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003077
Chris Lattner3dfff972009-12-17 05:29:40 +00003078 case 26: // DOS & CP/M EOF: "^Z".
3079 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003080 if (LangOpts.MicrosoftExt) {
3081 if (!isLexingRawMode())
3082 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003083 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003084 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003085
Chris Lattner3dfff972009-12-17 05:29:40 +00003086 // If Microsoft extensions are disabled, this is just random garbage.
3087 Kind = tok::unknown;
3088 break;
Taewook Ohcebac482017-12-06 17:00:53 +00003089
Chris Lattner22eb9722006-06-18 05:43:12 +00003090 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003091 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003092 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003093 LLVM_FALLTHROUGH;
3094 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003095 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003096 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003097 if (ParsingPreprocessorDirective) {
3098 // Done parsing the "line".
3099 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003100
Chris Lattner457fc152006-07-29 06:30:25 +00003101 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003102 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003103 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003104
Chris Lattner22eb9722006-06-18 05:43:12 +00003105 // Since we consumed a newline, we are back at the start of a line.
3106 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003107 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003108
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003109 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003110 break;
3111 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003112
Chris Lattner22eb9722006-06-18 05:43:12 +00003113 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003114 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003115
Eli Friedman0834a4b2013-09-19 00:41:32 +00003116 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3117 return true; // KeepWhitespaceMode
3118
3119 // We only saw whitespace, so just try again with this lexer.
3120 // (We manually eliminate the tail call to avoid recursion.)
3121 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003122 case ' ':
3123 case '\t':
3124 case '\f':
3125 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003126 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003127 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003128 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3129 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003130
3131 SkipIgnoredUnits:
3132 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattnerb9b85972007-07-22 06:29:05 +00003134 // If the next token is obviously a // or /* */ comment, skip it efficiently
3135 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003136 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003137 LangOpts.LineComment &&
3138 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003139 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3140 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003141 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003142 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003143 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3144 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003145 goto SkipIgnoredUnits;
3146 } else if (isHorizontalWhitespace(*CurPtr)) {
3147 goto SkipHorizontalWhitespace;
3148 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003149 // We only saw whitespace, so just try again with this lexer.
3150 // (We manually eliminate the tail call to avoid recursion.)
3151 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003152
Chris Lattner2b15cf72008-01-03 17:58:54 +00003153 // C99 6.4.4.1: Integer Constants.
3154 // C99 6.4.4.2: Floating Constants.
3155 case '0': case '1': case '2': case '3': case '4':
3156 case '5': case '6': case '7': case '8': case '9':
3157 // Notify MIOpt that we read a non-whitespace/non-comment token.
3158 MIOpt.ReadToken();
3159 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003160
Richard Smith9b362092013-03-09 23:56:02 +00003161 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003162 // Notify MIOpt that we read a non-whitespace/non-comment token.
3163 MIOpt.ReadToken();
3164
Richard Smith9b362092013-03-09 23:56:02 +00003165 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003166 Char = getCharAndSize(CurPtr, SizeTmp);
3167
3168 // UTF-16 string literal
3169 if (Char == '"')
3170 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3171 tok::utf16_string_literal);
3172
3173 // UTF-16 character constant
3174 if (Char == '\'')
3175 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3176 tok::utf16_char_constant);
3177
Craig Topper54edcca2011-08-11 04:06:15 +00003178 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003179 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3180 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003181 return LexRawStringLiteral(Result,
3182 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3183 SizeTmp2, Result),
3184 tok::utf16_string_literal);
3185
3186 if (Char == '8') {
3187 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3188
3189 // UTF-8 string literal
3190 if (Char2 == '"')
3191 return LexStringLiteral(Result,
3192 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3193 SizeTmp2, Result),
3194 tok::utf8_string_literal);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003195 if (Char2 == '\'' && LangOpts.CPlusPlus17)
Richard Smith3e3a7052014-11-08 06:08:42 +00003196 return LexCharConstant(
3197 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3198 SizeTmp2, Result),
3199 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003200
Richard Smith9b362092013-03-09 23:56:02 +00003201 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003202 unsigned SizeTmp3;
3203 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3204 // UTF-8 raw string literal
3205 if (Char3 == '"') {
3206 return LexRawStringLiteral(Result,
3207 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3208 SizeTmp2, Result),
3209 SizeTmp3, Result),
3210 tok::utf8_string_literal);
3211 }
3212 }
3213 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003214 }
3215
3216 // treat u like the start of an identifier.
3217 return LexIdentifier(Result, CurPtr);
3218
Richard Smith9b362092013-03-09 23:56:02 +00003219 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003220 // Notify MIOpt that we read a non-whitespace/non-comment token.
3221 MIOpt.ReadToken();
3222
Richard Smith9b362092013-03-09 23:56:02 +00003223 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003224 Char = getCharAndSize(CurPtr, SizeTmp);
3225
3226 // UTF-32 string literal
3227 if (Char == '"')
3228 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3229 tok::utf32_string_literal);
3230
3231 // UTF-32 character constant
3232 if (Char == '\'')
3233 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3234 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003235
3236 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003237 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3238 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003239 return LexRawStringLiteral(Result,
3240 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3241 SizeTmp2, Result),
3242 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003243 }
3244
3245 // treat U like the start of an identifier.
3246 return LexIdentifier(Result, CurPtr);
3247
Craig Topper54edcca2011-08-11 04:06:15 +00003248 case 'R': // Identifier or C++0x raw string literal
3249 // Notify MIOpt that we read a non-whitespace/non-comment token.
3250 MIOpt.ReadToken();
3251
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003252 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003253 Char = getCharAndSize(CurPtr, SizeTmp);
3254
3255 if (Char == '"')
3256 return LexRawStringLiteral(Result,
3257 ConsumeChar(CurPtr, SizeTmp, Result),
3258 tok::string_literal);
3259 }
3260
3261 // treat R like the start of an identifier.
3262 return LexIdentifier(Result, CurPtr);
3263
Chris Lattner2b15cf72008-01-03 17:58:54 +00003264 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003265 // Notify MIOpt that we read a non-whitespace/non-comment token.
3266 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003267 Char = getCharAndSize(CurPtr, SizeTmp);
3268
3269 // Wide string literal.
3270 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003271 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003272 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003273
Craig Topper54edcca2011-08-11 04:06:15 +00003274 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003275 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003276 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3277 return LexRawStringLiteral(Result,
3278 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3279 SizeTmp2, Result),
3280 tok::wide_string_literal);
3281
Chris Lattner22eb9722006-06-18 05:43:12 +00003282 // Wide character constant.
3283 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003284 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3285 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003286 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003287 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003288
Chris Lattner22eb9722006-06-18 05:43:12 +00003289 // C99 6.4.2: Identifiers.
3290 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3291 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003292 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003293 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3294 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3295 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003296 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003297 case 'v': case 'w': case 'x': case 'y': case 'z':
3298 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003299 // Notify MIOpt that we read a non-whitespace/non-comment token.
3300 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003302
3303 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003304 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003305 if (!isLexingRawMode())
3306 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003307 // Notify MIOpt that we read a non-whitespace/non-comment token.
3308 MIOpt.ReadToken();
3309 return LexIdentifier(Result, CurPtr);
3310 }
Mike Stump11289f42009-09-09 15:08:12 +00003311
Chris Lattnerb11c3232008-10-12 04:51:35 +00003312 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003313 break;
Mike Stump11289f42009-09-09 15:08:12 +00003314
Chris Lattner22eb9722006-06-18 05:43:12 +00003315 // C99 6.4.4: Character Constants.
3316 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003317 // Notify MIOpt that we read a non-whitespace/non-comment token.
3318 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003319 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003320
3321 // C99 6.4.5: String Literals.
3322 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003323 // Notify MIOpt that we read a non-whitespace/non-comment token.
3324 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003325 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003326
3327 // C99 6.4.6: Punctuators.
3328 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 break;
3331 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003332 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003333 break;
3334 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003335 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003336 break;
3337 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003338 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003339 break;
3340 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003341 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003342 break;
3343 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003344 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003345 break;
3346 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 break;
3349 case '.':
3350 Char = getCharAndSize(CurPtr, SizeTmp);
3351 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003352 // Notify MIOpt that we read a non-whitespace/non-comment token.
3353 MIOpt.ReadToken();
3354
Chris Lattner22eb9722006-06-18 05:43:12 +00003355 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003356 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003357 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003358 CurPtr += SizeTmp;
3359 } else if (Char == '.' &&
3360 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003361 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003362 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3363 SizeTmp2, Result);
3364 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003365 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003366 }
3367 break;
3368 case '&':
3369 Char = getCharAndSize(CurPtr, SizeTmp);
3370 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003371 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003372 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3373 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003374 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003375 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3376 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003378 }
3379 break;
Mike Stump11289f42009-09-09 15:08:12 +00003380 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003381 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003382 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003383 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3384 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003385 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 }
3387 break;
3388 case '+':
3389 Char = getCharAndSize(CurPtr, SizeTmp);
3390 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003392 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003393 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003395 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003396 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003397 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003398 }
3399 break;
3400 case '-':
3401 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003402 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003403 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003404 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003405 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003406 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003407 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3408 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003409 Kind = tok::arrowstar;
3410 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003412 Kind = tok::arrow;
3413 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003414 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003415 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003416 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003417 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003418 }
3419 break;
3420 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003421 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003422 break;
3423 case '!':
3424 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003425 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3427 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003428 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003429 }
3430 break;
3431 case '/':
3432 // 6.4.9: Comments
3433 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003434 if (Char == '/') { // Line comment.
3435 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003436 // want to lex this as a comment. There is one problem with this though,
3437 // that in one particular corner case, this can change the behavior of the
3438 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003439 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003440 // "foo". Check to see if the character after the second slash is a '*'.
3441 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003442 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003443 bool TreatAsComment = LangOpts.LineComment &&
3444 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003445 if (!TreatAsComment)
3446 if (!(PP && PP->isPreprocessedOutput()))
3447 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3448
3449 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003450 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3451 TokAtPhysicalStartOfLine))
3452 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003453
Chris Lattner58827712009-01-16 22:39:25 +00003454 // It is common for the tokens immediately after a // comment to be
3455 // whitespace (indentation for the next line). Instead of going through
3456 // the big switch, handle it efficiently now.
3457 goto SkipIgnoredUnits;
3458 }
3459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattner58827712009-01-16 22:39:25 +00003461 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003462 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3463 TokAtPhysicalStartOfLine))
3464 return true; // There is a token to return.
3465
3466 // We only saw whitespace, so just try again with this lexer.
3467 // (We manually eliminate the tail call to avoid recursion.)
3468 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003469 }
Mike Stump11289f42009-09-09 15:08:12 +00003470
Chris Lattner58827712009-01-16 22:39:25 +00003471 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003473 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 }
3477 break;
3478 case '%':
3479 Char = getCharAndSize(CurPtr, SizeTmp);
3480 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003481 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003482 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003483 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003484 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003485 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003486 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003487 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003488 Char = getCharAndSize(CurPtr, SizeTmp);
3489 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003490 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003491 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3492 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003493 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003494 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003495 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003496 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003497 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003498 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003499 // We parsed a # character. If this occurs at the start of the line,
3500 // it's actually the start of a preprocessing directive. Callback to
3501 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003502 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003503 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003504 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Chris Lattner2534324a2009-03-18 20:58:27 +00003506 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003507 }
3508 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003509 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003510 }
3511 break;
3512 case '<':
3513 Char = getCharAndSize(CurPtr, SizeTmp);
3514 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003515 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003517 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3518 if (After == '=') {
3519 Kind = tok::lesslessequal;
3520 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3521 SizeTmp2, Result);
3522 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3523 // If this is actually a '<<<<<<<' version control conflict marker,
3524 // recognize it as such and recover nicely.
3525 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003526 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3527 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3528 // ignore it.
3529 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003530 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003531 Kind = tok::lesslessless;
3532 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3533 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003534 } else {
3535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3536 Kind = tok::lessless;
3537 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003538 } else if (Char == '=') {
Richard Smithedbf5972017-12-01 01:07:10 +00003539 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3540 if (After == '>') {
3541 if (getLangOpts().CPlusPlus2a) {
3542 if (!isLexingRawMode())
3543 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3544 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3545 SizeTmp2, Result);
3546 Kind = tok::spaceship;
3547 break;
3548 }
3549 // Suggest adding a space between the '<=' and the '>' to avoid a
3550 // change in semantics if this turns up in C++ <=17 mode.
3551 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3552 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3553 << FixItHint::CreateInsertion(
3554 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3555 }
3556 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003557 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003558 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003559 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003560 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003561 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3562 // C++0x [lex.pptoken]p3:
3563 // Otherwise, if the next three characters are <:: and the subsequent
3564 // character is neither : nor >, the < is treated as a preprocessor
3565 // token by itself and not as the first character of the alternative
3566 // token <:.
3567 unsigned SizeTmp3;
3568 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3569 if (After != ':' && After != '>') {
3570 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003571 if (!isLexingRawMode())
3572 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003573 break;
3574 }
3575 }
3576
Chris Lattner22eb9722006-06-18 05:43:12 +00003577 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003578 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003579 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003580 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003581 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003582 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3583 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003584 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003585 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003586 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 }
3588 break;
3589 case '>':
3590 Char = getCharAndSize(CurPtr, SizeTmp);
3591 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003592 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003593 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003594 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003595 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3596 if (After == '=') {
3597 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3598 SizeTmp2, Result);
3599 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003600 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3601 // If this is actually a '>>>>' conflict marker, recognize it as such
3602 // and recover nicely.
3603 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003604 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3605 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3606 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003607 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003608 Kind = tok::greatergreatergreater;
3609 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3610 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003611 } else {
3612 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3613 Kind = tok::greatergreater;
3614 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003615 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003616 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003617 }
3618 break;
3619 case '^':
3620 Char = getCharAndSize(CurPtr, SizeTmp);
3621 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003622 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003623 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003624 } else if (LangOpts.OpenCL && Char == '^') {
3625 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3626 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003627 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003628 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003629 }
3630 break;
3631 case '|':
3632 Char = getCharAndSize(CurPtr, SizeTmp);
3633 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003634 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003635 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3636 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003637 // If this is '|||||||' and we're in a conflict marker, ignore it.
3638 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3639 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003640 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003641 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3642 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003643 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003644 }
3645 break;
3646 case ':':
3647 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003648 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003649 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003650 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Aaron Ballman606093a2017-10-15 15:01:42 +00003651 } else if ((LangOpts.CPlusPlus ||
3652 LangOpts.DoubleSquareBracketAttributes) &&
3653 Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003654 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003655 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003656 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003657 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003658 }
3659 break;
3660 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003661 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003662 break;
3663 case '=':
3664 Char = getCharAndSize(CurPtr, SizeTmp);
3665 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003666 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003667 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3668 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003669
Chris Lattnerb11c3232008-10-12 04:51:35 +00003670 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003671 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003672 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003673 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003674 }
3675 break;
3676 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003677 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003678 break;
3679 case '#':
3680 Char = getCharAndSize(CurPtr, SizeTmp);
3681 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003682 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003683 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003684 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003685 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003686 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003687 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003688 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003689 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003690 // We parsed a # character. If this occurs at the start of the line,
3691 // it's actually the start of a preprocessing directive. Callback to
3692 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003693 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003694 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003695 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003696
Chris Lattner2534324a2009-03-18 20:58:27 +00003697 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003698 }
3699 break;
3700
Chris Lattner2b15cf72008-01-03 17:58:54 +00003701 case '@':
3702 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003703 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003704 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003705 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003706 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003707 break;
Mike Stump11289f42009-09-09 15:08:12 +00003708
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003709 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003710 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003711 if (!LangOpts.AsmPreprocessor) {
3712 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3713 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3714 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3715 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003716
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003717 // We only saw whitespace, so just try again with this lexer.
3718 // (We manually eliminate the tail call to avoid recursion.)
3719 goto LexNextToken;
3720 }
3721
3722 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003723 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003724 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003725
Chris Lattnerb11c3232008-10-12 04:51:35 +00003726 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003727 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003728
3729 default: {
3730 if (isASCII(Char)) {
3731 Kind = tok::unknown;
3732 break;
3733 }
3734
Justin Lebar90910552016-09-30 00:38:45 +00003735 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003736
3737 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3738 // an escaped newline.
3739 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003740 llvm::ConversionResult Status =
3741 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3742 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003743 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003744 llvm::strictConversion);
3745 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003746 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3747 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3748 return true; // KeepWhitespaceMode
3749
3750 // We only saw whitespace, so just try again with this lexer.
3751 // (We manually eliminate the tail call to avoid recursion.)
3752 goto LexNextToken;
3753 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003754 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003755 }
Taewook Ohcebac482017-12-06 17:00:53 +00003756
Jordan Rosecc538342013-01-31 19:48:48 +00003757 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3758 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003759 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003760 Kind = tok::unknown;
3761 break;
3762 }
3763
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003764 // Non-ASCII characters tend to creep into source code unintentionally.
3765 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003766 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003767 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003768
3769 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003770 // We're pretending the character didn't exist, so just try again with
3771 // this lexer.
3772 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003773 goto LexNextToken;
3774 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003775 }
Mike Stump11289f42009-09-09 15:08:12 +00003776
Chris Lattner371ac8a2006-07-04 07:11:10 +00003777 // Notify MIOpt that we read a non-whitespace/non-comment token.
3778 MIOpt.ReadToken();
3779
Chris Lattnerd01e2912006-06-18 16:22:51 +00003780 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003781 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003782 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003783
3784HandleDirective:
3785 // We parsed a # character and it's the start of a preprocessing directive.
3786
3787 FormTokenWithChars(Result, CurPtr, tok::hash);
3788 PP->HandleDirective(Result);
3789
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003790 if (PP->hadModuleLoaderFatalFailure()) {
3791 // With a fatal failure in the module loader, we abort parsing.
3792 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003793 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003794 }
3795
Eli Friedman0834a4b2013-09-19 00:41:32 +00003796 // We parsed the directive; lex a token with the new state.
3797 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003798}