blob: 67dcff6b71534412c674ca32f945b45c4e5517d1 [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
Alex Lorenzebbbb812017-11-03 18:11:22 +00001215Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1216 const SourceManager &SM,
1217 const LangOptions &LangOpts) {
Anna Zaks59a3c802011-07-27 21:43:43 +00001218 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001219 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Alex Lorenzebbbb812017-11-03 18:11:22 +00001220 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001221 }
1222 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1223
1224 // Break down the source location.
1225 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1226
1227 // Try to load the file buffer.
1228 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001229 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001230 if (InvalidTemp)
Alex Lorenzebbbb812017-11-03 18:11:22 +00001231 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001232
1233 const char *TokenBegin = File.data() + LocInfo.second;
1234
1235 // Lex from the start of the given location.
1236 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1237 TokenBegin, File.end());
1238 // Find the token.
1239 Token Tok;
1240 lexer.LexFromRawLexer(Tok);
Alex Lorenzebbbb812017-11-03 18:11:22 +00001241 return Tok;
1242}
1243
1244/// \brief Checks that the given token is the first token that occurs after the
1245/// given location (this excludes comments and whitespace). Returns the location
1246/// immediately after the specified token. If the token is not found or the
1247/// location is inside a macro, the returned source location will be invalid.
1248SourceLocation Lexer::findLocationAfterToken(
1249 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1250 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1251 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1252 if (!Tok || Tok->isNot(TKind))
Anna Zaks59a3c802011-07-27 21:43:43 +00001253 return SourceLocation();
Alex Lorenzebbbb812017-11-03 18:11:22 +00001254 SourceLocation TokenLoc = Tok->getLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001255
1256 // Calculate how much whitespace needs to be skipped if any.
1257 unsigned NumWhitespaceChars = 0;
1258 if (SkipTrailingWhitespaceAndNewLine) {
Alex Lorenzebbbb812017-11-03 18:11:22 +00001259 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
Anna Zaks59a3c802011-07-27 21:43:43 +00001260 unsigned char C = *TokenEnd;
1261 while (isHorizontalWhitespace(C)) {
1262 C = *(++TokenEnd);
1263 NumWhitespaceChars++;
1264 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001265
1266 // Skip \r, \n, \r\n, or \n\r
1267 if (C == '\n' || C == '\r') {
1268 char PrevC = C;
1269 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001270 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001271 if ((C == '\n' || C == '\r') && C != PrevC)
1272 NumWhitespaceChars++;
1273 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001274 }
1275
Alex Lorenzebbbb812017-11-03 18:11:22 +00001276 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001277}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001278
Chris Lattner22eb9722006-06-18 05:43:12 +00001279/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1280/// get its size, and return it. This is tricky in several cases:
1281/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1282/// then either return the trigraph (skipping 3 chars) or the '?',
1283/// depending on whether trigraphs are enabled or not.
1284/// 2. If this is an escaped newline (potentially with whitespace between
1285/// the backslash and newline), implicitly skip the newline and return
1286/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001287///
1288/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1289/// know that we can accumulate into Size, and that we have already incremented
1290/// Ptr by Size bytes.
1291///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001292/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1293/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001294///
1295char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001296 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001297 // If we have a slash, look for an escaped newline.
1298 if (Ptr[0] == '\\') {
1299 ++Size;
1300 ++Ptr;
1301Slash:
1302 // Common case, backslash-char where the char is not whitespace.
1303 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattnerc1835952009-06-23 05:15:06 +00001305 // See if we have optional whitespace characters between the slash and
1306 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001307 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1308 // Remember that this token needs to be cleaned.
1309 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001310
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001311 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001312 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001313 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001315 // Found backslash<whitespace><newline>. Parse the char after it.
1316 Size += EscapedNewLineSize;
1317 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001318
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001319 // Use slow version to accumulate a correct size field.
1320 return getCharAndSizeSlow(Ptr, Size, Tok);
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 // Otherwise, this is not an escaped newline, just return the slash.
1324 return '\\';
1325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 // If this is a trigraph, process it.
1328 if (Ptr[0] == '?' && Ptr[1] == '?') {
1329 // If this is actually a legal trigraph (not something like "??x"), emit
1330 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001331 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001332 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001333 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001334
1335 Ptr += 3;
1336 Size += 3;
1337 if (C == '\\') goto Slash;
1338 return C;
1339 }
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 // If this is neither, return a single character.
1343 ++Size;
1344 return *Ptr;
1345}
1346
1347/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1348/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1349/// and that we have already incremented Ptr by Size bytes.
1350///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001351/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1352/// be updated to match.
1353char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001354 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 // If we have a slash, look for an escaped newline.
1356 if (Ptr[0] == '\\') {
1357 ++Size;
1358 ++Ptr;
1359Slash:
1360 // Common case, backslash-char where the char is not whitespace.
1361 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001362
Chris Lattner22eb9722006-06-18 05:43:12 +00001363 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001364 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1365 // Found backslash<whitespace><newline>. Parse the char after it.
1366 Size += EscapedNewLineSize;
1367 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001369 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001370 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 // Otherwise, this is not an escaped newline, just return the slash.
1374 return '\\';
1375 }
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001378 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001379 // If this is actually a legal trigraph (not something like "??x"), return
1380 // it.
1381 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1382 Ptr += 3;
1383 Size += 3;
1384 if (C == '\\') goto Slash;
1385 return C;
1386 }
1387 }
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner22eb9722006-06-18 05:43:12 +00001389 // If this is neither, return a single character.
1390 ++Size;
1391 return *Ptr;
1392}
1393
Chris Lattner22eb9722006-06-18 05:43:12 +00001394//===----------------------------------------------------------------------===//
1395// Helper methods for lexing.
1396//===----------------------------------------------------------------------===//
1397
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001398/// \brief Routine that indiscriminately sets the offset into the source file.
1399void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1400 BufferPtr = BufferStart + Offset;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001401 if (BufferPtr > BufferEnd)
1402 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001403 // FIXME: What exactly does the StartOfLine bit mean? There are two
1404 // possible meanings for the "start" of the line: the first token on the
1405 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001406 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001407 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001408}
1409
Jordan Rose58c61e02013-02-09 01:10:25 +00001410static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001411 if (LangOpts.AsmPreprocessor) {
1412 return false;
1413 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001414 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1415 C11AllowedIDCharRanges);
1416 return C11AllowedIDChars.contains(C);
1417 } else if (LangOpts.CPlusPlus) {
1418 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1419 CXX03AllowedIDCharRanges);
1420 return CXX03AllowedIDChars.contains(C);
1421 } else {
1422 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1423 C99AllowedIDCharRanges);
1424 return C99AllowedIDChars.contains(C);
1425 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001426}
1427
Jordan Rose58c61e02013-02-09 01:10:25 +00001428static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1429 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001430 if (LangOpts.AsmPreprocessor) {
1431 return false;
1432 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001433 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1434 C11DisallowedInitialIDCharRanges);
1435 return !C11DisallowedInitialIDChars.contains(C);
1436 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001437 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001438 } else {
1439 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1440 C99DisallowedInitialIDCharRanges);
1441 return !C99DisallowedInitialIDChars.contains(C);
1442 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001443}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001444
Jordan Rose58c61e02013-02-09 01:10:25 +00001445static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1446 const char *End) {
1447 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1448 L.getSourceLocation(End));
1449}
1450
1451static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1452 CharSourceRange Range, bool IsFirst) {
1453 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001454 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001455 enum {
1456 CannotAppearInIdentifier = 0,
1457 CannotStartIdentifier
1458 };
1459
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001460 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1461 C99AllowedIDCharRanges);
1462 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1463 C99DisallowedInitialIDCharRanges);
1464 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001465 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1466 << Range
1467 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001468 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001469 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1470 << Range
1471 << CannotStartIdentifier;
1472 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001473 }
1474
Jordan Rose58c61e02013-02-09 01:10:25 +00001475 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001476 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001477 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1478 CXX03AllowedIDCharRanges);
1479 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001480 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1481 << Range;
1482 }
1483 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001484}
1485
1486bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1487 Token &Result) {
1488 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001489 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001490 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1491 return false;
1492
1493 if (!isLexingRawMode())
1494 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495 makeCharRange(*this, CurPtr, UCNPtr),
1496 /*IsFirst=*/false);
1497
1498 Result.setFlag(Token::HasUCN);
1499 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1500 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1501 CurPtr = UCNPtr;
1502 else
1503 while (CurPtr != UCNPtr)
1504 (void)getAndAdvanceChar(CurPtr, Result);
1505 return true;
1506}
1507
1508bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1509 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001510 llvm::UTF32 CodePoint;
1511 llvm::ConversionResult Result =
1512 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1513 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001514 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001515 llvm::strictConversion);
1516 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001517 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1518 return false;
1519
1520 if (!isLexingRawMode())
1521 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1522 makeCharRange(*this, CurPtr, UnicodePtr),
1523 /*IsFirst=*/false);
1524
1525 CurPtr = UnicodePtr;
1526 return true;
1527}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001528
Eli Friedman0834a4b2013-09-19 00:41:32 +00001529bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001530 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1531 unsigned Size;
1532 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001533 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001535
Chris Lattner22eb9722006-06-18 05:43:12 +00001536 --CurPtr; // Back up over the skipped character.
1537
1538 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1539 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001540 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001541 // TODO: Could merge these checks into an InfoTable flag to make the
1542 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001543 if (isASCII(C) && C != '\\' && C != '?' &&
1544 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001545FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001546 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001547 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1548 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001549
Chris Lattner0f1f5052006-07-20 04:16:23 +00001550 // If we are in raw mode, return this identifier raw. There is no need to
1551 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001552 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001553 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001554
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001555 // Fill in Result.IdentifierInfo and update the token kind,
1556 // looking up the identifier in the identifier table.
1557 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001558
Chris Lattnerc5a00062006-06-18 16:41:01 +00001559 // Finally, now that we know we have an identifier, pass this off to the
1560 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001561 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001562 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001563
1564 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1565 && II->getPPKeywordID() == tok::pp_not_keyword
1566 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1567 // Return the code-completion token.
1568 Result.setKind(tok::code_completion);
1569 cutOffLexing();
1570 return true;
1571 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001572 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 }
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001578 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 if (C == '$') {
1580 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001581 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001582
Chris Lattner22eb9722006-06-18 05:43:12 +00001583 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001584 if (!isLexingRawMode())
1585 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001586 CurPtr = ConsumeChar(CurPtr, Size, Result);
1587 C = getCharAndSize(CurPtr, Size);
1588 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001589
Richard Smith8b7258b2014-02-17 21:52:30 +00001590 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001591 C = getCharAndSize(CurPtr, Size);
1592 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001593 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001594 C = getCharAndSize(CurPtr, Size);
1595 continue;
1596 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001597 goto FinishIdentifier;
1598 }
1599
1600 // Otherwise, this character is good, consume it.
1601 CurPtr = ConsumeChar(CurPtr, Size, Result);
1602
1603 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001604 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001605 CurPtr = ConsumeChar(CurPtr, Size, Result);
1606 C = getCharAndSize(CurPtr, Size);
1607 }
1608 }
1609}
1610
Douglas Gregor759ef232010-08-30 14:50:47 +00001611/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001612/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001613bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001614 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001615 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001616 if (C1 != '0')
1617 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001618 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001619 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001620}
Chris Lattner22eb9722006-06-18 05:43:12 +00001621
Nate Begeman5eee9332008-04-14 02:26:39 +00001622/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001623/// constant. From[-1] is the first character lexed. Return the end of the
1624/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001625bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 unsigned Size;
1627 char C = getCharAndSize(CurPtr, Size);
1628 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001629 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001630 CurPtr = ConsumeChar(CurPtr, Size, Result);
1631 PrevCh = C;
1632 C = getCharAndSize(CurPtr, Size);
1633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner22eb9722006-06-18 05:43:12 +00001635 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001636 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1637 // If we are in Microsoft mode, don't continue if the constant is hex.
1638 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001639 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001640 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1641 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001642
1643 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001644 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001645 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001646 // not-quite-conforming extension. Only do so if this looks like it's
1647 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1648 bool IsHexFloat = true;
1649 if (!LangOpts.C99) {
1650 if (!isHexaLiteral(BufferPtr, LangOpts))
1651 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001652 else if (!getLangOpts().CPlusPlus1z &&
1653 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001654 IsHexFloat = false;
1655 }
1656 if (IsHexFloat)
1657 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1658 }
Mike Stump11289f42009-09-09 15:08:12 +00001659
Richard Smithfde94852013-09-26 03:33:06 +00001660 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001661 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001662 unsigned NextSize;
1663 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001664 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001665 if (!isLexingRawMode())
1666 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1667 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001668 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001669 return LexNumericConstant(Result, CurPtr);
1670 }
1671 }
1672
Richard Smith8b7258b2014-02-17 21:52:30 +00001673 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1674 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1675 return LexNumericConstant(Result, CurPtr);
1676 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1677 return LexNumericConstant(Result, CurPtr);
1678
Chris Lattnerd01e2912006-06-18 16:22:51 +00001679 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001680 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001681 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001682 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001683 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001684}
1685
Richard Smithe18f0fa2012-03-05 04:02:15 +00001686/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001687/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001688const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1689 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001690 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001691
Richard Smith8b7258b2014-02-17 21:52:30 +00001692 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001693 unsigned Size;
1694 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001695 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001696
Richard Smith8b7258b2014-02-17 21:52:30 +00001697 if (!isIdentifierHead(C)) {
1698 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1699 Consumed = true;
1700 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1701 Consumed = true;
1702 else
1703 return CurPtr;
1704 }
1705
1706 if (!getLangOpts().CPlusPlus11) {
1707 if (!isLexingRawMode())
1708 Diag(CurPtr,
1709 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1710 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1711 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1712 return CurPtr;
1713 }
1714
1715 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1716 // that does not start with an underscore is ill-formed. As a conforming
1717 // extension, we treat all such suffixes as if they had whitespace before
1718 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1719 // likely to be a ud-suffix than a macro, however, and accept that.
1720 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001721 bool IsUDSuffix = false;
1722 if (C == '_')
1723 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001724 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001725 // In C++1y, we need to look ahead a few characters to see if this is a
1726 // valid suffix for a string literal or a numeric literal (this could be
1727 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001728 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001729 char Buffer[MaxStandardSuffixLength] = { C };
1730 unsigned Consumed = Size;
1731 unsigned Chars = 1;
1732 while (true) {
1733 unsigned NextSize;
1734 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1735 getLangOpts());
1736 if (!isIdentifierBody(Next)) {
1737 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001738 const StringRef CompleteSuffix(Buffer, Chars);
1739 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1740 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001741 break;
1742 }
1743
1744 if (Chars == MaxStandardSuffixLength)
1745 // Too long: can't be a standard suffix.
1746 break;
1747
1748 Buffer[Chars++] = Next;
1749 Consumed += NextSize;
1750 }
Richard Smithf4198b72013-07-23 08:14:48 +00001751 }
1752
1753 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001754 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001755 Diag(CurPtr, getLangOpts().MSVCCompat
1756 ? diag::ext_ms_reserved_user_defined_literal
1757 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001758 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001759 return CurPtr;
1760 }
1761
Richard Smith8b7258b2014-02-17 21:52:30 +00001762 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001763 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001764
1765 Result.setFlag(Token::HasUDSuffix);
1766 while (true) {
1767 C = getCharAndSize(CurPtr, Size);
1768 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1769 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1770 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1771 else break;
1772 }
1773
Richard Smithe18f0fa2012-03-05 04:02:15 +00001774 return CurPtr;
1775}
1776
Chris Lattner22eb9722006-06-18 05:43:12 +00001777/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001778/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001779bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001780 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001781 // Does this string contain the \0 character?
1782 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Richard Smithacd4d3d2011-10-15 01:18:56 +00001784 if (!isLexingRawMode() &&
1785 (Kind == tok::utf8_string_literal ||
1786 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001787 Kind == tok::utf32_string_literal))
1788 Diag(BufferPtr, getLangOpts().CPlusPlus
1789 ? diag::warn_cxx98_compat_unicode_literal
1790 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001791
Chris Lattner22eb9722006-06-18 05:43:12 +00001792 char C = getAndAdvanceChar(CurPtr, Result);
1793 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001794 // Skip escaped characters. Escaped newlines will already be processed by
1795 // getAndAdvanceChar.
1796 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001798
Chris Lattner52d96ac2010-05-30 23:27:38 +00001799 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001800 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001801 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001802 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001803 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001804 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001805 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001806
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001807 if (C == 0) {
1808 if (isCodeCompletionPoint(CurPtr-1)) {
1809 PP->CodeCompleteNaturalLanguage();
1810 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001811 cutOffLexing();
1812 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001813 }
1814
Chris Lattner52d96ac2010-05-30 23:27:38 +00001815 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001816 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001817 C = getAndAdvanceChar(CurPtr, Result);
1818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
Richard Smithe18f0fa2012-03-05 04:02:15 +00001820 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001821 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001822 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001823
Chris Lattner5a78a022006-07-20 06:02:19 +00001824 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001825 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001826 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001827
Chris Lattnerd01e2912006-06-18 16:22:51 +00001828 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001829 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001830 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001831 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001832 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001833}
1834
Craig Topper54edcca2011-08-11 04:06:15 +00001835/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1836/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001837bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001838 tok::TokenKind Kind) {
1839 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1840 // Between the initial and final double quote characters of the raw string,
1841 // any transformations performed in phases 1 and 2 (trigraphs,
1842 // universal-character-names, and line splicing) are reverted.
1843
Richard Smithacd4d3d2011-10-15 01:18:56 +00001844 if (!isLexingRawMode())
1845 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1846
Craig Topper54edcca2011-08-11 04:06:15 +00001847 unsigned PrefixLen = 0;
1848
1849 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1850 ++PrefixLen;
1851
1852 // If the last character was not a '(', then we didn't lex a valid delimiter.
1853 if (CurPtr[PrefixLen] != '(') {
1854 if (!isLexingRawMode()) {
1855 const char *PrefixEnd = &CurPtr[PrefixLen];
1856 if (PrefixLen == 16) {
1857 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1858 } else {
1859 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1860 << StringRef(PrefixEnd, 1);
1861 }
1862 }
1863
1864 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1865 // it's possible the '"' was intended to be part of the raw string, but
1866 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001867 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001868 char C = *CurPtr++;
1869
1870 if (C == '"')
1871 break;
1872 if (C == 0 && CurPtr-1 == BufferEnd) {
1873 --CurPtr;
1874 break;
1875 }
1876 }
1877
1878 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001879 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001880 }
1881
1882 // Save prefix and move CurPtr past it
1883 const char *Prefix = CurPtr;
1884 CurPtr += PrefixLen + 1; // skip over prefix and '('
1885
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001886 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001887 char C = *CurPtr++;
1888
1889 if (C == ')') {
1890 // Check for prefix match and closing quote.
1891 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1892 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1893 break;
1894 }
1895 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1896 if (!isLexingRawMode())
1897 Diag(BufferPtr, diag::err_unterminated_raw_string)
1898 << StringRef(Prefix, PrefixLen);
1899 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001900 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001901 }
1902 }
1903
Richard Smithe18f0fa2012-03-05 04:02:15 +00001904 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001905 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001906 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001907
Craig Topper54edcca2011-08-11 04:06:15 +00001908 // Update the location of token as well as BufferPtr.
1909 const char *TokStart = BufferPtr;
1910 FormTokenWithChars(Result, CurPtr, Kind);
1911 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001912 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001913}
1914
Chris Lattner22eb9722006-06-18 05:43:12 +00001915/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1916/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001917bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001918 // Does this string contain the \0 character?
1919 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001920 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 char C = getAndAdvanceChar(CurPtr, Result);
1922 while (C != '>') {
1923 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001924 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001926 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001927 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001928 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1929 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001930 // If the filename is unterminated, then it must just be a lone <
1931 // character. Return this as such.
1932 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001933 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001934 } else if (C == 0) {
1935 NulCharacter = CurPtr-1;
1936 }
1937 C = getAndAdvanceChar(CurPtr, Result);
1938 }
Mike Stump11289f42009-09-09 15:08:12 +00001939
Chris Lattner5a78a022006-07-20 06:02:19 +00001940 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001941 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001942 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001943
Chris Lattnerd01e2912006-06-18 16:22:51 +00001944 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001945 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001946 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001947 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001948 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001949}
1950
Chris Lattner22eb9722006-06-18 05:43:12 +00001951/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001952/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001953bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001954 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001955 // Does this character contain the \0 character?
1956 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001957
Richard Smith3e3a7052014-11-08 06:08:42 +00001958 if (!isLexingRawMode()) {
1959 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1960 Diag(BufferPtr, getLangOpts().CPlusPlus
1961 ? diag::warn_cxx98_compat_unicode_literal
1962 : diag::warn_c99_compat_unicode_literal);
1963 else if (Kind == tok::utf8_char_constant)
1964 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1965 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001966
Chris Lattner22eb9722006-06-18 05:43:12 +00001967 char C = getAndAdvanceChar(CurPtr, Result);
1968 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001969 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001970 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001971 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001972 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001973 }
1974
1975 while (C != '\'') {
1976 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001977 if (C == '\\')
1978 C = getAndAdvanceChar(CurPtr, Result);
1979
1980 if (C == '\n' || C == '\r' || // Newline.
1981 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001982 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001983 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001984 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001985 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001986 }
1987
1988 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001989 if (isCodeCompletionPoint(CurPtr-1)) {
1990 PP->CodeCompleteNaturalLanguage();
1991 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001992 cutOffLexing();
1993 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001994 }
1995
Chris Lattner86851b82010-07-07 23:24:27 +00001996 NulCharacter = CurPtr-1;
1997 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001998 C = getAndAdvanceChar(CurPtr, Result);
1999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Richard Smithe18f0fa2012-03-05 04:02:15 +00002001 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002002 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002003 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002004
Chris Lattner86851b82010-07-07 23:24:27 +00002005 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002006 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002007 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002008
Chris Lattnerd01e2912006-06-18 16:22:51 +00002009 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002010 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002011 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002012 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002013 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002014}
2015
2016/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2017/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002018///
2019/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2020///
Eli Friedman0834a4b2013-09-19 00:41:32 +00002021bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2022 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002023 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002024 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2025
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002026 unsigned char Char = *CurPtr;
2027
2028 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002029 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002030 // Skip horizontal whitespace very aggressively.
2031 while (isHorizontalWhitespace(Char))
2032 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002033
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002034 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002035 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002036 break;
Mike Stump11289f42009-09-09 15:08:12 +00002037
Chris Lattner22eb9722006-06-18 05:43:12 +00002038 if (ParsingPreprocessorDirective) {
2039 // End of preprocessor directive line, let LexTokenInternal handle this.
2040 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002041 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002044 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002045 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 Char = *++CurPtr;
2047 }
2048
Chris Lattner4d963442008-10-12 04:05:48 +00002049 // If the client wants us to return whitespace, return it now.
2050 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002051 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002052 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002053 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002054 IsAtPhysicalStartOfLine = true;
2055 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002056 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002057 return true;
2058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002060 // If this isn't immediately after a newline, there is leading space.
2061 char PrevChar = CurPtr[-1];
2062 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2063
2064 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002065 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002066 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002067 TokAtPhysicalStartOfLine = true;
2068 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002069
Chris Lattner22eb9722006-06-18 05:43:12 +00002070 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002071 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002072}
2073
Nico Weber158a31a2012-11-11 07:02:14 +00002074/// We have just read the // characters from input. Skip until we find the
2075/// newline character thats terminate the comment. Then update BufferPtr and
2076/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002077///
2078/// If we're in KeepCommentMode or any CommentHandler has inserted
2079/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002080bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2081 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002082 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002084 if (!LangOpts.LineComment && !isLexingRawMode()) {
2085 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002086
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 // Mark them enabled so we only emit one warning for this translation
2088 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002089 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Chris Lattner22eb9722006-06-18 05:43:12 +00002092 // Scan over the body of the comment. The common case, when scanning, is that
2093 // the comment contains normal ascii characters with nothing interesting in
2094 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002095 //
2096 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2097 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002099 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002100 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002101 // Skip over characters in the fast loop.
2102 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002103 C != '\n' && C != '\r') // Newline or DOS-style newline.
2104 C = *++CurPtr;
2105
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002106 const char *NextLine = CurPtr;
2107 if (C != 0) {
2108 // We found a newline, see if it's escaped.
2109 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002110 bool HasSpace = false;
2111 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002112 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002113 HasSpace = true;
2114 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002115
Richard Smith4c132e52017-04-18 21:45:04 +00002116 if (*EscapePtr == '\\')
2117 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002118 CurPtr = EscapePtr;
2119 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002120 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2121 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002122 CurPtr = EscapePtr-2;
2123 else
2124 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002125
2126 // If there was space between the backslash and newline, warn about it.
2127 if (HasSpace && !isLexingRawMode())
2128 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002132 // properly decode the character. Read it in raw mode to avoid emitting
2133 // diagnostics about things like trigraphs. If we see an escaped newline,
2134 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002136 bool OldRawMode = isLexingRawMode();
2137 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002138 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002139 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002140
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002141 // If we only read only one character, then no special handling is needed.
2142 // We're done and can skip forward to the newline.
2143 if (C != 0 && CurPtr == OldPtr+1) {
2144 CurPtr = NextLine;
2145 break;
2146 }
2147
Chris Lattner22eb9722006-06-18 05:43:12 +00002148 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002149 // \n, then we had an escaped newline within the comment. Emit diagnostic
2150 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002151 if (CurPtr != OldPtr + 1 && C != '/' &&
2152 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002153 for (; OldPtr != CurPtr; ++OldPtr)
2154 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002155 // Okay, we found a // comment that ends in a newline, if the next
2156 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002157 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002158 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002159 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002160 ++ForwardPtr;
2161 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2162 break;
2163 }
Mike Stump11289f42009-09-09 15:08:12 +00002164
Chris Lattner6d27a162008-11-22 02:02:22 +00002165 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002166 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002167 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 }
2169 }
Mike Stump11289f42009-09-09 15:08:12 +00002170
Richard Smith1d2ae942017-04-17 23:44:51 +00002171 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2172 --CurPtr;
2173 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002174 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002175
2176 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2177 PP->CodeCompleteNaturalLanguage();
2178 cutOffLexing();
2179 return false;
2180 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002181 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002182
Chris Lattner93ddf802010-02-03 21:06:21 +00002183 // Found but did not consume the newline. Notify comment handlers about the
2184 // comment unless we're in a #if 0 block.
2185 if (PP && !isLexingRawMode() &&
2186 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2187 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002188 BufferPtr = CurPtr;
2189 return true; // A token has to be returned.
2190 }
Mike Stump11289f42009-09-09 15:08:12 +00002191
Chris Lattner457fc152006-07-29 06:30:25 +00002192 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002193 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002194 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002195
2196 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002197 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002198 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002199 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002200 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattner22eb9722006-06-18 05:43:12 +00002203 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002204 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002205 // contribute to another token), it isn't needed for correctness. Note that
2206 // this is ok even in KeepWhitespaceMode, because we would have returned the
2207 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002208 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattner22eb9722006-06-18 05:43:12 +00002210 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002211 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002212 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002213 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002214 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002215 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002216 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002217}
Chris Lattner22eb9722006-06-18 05:43:12 +00002218
Nico Weber158a31a2012-11-11 07:02:14 +00002219/// If in save-comment mode, package up this Line comment in an appropriate
2220/// way and return it.
2221bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002222 // If we're not in a preprocessor directive, just return the // comment
2223 // directly.
2224 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002225
David Blaikied5321242012-06-06 18:52:13 +00002226 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002227 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002228
Nico Weber158a31a2012-11-11 07:02:14 +00002229 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002230 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002231 bool Invalid = false;
2232 std::string Spelling = PP->getSpelling(Result, &Invalid);
2233 if (Invalid)
2234 return true;
2235
Nico Weber158a31a2012-11-11 07:02:14 +00002236 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002237 Spelling[1] = '*'; // Change prefix to "/*".
2238 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002239
Chris Lattnerb11c3232008-10-12 04:51:35 +00002240 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002241 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002242 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002243 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002244}
2245
Chris Lattnercb283342006-06-18 06:48:37 +00002246/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002247/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2248/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002249static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002250 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002251 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002252
Chris Lattner22eb9722006-06-18 05:43:12 +00002253 // Back up off the newline.
2254 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattner22eb9722006-06-18 05:43:12 +00002256 // If this is a two-character newline sequence, skip the other character.
2257 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2258 // \n\n or \r\r -> not escaped newline.
2259 if (CurPtr[0] == CurPtr[1])
2260 return false;
2261 // \n\r or \r\n -> skip the newline.
2262 --CurPtr;
2263 }
Mike Stump11289f42009-09-09 15:08:12 +00002264
Chris Lattner22eb9722006-06-18 05:43:12 +00002265 // If we have horizontal whitespace, skip over it. We allow whitespace
2266 // between the slash and newline.
2267 bool HasSpace = false;
2268 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2269 --CurPtr;
2270 HasSpace = true;
2271 }
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattner22eb9722006-06-18 05:43:12 +00002273 // If we have a slash, we know this is an escaped newline.
2274 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002275 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002276 } else {
2277 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002278 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2279 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002280 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002281
Chris Lattnercb283342006-06-18 06:48:37 +00002282 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002283 CurPtr -= 2;
2284
2285 // If no trigraphs are enabled, warn that we ignored this trigraph and
2286 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002287 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002288 if (!L->isLexingRawMode())
2289 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002290 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002291 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002292 if (!L->isLexingRawMode())
2293 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 }
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattner22eb9722006-06-18 05:43:12 +00002296 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002297 if (!L->isLexingRawMode())
2298 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattner22eb9722006-06-18 05:43:12 +00002300 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002301 if (HasSpace && !L->isLexingRawMode())
2302 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002303
Chris Lattnercb283342006-06-18 06:48:37 +00002304 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002305}
2306
Chris Lattneraded4a92006-10-27 04:42:31 +00002307#ifdef __SSE2__
2308#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002309#elif __ALTIVEC__
2310#include <altivec.h>
2311#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002312#endif
2313
James Dennettf442d242012-06-17 03:40:43 +00002314/// We have just read from input the / and * characters that started a comment.
2315/// Read until we find the * and / characters that terminate the comment.
2316/// Note that we don't bother decoding trigraphs or escaped newlines in block
2317/// comments, because they cannot cause the comment to end. The only thing
2318/// that can happen is the comment could end with an escaped newline between
2319/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002320///
Chris Lattner87d02082010-01-18 22:35:47 +00002321/// If we're in KeepCommentMode or any CommentHandler has inserted
2322/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002323bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2324 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002325 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002326 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002327 // optimization helps people who like to put a lot of * characters in their
2328 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002329
2330 // The first character we get with newlines and trigraphs skipped to handle
2331 // the degenerate /*/ case below correctly if the * has an escaped newline
2332 // after it.
2333 unsigned CharSize;
2334 unsigned char C = getCharAndSize(CurPtr, CharSize);
2335 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002336 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002337 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002338 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002339 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002340
Chris Lattner99e7d232008-10-12 04:19:49 +00002341 // KeepWhitespaceMode should return this broken comment as a token. Since
2342 // it isn't a well formed comment, just return it as an 'unknown' token.
2343 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002344 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002345 return true;
2346 }
Mike Stump11289f42009-09-09 15:08:12 +00002347
Chris Lattner99e7d232008-10-12 04:19:49 +00002348 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002349 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002350 }
Mike Stump11289f42009-09-09 15:08:12 +00002351
Chris Lattnerc850ad62007-07-21 23:43:37 +00002352 // Check to see if the first character after the '/*' is another /. If so,
2353 // then this slash does not end the block comment, it is part of it.
2354 if (C == '/')
2355 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002356
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002357 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002358 // Skip over all non-interesting characters until we find end of buffer or a
2359 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002360 if (CurPtr + 24 < BufferEnd &&
2361 // If there is a code-completion point avoid the fast scan because it
2362 // doesn't check for '\0'.
2363 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002364 // While not aligned to a 16-byte boundary.
2365 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2366 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattner6cc3e362006-10-27 04:12:35 +00002368 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002369
2370#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002371 __m128i Slashes = _mm_set1_epi8('/');
2372 while (CurPtr+16 <= BufferEnd) {
2373 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2374 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002375 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002376 // Adjust the pointer to point directly after the first slash. It's
2377 // not necessary to set C here, it will be overwritten at the end of
2378 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002379 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002380 goto FoundSlash;
2381 }
Roman Divacky61509902014-04-03 18:04:52 +00002382 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002383 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002384#elif __ALTIVEC__
2385 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002386 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002387 '/', '/', '/', '/', '/', '/', '/', '/'
2388 };
2389 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002390 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002391 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002392#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002393 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002394 while (CurPtr[0] != '/' &&
2395 CurPtr[1] != '/' &&
2396 CurPtr[2] != '/' &&
2397 CurPtr[3] != '/' &&
2398 CurPtr+4 < BufferEnd) {
2399 CurPtr += 4;
2400 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002401#endif
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattneraded4a92006-10-27 04:42:31 +00002403 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002404 C = *CurPtr++;
2405 }
Mike Stump11289f42009-09-09 15:08:12 +00002406
Chris Lattneraded4a92006-10-27 04:42:31 +00002407 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002408 while (C != '/' && C != '\0')
2409 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002410
Chris Lattner22eb9722006-06-18 05:43:12 +00002411 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002412 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002413 if (CurPtr[-2] == '*') // We found the final */. We're done!
2414 break;
Mike Stump11289f42009-09-09 15:08:12 +00002415
Chris Lattner22eb9722006-06-18 05:43:12 +00002416 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002417 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002418 // We found the final */, though it had an escaped newline between the
2419 // * and /. We're done!
2420 break;
2421 }
2422 }
2423 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2424 // If this is a /* inside of the comment, emit a warning. Don't do this
2425 // if this is a /*/, which will end the comment. This misses cases with
2426 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002427 if (!isLexingRawMode())
2428 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002429 }
2430 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002431 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002432 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002433 // Note: the user probably forgot a */. We could continue immediately
2434 // after the /*, but this would involve lexing a lot of what really is the
2435 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002436 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002437
Chris Lattner99e7d232008-10-12 04:19:49 +00002438 // KeepWhitespaceMode should return this broken comment as a token. Since
2439 // it isn't a well formed comment, just return it as an 'unknown' token.
2440 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002441 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002442 return true;
2443 }
Mike Stump11289f42009-09-09 15:08:12 +00002444
Chris Lattner99e7d232008-10-12 04:19:49 +00002445 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002446 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002447 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2448 PP->CodeCompleteNaturalLanguage();
2449 cutOffLexing();
2450 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002451 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002452
Chris Lattner22eb9722006-06-18 05:43:12 +00002453 C = *CurPtr++;
2454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner93ddf802010-02-03 21:06:21 +00002456 // Notify comment handlers about the comment unless we're in a #if 0 block.
2457 if (PP && !isLexingRawMode() &&
2458 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2459 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002460 BufferPtr = CurPtr;
2461 return true; // A token has to be returned.
2462 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002463
Chris Lattner457fc152006-07-29 06:30:25 +00002464 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002465 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002466 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002467 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002468 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002469
2470 // It is common for the tokens immediately after a /**/ comment to be
2471 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002472 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2473 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002474 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002475 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002476 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002477 }
2478
2479 // Otherwise, just return so that the next character will be lexed as a token.
2480 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002481 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002482 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002483}
2484
2485//===----------------------------------------------------------------------===//
2486// Primary Lexing Entry Points
2487//===----------------------------------------------------------------------===//
2488
Chris Lattner22eb9722006-06-18 05:43:12 +00002489/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2490/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002491void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002492 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2493 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002494 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002495
2496 // CurPtr - Cache BufferPtr in an automatic variable.
2497 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002498 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002499 char Char = getAndAdvanceChar(CurPtr, Tmp);
2500 switch (Char) {
2501 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002502 if (Result)
2503 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002504 break;
2505 case 0: // Null.
2506 // Found end of file?
2507 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002508 if (isCodeCompletionPoint(CurPtr-1)) {
2509 PP->CodeCompleteNaturalLanguage();
2510 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002511 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002512 }
2513
Chris Lattner22eb9722006-06-18 05:43:12 +00002514 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002515 if (Result)
2516 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002517 break;
2518 }
2519 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002520 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002521 case '\r':
2522 case '\n':
2523 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2524 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2525 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002526
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002527 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002528 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002529 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002530 if (PP)
2531 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002532 Lex(Tmp);
2533 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002534 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002535
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002536 // Finally, we're done;
2537 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002538 }
2539 }
2540}
2541
2542/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2543/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002544/// This returns true if Result contains a token, false if PP.Lex should be
2545/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002546bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002547 // If we hit the end of the file while parsing a preprocessor directive,
2548 // end the preprocessor directive first. The next token returned will
2549 // then be the end of file.
2550 if (ParsingPreprocessorDirective) {
2551 // Done parsing the "line".
2552 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002553 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002554 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Chris Lattner457fc152006-07-29 06:30:25 +00002556 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002557 if (PP)
2558 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002559 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002560 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002561
Chris Lattner30a2fa12006-07-19 06:31:49 +00002562 // If we are in raw mode, return this event as an EOF token. Let the caller
2563 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002564 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002565 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002566 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002567 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002568 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002569 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002570
Erik Verbruggen795eee92017-07-05 09:44:07 +00002571 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002572 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2573 ConditionalStack.clear();
2574 }
2575
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002576 // Issue diagnostics for unterminated #if and missing newline.
2577
Chris Lattner30a2fa12006-07-19 06:31:49 +00002578 // If we are in a #if directive, emit an error.
2579 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002580 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002581 PP->Diag(ConditionalStack.back().IfLoc,
2582 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002583 ConditionalStack.pop_back();
2584 }
Mike Stump11289f42009-09-09 15:08:12 +00002585
Chris Lattner8f96d042008-04-12 05:54:25 +00002586 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2587 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002588 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2589 DiagnosticsEngine &Diags = PP->getDiagnostics();
2590 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2591 unsigned DiagID;
2592
2593 if (LangOpts.CPlusPlus11) {
2594 // C++11 [lex.phases] 2.2 p2
2595 // Prefer the C++98 pedantic compatibility warning over the generic,
2596 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002597 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002598 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2599 } else {
2600 DiagID = diag::warn_no_newline_eof;
2601 }
2602 } else {
2603 DiagID = diag::ext_no_newline_eof;
2604 }
2605
2606 Diag(BufferEnd, DiagID)
2607 << FixItHint::CreateInsertion(EndLoc, "\n");
2608 }
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattner22eb9722006-06-18 05:43:12 +00002610 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002611
2612 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002613 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002614}
2615
Chris Lattner678c8802006-07-11 05:46:12 +00002616/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2617/// the specified lexer will return a tok::l_paren token, 0 if it is something
2618/// else and 2 if there are no more tokens in the buffer controlled by the
2619/// lexer.
2620unsigned Lexer::isNextPPTokenLParen() {
2621 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002622
Chris Lattner678c8802006-07-11 05:46:12 +00002623 // Switch to 'skipping' mode. This will ensure that we can lex a token
2624 // without emitting diagnostics, disables macro expansion, and will cause EOF
2625 // to return an EOF token instead of popping the include stack.
2626 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Chris Lattner678c8802006-07-11 05:46:12 +00002628 // Save state that can be changed while lexing so that we can restore it.
2629 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002630 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002631 bool atStartOfLine = IsAtStartOfLine;
2632 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2633 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002634
Chris Lattner146762e2007-07-20 16:59:19 +00002635 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002636 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002637
Chris Lattner678c8802006-07-11 05:46:12 +00002638 // Restore state that may have changed.
2639 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002640 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002641 HasLeadingSpace = leadingSpace;
2642 IsAtStartOfLine = atStartOfLine;
2643 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002644
Chris Lattner678c8802006-07-11 05:46:12 +00002645 // Restore the lexer back to non-skipping mode.
2646 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002647
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002648 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002649 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002650 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002651}
2652
James Dennettf442d242012-06-17 03:40:43 +00002653/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002654static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2655 ConflictMarkerKind CMK) {
2656 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2657 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002658 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002659 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002660 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002661 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002662 if (Pos == 0 ||
2663 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002664 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2665 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002666 continue;
2667 }
2668 return RestOfBuffer.data()+Pos;
2669 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002670 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002671}
2672
2673/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2674/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2675/// and recover nicely. This returns true if it is a conflict marker and false
2676/// if not.
2677bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2678 // Only a conflict marker if it starts at the beginning of a line.
2679 if (CurPtr != BufferStart &&
2680 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2681 return false;
2682
Richard Smitha9e33d42011-10-12 00:37:51 +00002683 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002684 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2685 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002686 return false;
2687
2688 // If we have a situation where we don't care about conflict markers, ignore
2689 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002690 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002691 return false;
2692
Richard Smitha9e33d42011-10-12 00:37:51 +00002693 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2694
2695 // Check to see if there is an ending marker somewhere in the buffer at the
2696 // start of a line to terminate this conflict marker.
2697 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002698 // We found a match. We are really in a conflict marker.
2699 // Diagnose this, and ignore to the end of line.
2700 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002701 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002702
2703 // Skip ahead to the end of line. We know this exists because the
2704 // end-of-conflict marker starts with \r or \n.
2705 while (*CurPtr != '\r' && *CurPtr != '\n') {
2706 assert(CurPtr != BufferEnd && "Didn't find end of line");
2707 ++CurPtr;
2708 }
2709 BufferPtr = CurPtr;
2710 return true;
2711 }
2712
2713 // No end of conflict marker found.
2714 return false;
2715}
2716
Richard Smitha9e33d42011-10-12 00:37:51 +00002717/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2718/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2719/// is the end of a conflict marker. Handle it by ignoring up until the end of
2720/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002721bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2722 // Only a conflict marker if it starts at the beginning of a line.
2723 if (CurPtr != BufferStart &&
2724 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2725 return false;
2726
2727 // If we have a situation where we don't care about conflict markers, ignore
2728 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002729 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002730 return false;
2731
Richard Smitha9e33d42011-10-12 00:37:51 +00002732 // Check to see if we have the marker (4 characters in a row).
2733 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002734 if (CurPtr[i] != CurPtr[0])
2735 return false;
2736
2737 // If we do have it, search for the end of the conflict marker. This could
2738 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2739 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002740 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2741 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002742 CurPtr = End;
2743
2744 // Skip ahead to the end of line.
2745 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2746 ++CurPtr;
2747
2748 BufferPtr = CurPtr;
2749
2750 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002751 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002752 return true;
2753 }
2754
2755 return false;
2756}
2757
Alex Lorenz1be800c52017-04-19 08:58:56 +00002758static const char *findPlaceholderEnd(const char *CurPtr,
2759 const char *BufferEnd) {
2760 if (CurPtr == BufferEnd)
2761 return nullptr;
2762 BufferEnd -= 1; // Scan until the second last character.
2763 for (; CurPtr != BufferEnd; ++CurPtr) {
2764 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2765 return CurPtr + 2;
2766 }
2767 return nullptr;
2768}
2769
2770bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2771 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002772 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002773 return false;
2774 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2775 if (!End)
2776 return false;
2777 const char *Start = CurPtr - 1;
2778 if (!LangOpts.AllowEditorPlaceholders)
2779 Diag(Start, diag::err_placeholder_in_source);
2780 Result.startToken();
2781 FormTokenWithChars(Result, End, tok::raw_identifier);
2782 Result.setRawIdentifierData(Start);
2783 PP->LookUpIdentifierInfo(Result);
2784 Result.setFlag(Token::IsEditorPlaceholder);
2785 BufferPtr = End;
2786 return true;
2787}
2788
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002789bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2790 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002791 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002792 return Loc == PP->getCodeCompletionLoc();
2793 }
2794
2795 return false;
2796}
2797
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002798uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2799 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002800 unsigned CharSize;
2801 char Kind = getCharAndSize(StartPtr, CharSize);
2802
2803 unsigned NumHexDigits;
2804 if (Kind == 'u')
2805 NumHexDigits = 4;
2806 else if (Kind == 'U')
2807 NumHexDigits = 8;
2808 else
2809 return 0;
2810
Jordan Rosec0cba272013-01-27 20:12:04 +00002811 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002812 if (Result && !isLexingRawMode())
2813 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002814 return 0;
2815 }
2816
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002817 const char *CurPtr = StartPtr + CharSize;
2818 const char *KindLoc = &CurPtr[-1];
2819
2820 uint32_t CodePoint = 0;
2821 for (unsigned i = 0; i < NumHexDigits; ++i) {
2822 char C = getCharAndSize(CurPtr, CharSize);
2823
2824 unsigned Value = llvm::hexDigitValue(C);
2825 if (Value == -1U) {
2826 if (Result && !isLexingRawMode()) {
2827 if (i == 0) {
2828 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2829 << StringRef(KindLoc, 1);
2830 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002831 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002832
2833 // If the user wrote \U1234, suggest a fixit to \u.
2834 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002835 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002836 Diag(KindLoc, diag::note_ucn_four_not_eight)
2837 << FixItHint::CreateReplacement(URange, "u");
2838 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002839 }
2840 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002841
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002842 return 0;
2843 }
2844
2845 CodePoint <<= 4;
2846 CodePoint += Value;
2847
2848 CurPtr += CharSize;
2849 }
2850
2851 if (Result) {
2852 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002853 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002854 StartPtr = CurPtr;
2855 else
2856 while (StartPtr != CurPtr)
2857 (void)getAndAdvanceChar(StartPtr, *Result);
2858 } else {
2859 StartPtr = CurPtr;
2860 }
2861
Justin Bogner53535132013-10-21 05:02:28 +00002862 // Don't apply C family restrictions to UCNs in assembly mode
2863 if (LangOpts.AsmPreprocessor)
2864 return CodePoint;
2865
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002866 // C99 6.4.3p2: A universal character name shall not specify a character whose
2867 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2868 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2869 // C++11 [lex.charset]p2: If the hexadecimal value for a
2870 // universal-character-name corresponds to a surrogate code point (in the
2871 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2872 // if the hexadecimal value for a universal-character-name outside the
2873 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2874 // string literal corresponds to a control character (in either of the
2875 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2876 // basic source character set, the program is ill-formed.
2877 if (CodePoint < 0xA0) {
2878 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2879 return CodePoint;
2880
2881 // We don't use isLexingRawMode() here because we need to warn about bad
2882 // UCNs even when skipping preprocessing tokens in a #if block.
2883 if (Result && PP) {
2884 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2885 Diag(BufferPtr, diag::err_ucn_control_character);
2886 else {
2887 char C = static_cast<char>(CodePoint);
2888 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2889 }
2890 }
2891
2892 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002893
2894 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002895 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002896 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002897 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002898 if (Result && PP) {
2899 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2900 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2901 else
2902 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2903 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002904 return 0;
2905 }
2906
2907 return CodePoint;
2908}
2909
Eli Friedman0834a4b2013-09-19 00:41:32 +00002910bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2911 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002912 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2913 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002914 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002915 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002916 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002917 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002918
2919 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002920 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002921 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002922 return false;
2923}
Jordan Rose4246ae02013-01-24 20:50:50 +00002924
Eli Friedman0834a4b2013-09-19 00:41:32 +00002925bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002926 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2927 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2928 !PP->isPreprocessedOutput()) {
2929 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2930 makeCharRange(*this, BufferPtr, CurPtr),
2931 /*IsFirst=*/true);
2932 }
2933
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002934 MIOpt.ReadToken();
2935 return LexIdentifier(Result, CurPtr);
2936 }
2937
Jordan Rosecc538342013-01-31 19:48:48 +00002938 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2939 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002940 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002941 // Non-ASCII characters tend to creep into source code unintentionally.
2942 // Instead of letting the parser complain about the unknown token,
2943 // just drop the character.
2944 // Note that we can /only/ do this when the non-ASCII character is actually
2945 // spelled as Unicode, not written as a UCN. The standard requires that
2946 // we not throw away any possible preprocessor tokens, but there's a
2947 // loophole in the mapping of Unicode characters to basic character set
2948 // characters that allows us to map these particular characters to, say,
2949 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002950 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002951 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002952
2953 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002954 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002955 }
2956
2957 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2958 // up by accident.
2959 MIOpt.ReadToken();
2960 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002961 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002962}
2963
Eli Friedman0834a4b2013-09-19 00:41:32 +00002964void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2965 IsAtStartOfLine = Result.isAtStartOfLine();
2966 HasLeadingSpace = Result.hasLeadingSpace();
2967 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2968 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2969}
2970
2971bool Lexer::Lex(Token &Result) {
2972 // Start a new token.
2973 Result.startToken();
2974
2975 // Set up misc whitespace flags for LexTokenInternal.
2976 if (IsAtStartOfLine) {
2977 Result.setFlag(Token::StartOfLine);
2978 IsAtStartOfLine = false;
2979 }
2980
2981 if (HasLeadingSpace) {
2982 Result.setFlag(Token::LeadingSpace);
2983 HasLeadingSpace = false;
2984 }
2985
2986 if (HasLeadingEmptyMacro) {
2987 Result.setFlag(Token::LeadingEmptyMacro);
2988 HasLeadingEmptyMacro = false;
2989 }
2990
2991 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2992 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002993 bool isRawLex = isLexingRawMode();
2994 (void) isRawLex;
2995 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2996 // (After the LexTokenInternal call, the lexer might be destroyed.)
2997 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2998 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002999}
Chris Lattner22eb9722006-06-18 05:43:12 +00003000
3001/// LexTokenInternal - This implements a simple C family lexer. It is an
3002/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003003/// has a null character at the end of the file. This returns a preprocessing
3004/// token, not a normal token, as such, it is an internal interface. It assumes
3005/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003006bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003007LexNextToken:
3008 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003009 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003010 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Chris Lattner22eb9722006-06-18 05:43:12 +00003012 // CurPtr - Cache BufferPtr in an automatic variable.
3013 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003014
Chris Lattnereb54b592006-07-10 06:34:27 +00003015 // Small amounts of horizontal whitespace is very common between tokens.
3016 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3017 ++CurPtr;
3018 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3019 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003020
Chris Lattner4d963442008-10-12 04:05:48 +00003021 // If we are keeping whitespace and other tokens, just return what we just
3022 // skipped. The next lexer invocation will return the token after the
3023 // whitespace.
3024 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003025 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003026 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003027 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Chris Lattnereb54b592006-07-10 06:34:27 +00003030 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003031 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003032 }
Mike Stump11289f42009-09-09 15:08:12 +00003033
Chris Lattner22eb9722006-06-18 05:43:12 +00003034 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003035
Chris Lattner22eb9722006-06-18 05:43:12 +00003036 // Read a character, advancing over it.
3037 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003038 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003039
Chris Lattner22eb9722006-06-18 05:43:12 +00003040 switch (Char) {
3041 case 0: // Null.
3042 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003043 if (CurPtr-1 == BufferEnd)
3044 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003045
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003046 // Check if we are performing code completion.
3047 if (isCodeCompletionPoint(CurPtr-1)) {
3048 // Return the code-completion token.
3049 Result.startToken();
3050 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003051 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003052 }
3053
Chris Lattner6d27a162008-11-22 02:02:22 +00003054 if (!isLexingRawMode())
3055 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003056 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003057 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3058 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003059
Eli Friedman0834a4b2013-09-19 00:41:32 +00003060 // We know the lexer hasn't changed, so just try again with this lexer.
3061 // (We manually eliminate the tail call to avoid recursion.)
3062 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003063
3064 case 26: // DOS & CP/M EOF: "^Z".
3065 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003066 if (LangOpts.MicrosoftExt) {
3067 if (!isLexingRawMode())
3068 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003069 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003070 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003071
Chris Lattner3dfff972009-12-17 05:29:40 +00003072 // If Microsoft extensions are disabled, this is just random garbage.
3073 Kind = tok::unknown;
3074 break;
3075
Chris Lattner22eb9722006-06-18 05:43:12 +00003076 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003077 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003078 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003079 LLVM_FALLTHROUGH;
3080 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003081 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003082 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003083 if (ParsingPreprocessorDirective) {
3084 // Done parsing the "line".
3085 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattner457fc152006-07-29 06:30:25 +00003087 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003088 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003089 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003090
Chris Lattner22eb9722006-06-18 05:43:12 +00003091 // Since we consumed a newline, we are back at the start of a line.
3092 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003093 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003094
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003095 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003096 break;
3097 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003098
Chris Lattner22eb9722006-06-18 05:43:12 +00003099 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003100 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003101
Eli Friedman0834a4b2013-09-19 00:41:32 +00003102 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3103 return true; // KeepWhitespaceMode
3104
3105 // We only saw whitespace, so just try again with this lexer.
3106 // (We manually eliminate the tail call to avoid recursion.)
3107 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003108 case ' ':
3109 case '\t':
3110 case '\f':
3111 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003112 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003113 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003114 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3115 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003116
3117 SkipIgnoredUnits:
3118 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003119
Chris Lattnerb9b85972007-07-22 06:29:05 +00003120 // If the next token is obviously a // or /* */ comment, skip it efficiently
3121 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003122 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003123 LangOpts.LineComment &&
3124 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003125 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3126 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003127 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003128 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003129 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3130 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003131 goto SkipIgnoredUnits;
3132 } else if (isHorizontalWhitespace(*CurPtr)) {
3133 goto SkipHorizontalWhitespace;
3134 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003135 // We only saw whitespace, so just try again with this lexer.
3136 // (We manually eliminate the tail call to avoid recursion.)
3137 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003138
Chris Lattner2b15cf72008-01-03 17:58:54 +00003139 // C99 6.4.4.1: Integer Constants.
3140 // C99 6.4.4.2: Floating Constants.
3141 case '0': case '1': case '2': case '3': case '4':
3142 case '5': case '6': case '7': case '8': case '9':
3143 // Notify MIOpt that we read a non-whitespace/non-comment token.
3144 MIOpt.ReadToken();
3145 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003146
Richard Smith9b362092013-03-09 23:56:02 +00003147 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003148 // Notify MIOpt that we read a non-whitespace/non-comment token.
3149 MIOpt.ReadToken();
3150
Richard Smith9b362092013-03-09 23:56:02 +00003151 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003152 Char = getCharAndSize(CurPtr, SizeTmp);
3153
3154 // UTF-16 string literal
3155 if (Char == '"')
3156 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3157 tok::utf16_string_literal);
3158
3159 // UTF-16 character constant
3160 if (Char == '\'')
3161 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3162 tok::utf16_char_constant);
3163
Craig Topper54edcca2011-08-11 04:06:15 +00003164 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003165 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3166 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003167 return LexRawStringLiteral(Result,
3168 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3169 SizeTmp2, Result),
3170 tok::utf16_string_literal);
3171
3172 if (Char == '8') {
3173 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3174
3175 // UTF-8 string literal
3176 if (Char2 == '"')
3177 return LexStringLiteral(Result,
3178 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3179 SizeTmp2, Result),
3180 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003181 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3182 return LexCharConstant(
3183 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3184 SizeTmp2, Result),
3185 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003186
Richard Smith9b362092013-03-09 23:56:02 +00003187 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003188 unsigned SizeTmp3;
3189 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3190 // UTF-8 raw string literal
3191 if (Char3 == '"') {
3192 return LexRawStringLiteral(Result,
3193 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3194 SizeTmp2, Result),
3195 SizeTmp3, Result),
3196 tok::utf8_string_literal);
3197 }
3198 }
3199 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003200 }
3201
3202 // treat u like the start of an identifier.
3203 return LexIdentifier(Result, CurPtr);
3204
Richard Smith9b362092013-03-09 23:56:02 +00003205 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003206 // Notify MIOpt that we read a non-whitespace/non-comment token.
3207 MIOpt.ReadToken();
3208
Richard Smith9b362092013-03-09 23:56:02 +00003209 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003210 Char = getCharAndSize(CurPtr, SizeTmp);
3211
3212 // UTF-32 string literal
3213 if (Char == '"')
3214 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3215 tok::utf32_string_literal);
3216
3217 // UTF-32 character constant
3218 if (Char == '\'')
3219 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3220 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003221
3222 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003223 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3224 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003225 return LexRawStringLiteral(Result,
3226 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3227 SizeTmp2, Result),
3228 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003229 }
3230
3231 // treat U like the start of an identifier.
3232 return LexIdentifier(Result, CurPtr);
3233
Craig Topper54edcca2011-08-11 04:06:15 +00003234 case 'R': // Identifier or C++0x raw string literal
3235 // Notify MIOpt that we read a non-whitespace/non-comment token.
3236 MIOpt.ReadToken();
3237
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003238 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003239 Char = getCharAndSize(CurPtr, SizeTmp);
3240
3241 if (Char == '"')
3242 return LexRawStringLiteral(Result,
3243 ConsumeChar(CurPtr, SizeTmp, Result),
3244 tok::string_literal);
3245 }
3246
3247 // treat R like the start of an identifier.
3248 return LexIdentifier(Result, CurPtr);
3249
Chris Lattner2b15cf72008-01-03 17:58:54 +00003250 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003251 // Notify MIOpt that we read a non-whitespace/non-comment token.
3252 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003253 Char = getCharAndSize(CurPtr, SizeTmp);
3254
3255 // Wide string literal.
3256 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003257 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003258 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003259
Craig Topper54edcca2011-08-11 04:06:15 +00003260 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003261 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003262 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3263 return LexRawStringLiteral(Result,
3264 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3265 SizeTmp2, Result),
3266 tok::wide_string_literal);
3267
Chris Lattner22eb9722006-06-18 05:43:12 +00003268 // Wide character constant.
3269 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003270 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3271 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003272 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003273 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003274
Chris Lattner22eb9722006-06-18 05:43:12 +00003275 // C99 6.4.2: Identifiers.
3276 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3277 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003278 case 'O': case 'P': case 'Q': /*'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 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3281 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003282 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003283 case 'v': case 'w': case 'x': case 'y': case 'z':
3284 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003285 // Notify MIOpt that we read a non-whitespace/non-comment token.
3286 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003287 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003288
3289 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003290 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003291 if (!isLexingRawMode())
3292 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003293 // Notify MIOpt that we read a non-whitespace/non-comment token.
3294 MIOpt.ReadToken();
3295 return LexIdentifier(Result, CurPtr);
3296 }
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattnerb11c3232008-10-12 04:51:35 +00003298 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003299 break;
Mike Stump11289f42009-09-09 15:08:12 +00003300
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 // C99 6.4.4: Character Constants.
3302 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003303 // Notify MIOpt that we read a non-whitespace/non-comment token.
3304 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003305 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003306
3307 // C99 6.4.5: String Literals.
3308 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003309 // Notify MIOpt that we read a non-whitespace/non-comment token.
3310 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003311 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003312
3313 // C99 6.4.6: Punctuators.
3314 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003315 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003316 break;
3317 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003318 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003319 break;
3320 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003321 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003322 break;
3323 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003324 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003325 break;
3326 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003327 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003328 break;
3329 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003330 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003331 break;
3332 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003333 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003334 break;
3335 case '.':
3336 Char = getCharAndSize(CurPtr, SizeTmp);
3337 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003338 // Notify MIOpt that we read a non-whitespace/non-comment token.
3339 MIOpt.ReadToken();
3340
Chris Lattner22eb9722006-06-18 05:43:12 +00003341 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003342 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003343 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003344 CurPtr += SizeTmp;
3345 } else if (Char == '.' &&
3346 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3349 SizeTmp2, Result);
3350 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003351 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003352 }
3353 break;
3354 case '&':
3355 Char = getCharAndSize(CurPtr, SizeTmp);
3356 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003357 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003358 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3359 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003360 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003361 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3362 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003363 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003364 }
3365 break;
Mike Stump11289f42009-09-09 15:08:12 +00003366 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003367 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003368 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003369 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3370 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003371 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003372 }
3373 break;
3374 case '+':
3375 Char = getCharAndSize(CurPtr, SizeTmp);
3376 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003377 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003378 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003379 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003380 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003381 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003382 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003383 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003384 }
3385 break;
3386 case '-':
3387 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003388 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003390 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003391 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003392 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003393 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3394 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003395 Kind = tok::arrowstar;
3396 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003397 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003398 Kind = tok::arrow;
3399 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003400 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003401 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003402 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003403 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003404 }
3405 break;
3406 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003407 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003408 break;
3409 case '!':
3410 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003411 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003412 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3413 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003414 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003415 }
3416 break;
3417 case '/':
3418 // 6.4.9: Comments
3419 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003420 if (Char == '/') { // Line comment.
3421 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003422 // want to lex this as a comment. There is one problem with this though,
3423 // that in one particular corner case, this can change the behavior of the
3424 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003425 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003426 // "foo". Check to see if the character after the second slash is a '*'.
3427 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003428 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003429 bool TreatAsComment = LangOpts.LineComment &&
3430 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003431 if (!TreatAsComment)
3432 if (!(PP && PP->isPreprocessedOutput()))
3433 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3434
3435 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003436 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3437 TokAtPhysicalStartOfLine))
3438 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003439
Chris Lattner58827712009-01-16 22:39:25 +00003440 // It is common for the tokens immediately after a // comment to be
3441 // whitespace (indentation for the next line). Instead of going through
3442 // the big switch, handle it efficiently now.
3443 goto SkipIgnoredUnits;
3444 }
3445 }
Mike Stump11289f42009-09-09 15:08:12 +00003446
Chris Lattner58827712009-01-16 22:39:25 +00003447 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003448 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3449 TokAtPhysicalStartOfLine))
3450 return true; // There is a token to return.
3451
3452 // We only saw whitespace, so just try again with this lexer.
3453 // (We manually eliminate the tail call to avoid recursion.)
3454 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003455 }
Mike Stump11289f42009-09-09 15:08:12 +00003456
Chris Lattner58827712009-01-16 22:39:25 +00003457 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003458 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003459 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003460 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003461 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003462 }
3463 break;
3464 case '%':
3465 Char = getCharAndSize(CurPtr, SizeTmp);
3466 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003467 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003468 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003469 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003470 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003472 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003474 Char = getCharAndSize(CurPtr, SizeTmp);
3475 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003476 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003477 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3478 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003479 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003480 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003481 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003482 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003483 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003484 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003485 // We parsed a # character. If this occurs at the start of the line,
3486 // it's actually the start of a preprocessing directive. Callback to
3487 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003488 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003489 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003490 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003491
Chris Lattner2534324a2009-03-18 20:58:27 +00003492 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003493 }
3494 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003495 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003496 }
3497 break;
3498 case '<':
3499 Char = getCharAndSize(CurPtr, SizeTmp);
3500 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003501 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003503 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3504 if (After == '=') {
3505 Kind = tok::lesslessequal;
3506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3507 SizeTmp2, Result);
3508 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3509 // If this is actually a '<<<<<<<' version control conflict marker,
3510 // recognize it as such and recover nicely.
3511 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003512 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3513 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3514 // ignore it.
3515 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003516 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003517 Kind = tok::lesslessless;
3518 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3519 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003520 } else {
3521 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3522 Kind = tok::lessless;
3523 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003524 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003525 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003526 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003527 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003528 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003529 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3530 // C++0x [lex.pptoken]p3:
3531 // Otherwise, if the next three characters are <:: and the subsequent
3532 // character is neither : nor >, the < is treated as a preprocessor
3533 // token by itself and not as the first character of the alternative
3534 // token <:.
3535 unsigned SizeTmp3;
3536 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3537 if (After != ':' && After != '>') {
3538 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003539 if (!isLexingRawMode())
3540 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003541 break;
3542 }
3543 }
3544
Chris Lattner22eb9722006-06-18 05:43:12 +00003545 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003546 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003547 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003548 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003549 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003550 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3551 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003552 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003553 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003554 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003555 }
3556 break;
3557 case '>':
3558 Char = getCharAndSize(CurPtr, SizeTmp);
3559 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003560 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003561 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003562 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003563 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3564 if (After == '=') {
3565 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3566 SizeTmp2, Result);
3567 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003568 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3569 // If this is actually a '>>>>' conflict marker, recognize it as such
3570 // and recover nicely.
3571 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003572 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3573 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3574 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003575 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003576 Kind = tok::greatergreatergreater;
3577 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3578 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003579 } else {
3580 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3581 Kind = tok::greatergreater;
3582 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003583 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003584 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003585 }
3586 break;
3587 case '^':
3588 Char = getCharAndSize(CurPtr, SizeTmp);
3589 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003590 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003591 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003592 } else if (LangOpts.OpenCL && Char == '^') {
3593 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3594 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003595 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003596 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003597 }
3598 break;
3599 case '|':
3600 Char = getCharAndSize(CurPtr, SizeTmp);
3601 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003602 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003603 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3604 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003605 // If this is '|||||||' and we're in a conflict marker, ignore it.
3606 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3607 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003608 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003609 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3610 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003611 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003612 }
3613 break;
3614 case ':':
3615 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003616 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003617 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003618 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Aaron Ballman606093a2017-10-15 15:01:42 +00003619 } else if ((LangOpts.CPlusPlus ||
3620 LangOpts.DoubleSquareBracketAttributes) &&
3621 Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003622 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003623 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003624 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003625 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003626 }
3627 break;
3628 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003629 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003630 break;
3631 case '=':
3632 Char = getCharAndSize(CurPtr, SizeTmp);
3633 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003634 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003635 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3636 goto LexNextToken;
3637
Chris Lattnerb11c3232008-10-12 04:51:35 +00003638 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003639 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003640 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003641 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003642 }
3643 break;
3644 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003645 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003646 break;
3647 case '#':
3648 Char = getCharAndSize(CurPtr, SizeTmp);
3649 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003650 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003651 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003652 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003653 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003654 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003655 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003656 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003657 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003658 // We parsed a # character. If this occurs at the start of the line,
3659 // it's actually the start of a preprocessing directive. Callback to
3660 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003661 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003662 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003663 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattner2534324a2009-03-18 20:58:27 +00003665 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003666 }
3667 break;
3668
Chris Lattner2b15cf72008-01-03 17:58:54 +00003669 case '@':
3670 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003671 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003672 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003673 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003674 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003675 break;
Mike Stump11289f42009-09-09 15:08:12 +00003676
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003677 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003678 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003679 if (!LangOpts.AsmPreprocessor) {
3680 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3681 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3682 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3683 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003684
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003685 // We only saw whitespace, so just try again with this lexer.
3686 // (We manually eliminate the tail call to avoid recursion.)
3687 goto LexNextToken;
3688 }
3689
3690 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003691 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003692 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003693
Chris Lattnerb11c3232008-10-12 04:51:35 +00003694 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003695 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003696
3697 default: {
3698 if (isASCII(Char)) {
3699 Kind = tok::unknown;
3700 break;
3701 }
3702
Justin Lebar90910552016-09-30 00:38:45 +00003703 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003704
3705 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3706 // an escaped newline.
3707 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003708 llvm::ConversionResult Status =
3709 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3710 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003711 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003712 llvm::strictConversion);
3713 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003714 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3715 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3716 return true; // KeepWhitespaceMode
3717
3718 // We only saw whitespace, so just try again with this lexer.
3719 // (We manually eliminate the tail call to avoid recursion.)
3720 goto LexNextToken;
3721 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003722 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003723 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003724
Jordan Rosecc538342013-01-31 19:48:48 +00003725 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3726 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003727 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003728 Kind = tok::unknown;
3729 break;
3730 }
3731
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003732 // Non-ASCII characters tend to creep into source code unintentionally.
3733 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003734 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003735 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003736
3737 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003738 // We're pretending the character didn't exist, so just try again with
3739 // this lexer.
3740 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003741 goto LexNextToken;
3742 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003743 }
Mike Stump11289f42009-09-09 15:08:12 +00003744
Chris Lattner371ac8a2006-07-04 07:11:10 +00003745 // Notify MIOpt that we read a non-whitespace/non-comment token.
3746 MIOpt.ReadToken();
3747
Chris Lattnerd01e2912006-06-18 16:22:51 +00003748 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003749 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003750 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003751
3752HandleDirective:
3753 // We parsed a # character and it's the start of a preprocessing directive.
3754
3755 FormTokenWithChars(Result, CurPtr, tok::hash);
3756 PP->HandleDirective(Result);
3757
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003758 if (PP->hadModuleLoaderFatalFailure()) {
3759 // With a fatal failure in the module loader, we abort parsing.
3760 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003761 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003762 }
3763
Eli Friedman0834a4b2013-09-19 00:41:32 +00003764 // We parsed the directive; lex a token with the new state.
3765 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003766}