blob: b85e0f03dc06727042ab1f77ed59ce3798505948 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000013
14#include "clang/Lex/Lexer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "UnicodeCharSets.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000016#include "clang/Basic/CharInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000018#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/LexDiagnostic.h"
Richard Smith2a988622013-09-24 04:06:10 +000020#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.h"
Alex Lorenzfb7654a2017-06-16 20:13:39 +000022#include "clang/Lex/PreprocessorOptions.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000023#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000025#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000026#include "llvm/Support/ConvertUTF.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000027#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000028#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "llvm/Support/UnicodeCharRanges.h"
30#include <algorithm>
31#include <cassert>
32#include <cstddef>
33#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000034#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include <string>
36#include <tuple>
37#include <utility>
38
Chris Lattner22eb9722006-06-18 05:43:12 +000039using namespace clang;
40
Chris Lattner4894f482007-10-07 08:47:24 +000041//===----------------------------------------------------------------------===//
42// Token Class Implementation
43//===----------------------------------------------------------------------===//
44
Mike Stump11289f42009-09-09 15:08:12 +000045/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000046bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Alex Lorenzd4754662017-05-17 11:08:36 +000047 if (isAnnotation())
48 return false;
Douglas Gregor90abb6d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000052}
53
54/// getObjCKeywordID - Return the ObjC keyword kind.
55tok::ObjCKeywordKind Token::getObjCKeywordID() const {
Alex Lorenzd4754662017-05-17 11:08:36 +000056 if (isAnnotation())
57 return tok::objc_not_keyword;
Chris Lattner4894f482007-10-07 08:47:24 +000058 IdentifierInfo *specId = getIdentifierInfo();
59 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
60}
61
62//===----------------------------------------------------------------------===//
63// Lexer Class Implementation
64//===----------------------------------------------------------------------===//
65
David Blaikie68e081d2011-12-20 02:48:34 +000066void Lexer::anchor() { }
67
Mike Stump11289f42009-09-09 15:08:12 +000068void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000070 BufferStart = BufStart;
71 BufferPtr = BufPtr;
72 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattnerf76b9202009-01-17 06:55:17 +000074 assert(BufEnd[0] == 0 &&
75 "We assume that the input buffer has a null character at the end"
76 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000077
Eric Christopher7f36a792011-04-09 00:01:04 +000078 // Check whether we have a BOM in the beginning of the buffer. If yes - act
79 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
80 // skip the UTF-8 BOM if it's present.
81 if (BufferStart == BufferPtr) {
82 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000083 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000084 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000085 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
86 .Default(0);
87
88 // Skip the BOM.
89 BufferPtr += BOMLength;
90 }
91
Chris Lattnerf76b9202009-01-17 06:55:17 +000092 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000093 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000094
Chris Lattnerf76b9202009-01-17 06:55:17 +000095 // Start of the file is a start of line.
96 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000097 IsAtPhysicalStartOfLine = true;
98
99 HasLeadingSpace = false;
100 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Chris Lattnerf76b9202009-01-17 06:55:17 +0000102 // We are not after parsing a #.
103 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000104
Chris Lattnerf76b9202009-01-17 06:55:17 +0000105 // We are not after parsing #include.
106 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattnerf76b9202009-01-17 06:55:17 +0000108 // We are not in raw mode. Raw mode disables diagnostics and interpretation
109 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
110 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
111 // or otherwise skipping over tokens.
112 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerf76b9202009-01-17 06:55:17 +0000114 // Default to not keeping comments.
115 ExtendedTokenMode = 0;
116}
117
Chris Lattner5965a282009-01-17 07:56:59 +0000118/// Lexer constructor - Create a new lexer object for the specified buffer
119/// with the specified preprocessor managing the lexing process. This lexer
120/// assumes that the associated file buffer and Preprocessor objects will
121/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000122Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000123 : PreprocessorLexer(&PP, FID),
124 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000125 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000126
Chris Lattner5965a282009-01-17 07:56:59 +0000127 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
128 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000129
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000130 resetExtendedTokenMode();
131}
132
133void Lexer::resetExtendedTokenMode() {
134 assert(PP && "Cannot reset token mode without a preprocessor");
135 if (LangOpts.TraditionalCPP)
136 SetKeepWhitespaceMode(true);
137 else
138 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000139}
Chris Lattner4894f482007-10-07 08:47:24 +0000140
Chris Lattner02b436a2007-10-17 20:41:00 +0000141/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000142/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000143/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000144Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000145 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000147
Chris Lattnerf76b9202009-01-17 06:55:17 +0000148 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000149
Chris Lattner02b436a2007-10-17 20:41:00 +0000150 // We *are* in raw mode.
151 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000152}
153
Chris Lattner08354fe2009-01-17 07:35:14 +0000154/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000155/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000156/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000157Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000158 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000159 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
160 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000161
Chris Lattner757169b2009-01-17 08:27:52 +0000162/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
163/// _Pragma expansion. This has a variety of magic semantics that this method
164/// sets up. It returns a new'd Lexer that must be delete'd when done.
165///
166/// On entrance to this routine, TokStartLoc is a macro location which has a
167/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000168/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000169/// "expanded from".
170///
Alp Toker7755aff2014-05-18 18:37:59 +0000171/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000172/// normal lexer that remaps tokens as they fly by. This would require making
173/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
174/// interface that could handle this stuff. This would pull GetMappedTokenLoc
175/// out of the critical path of the lexer!
176///
Mike Stump11289f42009-09-09 15:08:12 +0000177Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000178 SourceLocation ExpansionLocStart,
179 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000180 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000181 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000182
183 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000184 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000185 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
186 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner757169b2009-01-17 08:27:52 +0000188 // Now that the lexer is created, change the start/end locations so that we
189 // just lex the subsection of the file that we want. This is lexing from a
190 // scratch buffer.
191 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattner757169b2009-01-17 08:27:52 +0000193 L->BufferPtr = StrData;
194 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000195 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000196
197 // Set the SourceLocation with the remapping information. This ensures that
198 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000199 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
200 ExpansionLocStart,
201 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner757169b2009-01-17 08:27:52 +0000203 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000204 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000205 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattner757169b2009-01-17 08:27:52 +0000207 // This lexer really is for _Pragma.
208 L->Is_PragmaLexer = true;
209 return L;
210}
211
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000212/// Stringify - Convert the specified string into a C string, with surrounding
213/// ""'s, and with escaped \ and " characters.
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000214std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000215 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000216 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000217 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000218 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000219 Result.insert(Result.begin()+i, '\\');
220 ++i; ++e;
221 }
222 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000223 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000224}
225
Chris Lattner4c4a2452007-07-24 06:57:14 +0000226/// Stringify - Convert the specified string into a C string by escaping '\'
227/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000228void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000229 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
230 if (Str[i] == '\\' || Str[i] == '"') {
231 Str.insert(Str.begin()+i, '\\');
232 ++i; ++e;
233 }
234 }
235}
236
Chris Lattner39720112010-11-17 07:26:20 +0000237//===----------------------------------------------------------------------===//
238// Token Spelling
239//===----------------------------------------------------------------------===//
240
Richard Smith9a67f472012-11-28 07:29:00 +0000241/// \brief Slow case of getSpelling. Extract the characters comprising the
242/// spelling of this token from the provided input buffer.
243static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
244 const LangOptions &LangOpts, char *Spelling) {
245 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
246
247 size_t Length = 0;
248 const char *BufEnd = BufPtr + Tok.getLength();
249
Craig Toppera6324c92015-10-22 15:35:21 +0000250 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000251 // Munch the encoding-prefix and opening double-quote.
252 while (BufPtr < BufEnd) {
253 unsigned Size;
254 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
255 BufPtr += Size;
256
257 if (Spelling[Length - 1] == '"')
258 break;
259 }
260
261 // Raw string literals need special handling; trigraph expansion and line
262 // splicing do not occur within their d-char-sequence nor within their
263 // r-char-sequence.
264 if (Length >= 2 &&
265 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
266 // Search backwards from the end of the token to find the matching closing
267 // quote.
268 const char *RawEnd = BufEnd;
269 do --RawEnd; while (*RawEnd != '"');
270 size_t RawLength = RawEnd - BufPtr + 1;
271
272 // Everything between the quotes is included verbatim in the spelling.
273 memcpy(Spelling + Length, BufPtr, RawLength);
274 Length += RawLength;
275 BufPtr += RawLength;
276
277 // The rest of the token is lexed normally.
278 }
279 }
280
281 while (BufPtr < BufEnd) {
282 unsigned Size;
283 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
284 BufPtr += Size;
285 }
286
287 assert(Length < Tok.getLength() &&
288 "NeedsCleaning flag set on token that didn't need cleaning!");
289 return Length;
290}
291
Chris Lattner39720112010-11-17 07:26:20 +0000292/// getSpelling() - Return the 'spelling' of this token. The spelling of a
293/// token are the characters used to represent the token in the source file
294/// after trigraph expansion and escaped-newline folding. In particular, this
295/// wants to get the true, uncanonicalized, spelling of things like digraphs
296/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000297StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000298 SmallVectorImpl<char> &buffer,
299 const SourceManager &SM,
300 const LangOptions &options,
301 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000302 // Break down the source location.
303 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
304
305 // Try to the load the file buffer.
306 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000307 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000308 if (invalidTemp) {
309 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000310 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000311 }
312
313 const char *tokenBegin = file.data() + locInfo.second;
314
315 // Lex from the start of the given location.
316 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
317 file.begin(), tokenBegin, file.end());
318 Token token;
319 lexer.LexFromRawLexer(token);
320
321 unsigned length = token.getLength();
322
323 // Common case: no need for cleaning.
324 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000326
Richard Smith9a67f472012-11-28 07:29:00 +0000327 // Hard case, we need to relex the characters into the string.
328 buffer.resize(length);
329 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000330 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000331}
332
333/// getSpelling() - Return the 'spelling' of this token. The spelling of a
334/// token are the characters used to represent the token in the source file
335/// after trigraph expansion and escaped-newline folding. In particular, this
336/// wants to get the true, uncanonicalized, spelling of things like digraphs
337/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000338std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000339 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000340 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000341
Chris Lattner39720112010-11-17 07:26:20 +0000342 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000343 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000344 &CharDataInvalid);
345 if (Invalid)
346 *Invalid = CharDataInvalid;
347 if (CharDataInvalid)
348 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000349
350 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000351 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000352 return std::string(TokStart, TokStart + Tok.getLength());
353
Chris Lattner39720112010-11-17 07:26:20 +0000354 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000355 Result.resize(Tok.getLength());
356 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000357 return Result;
358}
359
360/// getSpelling - This method is used to get the spelling of a token into a
361/// preallocated buffer, instead of as an std::string. The caller is required
362/// to allocate enough space for the token, which is guaranteed to be at least
363/// Tok.getLength() bytes long. The actual length of the token is returned.
364///
365/// Note that this method may do two possible things: it may either fill in
366/// the buffer specified with characters, or it may *change the input pointer*
367/// to point to a constant buffer with the data already in it (avoiding a
368/// copy). The caller is not allowed to modify the returned buffer pointer
369/// if an internal buffer is returned.
370unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
371 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000372 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000373 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000374
Craig Topperd2d442c2014-05-17 23:10:59 +0000375 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000376 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
377 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000378 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000379 else if (!Tok.hasUCN()) {
380 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
381 // Just return the string from the identifier table, which is very quick.
382 Buffer = II->getNameStart();
383 return II->getLength();
384 }
Chris Lattner39720112010-11-17 07:26:20 +0000385 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000386
387 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000388 if (Tok.isLiteral())
389 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000390
Craig Topperd2d442c2014-05-17 23:10:59 +0000391 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000393 bool CharDataInvalid = false;
394 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
395 if (Invalid)
396 *Invalid = CharDataInvalid;
397 if (CharDataInvalid) {
398 Buffer = "";
399 return 0;
400 }
401 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000402
Chris Lattner39720112010-11-17 07:26:20 +0000403 // If this token contains nothing interesting, return it directly.
404 if (!Tok.needsCleaning()) {
405 Buffer = TokStart;
406 return Tok.getLength();
407 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000408
Chris Lattner39720112010-11-17 07:26:20 +0000409 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000410 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000411}
412
Chris Lattner8e129c22007-10-17 21:18:47 +0000413/// MeasureTokenLength - Relex the token at the specified location and return
414/// its length in bytes in the input file. If the token needs cleaning (e.g.
415/// includes a trigraph or an escaped newline) then this count includes bytes
416/// that are part of that.
417unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000418 const SourceManager &SM,
419 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000420 Token TheTok;
421 if (getRawToken(Loc, TheTok, SM, LangOpts))
422 return 0;
423 return TheTok.getLength();
424}
425
426/// \brief Relex the token at the specified location.
427/// \returns true if there was a failure, false on success.
428bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
429 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000430 const LangOptions &LangOpts,
431 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000432 // TODO: this could be special cased for common tokens like identifiers, ')',
433 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000434 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000435 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
436 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000437
438 // If this comes from a macro expansion, we really do want the macro name, not
439 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000440 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000441 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000442 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000443 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000444 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000445 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000446
447 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000448
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000449 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000450 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000451
Chris Lattner8e129c22007-10-17 21:18:47 +0000452 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000453 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
454 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000455 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000456 TheLexer.LexFromRawLexer(Result);
457 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000458}
459
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000460/// Returns the pointer that points to the beginning of line that contains
461/// the given offset, or null if the offset if invalid.
462static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
463 const char *BufStart = Buffer.data();
464 if (Offset >= Buffer.size())
465 return nullptr;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000466
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000467 const char *LexStart = BufStart + Offset;
468 for (; LexStart != BufStart; --LexStart) {
469 if (isVerticalWhitespace(LexStart[0]) &&
470 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
471 // LexStart should point at first character of logical line.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000472 ++LexStart;
473 break;
474 }
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000475 }
476 return LexStart;
477}
478
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000479static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
480 const SourceManager &SM,
481 const LangOptions &LangOpts) {
482 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000483 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000484 if (LocInfo.first.isInvalid())
485 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000486
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000487 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000489 if (Invalid)
490 return Loc;
491
492 // Back up from the current location until we hit the beginning of a line
493 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000494 const char *StrData = Buffer.data() + LocInfo.second;
495 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
496 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000497 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000498
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000499 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000500 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000501 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
502 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000503 TheLexer.SetCommentRetentionState(true);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000504
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000505 // Lex tokens until we find the token that contains the source location.
506 Token TheTok;
507 do {
508 TheLexer.LexFromRawLexer(TheTok);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000509
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000510 if (TheLexer.getBufferLocation() > StrData) {
511 // Lexing this token has taken the lexer past the source location we're
512 // looking for. If the current token encompasses our source location,
513 // return the beginning of that token.
514 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
515 return TheTok.getLocation();
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000516
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000517 // We ended up skipping over the source location entirely, which means
518 // that it points into whitespace. We're done here.
519 break;
520 }
521 } while (TheTok.getKind() != tok::eof);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000522
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000523 // We've passed our source location; just return the original source location.
524 return Loc;
525}
526
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000527SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
528 const SourceManager &SM,
529 const LangOptions &LangOpts) {
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000530 if (Loc.isFileID())
531 return getBeginningOfFileToken(Loc, SM, LangOpts);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000532
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000533 if (!SM.isMacroArgExpansion(Loc))
534 return Loc;
535
536 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
537 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
538 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
539 std::pair<FileID, unsigned> BeginFileLocInfo =
540 SM.getDecomposedLoc(BeginFileLoc);
541 assert(FileLocInfo.first == BeginFileLocInfo.first &&
542 FileLocInfo.second >= BeginFileLocInfo.second);
543 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000544}
545
Douglas Gregoraf82e352010-07-20 20:18:03 +0000546namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000547
Douglas Gregoraf82e352010-07-20 20:18:03 +0000548 enum PreambleDirectiveKind {
549 PDK_Skipped,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000550 PDK_Unknown
551 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000552
553} // end anonymous namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000554
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000555PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
556 const LangOptions &LangOpts,
557 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000558 // Create a lexer starting at the beginning of the file. Note that we use a
559 // "fake" file source location at offset 1 so that the lexer will track our
560 // position within the file.
561 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000562 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000563 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
564 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000565 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000566
Douglas Gregoraf82e352010-07-20 20:18:03 +0000567 bool InPreprocessorDirective = false;
568 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000569 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000570
571 unsigned MaxLineOffset = 0;
572 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000573 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000574 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000575 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000576 char ch = *CurPtr++;
577 if (ch == '\n') {
578 ++CurLine;
579 if (CurLine == MaxLines)
580 break;
581 }
582 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000583 if (CurPtr != Buffer.end())
584 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000585 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000586
Douglas Gregoraf82e352010-07-20 20:18:03 +0000587 do {
588 TheLexer.LexFromRawLexer(TheTok);
589
590 if (InPreprocessorDirective) {
591 // If we've hit the end of the file, we're done.
592 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000593 break;
594 }
595
596 // If we haven't hit the end of the preprocessor directive, skip this
597 // token.
598 if (!TheTok.isAtStartOfLine())
599 continue;
600
601 // We've passed the end of the preprocessor directive, and will look
602 // at this token again below.
603 InPreprocessorDirective = false;
604 }
605
Douglas Gregor028d3e42010-08-09 20:45:32 +0000606 // Keep track of the # of lines in the preamble.
607 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000608 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000609
610 // If we were asked to limit the number of lines in the preamble,
611 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000612 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000613 break;
614 }
615
Douglas Gregoraf82e352010-07-20 20:18:03 +0000616 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000617 if (TheTok.getKind() == tok::comment) {
618 if (ActiveCommentLoc.isInvalid())
619 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000620 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000621 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622
623 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
624 // This is the start of a preprocessor directive.
625 Token HashTok = TheTok;
626 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000627 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000628
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000629 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000630 // we don't have an identifier table available. Instead, just look at
631 // the raw identifier to recognize and categorize preprocessor directives.
632 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000633 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000634 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000635 PreambleDirectiveKind PDK
636 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
637 .Case("include", PDK_Skipped)
638 .Case("__include_macros", PDK_Skipped)
639 .Case("define", PDK_Skipped)
640 .Case("undef", PDK_Skipped)
641 .Case("line", PDK_Skipped)
642 .Case("error", PDK_Skipped)
643 .Case("pragma", PDK_Skipped)
644 .Case("import", PDK_Skipped)
645 .Case("include_next", PDK_Skipped)
646 .Case("warning", PDK_Skipped)
647 .Case("ident", PDK_Skipped)
648 .Case("sccs", PDK_Skipped)
649 .Case("assert", PDK_Skipped)
650 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000651 .Case("if", PDK_Skipped)
652 .Case("ifdef", PDK_Skipped)
653 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000654 .Case("elif", PDK_Skipped)
655 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000656 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000657 .Default(PDK_Unknown);
658
659 switch (PDK) {
660 case PDK_Skipped:
661 continue;
662
Douglas Gregoraf82e352010-07-20 20:18:03 +0000663 case PDK_Unknown:
664 // We don't know what this directive is; stop at the '#'.
665 break;
666 }
667 }
668
669 // We only end up here if we didn't recognize the preprocessor
670 // directive or it was one that can't occur in the preamble at this
671 // point. Roll back the current token to the location of the '#'.
672 InPreprocessorDirective = false;
673 TheTok = HashTok;
674 }
675
Douglas Gregor028d3e42010-08-09 20:45:32 +0000676 // We hit a token that we don't recognize as being in the
677 // "preprocessing only" part of the file, so we're no longer in
678 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000679 break;
680 } while (true);
681
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000682 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000683 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000684 End = ActiveCommentLoc; // don't truncate a decl comment.
685 else
686 End = TheTok.getLocation();
687
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000688 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000689 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000690}
691
Chris Lattner2a6ee912010-11-17 07:05:50 +0000692/// AdvanceToTokenCharacter - Given a location that specifies the start of a
693/// token, return a new location that specifies a character within the token.
694SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
695 unsigned CharNo,
696 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000698 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000699 // character is. This needs to take into consideration newlines and
700 // trigraphs.
701 bool Invalid = false;
702 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
703
704 // If they request the first char of the token, we're trivially done.
705 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
706 return TokStart;
707
708 unsigned PhysOffset = 0;
709
710 // The usual case is that tokens don't contain anything interesting. Skip
711 // over the uninteresting characters. If a token only consists of simple
712 // chars, this method is extremely fast.
713 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
714 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000715 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000716 ++TokPtr;
717 --CharNo;
718 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000719 }
720
721 // If we have a character that may be a trigraph or escaped newline, use a
722 // lexer to parse it correctly.
723 for (; CharNo; --CharNo) {
724 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000725 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000726 TokPtr += Size;
727 PhysOffset += Size;
728 }
729
730 // Final detail: if we end up on an escaped newline, we want to return the
731 // location of the actual byte of the token. For example foo\<newline>bar
732 // advanced by 3 should return the location of b, not of \\. One compounding
733 // detail of this is that the escape may be made by a trigraph.
734 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
735 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
736
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000737 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000738}
739
740/// \brief Computes the source location just past the end of the
741/// token at this source location.
742///
743/// This routine can be used to produce a source location that
744/// points just past the end of the token referenced by \p Loc, and
745/// is generally used when a diagnostic needs to point just after a
746/// token where it expected something different that it received. If
747/// the returned source location would not be meaningful (e.g., if
748/// it points into a macro), this routine returns an invalid
749/// source location.
750///
751/// \param Offset an offset from the end of the token, where the source
752/// location should refer to. The default offset (0) produces a source
753/// location pointing just past the end of the token; an offset of 1 produces
754/// a source location pointing to the last character in the token, etc.
755SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
756 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000758 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000759 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000760
761 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000762 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000763 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000764 }
765
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000767 if (Len > Offset)
768 Len = Len - Offset;
769 else
770 return Loc;
771
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000772 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000773}
774
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000775/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000776/// token of the macro expansion.
777bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000778 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000779 const LangOptions &LangOpts,
780 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000781 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
782
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000783 SourceLocation expansionLoc;
784 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
785 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000786
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000787 if (expansionLoc.isFileID()) {
788 // No other macro expansions, this is the first.
789 if (MacroBegin)
790 *MacroBegin = expansionLoc;
791 return true;
792 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000793
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000794 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000795}
796
797/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000798/// token of the macro expansion.
799bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000800 const SourceManager &SM,
801 const LangOptions &LangOpts,
802 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000803 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
804
805 SourceLocation spellLoc = SM.getSpellingLoc(loc);
806 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
807 if (tokLen == 0)
808 return false;
809
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000810 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
811 SourceLocation expansionLoc;
812 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
813 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000814
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000815 if (expansionLoc.isFileID()) {
816 // No other macro expansions.
817 if (MacroEnd)
818 *MacroEnd = expansionLoc;
819 return true;
820 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000821
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000822 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000823}
824
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000825static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000826 const SourceManager &SM,
827 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000828 SourceLocation Begin = Range.getBegin();
829 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000830 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000831 if (Range.isTokenRange()) {
832 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
833 if (End.isInvalid())
834 return CharSourceRange();
835 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000836
837 // Break down the source locations.
838 FileID FID;
839 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000840 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000841 if (FID.isInvalid())
842 return CharSourceRange();
843
844 unsigned EndOffs;
845 if (!SM.isInFileID(End, FID, &EndOffs) ||
846 BeginOffs > EndOffs)
847 return CharSourceRange();
848
849 return CharSourceRange::getCharRange(Begin, End);
850}
851
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000852CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000853 const SourceManager &SM,
854 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000855 SourceLocation Begin = Range.getBegin();
856 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000857 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000858 return CharSourceRange();
859
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000860 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000861 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000862
863 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000864 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
865 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000866 Range.setBegin(Begin);
867 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000868 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000869
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000870 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
872 &End)) ||
873 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
874 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000875 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000876 Range.setEnd(End);
877 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000878 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000879
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000880 assert(Begin.isMacroID() && End.isMacroID());
881 SourceLocation MacroBegin, MacroEnd;
882 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000883 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
884 &MacroEnd)) ||
885 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
886 &MacroEnd)))) {
887 Range.setBegin(MacroBegin);
888 Range.setEnd(MacroEnd);
889 return makeRangeFromFileLocs(Range, SM, LangOpts);
890 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000891
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000892 bool Invalid = false;
893 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
894 &Invalid);
895 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000896 return CharSourceRange();
897
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000898 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
899 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
900 &Invalid);
901 if (Invalid)
902 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000903
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000904 if (EndEntry.getExpansion().isMacroArgExpansion() &&
905 BeginEntry.getExpansion().getExpansionLocStart() ==
906 EndEntry.getExpansion().getExpansionLocStart()) {
907 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
908 Range.setEnd(SM.getImmediateSpellingLoc(End));
909 return makeFileCharRange(Range, SM, LangOpts);
910 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000911 }
912
913 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000914}
915
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000916StringRef Lexer::getSourceText(CharSourceRange Range,
917 const SourceManager &SM,
918 const LangOptions &LangOpts,
919 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000920 Range = makeFileCharRange(Range, SM, LangOpts);
921 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000922 if (Invalid) *Invalid = true;
923 return StringRef();
924 }
925
926 // Break down the source location.
927 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
928 if (beginInfo.first.isInvalid()) {
929 if (Invalid) *Invalid = true;
930 return StringRef();
931 }
932
933 unsigned EndOffs;
934 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
935 beginInfo.second > EndOffs) {
936 if (Invalid) *Invalid = true;
937 return StringRef();
938 }
939
940 // Try to the load the file buffer.
941 bool invalidTemp = false;
942 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
943 if (invalidTemp) {
944 if (Invalid) *Invalid = true;
945 return StringRef();
946 }
947
948 if (Invalid) *Invalid = false;
949 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
950}
951
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000952StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
953 const SourceManager &SM,
954 const LangOptions &LangOpts) {
955 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000956
957 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000958 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000959 FileID FID = SM.getFileID(Loc);
960 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
961 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
962 Loc = Expansion.getExpansionLocStart();
963 if (!Expansion.isMacroArgExpansion())
964 break;
965
966 // For macro arguments we need to check that the argument did not come
967 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
968
969 // Loc points to the argument id of the macro definition, move to the
970 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000971 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000972 SourceLocation SpellLoc = Expansion.getSpellingLoc();
973 if (SpellLoc.isFileID())
974 break; // No inner macro.
975
976 // If spelling location resides in the same FileID as macro expansion
977 // location, it means there is no inner macro.
978 FileID MacroFID = SM.getFileID(Loc);
979 if (SM.isInFileID(SpellLoc, MacroFID))
980 break;
981
982 // Argument came from inner macro.
983 Loc = SpellLoc;
984 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000985
986 // Find the spelling location of the start of the non-argument expansion
987 // range. This is where the macro name was spelled in order to begin
988 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000989 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000990
991 // Dig out the buffer where the macro name was spelled and the extents of the
992 // name so that we can render it into the expansion note.
993 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
994 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
995 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
996 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
997}
998
Richard Trieu3a5c9582016-01-26 02:51:55 +0000999StringRef Lexer::getImmediateMacroNameForDiagnostics(
1000 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1001 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1002 // Walk past macro argument expanions.
1003 while (SM.isMacroArgExpansion(Loc))
1004 Loc = SM.getImmediateExpansionRange(Loc).first;
1005
1006 // If the macro's spelling has no FileID, then it's actually a token paste
1007 // or stringization (or similar) and not a macro at all.
1008 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1009 return StringRef();
1010
1011 // Find the spelling location of the start of the non-argument expansion
1012 // range. This is where the macro name was spelled in order to begin
1013 // expanding this macro.
1014 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1015
1016 // Dig out the buffer where the macro name was spelled and the extents of the
1017 // name so that we can render it into the expansion note.
1018 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1019 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1020 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1021 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1022}
1023
Jordan Rose288c4212012-06-07 01:10:31 +00001024bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001025 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001026}
1027
Alexander Kornienkocf007a72017-08-10 10:06:16 +00001028bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1029 assert(isVerticalWhitespace(Str[0]));
1030 if (Str - 1 < BufferStart)
1031 return false;
1032
1033 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1034 (Str[0] == '\r' && Str[-1] == '\n')) {
1035 if (Str - 2 < BufferStart)
1036 return false;
1037 --Str;
1038 }
1039 --Str;
1040
1041 // Rewind to first non-space character:
1042 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1043 --Str;
1044
1045 return *Str == '\\';
1046}
1047
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001048StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1049 const SourceManager &SM) {
1050 if (Loc.isInvalid() || Loc.isMacroID())
1051 return "";
1052 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1053 if (LocInfo.first.isInvalid())
1054 return "";
1055 bool Invalid = false;
1056 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1057 if (Invalid)
1058 return "";
1059 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1060 if (!Line)
1061 return "";
1062 StringRef Rest = Buffer.substr(Line - Buffer.data());
1063 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1064 return NumWhitespaceChars == StringRef::npos
1065 ? ""
1066 : Rest.take_front(NumWhitespaceChars);
1067}
1068
Chris Lattner22eb9722006-06-18 05:43:12 +00001069//===----------------------------------------------------------------------===//
1070// Diagnostics forwarding code.
1071//===----------------------------------------------------------------------===//
1072
Chris Lattner619c1742007-07-22 18:38:25 +00001073/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001074/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001075/// This is currently only used for _Pragma implementation, so it is the slow
1076/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001077static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1078 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001079static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1080 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001081 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001082 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001083
Chris Lattner619c1742007-07-22 18:38:25 +00001084 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001085 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001086 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001087 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001089 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001090 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001091 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001092 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001093
Chris Lattner9dc9c202009-02-15 20:52:18 +00001094 // Figure out the expansion loc range, which is the range covered by the
1095 // original _Pragma(...) sequence.
1096 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001097 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001098
Chandler Carruth115b0772011-07-26 03:03:05 +00001099 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001100}
1101
Chris Lattner22eb9722006-06-18 05:43:12 +00001102/// getSourceLocation - Return a source location identifier for the specified
1103/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001104SourceLocation Lexer::getSourceLocation(const char *Loc,
1105 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001106 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001107 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001108
1109 // In the normal case, we're just lexing from a simple file buffer, return
1110 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001111 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001112 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001113 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001114
Chris Lattnerd32480d2009-01-17 06:22:33 +00001115 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1116 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001117 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001118 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001119}
1120
Chris Lattner22eb9722006-06-18 05:43:12 +00001121/// Diag - Forwarding function for diagnostics. This translate a source
1122/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001123DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001124 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001125}
1126
1127//===----------------------------------------------------------------------===//
1128// Trigraph and Escaped Newline Handling Code.
1129//===----------------------------------------------------------------------===//
1130
1131/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1132/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1133static char GetTrigraphCharForLetter(char Letter) {
1134 switch (Letter) {
1135 default: return 0;
1136 case '=': return '#';
1137 case ')': return ']';
1138 case '(': return '[';
1139 case '!': return '|';
1140 case '\'': return '^';
1141 case '>': return '}';
1142 case '/': return '\\';
1143 case '<': return '{';
1144 case '-': return '~';
1145 }
1146}
1147
1148/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1149/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1150/// return the result character. Finally, emit a warning about trigraph use
1151/// whether trigraphs are enabled or not.
1152static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1153 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001154 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001155
David Blaikiebbafb8a2012-03-11 07:00:24 +00001156 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001157 if (!L->isLexingRawMode())
1158 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001159 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattner6d27a162008-11-22 02:02:22 +00001162 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001163 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001164 return Res;
1165}
1166
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001167/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1168/// 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 +00001169/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001170unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1171 unsigned Size = 0;
1172 while (isWhitespace(Ptr[Size])) {
1173 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001174
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001175 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1176 continue;
1177
1178 // If this is a \r\n or \n\r, skip the other half.
1179 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1180 Ptr[Size-1] != Ptr[Size])
1181 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001183 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001184 }
1185
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001186 // Not an escaped newline, must be a \t or something else.
1187 return 0;
1188}
1189
Chris Lattner38b2cde2009-04-18 22:27:02 +00001190/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1191/// them), skip over them and return the first non-escaped-newline found,
1192/// otherwise return P.
1193const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001194 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001195 const char *AfterEscape;
1196 if (*P == '\\') {
1197 AfterEscape = P+1;
1198 } else if (*P == '?') {
1199 // If not a trigraph for escape, bail out.
1200 if (P[1] != '?' || P[2] != '/')
1201 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001202 // FIXME: Take LangOpts into account; the language might not
1203 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001204 AfterEscape = P+3;
1205 } else {
1206 return P;
1207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
Chris Lattner38b2cde2009-04-18 22:27:02 +00001209 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1210 if (NewLineSize == 0) return P;
1211 P = AfterEscape+NewLineSize;
1212 }
1213}
1214
Anna Zaks59a3c802011-07-27 21:43:43 +00001215/// \brief Checks that the given token is the first token that occurs after the
1216/// given location (this excludes comments and whitespace). Returns the location
1217/// immediately after the specified token. If the token is not found or the
1218/// location is inside a macro, the returned source location will be invalid.
1219SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1220 tok::TokenKind TKind,
1221 const SourceManager &SM,
1222 const LangOptions &LangOpts,
1223 bool SkipTrailingWhitespaceAndNewLine) {
1224 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001225 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001226 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001227 }
1228 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1229
1230 // Break down the source location.
1231 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1232
1233 // Try to load the file buffer.
1234 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001235 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001236 if (InvalidTemp)
1237 return SourceLocation();
1238
1239 const char *TokenBegin = File.data() + LocInfo.second;
1240
1241 // Lex from the start of the given location.
1242 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1243 TokenBegin, File.end());
1244 // Find the token.
1245 Token Tok;
1246 lexer.LexFromRawLexer(Tok);
1247 if (Tok.isNot(TKind))
1248 return SourceLocation();
1249 SourceLocation TokenLoc = Tok.getLocation();
1250
1251 // Calculate how much whitespace needs to be skipped if any.
1252 unsigned NumWhitespaceChars = 0;
1253 if (SkipTrailingWhitespaceAndNewLine) {
1254 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1255 Tok.getLength();
1256 unsigned char C = *TokenEnd;
1257 while (isHorizontalWhitespace(C)) {
1258 C = *(++TokenEnd);
1259 NumWhitespaceChars++;
1260 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001261
1262 // Skip \r, \n, \r\n, or \n\r
1263 if (C == '\n' || C == '\r') {
1264 char PrevC = C;
1265 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001266 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001267 if ((C == '\n' || C == '\r') && C != PrevC)
1268 NumWhitespaceChars++;
1269 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001270 }
1271
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001272 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001273}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001274
Chris Lattner22eb9722006-06-18 05:43:12 +00001275/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1276/// get its size, and return it. This is tricky in several cases:
1277/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1278/// then either return the trigraph (skipping 3 chars) or the '?',
1279/// depending on whether trigraphs are enabled or not.
1280/// 2. If this is an escaped newline (potentially with whitespace between
1281/// the backslash and newline), implicitly skip the newline and return
1282/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001283///
1284/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1285/// know that we can accumulate into Size, and that we have already incremented
1286/// Ptr by Size bytes.
1287///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001288/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1289/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001290///
1291char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001292 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 // If we have a slash, look for an escaped newline.
1294 if (Ptr[0] == '\\') {
1295 ++Size;
1296 ++Ptr;
1297Slash:
1298 // Common case, backslash-char where the char is not whitespace.
1299 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattnerc1835952009-06-23 05:15:06 +00001301 // See if we have optional whitespace characters between the slash and
1302 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001303 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1304 // Remember that this token needs to be cleaned.
1305 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001306
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001307 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001308 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001309 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001311 // Found backslash<whitespace><newline>. Parse the char after it.
1312 Size += EscapedNewLineSize;
1313 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001314
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001315 // Use slow version to accumulate a correct size field.
1316 return getCharAndSizeSlow(Ptr, Size, Tok);
1317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 // Otherwise, this is not an escaped newline, just return the slash.
1320 return '\\';
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 // If this is a trigraph, process it.
1324 if (Ptr[0] == '?' && Ptr[1] == '?') {
1325 // If this is actually a legal trigraph (not something like "??x"), emit
1326 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001327 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001329 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001330
1331 Ptr += 3;
1332 Size += 3;
1333 if (C == '\\') goto Slash;
1334 return C;
1335 }
1336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // If this is neither, return a single character.
1339 ++Size;
1340 return *Ptr;
1341}
1342
1343/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1344/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1345/// and that we have already incremented Ptr by Size bytes.
1346///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001347/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1348/// be updated to match.
1349char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001350 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001351 // If we have a slash, look for an escaped newline.
1352 if (Ptr[0] == '\\') {
1353 ++Size;
1354 ++Ptr;
1355Slash:
1356 // Common case, backslash-char where the char is not whitespace.
1357 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001360 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1361 // Found backslash<whitespace><newline>. Parse the char after it.
1362 Size += EscapedNewLineSize;
1363 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001365 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001366 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattner22eb9722006-06-18 05:43:12 +00001369 // Otherwise, this is not an escaped newline, just return the slash.
1370 return '\\';
1371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001374 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001375 // If this is actually a legal trigraph (not something like "??x"), return
1376 // it.
1377 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1378 Ptr += 3;
1379 Size += 3;
1380 if (C == '\\') goto Slash;
1381 return C;
1382 }
1383 }
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner22eb9722006-06-18 05:43:12 +00001385 // If this is neither, return a single character.
1386 ++Size;
1387 return *Ptr;
1388}
1389
Chris Lattner22eb9722006-06-18 05:43:12 +00001390//===----------------------------------------------------------------------===//
1391// Helper methods for lexing.
1392//===----------------------------------------------------------------------===//
1393
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001394/// \brief Routine that indiscriminately sets the offset into the source file.
1395void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1396 BufferPtr = BufferStart + Offset;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001397 if (BufferPtr > BufferEnd)
1398 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001399 // FIXME: What exactly does the StartOfLine bit mean? There are two
1400 // possible meanings for the "start" of the line: the first token on the
1401 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001402 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001403 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001404}
1405
Jordan Rose58c61e02013-02-09 01:10:25 +00001406static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001407 if (LangOpts.AsmPreprocessor) {
1408 return false;
1409 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001410 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1411 C11AllowedIDCharRanges);
1412 return C11AllowedIDChars.contains(C);
1413 } else if (LangOpts.CPlusPlus) {
1414 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1415 CXX03AllowedIDCharRanges);
1416 return CXX03AllowedIDChars.contains(C);
1417 } else {
1418 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1419 C99AllowedIDCharRanges);
1420 return C99AllowedIDChars.contains(C);
1421 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001422}
1423
Jordan Rose58c61e02013-02-09 01:10:25 +00001424static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1425 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001426 if (LangOpts.AsmPreprocessor) {
1427 return false;
1428 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001429 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1430 C11DisallowedInitialIDCharRanges);
1431 return !C11DisallowedInitialIDChars.contains(C);
1432 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001433 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001434 } else {
1435 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1436 C99DisallowedInitialIDCharRanges);
1437 return !C99DisallowedInitialIDChars.contains(C);
1438 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001439}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001440
Jordan Rose58c61e02013-02-09 01:10:25 +00001441static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1442 const char *End) {
1443 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1444 L.getSourceLocation(End));
1445}
1446
1447static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1448 CharSourceRange Range, bool IsFirst) {
1449 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001450 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001451 enum {
1452 CannotAppearInIdentifier = 0,
1453 CannotStartIdentifier
1454 };
1455
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001456 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1457 C99AllowedIDCharRanges);
1458 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1459 C99DisallowedInitialIDCharRanges);
1460 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001461 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1462 << Range
1463 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001464 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001465 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1466 << Range
1467 << CannotStartIdentifier;
1468 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001469 }
1470
Jordan Rose58c61e02013-02-09 01:10:25 +00001471 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001472 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001473 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1474 CXX03AllowedIDCharRanges);
1475 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001476 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1477 << Range;
1478 }
1479 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001480}
1481
1482bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1483 Token &Result) {
1484 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001485 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001486 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1487 return false;
1488
1489 if (!isLexingRawMode())
1490 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1491 makeCharRange(*this, CurPtr, UCNPtr),
1492 /*IsFirst=*/false);
1493
1494 Result.setFlag(Token::HasUCN);
1495 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1496 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1497 CurPtr = UCNPtr;
1498 else
1499 while (CurPtr != UCNPtr)
1500 (void)getAndAdvanceChar(CurPtr, Result);
1501 return true;
1502}
1503
1504bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1505 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001506 llvm::UTF32 CodePoint;
1507 llvm::ConversionResult Result =
1508 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1509 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001510 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001511 llvm::strictConversion);
1512 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001513 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1514 return false;
1515
1516 if (!isLexingRawMode())
1517 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1518 makeCharRange(*this, CurPtr, UnicodePtr),
1519 /*IsFirst=*/false);
1520
1521 CurPtr = UnicodePtr;
1522 return true;
1523}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001524
Eli Friedman0834a4b2013-09-19 00:41:32 +00001525bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1527 unsigned Size;
1528 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001529 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001531
Chris Lattner22eb9722006-06-18 05:43:12 +00001532 --CurPtr; // Back up over the skipped character.
1533
1534 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1535 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001536 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001537 // TODO: Could merge these checks into an InfoTable flag to make the
1538 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001539 if (isASCII(C) && C != '\\' && C != '?' &&
1540 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001541FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001542 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001543 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1544 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattner0f1f5052006-07-20 04:16:23 +00001546 // If we are in raw mode, return this identifier raw. There is no need to
1547 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001548 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001549 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001550
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001551 // Fill in Result.IdentifierInfo and update the token kind,
1552 // looking up the identifier in the identifier table.
1553 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001554
Chris Lattnerc5a00062006-06-18 16:41:01 +00001555 // Finally, now that we know we have an identifier, pass this off to the
1556 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001557 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001558 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001559
1560 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1561 && II->getPPKeywordID() == tok::pp_not_keyword
1562 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1563 // Return the code-completion token.
1564 Result.setKind(tok::code_completion);
1565 cutOffLexing();
1566 return true;
1567 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001568 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 }
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001574 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 if (C == '$') {
1576 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001577 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001578
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001580 if (!isLexingRawMode())
1581 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001582 CurPtr = ConsumeChar(CurPtr, Size, Result);
1583 C = getCharAndSize(CurPtr, Size);
1584 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001585
Richard Smith8b7258b2014-02-17 21:52:30 +00001586 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001587 C = getCharAndSize(CurPtr, Size);
1588 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001589 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001590 C = getCharAndSize(CurPtr, Size);
1591 continue;
1592 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 goto FinishIdentifier;
1594 }
1595
1596 // Otherwise, this character is good, consume it.
1597 CurPtr = ConsumeChar(CurPtr, Size, Result);
1598
1599 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001600 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 CurPtr = ConsumeChar(CurPtr, Size, Result);
1602 C = getCharAndSize(CurPtr, Size);
1603 }
1604 }
1605}
1606
Douglas Gregor759ef232010-08-30 14:50:47 +00001607/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001608/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001609bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001610 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001611 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001612 if (C1 != '0')
1613 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001614 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001615 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001616}
Chris Lattner22eb9722006-06-18 05:43:12 +00001617
Nate Begeman5eee9332008-04-14 02:26:39 +00001618/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001619/// constant. From[-1] is the first character lexed. Return the end of the
1620/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001621bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001622 unsigned Size;
1623 char C = getCharAndSize(CurPtr, Size);
1624 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001625 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 CurPtr = ConsumeChar(CurPtr, Size, Result);
1627 PrevCh = C;
1628 C = getCharAndSize(CurPtr, Size);
1629 }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Chris Lattner22eb9722006-06-18 05:43:12 +00001631 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001632 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1633 // If we are in Microsoft mode, don't continue if the constant is hex.
1634 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001635 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001636 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1637 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001638
1639 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001640 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001641 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001642 // not-quite-conforming extension. Only do so if this looks like it's
1643 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1644 bool IsHexFloat = true;
1645 if (!LangOpts.C99) {
1646 if (!isHexaLiteral(BufferPtr, LangOpts))
1647 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001648 else if (!getLangOpts().CPlusPlus1z &&
1649 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001650 IsHexFloat = false;
1651 }
1652 if (IsHexFloat)
1653 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Richard Smithfde94852013-09-26 03:33:06 +00001656 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001657 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001658 unsigned NextSize;
1659 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001660 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001661 if (!isLexingRawMode())
1662 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1663 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001664 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001665 return LexNumericConstant(Result, CurPtr);
1666 }
1667 }
1668
Richard Smith8b7258b2014-02-17 21:52:30 +00001669 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1670 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1671 return LexNumericConstant(Result, CurPtr);
1672 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1673 return LexNumericConstant(Result, CurPtr);
1674
Chris Lattnerd01e2912006-06-18 16:22:51 +00001675 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001676 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001677 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001678 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001679 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001680}
1681
Richard Smithe18f0fa2012-03-05 04:02:15 +00001682/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001683/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001684const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1685 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001686 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001687
Richard Smith8b7258b2014-02-17 21:52:30 +00001688 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001689 unsigned Size;
1690 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001691 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001692
Richard Smith8b7258b2014-02-17 21:52:30 +00001693 if (!isIdentifierHead(C)) {
1694 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1695 Consumed = true;
1696 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1697 Consumed = true;
1698 else
1699 return CurPtr;
1700 }
1701
1702 if (!getLangOpts().CPlusPlus11) {
1703 if (!isLexingRawMode())
1704 Diag(CurPtr,
1705 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1706 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1707 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1708 return CurPtr;
1709 }
1710
1711 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1712 // that does not start with an underscore is ill-formed. As a conforming
1713 // extension, we treat all such suffixes as if they had whitespace before
1714 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1715 // likely to be a ud-suffix than a macro, however, and accept that.
1716 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001717 bool IsUDSuffix = false;
1718 if (C == '_')
1719 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001720 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001721 // In C++1y, we need to look ahead a few characters to see if this is a
1722 // valid suffix for a string literal or a numeric literal (this could be
1723 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001724 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001725 char Buffer[MaxStandardSuffixLength] = { C };
1726 unsigned Consumed = Size;
1727 unsigned Chars = 1;
1728 while (true) {
1729 unsigned NextSize;
1730 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1731 getLangOpts());
1732 if (!isIdentifierBody(Next)) {
1733 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001734 const StringRef CompleteSuffix(Buffer, Chars);
1735 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1736 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001737 break;
1738 }
1739
1740 if (Chars == MaxStandardSuffixLength)
1741 // Too long: can't be a standard suffix.
1742 break;
1743
1744 Buffer[Chars++] = Next;
1745 Consumed += NextSize;
1746 }
Richard Smithf4198b72013-07-23 08:14:48 +00001747 }
1748
1749 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001750 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001751 Diag(CurPtr, getLangOpts().MSVCCompat
1752 ? diag::ext_ms_reserved_user_defined_literal
1753 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001754 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001755 return CurPtr;
1756 }
1757
Richard Smith8b7258b2014-02-17 21:52:30 +00001758 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001759 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001760
1761 Result.setFlag(Token::HasUDSuffix);
1762 while (true) {
1763 C = getCharAndSize(CurPtr, Size);
1764 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1765 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1766 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1767 else break;
1768 }
1769
Richard Smithe18f0fa2012-03-05 04:02:15 +00001770 return CurPtr;
1771}
1772
Chris Lattner22eb9722006-06-18 05:43:12 +00001773/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001774/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001775bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001776 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001777 // Does this string contain the \0 character?
1778 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Richard Smithacd4d3d2011-10-15 01:18:56 +00001780 if (!isLexingRawMode() &&
1781 (Kind == tok::utf8_string_literal ||
1782 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001783 Kind == tok::utf32_string_literal))
1784 Diag(BufferPtr, getLangOpts().CPlusPlus
1785 ? diag::warn_cxx98_compat_unicode_literal
1786 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001787
Chris Lattner22eb9722006-06-18 05:43:12 +00001788 char C = getAndAdvanceChar(CurPtr, Result);
1789 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001790 // Skip escaped characters. Escaped newlines will already be processed by
1791 // getAndAdvanceChar.
1792 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001793 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001794
Chris Lattner52d96ac2010-05-30 23:27:38 +00001795 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001796 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001797 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001798 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001799 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001800 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001801 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001802
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001803 if (C == 0) {
1804 if (isCodeCompletionPoint(CurPtr-1)) {
1805 PP->CodeCompleteNaturalLanguage();
1806 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001807 cutOffLexing();
1808 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001809 }
1810
Chris Lattner52d96ac2010-05-30 23:27:38 +00001811 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001812 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001813 C = getAndAdvanceChar(CurPtr, Result);
1814 }
Mike Stump11289f42009-09-09 15:08:12 +00001815
Richard Smithe18f0fa2012-03-05 04:02:15 +00001816 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001818 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001819
Chris Lattner5a78a022006-07-20 06:02:19 +00001820 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001821 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001822 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001823
Chris Lattnerd01e2912006-06-18 16:22:51 +00001824 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001825 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001826 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001827 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001828 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001829}
1830
Craig Topper54edcca2011-08-11 04:06:15 +00001831/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1832/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001833bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001834 tok::TokenKind Kind) {
1835 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1836 // Between the initial and final double quote characters of the raw string,
1837 // any transformations performed in phases 1 and 2 (trigraphs,
1838 // universal-character-names, and line splicing) are reverted.
1839
Richard Smithacd4d3d2011-10-15 01:18:56 +00001840 if (!isLexingRawMode())
1841 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1842
Craig Topper54edcca2011-08-11 04:06:15 +00001843 unsigned PrefixLen = 0;
1844
1845 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1846 ++PrefixLen;
1847
1848 // If the last character was not a '(', then we didn't lex a valid delimiter.
1849 if (CurPtr[PrefixLen] != '(') {
1850 if (!isLexingRawMode()) {
1851 const char *PrefixEnd = &CurPtr[PrefixLen];
1852 if (PrefixLen == 16) {
1853 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1854 } else {
1855 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1856 << StringRef(PrefixEnd, 1);
1857 }
1858 }
1859
1860 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1861 // it's possible the '"' was intended to be part of the raw string, but
1862 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001863 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001864 char C = *CurPtr++;
1865
1866 if (C == '"')
1867 break;
1868 if (C == 0 && CurPtr-1 == BufferEnd) {
1869 --CurPtr;
1870 break;
1871 }
1872 }
1873
1874 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001875 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001876 }
1877
1878 // Save prefix and move CurPtr past it
1879 const char *Prefix = CurPtr;
1880 CurPtr += PrefixLen + 1; // skip over prefix and '('
1881
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001882 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001883 char C = *CurPtr++;
1884
1885 if (C == ')') {
1886 // Check for prefix match and closing quote.
1887 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1888 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1889 break;
1890 }
1891 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1892 if (!isLexingRawMode())
1893 Diag(BufferPtr, diag::err_unterminated_raw_string)
1894 << StringRef(Prefix, PrefixLen);
1895 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001896 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001897 }
1898 }
1899
Richard Smithe18f0fa2012-03-05 04:02:15 +00001900 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001902 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001903
Craig Topper54edcca2011-08-11 04:06:15 +00001904 // Update the location of token as well as BufferPtr.
1905 const char *TokStart = BufferPtr;
1906 FormTokenWithChars(Result, CurPtr, Kind);
1907 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001908 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001909}
1910
Chris Lattner22eb9722006-06-18 05:43:12 +00001911/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1912/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001913bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001914 // Does this string contain the \0 character?
1915 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001916 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 char C = getAndAdvanceChar(CurPtr, Result);
1918 while (C != '>') {
1919 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001920 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001922 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001924 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1925 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001926 // If the filename is unterminated, then it must just be a lone <
1927 // character. Return this as such.
1928 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001929 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001930 } else if (C == 0) {
1931 NulCharacter = CurPtr-1;
1932 }
1933 C = getAndAdvanceChar(CurPtr, Result);
1934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
Chris Lattner5a78a022006-07-20 06:02:19 +00001936 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001937 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001938 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001939
Chris Lattnerd01e2912006-06-18 16:22:51 +00001940 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001941 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001942 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001943 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001944 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001945}
1946
Chris Lattner22eb9722006-06-18 05:43:12 +00001947/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001948/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001949bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001950 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001951 // Does this character contain the \0 character?
1952 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001953
Richard Smith3e3a7052014-11-08 06:08:42 +00001954 if (!isLexingRawMode()) {
1955 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1956 Diag(BufferPtr, getLangOpts().CPlusPlus
1957 ? diag::warn_cxx98_compat_unicode_literal
1958 : diag::warn_c99_compat_unicode_literal);
1959 else if (Kind == tok::utf8_char_constant)
1960 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1961 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001962
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 char C = getAndAdvanceChar(CurPtr, Result);
1964 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001965 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001966 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001967 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001968 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001969 }
1970
1971 while (C != '\'') {
1972 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001973 if (C == '\\')
1974 C = getAndAdvanceChar(CurPtr, Result);
1975
1976 if (C == '\n' || C == '\r' || // Newline.
1977 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001978 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001979 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001980 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001981 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001982 }
1983
1984 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001985 if (isCodeCompletionPoint(CurPtr-1)) {
1986 PP->CodeCompleteNaturalLanguage();
1987 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001988 cutOffLexing();
1989 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001990 }
1991
Chris Lattner86851b82010-07-07 23:24:27 +00001992 NulCharacter = CurPtr-1;
1993 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001994 C = getAndAdvanceChar(CurPtr, Result);
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Richard Smithe18f0fa2012-03-05 04:02:15 +00001997 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001998 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001999 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002000
Chris Lattner86851b82010-07-07 23:24:27 +00002001 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002002 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002003 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002004
Chris Lattnerd01e2912006-06-18 16:22:51 +00002005 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002006 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002007 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002008 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002009 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002010}
2011
2012/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2013/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002014///
2015/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2016///
Eli Friedman0834a4b2013-09-19 00:41:32 +00002017bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2018 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002020 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2021
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002022 unsigned char Char = *CurPtr;
2023
2024 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002025 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 // Skip horizontal whitespace very aggressively.
2027 while (isHorizontalWhitespace(Char))
2028 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002030 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002031 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 break;
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 if (ParsingPreprocessorDirective) {
2035 // End of preprocessor directive line, let LexTokenInternal handle this.
2036 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002037 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002040 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002041 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 Char = *++CurPtr;
2043 }
2044
Chris Lattner4d963442008-10-12 04:05:48 +00002045 // If the client wants us to return whitespace, return it now.
2046 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002047 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002048 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002049 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002050 IsAtPhysicalStartOfLine = true;
2051 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002052 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002053 return true;
2054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002056 // If this isn't immediately after a newline, there is leading space.
2057 char PrevChar = CurPtr[-1];
2058 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2059
2060 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002061 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002062 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002063 TokAtPhysicalStartOfLine = true;
2064 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002065
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002067 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002068}
2069
Nico Weber158a31a2012-11-11 07:02:14 +00002070/// We have just read the // characters from input. Skip until we find the
2071/// newline character thats terminate the comment. Then update BufferPtr and
2072/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002073///
2074/// If we're in KeepCommentMode or any CommentHandler has inserted
2075/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002076bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2077 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002078 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002079 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002080 if (!LangOpts.LineComment && !isLexingRawMode()) {
2081 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002082
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 // Mark them enabled so we only emit one warning for this translation
2084 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002085 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Chris Lattner22eb9722006-06-18 05:43:12 +00002088 // Scan over the body of the comment. The common case, when scanning, is that
2089 // the comment contains normal ascii characters with nothing interesting in
2090 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002091 //
2092 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2093 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002095 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002097 // Skip over characters in the fast loop.
2098 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002099 C != '\n' && C != '\r') // Newline or DOS-style newline.
2100 C = *++CurPtr;
2101
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002102 const char *NextLine = CurPtr;
2103 if (C != 0) {
2104 // We found a newline, see if it's escaped.
2105 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002106 bool HasSpace = false;
2107 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002108 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002109 HasSpace = true;
2110 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002111
Richard Smith4c132e52017-04-18 21:45:04 +00002112 if (*EscapePtr == '\\')
2113 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002114 CurPtr = EscapePtr;
2115 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002116 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2117 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002118 CurPtr = EscapePtr-2;
2119 else
2120 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002121
2122 // If there was space between the backslash and newline, warn about it.
2123 if (HasSpace && !isLexingRawMode())
2124 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattner22eb9722006-06-18 05:43:12 +00002127 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002128 // properly decode the character. Read it in raw mode to avoid emitting
2129 // diagnostics about things like trigraphs. If we see an escaped newline,
2130 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002132 bool OldRawMode = isLexingRawMode();
2133 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002134 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002135 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002136
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002137 // If we only read only one character, then no special handling is needed.
2138 // We're done and can skip forward to the newline.
2139 if (C != 0 && CurPtr == OldPtr+1) {
2140 CurPtr = NextLine;
2141 break;
2142 }
2143
Chris Lattner22eb9722006-06-18 05:43:12 +00002144 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002145 // \n, then we had an escaped newline within the comment. Emit diagnostic
2146 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002147 if (CurPtr != OldPtr + 1 && C != '/' &&
2148 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002149 for (; OldPtr != CurPtr; ++OldPtr)
2150 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002151 // Okay, we found a // comment that ends in a newline, if the next
2152 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002153 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002154 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002155 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002156 ++ForwardPtr;
2157 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2158 break;
2159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Chris Lattner6d27a162008-11-22 02:02:22 +00002161 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002162 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002163 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 }
2165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Richard Smith1d2ae942017-04-17 23:44:51 +00002167 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2168 --CurPtr;
2169 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002170 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002171
2172 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2173 PP->CodeCompleteNaturalLanguage();
2174 cutOffLexing();
2175 return false;
2176 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002177 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002178
Chris Lattner93ddf802010-02-03 21:06:21 +00002179 // Found but did not consume the newline. Notify comment handlers about the
2180 // comment unless we're in a #if 0 block.
2181 if (PP && !isLexingRawMode() &&
2182 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2183 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002184 BufferPtr = CurPtr;
2185 return true; // A token has to be returned.
2186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattner457fc152006-07-29 06:30:25 +00002188 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002189 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002190 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002191
2192 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002193 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002194 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002196 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattner22eb9722006-06-18 05:43:12 +00002199 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002200 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002201 // contribute to another token), it isn't needed for correctness. Note that
2202 // this is ok even in KeepWhitespaceMode, because we would have returned the
2203 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattner22eb9722006-06-18 05:43:12 +00002206 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002207 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002208 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002209 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002210 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002211 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002212 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002213}
Chris Lattner22eb9722006-06-18 05:43:12 +00002214
Nico Weber158a31a2012-11-11 07:02:14 +00002215/// If in save-comment mode, package up this Line comment in an appropriate
2216/// way and return it.
2217bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002218 // If we're not in a preprocessor directive, just return the // comment
2219 // directly.
2220 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002221
David Blaikied5321242012-06-06 18:52:13 +00002222 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002223 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002224
Nico Weber158a31a2012-11-11 07:02:14 +00002225 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002226 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002227 bool Invalid = false;
2228 std::string Spelling = PP->getSpelling(Result, &Invalid);
2229 if (Invalid)
2230 return true;
2231
Nico Weber158a31a2012-11-11 07:02:14 +00002232 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002233 Spelling[1] = '*'; // Change prefix to "/*".
2234 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattnerb11c3232008-10-12 04:51:35 +00002236 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002237 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002238 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002239 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002240}
2241
Chris Lattnercb283342006-06-18 06:48:37 +00002242/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002243/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2244/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002245static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002246 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002248
Chris Lattner22eb9722006-06-18 05:43:12 +00002249 // Back up off the newline.
2250 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002251
Chris Lattner22eb9722006-06-18 05:43:12 +00002252 // If this is a two-character newline sequence, skip the other character.
2253 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2254 // \n\n or \r\r -> not escaped newline.
2255 if (CurPtr[0] == CurPtr[1])
2256 return false;
2257 // \n\r or \r\n -> skip the newline.
2258 --CurPtr;
2259 }
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 // If we have horizontal whitespace, skip over it. We allow whitespace
2262 // between the slash and newline.
2263 bool HasSpace = false;
2264 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2265 --CurPtr;
2266 HasSpace = true;
2267 }
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattner22eb9722006-06-18 05:43:12 +00002269 // If we have a slash, we know this is an escaped newline.
2270 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002271 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002272 } else {
2273 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002274 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2275 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattnercb283342006-06-18 06:48:37 +00002278 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002279 CurPtr -= 2;
2280
2281 // If no trigraphs are enabled, warn that we ignored this trigraph and
2282 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002283 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002284 if (!L->isLexingRawMode())
2285 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002286 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002287 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002288 if (!L->isLexingRawMode())
2289 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002290 }
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattner22eb9722006-06-18 05:43:12 +00002292 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002293 if (!L->isLexingRawMode())
2294 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner22eb9722006-06-18 05:43:12 +00002296 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002297 if (HasSpace && !L->isLexingRawMode())
2298 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattnercb283342006-06-18 06:48:37 +00002300 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002301}
2302
Chris Lattneraded4a92006-10-27 04:42:31 +00002303#ifdef __SSE2__
2304#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002305#elif __ALTIVEC__
2306#include <altivec.h>
2307#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002308#endif
2309
James Dennettf442d242012-06-17 03:40:43 +00002310/// We have just read from input the / and * characters that started a comment.
2311/// Read until we find the * and / characters that terminate the comment.
2312/// Note that we don't bother decoding trigraphs or escaped newlines in block
2313/// comments, because they cannot cause the comment to end. The only thing
2314/// that can happen is the comment could end with an escaped newline between
2315/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002316///
Chris Lattner87d02082010-01-18 22:35:47 +00002317/// If we're in KeepCommentMode or any CommentHandler has inserted
2318/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002319bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2320 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002321 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002322 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002323 // optimization helps people who like to put a lot of * characters in their
2324 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002325
2326 // The first character we get with newlines and trigraphs skipped to handle
2327 // the degenerate /*/ case below correctly if the * has an escaped newline
2328 // after it.
2329 unsigned CharSize;
2330 unsigned char C = getCharAndSize(CurPtr, CharSize);
2331 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002332 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002333 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002334 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002335 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002336
Chris Lattner99e7d232008-10-12 04:19:49 +00002337 // KeepWhitespaceMode should return this broken comment as a token. Since
2338 // it isn't a well formed comment, just return it as an 'unknown' token.
2339 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002340 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002341 return true;
2342 }
Mike Stump11289f42009-09-09 15:08:12 +00002343
Chris Lattner99e7d232008-10-12 04:19:49 +00002344 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002345 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002346 }
Mike Stump11289f42009-09-09 15:08:12 +00002347
Chris Lattnerc850ad62007-07-21 23:43:37 +00002348 // Check to see if the first character after the '/*' is another /. If so,
2349 // then this slash does not end the block comment, it is part of it.
2350 if (C == '/')
2351 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002352
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002353 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002354 // Skip over all non-interesting characters until we find end of buffer or a
2355 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002356 if (CurPtr + 24 < BufferEnd &&
2357 // If there is a code-completion point avoid the fast scan because it
2358 // doesn't check for '\0'.
2359 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002360 // While not aligned to a 16-byte boundary.
2361 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2362 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002363
Chris Lattner6cc3e362006-10-27 04:12:35 +00002364 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002365
2366#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002367 __m128i Slashes = _mm_set1_epi8('/');
2368 while (CurPtr+16 <= BufferEnd) {
2369 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2370 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002371 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002372 // Adjust the pointer to point directly after the first slash. It's
2373 // not necessary to set C here, it will be overwritten at the end of
2374 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002375 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002376 goto FoundSlash;
2377 }
Roman Divacky61509902014-04-03 18:04:52 +00002378 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002379 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002380#elif __ALTIVEC__
2381 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002382 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002383 '/', '/', '/', '/', '/', '/', '/', '/'
2384 };
2385 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002386 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002387 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002388#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002389 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002390 while (CurPtr[0] != '/' &&
2391 CurPtr[1] != '/' &&
2392 CurPtr[2] != '/' &&
2393 CurPtr[3] != '/' &&
2394 CurPtr+4 < BufferEnd) {
2395 CurPtr += 4;
2396 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002397#endif
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattneraded4a92006-10-27 04:42:31 +00002399 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002400 C = *CurPtr++;
2401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattneraded4a92006-10-27 04:42:31 +00002403 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002404 while (C != '/' && C != '\0')
2405 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002406
Chris Lattner22eb9722006-06-18 05:43:12 +00002407 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002408 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002409 if (CurPtr[-2] == '*') // We found the final */. We're done!
2410 break;
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chris Lattner22eb9722006-06-18 05:43:12 +00002412 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002413 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002414 // We found the final */, though it had an escaped newline between the
2415 // * and /. We're done!
2416 break;
2417 }
2418 }
2419 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2420 // If this is a /* inside of the comment, emit a warning. Don't do this
2421 // if this is a /*/, which will end the comment. This misses cases with
2422 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002423 if (!isLexingRawMode())
2424 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002425 }
2426 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002427 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002428 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002429 // Note: the user probably forgot a */. We could continue immediately
2430 // after the /*, but this would involve lexing a lot of what really is the
2431 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002432 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002433
Chris Lattner99e7d232008-10-12 04:19:49 +00002434 // KeepWhitespaceMode should return this broken comment as a token. Since
2435 // it isn't a well formed comment, just return it as an 'unknown' token.
2436 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002437 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002438 return true;
2439 }
Mike Stump11289f42009-09-09 15:08:12 +00002440
Chris Lattner99e7d232008-10-12 04:19:49 +00002441 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002442 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002443 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2444 PP->CodeCompleteNaturalLanguage();
2445 cutOffLexing();
2446 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002447 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002448
Chris Lattner22eb9722006-06-18 05:43:12 +00002449 C = *CurPtr++;
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Chris Lattner93ddf802010-02-03 21:06:21 +00002452 // Notify comment handlers about the comment unless we're in a #if 0 block.
2453 if (PP && !isLexingRawMode() &&
2454 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2455 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002456 BufferPtr = CurPtr;
2457 return true; // A token has to be returned.
2458 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002459
Chris Lattner457fc152006-07-29 06:30:25 +00002460 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002461 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002462 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002463 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002464 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002465
2466 // It is common for the tokens immediately after a /**/ comment to be
2467 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002468 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2469 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002470 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002471 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002472 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002473 }
2474
2475 // Otherwise, just return so that the next character will be lexed as a token.
2476 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002477 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002478 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002479}
2480
2481//===----------------------------------------------------------------------===//
2482// Primary Lexing Entry Points
2483//===----------------------------------------------------------------------===//
2484
Chris Lattner22eb9722006-06-18 05:43:12 +00002485/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2486/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002487void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002488 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2489 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002490 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002491
2492 // CurPtr - Cache BufferPtr in an automatic variable.
2493 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002494 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002495 char Char = getAndAdvanceChar(CurPtr, Tmp);
2496 switch (Char) {
2497 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002498 if (Result)
2499 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002500 break;
2501 case 0: // Null.
2502 // Found end of file?
2503 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002504 if (isCodeCompletionPoint(CurPtr-1)) {
2505 PP->CodeCompleteNaturalLanguage();
2506 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002507 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002508 }
2509
Chris Lattner22eb9722006-06-18 05:43:12 +00002510 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002511 if (Result)
2512 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002513 break;
2514 }
2515 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002516 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002517 case '\r':
2518 case '\n':
2519 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2520 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2521 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002522
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002523 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002524 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002525 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002526 if (PP)
2527 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002528 Lex(Tmp);
2529 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002530 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002531
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002532 // Finally, we're done;
2533 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002534 }
2535 }
2536}
2537
2538/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2539/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002540/// This returns true if Result contains a token, false if PP.Lex should be
2541/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002542bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002543 // If we hit the end of the file while parsing a preprocessor directive,
2544 // end the preprocessor directive first. The next token returned will
2545 // then be the end of file.
2546 if (ParsingPreprocessorDirective) {
2547 // Done parsing the "line".
2548 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002549 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002550 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Chris Lattner457fc152006-07-29 06:30:25 +00002552 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002553 if (PP)
2554 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002555 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002556 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002557
Chris Lattner30a2fa12006-07-19 06:31:49 +00002558 // If we are in raw mode, return this event as an EOF token. Let the caller
2559 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002560 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002561 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002562 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002563 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002564 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002565 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002566
Erik Verbruggen795eee92017-07-05 09:44:07 +00002567 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002568 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2569 ConditionalStack.clear();
2570 }
2571
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002572 // Issue diagnostics for unterminated #if and missing newline.
2573
Chris Lattner30a2fa12006-07-19 06:31:49 +00002574 // If we are in a #if directive, emit an error.
2575 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002576 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002577 PP->Diag(ConditionalStack.back().IfLoc,
2578 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002579 ConditionalStack.pop_back();
2580 }
Mike Stump11289f42009-09-09 15:08:12 +00002581
Chris Lattner8f96d042008-04-12 05:54:25 +00002582 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2583 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002584 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2585 DiagnosticsEngine &Diags = PP->getDiagnostics();
2586 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2587 unsigned DiagID;
2588
2589 if (LangOpts.CPlusPlus11) {
2590 // C++11 [lex.phases] 2.2 p2
2591 // Prefer the C++98 pedantic compatibility warning over the generic,
2592 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002593 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002594 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2595 } else {
2596 DiagID = diag::warn_no_newline_eof;
2597 }
2598 } else {
2599 DiagID = diag::ext_no_newline_eof;
2600 }
2601
2602 Diag(BufferEnd, DiagID)
2603 << FixItHint::CreateInsertion(EndLoc, "\n");
2604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605
Chris Lattner22eb9722006-06-18 05:43:12 +00002606 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002607
2608 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002609 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002610}
2611
Chris Lattner678c8802006-07-11 05:46:12 +00002612/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2613/// the specified lexer will return a tok::l_paren token, 0 if it is something
2614/// else and 2 if there are no more tokens in the buffer controlled by the
2615/// lexer.
2616unsigned Lexer::isNextPPTokenLParen() {
2617 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002618
Chris Lattner678c8802006-07-11 05:46:12 +00002619 // Switch to 'skipping' mode. This will ensure that we can lex a token
2620 // without emitting diagnostics, disables macro expansion, and will cause EOF
2621 // to return an EOF token instead of popping the include stack.
2622 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002623
Chris Lattner678c8802006-07-11 05:46:12 +00002624 // Save state that can be changed while lexing so that we can restore it.
2625 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002626 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002627 bool atStartOfLine = IsAtStartOfLine;
2628 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2629 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002630
Chris Lattner146762e2007-07-20 16:59:19 +00002631 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002632 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002633
Chris Lattner678c8802006-07-11 05:46:12 +00002634 // Restore state that may have changed.
2635 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002636 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002637 HasLeadingSpace = leadingSpace;
2638 IsAtStartOfLine = atStartOfLine;
2639 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002640
Chris Lattner678c8802006-07-11 05:46:12 +00002641 // Restore the lexer back to non-skipping mode.
2642 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002643
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002644 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002645 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002646 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002647}
2648
James Dennettf442d242012-06-17 03:40:43 +00002649/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002650static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2651 ConflictMarkerKind CMK) {
2652 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2653 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002654 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002655 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002656 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002657 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002658 if (Pos == 0 ||
2659 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002660 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2661 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002662 continue;
2663 }
2664 return RestOfBuffer.data()+Pos;
2665 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002666 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002667}
2668
2669/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2670/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2671/// and recover nicely. This returns true if it is a conflict marker and false
2672/// if not.
2673bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2674 // Only a conflict marker if it starts at the beginning of a line.
2675 if (CurPtr != BufferStart &&
2676 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2677 return false;
2678
Richard Smitha9e33d42011-10-12 00:37:51 +00002679 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002680 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2681 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002682 return false;
2683
2684 // If we have a situation where we don't care about conflict markers, ignore
2685 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002686 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002687 return false;
2688
Richard Smitha9e33d42011-10-12 00:37:51 +00002689 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2690
2691 // Check to see if there is an ending marker somewhere in the buffer at the
2692 // start of a line to terminate this conflict marker.
2693 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002694 // We found a match. We are really in a conflict marker.
2695 // Diagnose this, and ignore to the end of line.
2696 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002697 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002698
2699 // Skip ahead to the end of line. We know this exists because the
2700 // end-of-conflict marker starts with \r or \n.
2701 while (*CurPtr != '\r' && *CurPtr != '\n') {
2702 assert(CurPtr != BufferEnd && "Didn't find end of line");
2703 ++CurPtr;
2704 }
2705 BufferPtr = CurPtr;
2706 return true;
2707 }
2708
2709 // No end of conflict marker found.
2710 return false;
2711}
2712
Richard Smitha9e33d42011-10-12 00:37:51 +00002713/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2714/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2715/// is the end of a conflict marker. Handle it by ignoring up until the end of
2716/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002717bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2718 // Only a conflict marker if it starts at the beginning of a line.
2719 if (CurPtr != BufferStart &&
2720 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2721 return false;
2722
2723 // If we have a situation where we don't care about conflict markers, ignore
2724 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002725 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002726 return false;
2727
Richard Smitha9e33d42011-10-12 00:37:51 +00002728 // Check to see if we have the marker (4 characters in a row).
2729 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002730 if (CurPtr[i] != CurPtr[0])
2731 return false;
2732
2733 // If we do have it, search for the end of the conflict marker. This could
2734 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2735 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002736 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2737 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002738 CurPtr = End;
2739
2740 // Skip ahead to the end of line.
2741 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2742 ++CurPtr;
2743
2744 BufferPtr = CurPtr;
2745
2746 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002747 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002748 return true;
2749 }
2750
2751 return false;
2752}
2753
Alex Lorenz1be800c52017-04-19 08:58:56 +00002754static const char *findPlaceholderEnd(const char *CurPtr,
2755 const char *BufferEnd) {
2756 if (CurPtr == BufferEnd)
2757 return nullptr;
2758 BufferEnd -= 1; // Scan until the second last character.
2759 for (; CurPtr != BufferEnd; ++CurPtr) {
2760 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2761 return CurPtr + 2;
2762 }
2763 return nullptr;
2764}
2765
2766bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2767 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002768 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002769 return false;
2770 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2771 if (!End)
2772 return false;
2773 const char *Start = CurPtr - 1;
2774 if (!LangOpts.AllowEditorPlaceholders)
2775 Diag(Start, diag::err_placeholder_in_source);
2776 Result.startToken();
2777 FormTokenWithChars(Result, End, tok::raw_identifier);
2778 Result.setRawIdentifierData(Start);
2779 PP->LookUpIdentifierInfo(Result);
2780 Result.setFlag(Token::IsEditorPlaceholder);
2781 BufferPtr = End;
2782 return true;
2783}
2784
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002785bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2786 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002787 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002788 return Loc == PP->getCodeCompletionLoc();
2789 }
2790
2791 return false;
2792}
2793
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002794uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2795 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002796 unsigned CharSize;
2797 char Kind = getCharAndSize(StartPtr, CharSize);
2798
2799 unsigned NumHexDigits;
2800 if (Kind == 'u')
2801 NumHexDigits = 4;
2802 else if (Kind == 'U')
2803 NumHexDigits = 8;
2804 else
2805 return 0;
2806
Jordan Rosec0cba272013-01-27 20:12:04 +00002807 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002808 if (Result && !isLexingRawMode())
2809 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002810 return 0;
2811 }
2812
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002813 const char *CurPtr = StartPtr + CharSize;
2814 const char *KindLoc = &CurPtr[-1];
2815
2816 uint32_t CodePoint = 0;
2817 for (unsigned i = 0; i < NumHexDigits; ++i) {
2818 char C = getCharAndSize(CurPtr, CharSize);
2819
2820 unsigned Value = llvm::hexDigitValue(C);
2821 if (Value == -1U) {
2822 if (Result && !isLexingRawMode()) {
2823 if (i == 0) {
2824 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2825 << StringRef(KindLoc, 1);
2826 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002827 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002828
2829 // If the user wrote \U1234, suggest a fixit to \u.
2830 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002831 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002832 Diag(KindLoc, diag::note_ucn_four_not_eight)
2833 << FixItHint::CreateReplacement(URange, "u");
2834 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002835 }
2836 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002837
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002838 return 0;
2839 }
2840
2841 CodePoint <<= 4;
2842 CodePoint += Value;
2843
2844 CurPtr += CharSize;
2845 }
2846
2847 if (Result) {
2848 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002849 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002850 StartPtr = CurPtr;
2851 else
2852 while (StartPtr != CurPtr)
2853 (void)getAndAdvanceChar(StartPtr, *Result);
2854 } else {
2855 StartPtr = CurPtr;
2856 }
2857
Justin Bogner53535132013-10-21 05:02:28 +00002858 // Don't apply C family restrictions to UCNs in assembly mode
2859 if (LangOpts.AsmPreprocessor)
2860 return CodePoint;
2861
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002862 // C99 6.4.3p2: A universal character name shall not specify a character whose
2863 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2864 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2865 // C++11 [lex.charset]p2: If the hexadecimal value for a
2866 // universal-character-name corresponds to a surrogate code point (in the
2867 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2868 // if the hexadecimal value for a universal-character-name outside the
2869 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2870 // string literal corresponds to a control character (in either of the
2871 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2872 // basic source character set, the program is ill-formed.
2873 if (CodePoint < 0xA0) {
2874 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2875 return CodePoint;
2876
2877 // We don't use isLexingRawMode() here because we need to warn about bad
2878 // UCNs even when skipping preprocessing tokens in a #if block.
2879 if (Result && PP) {
2880 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2881 Diag(BufferPtr, diag::err_ucn_control_character);
2882 else {
2883 char C = static_cast<char>(CodePoint);
2884 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2885 }
2886 }
2887
2888 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002889
2890 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002891 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002892 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002893 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002894 if (Result && PP) {
2895 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2896 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2897 else
2898 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2899 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002900 return 0;
2901 }
2902
2903 return CodePoint;
2904}
2905
Eli Friedman0834a4b2013-09-19 00:41:32 +00002906bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2907 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002908 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2909 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002910 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002911 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002912 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002913 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002914
2915 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002916 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002917 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002918 return false;
2919}
Jordan Rose4246ae02013-01-24 20:50:50 +00002920
Eli Friedman0834a4b2013-09-19 00:41:32 +00002921bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002922 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2923 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2924 !PP->isPreprocessedOutput()) {
2925 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2926 makeCharRange(*this, BufferPtr, CurPtr),
2927 /*IsFirst=*/true);
2928 }
2929
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002930 MIOpt.ReadToken();
2931 return LexIdentifier(Result, CurPtr);
2932 }
2933
Jordan Rosecc538342013-01-31 19:48:48 +00002934 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2935 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002936 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002937 // Non-ASCII characters tend to creep into source code unintentionally.
2938 // Instead of letting the parser complain about the unknown token,
2939 // just drop the character.
2940 // Note that we can /only/ do this when the non-ASCII character is actually
2941 // spelled as Unicode, not written as a UCN. The standard requires that
2942 // we not throw away any possible preprocessor tokens, but there's a
2943 // loophole in the mapping of Unicode characters to basic character set
2944 // characters that allows us to map these particular characters to, say,
2945 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002946 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002947 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002948
2949 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002950 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002951 }
2952
2953 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2954 // up by accident.
2955 MIOpt.ReadToken();
2956 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002957 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002958}
2959
Eli Friedman0834a4b2013-09-19 00:41:32 +00002960void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2961 IsAtStartOfLine = Result.isAtStartOfLine();
2962 HasLeadingSpace = Result.hasLeadingSpace();
2963 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2964 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2965}
2966
2967bool Lexer::Lex(Token &Result) {
2968 // Start a new token.
2969 Result.startToken();
2970
2971 // Set up misc whitespace flags for LexTokenInternal.
2972 if (IsAtStartOfLine) {
2973 Result.setFlag(Token::StartOfLine);
2974 IsAtStartOfLine = false;
2975 }
2976
2977 if (HasLeadingSpace) {
2978 Result.setFlag(Token::LeadingSpace);
2979 HasLeadingSpace = false;
2980 }
2981
2982 if (HasLeadingEmptyMacro) {
2983 Result.setFlag(Token::LeadingEmptyMacro);
2984 HasLeadingEmptyMacro = false;
2985 }
2986
2987 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2988 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002989 bool isRawLex = isLexingRawMode();
2990 (void) isRawLex;
2991 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2992 // (After the LexTokenInternal call, the lexer might be destroyed.)
2993 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2994 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002995}
Chris Lattner22eb9722006-06-18 05:43:12 +00002996
2997/// LexTokenInternal - This implements a simple C family lexer. It is an
2998/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002999/// has a null character at the end of the file. This returns a preprocessing
3000/// token, not a normal token, as such, it is an internal interface. It assumes
3001/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003002bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003003LexNextToken:
3004 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003005 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003006 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003007
Chris Lattner22eb9722006-06-18 05:43:12 +00003008 // CurPtr - Cache BufferPtr in an automatic variable.
3009 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003010
Chris Lattnereb54b592006-07-10 06:34:27 +00003011 // Small amounts of horizontal whitespace is very common between tokens.
3012 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3013 ++CurPtr;
3014 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3015 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Chris Lattner4d963442008-10-12 04:05:48 +00003017 // If we are keeping whitespace and other tokens, just return what we just
3018 // skipped. The next lexer invocation will return the token after the
3019 // whitespace.
3020 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003021 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003022 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003023 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003024 }
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattnereb54b592006-07-10 06:34:27 +00003026 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003027 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Chris Lattner22eb9722006-06-18 05:43:12 +00003030 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003031
Chris Lattner22eb9722006-06-18 05:43:12 +00003032 // Read a character, advancing over it.
3033 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003034 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003035
Chris Lattner22eb9722006-06-18 05:43:12 +00003036 switch (Char) {
3037 case 0: // Null.
3038 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003039 if (CurPtr-1 == BufferEnd)
3040 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003042 // Check if we are performing code completion.
3043 if (isCodeCompletionPoint(CurPtr-1)) {
3044 // Return the code-completion token.
3045 Result.startToken();
3046 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003047 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003048 }
3049
Chris Lattner6d27a162008-11-22 02:02:22 +00003050 if (!isLexingRawMode())
3051 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003052 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003053 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3054 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003055
Eli Friedman0834a4b2013-09-19 00:41:32 +00003056 // We know the lexer hasn't changed, so just try again with this lexer.
3057 // (We manually eliminate the tail call to avoid recursion.)
3058 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003059
3060 case 26: // DOS & CP/M EOF: "^Z".
3061 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003062 if (LangOpts.MicrosoftExt) {
3063 if (!isLexingRawMode())
3064 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003065 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003066 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003067
Chris Lattner3dfff972009-12-17 05:29:40 +00003068 // If Microsoft extensions are disabled, this is just random garbage.
3069 Kind = tok::unknown;
3070 break;
3071
Chris Lattner22eb9722006-06-18 05:43:12 +00003072 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003073 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003074 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003075 LLVM_FALLTHROUGH;
3076 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003077 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003078 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003079 if (ParsingPreprocessorDirective) {
3080 // Done parsing the "line".
3081 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chris Lattner457fc152006-07-29 06:30:25 +00003083 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003084 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003085 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattner22eb9722006-06-18 05:43:12 +00003087 // Since we consumed a newline, we are back at the start of a line.
3088 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003089 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003090
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003091 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003092 break;
3093 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003094
Chris Lattner22eb9722006-06-18 05:43:12 +00003095 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003096 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003097
Eli Friedman0834a4b2013-09-19 00:41:32 +00003098 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3099 return true; // KeepWhitespaceMode
3100
3101 // We only saw whitespace, so just try again with this lexer.
3102 // (We manually eliminate the tail call to avoid recursion.)
3103 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003104 case ' ':
3105 case '\t':
3106 case '\f':
3107 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003108 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003109 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003110 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3111 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003112
3113 SkipIgnoredUnits:
3114 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003115
Chris Lattnerb9b85972007-07-22 06:29:05 +00003116 // If the next token is obviously a // or /* */ comment, skip it efficiently
3117 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003118 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003119 LangOpts.LineComment &&
3120 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003121 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3122 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003123 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003124 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003125 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3126 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003127 goto SkipIgnoredUnits;
3128 } else if (isHorizontalWhitespace(*CurPtr)) {
3129 goto SkipHorizontalWhitespace;
3130 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003131 // We only saw whitespace, so just try again with this lexer.
3132 // (We manually eliminate the tail call to avoid recursion.)
3133 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003134
Chris Lattner2b15cf72008-01-03 17:58:54 +00003135 // C99 6.4.4.1: Integer Constants.
3136 // C99 6.4.4.2: Floating Constants.
3137 case '0': case '1': case '2': case '3': case '4':
3138 case '5': case '6': case '7': case '8': case '9':
3139 // Notify MIOpt that we read a non-whitespace/non-comment token.
3140 MIOpt.ReadToken();
3141 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003142
Richard Smith9b362092013-03-09 23:56:02 +00003143 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003144 // Notify MIOpt that we read a non-whitespace/non-comment token.
3145 MIOpt.ReadToken();
3146
Richard Smith9b362092013-03-09 23:56:02 +00003147 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003148 Char = getCharAndSize(CurPtr, SizeTmp);
3149
3150 // UTF-16 string literal
3151 if (Char == '"')
3152 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3153 tok::utf16_string_literal);
3154
3155 // UTF-16 character constant
3156 if (Char == '\'')
3157 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3158 tok::utf16_char_constant);
3159
Craig Topper54edcca2011-08-11 04:06:15 +00003160 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003161 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3162 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003163 return LexRawStringLiteral(Result,
3164 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3165 SizeTmp2, Result),
3166 tok::utf16_string_literal);
3167
3168 if (Char == '8') {
3169 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3170
3171 // UTF-8 string literal
3172 if (Char2 == '"')
3173 return LexStringLiteral(Result,
3174 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3175 SizeTmp2, Result),
3176 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003177 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3178 return LexCharConstant(
3179 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3180 SizeTmp2, Result),
3181 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003182
Richard Smith9b362092013-03-09 23:56:02 +00003183 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003184 unsigned SizeTmp3;
3185 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3186 // UTF-8 raw string literal
3187 if (Char3 == '"') {
3188 return LexRawStringLiteral(Result,
3189 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3190 SizeTmp2, Result),
3191 SizeTmp3, Result),
3192 tok::utf8_string_literal);
3193 }
3194 }
3195 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003196 }
3197
3198 // treat u like the start of an identifier.
3199 return LexIdentifier(Result, CurPtr);
3200
Richard Smith9b362092013-03-09 23:56:02 +00003201 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003202 // Notify MIOpt that we read a non-whitespace/non-comment token.
3203 MIOpt.ReadToken();
3204
Richard Smith9b362092013-03-09 23:56:02 +00003205 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003206 Char = getCharAndSize(CurPtr, SizeTmp);
3207
3208 // UTF-32 string literal
3209 if (Char == '"')
3210 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3211 tok::utf32_string_literal);
3212
3213 // UTF-32 character constant
3214 if (Char == '\'')
3215 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3216 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003217
3218 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003219 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3220 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003221 return LexRawStringLiteral(Result,
3222 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3223 SizeTmp2, Result),
3224 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003225 }
3226
3227 // treat U like the start of an identifier.
3228 return LexIdentifier(Result, CurPtr);
3229
Craig Topper54edcca2011-08-11 04:06:15 +00003230 case 'R': // Identifier or C++0x raw string literal
3231 // Notify MIOpt that we read a non-whitespace/non-comment token.
3232 MIOpt.ReadToken();
3233
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003234 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003235 Char = getCharAndSize(CurPtr, SizeTmp);
3236
3237 if (Char == '"')
3238 return LexRawStringLiteral(Result,
3239 ConsumeChar(CurPtr, SizeTmp, Result),
3240 tok::string_literal);
3241 }
3242
3243 // treat R like the start of an identifier.
3244 return LexIdentifier(Result, CurPtr);
3245
Chris Lattner2b15cf72008-01-03 17:58:54 +00003246 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003247 // Notify MIOpt that we read a non-whitespace/non-comment token.
3248 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003249 Char = getCharAndSize(CurPtr, SizeTmp);
3250
3251 // Wide string literal.
3252 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003253 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003254 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003255
Craig Topper54edcca2011-08-11 04:06:15 +00003256 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003257 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003258 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3259 return LexRawStringLiteral(Result,
3260 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3261 SizeTmp2, Result),
3262 tok::wide_string_literal);
3263
Chris Lattner22eb9722006-06-18 05:43:12 +00003264 // Wide character constant.
3265 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003266 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3267 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003268 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003269 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003270
Chris Lattner22eb9722006-06-18 05:43:12 +00003271 // C99 6.4.2: Identifiers.
3272 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3273 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003274 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003275 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3276 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3277 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003278 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003279 case 'v': case 'w': case 'x': case 'y': case 'z':
3280 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003281 // Notify MIOpt that we read a non-whitespace/non-comment token.
3282 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003283 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003284
3285 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003286 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003287 if (!isLexingRawMode())
3288 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003289 // Notify MIOpt that we read a non-whitespace/non-comment token.
3290 MIOpt.ReadToken();
3291 return LexIdentifier(Result, CurPtr);
3292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Chris Lattnerb11c3232008-10-12 04:51:35 +00003294 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003295 break;
Mike Stump11289f42009-09-09 15:08:12 +00003296
Chris Lattner22eb9722006-06-18 05:43:12 +00003297 // C99 6.4.4: Character Constants.
3298 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003299 // Notify MIOpt that we read a non-whitespace/non-comment token.
3300 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003301 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003302
3303 // C99 6.4.5: String Literals.
3304 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003305 // Notify MIOpt that we read a non-whitespace/non-comment token.
3306 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003307 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003308
3309 // C99 6.4.6: Punctuators.
3310 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003311 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003312 break;
3313 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003314 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003315 break;
3316 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003317 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003318 break;
3319 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003320 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003321 break;
3322 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003323 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003324 break;
3325 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003327 break;
3328 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 break;
3331 case '.':
3332 Char = getCharAndSize(CurPtr, SizeTmp);
3333 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003334 // Notify MIOpt that we read a non-whitespace/non-comment token.
3335 MIOpt.ReadToken();
3336
Chris Lattner22eb9722006-06-18 05:43:12 +00003337 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003338 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003339 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003340 CurPtr += SizeTmp;
3341 } else if (Char == '.' &&
3342 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003343 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003344 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3345 SizeTmp2, Result);
3346 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 }
3349 break;
3350 case '&':
3351 Char = getCharAndSize(CurPtr, SizeTmp);
3352 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003353 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3355 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003356 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003357 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3358 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003359 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003360 }
3361 break;
Mike Stump11289f42009-09-09 15:08:12 +00003362 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003363 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003364 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003365 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3366 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003367 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003368 }
3369 break;
3370 case '+':
3371 Char = getCharAndSize(CurPtr, SizeTmp);
3372 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003373 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003374 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003375 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003376 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003378 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003379 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003380 }
3381 break;
3382 case '-':
3383 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003384 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003385 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003386 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003387 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003388 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003389 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3390 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003391 Kind = tok::arrowstar;
3392 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003393 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003394 Kind = tok::arrow;
3395 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003396 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003397 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003398 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003399 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003400 }
3401 break;
3402 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003403 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003404 break;
3405 case '!':
3406 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003407 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003408 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3409 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003410 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 }
3412 break;
3413 case '/':
3414 // 6.4.9: Comments
3415 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003416 if (Char == '/') { // Line comment.
3417 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003418 // want to lex this as a comment. There is one problem with this though,
3419 // that in one particular corner case, this can change the behavior of the
3420 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003421 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003422 // "foo". Check to see if the character after the second slash is a '*'.
3423 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003424 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003425 bool TreatAsComment = LangOpts.LineComment &&
3426 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003427 if (!TreatAsComment)
3428 if (!(PP && PP->isPreprocessedOutput()))
3429 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3430
3431 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003432 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3433 TokAtPhysicalStartOfLine))
3434 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003435
Chris Lattner58827712009-01-16 22:39:25 +00003436 // It is common for the tokens immediately after a // comment to be
3437 // whitespace (indentation for the next line). Instead of going through
3438 // the big switch, handle it efficiently now.
3439 goto SkipIgnoredUnits;
3440 }
3441 }
Mike Stump11289f42009-09-09 15:08:12 +00003442
Chris Lattner58827712009-01-16 22:39:25 +00003443 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003444 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3445 TokAtPhysicalStartOfLine))
3446 return true; // There is a token to return.
3447
3448 // We only saw whitespace, so just try again with this lexer.
3449 // (We manually eliminate the tail call to avoid recursion.)
3450 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Chris Lattner58827712009-01-16 22:39:25 +00003453 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003454 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003455 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003456 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003457 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003458 }
3459 break;
3460 case '%':
3461 Char = getCharAndSize(CurPtr, SizeTmp);
3462 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003463 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003464 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003465 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003466 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003467 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003468 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003469 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003470 Char = getCharAndSize(CurPtr, SizeTmp);
3471 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003472 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003473 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3474 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003475 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003476 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003477 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003478 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003479 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003480 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003481 // We parsed a # character. If this occurs at the start of the line,
3482 // it's actually the start of a preprocessing directive. Callback to
3483 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003484 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003485 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003486 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003487
Chris Lattner2534324a2009-03-18 20:58:27 +00003488 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003489 }
3490 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003491 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003492 }
3493 break;
3494 case '<':
3495 Char = getCharAndSize(CurPtr, SizeTmp);
3496 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003497 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003498 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003499 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3500 if (After == '=') {
3501 Kind = tok::lesslessequal;
3502 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3503 SizeTmp2, Result);
3504 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3505 // If this is actually a '<<<<<<<' version control conflict marker,
3506 // recognize it as such and recover nicely.
3507 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003508 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3509 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3510 // ignore it.
3511 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003512 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003513 Kind = tok::lesslessless;
3514 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3515 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003516 } else {
3517 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3518 Kind = tok::lessless;
3519 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003520 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003521 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003522 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003524 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003525 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3526 // C++0x [lex.pptoken]p3:
3527 // Otherwise, if the next three characters are <:: and the subsequent
3528 // character is neither : nor >, the < is treated as a preprocessor
3529 // token by itself and not as the first character of the alternative
3530 // token <:.
3531 unsigned SizeTmp3;
3532 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3533 if (After != ':' && After != '>') {
3534 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003535 if (!isLexingRawMode())
3536 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003537 break;
3538 }
3539 }
3540
Chris Lattner22eb9722006-06-18 05:43:12 +00003541 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003542 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003543 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003544 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003545 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003546 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3547 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003548 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003549 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003550 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003551 }
3552 break;
3553 case '>':
3554 Char = getCharAndSize(CurPtr, SizeTmp);
3555 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003556 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003557 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003558 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003559 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3560 if (After == '=') {
3561 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3562 SizeTmp2, Result);
3563 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003564 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3565 // If this is actually a '>>>>' conflict marker, recognize it as such
3566 // and recover nicely.
3567 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003568 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3569 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3570 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003571 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003572 Kind = tok::greatergreatergreater;
3573 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3574 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003575 } else {
3576 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3577 Kind = tok::greatergreater;
3578 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003579 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003580 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003581 }
3582 break;
3583 case '^':
3584 Char = getCharAndSize(CurPtr, SizeTmp);
3585 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003586 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003587 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003588 } else if (LangOpts.OpenCL && Char == '^') {
3589 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3590 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003591 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003592 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003593 }
3594 break;
3595 case '|':
3596 Char = getCharAndSize(CurPtr, SizeTmp);
3597 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003598 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003599 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3600 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003601 // If this is '|||||||' and we're in a conflict marker, ignore it.
3602 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3603 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003604 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003605 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3606 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003607 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003608 }
3609 break;
3610 case ':':
3611 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003612 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003613 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003614 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003615 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003616 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003617 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003618 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003619 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003620 }
3621 break;
3622 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003623 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003624 break;
3625 case '=':
3626 Char = getCharAndSize(CurPtr, SizeTmp);
3627 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003628 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003629 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3630 goto LexNextToken;
3631
Chris Lattnerb11c3232008-10-12 04:51:35 +00003632 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003633 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003634 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003635 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003636 }
3637 break;
3638 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003639 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003640 break;
3641 case '#':
3642 Char = getCharAndSize(CurPtr, SizeTmp);
3643 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003644 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003645 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003646 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003647 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003648 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003649 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003650 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003651 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003652 // We parsed a # character. If this occurs at the start of the line,
3653 // it's actually the start of a preprocessing directive. Callback to
3654 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003655 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003656 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003657 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003658
Chris Lattner2534324a2009-03-18 20:58:27 +00003659 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003660 }
3661 break;
3662
Chris Lattner2b15cf72008-01-03 17:58:54 +00003663 case '@':
3664 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003665 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003666 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003667 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003668 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003669 break;
Mike Stump11289f42009-09-09 15:08:12 +00003670
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003671 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003672 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003673 if (!LangOpts.AsmPreprocessor) {
3674 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3675 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3676 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3677 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003678
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003679 // We only saw whitespace, so just try again with this lexer.
3680 // (We manually eliminate the tail call to avoid recursion.)
3681 goto LexNextToken;
3682 }
3683
3684 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003685 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003686 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003687
Chris Lattnerb11c3232008-10-12 04:51:35 +00003688 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003689 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003690
3691 default: {
3692 if (isASCII(Char)) {
3693 Kind = tok::unknown;
3694 break;
3695 }
3696
Justin Lebar90910552016-09-30 00:38:45 +00003697 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003698
3699 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3700 // an escaped newline.
3701 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003702 llvm::ConversionResult Status =
3703 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3704 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003705 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003706 llvm::strictConversion);
3707 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003708 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3709 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3710 return true; // KeepWhitespaceMode
3711
3712 // We only saw whitespace, so just try again with this lexer.
3713 // (We manually eliminate the tail call to avoid recursion.)
3714 goto LexNextToken;
3715 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003716 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003717 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003718
Jordan Rosecc538342013-01-31 19:48:48 +00003719 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3720 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003721 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003722 Kind = tok::unknown;
3723 break;
3724 }
3725
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003726 // Non-ASCII characters tend to creep into source code unintentionally.
3727 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003728 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003729 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003730
3731 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003732 // We're pretending the character didn't exist, so just try again with
3733 // this lexer.
3734 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003735 goto LexNextToken;
3736 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003737 }
Mike Stump11289f42009-09-09 15:08:12 +00003738
Chris Lattner371ac8a2006-07-04 07:11:10 +00003739 // Notify MIOpt that we read a non-whitespace/non-comment token.
3740 MIOpt.ReadToken();
3741
Chris Lattnerd01e2912006-06-18 16:22:51 +00003742 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003743 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003744 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003745
3746HandleDirective:
3747 // We parsed a # character and it's the start of a preprocessing directive.
3748
3749 FormTokenWithChars(Result, CurPtr, tok::hash);
3750 PP->HandleDirective(Result);
3751
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003752 if (PP->hadModuleLoaderFatalFailure()) {
3753 // With a fatal failure in the module loader, we abort parsing.
3754 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003755 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003756 }
3757
Eli Friedman0834a4b2013-09-19 00:41:32 +00003758 // We parsed the directive; lex a token with the new state.
3759 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003760}