blob: 61bcef8cb760e52c9be65b05f70b44700d432b56 [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;
466 const char *StrData = BufStart + Offset;
467
468 if (StrData[0] == '\n' || StrData[0] == '\r')
469 return StrData;
470
471 const char *LexStart = StrData;
472 while (LexStart != BufStart) {
473 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
474 ++LexStart;
475 break;
476 }
477
478 --LexStart;
479 }
480 return LexStart;
481}
482
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000483static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
484 const SourceManager &SM,
485 const LangOptions &LangOpts) {
486 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000487 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000488 if (LocInfo.first.isInvalid())
489 return Loc;
490
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000491 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000493 if (Invalid)
494 return Loc;
495
496 // Back up from the current location until we hit the beginning of a line
497 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000498 const char *StrData = Buffer.data() + LocInfo.second;
499 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
500 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000501 return Loc;
502
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000503 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000504 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000505 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
506 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000507 TheLexer.SetCommentRetentionState(true);
508
509 // Lex tokens until we find the token that contains the source location.
510 Token TheTok;
511 do {
512 TheLexer.LexFromRawLexer(TheTok);
513
514 if (TheLexer.getBufferLocation() > StrData) {
515 // Lexing this token has taken the lexer past the source location we're
516 // looking for. If the current token encompasses our source location,
517 // return the beginning of that token.
518 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
519 return TheTok.getLocation();
520
521 // We ended up skipping over the source location entirely, which means
522 // that it points into whitespace. We're done here.
523 break;
524 }
525 } while (TheTok.getKind() != tok::eof);
526
527 // We've passed our source location; just return the original source location.
528 return Loc;
529}
530
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000531SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
532 const SourceManager &SM,
533 const LangOptions &LangOpts) {
534 if (Loc.isFileID())
535 return getBeginningOfFileToken(Loc, SM, LangOpts);
536
537 if (!SM.isMacroArgExpansion(Loc))
538 return Loc;
539
540 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
541 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
542 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000543 std::pair<FileID, unsigned> BeginFileLocInfo
544 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000545 assert(FileLocInfo.first == BeginFileLocInfo.first &&
546 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000547 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000548}
549
Douglas Gregoraf82e352010-07-20 20:18:03 +0000550namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000551
Douglas Gregoraf82e352010-07-20 20:18:03 +0000552 enum PreambleDirectiveKind {
553 PDK_Skipped,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000554 PDK_Unknown
555 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000556
557} // end anonymous namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000558
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000559std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000560 const LangOptions &LangOpts,
561 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000562 // Create a lexer starting at the beginning of the file. Note that we use a
563 // "fake" file source location at offset 1 so that the lexer will track our
564 // position within the file.
565 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000566 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000567 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
568 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000569 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000570
571 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
572 SourceLocation StartLoc = TheLexer.getSourceLocation();
573
Douglas Gregoraf82e352010-07-20 20:18:03 +0000574 bool InPreprocessorDirective = false;
575 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000576 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000577
578 unsigned MaxLineOffset = 0;
579 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000580 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000581 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000582 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000583 char ch = *CurPtr++;
584 if (ch == '\n') {
585 ++CurLine;
586 if (CurLine == MaxLines)
587 break;
588 }
589 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000590 if (CurPtr != Buffer.end())
591 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000592 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000593
Douglas Gregoraf82e352010-07-20 20:18:03 +0000594 do {
595 TheLexer.LexFromRawLexer(TheTok);
596
597 if (InPreprocessorDirective) {
598 // If we've hit the end of the file, we're done.
599 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000600 break;
601 }
602
603 // If we haven't hit the end of the preprocessor directive, skip this
604 // token.
605 if (!TheTok.isAtStartOfLine())
606 continue;
607
608 // We've passed the end of the preprocessor directive, and will look
609 // at this token again below.
610 InPreprocessorDirective = false;
611 }
612
Douglas Gregor028d3e42010-08-09 20:45:32 +0000613 // Keep track of the # of lines in the preamble.
614 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000615 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000616
617 // If we were asked to limit the number of lines in the preamble,
618 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000619 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000620 break;
621 }
622
Douglas Gregoraf82e352010-07-20 20:18:03 +0000623 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000624 if (TheTok.getKind() == tok::comment) {
625 if (ActiveCommentLoc.isInvalid())
626 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000627 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000628 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000629
630 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
631 // This is the start of a preprocessor directive.
632 Token HashTok = TheTok;
633 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000634 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000635
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000636 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000637 // we don't have an identifier table available. Instead, just look at
638 // the raw identifier to recognize and categorize preprocessor directives.
639 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000640 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000641 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000642 PreambleDirectiveKind PDK
643 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
644 .Case("include", PDK_Skipped)
645 .Case("__include_macros", PDK_Skipped)
646 .Case("define", PDK_Skipped)
647 .Case("undef", PDK_Skipped)
648 .Case("line", PDK_Skipped)
649 .Case("error", PDK_Skipped)
650 .Case("pragma", PDK_Skipped)
651 .Case("import", PDK_Skipped)
652 .Case("include_next", PDK_Skipped)
653 .Case("warning", PDK_Skipped)
654 .Case("ident", PDK_Skipped)
655 .Case("sccs", PDK_Skipped)
656 .Case("assert", PDK_Skipped)
657 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000658 .Case("if", PDK_Skipped)
659 .Case("ifdef", PDK_Skipped)
660 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000661 .Case("elif", PDK_Skipped)
662 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000663 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000664 .Default(PDK_Unknown);
665
666 switch (PDK) {
667 case PDK_Skipped:
668 continue;
669
Douglas Gregoraf82e352010-07-20 20:18:03 +0000670 case PDK_Unknown:
671 // We don't know what this directive is; stop at the '#'.
672 break;
673 }
674 }
675
676 // We only end up here if we didn't recognize the preprocessor
677 // directive or it was one that can't occur in the preamble at this
678 // point. Roll back the current token to the location of the '#'.
679 InPreprocessorDirective = false;
680 TheTok = HashTok;
681 }
682
Douglas Gregor028d3e42010-08-09 20:45:32 +0000683 // We hit a token that we don't recognize as being in the
684 // "preprocessing only" part of the file, so we're no longer in
685 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000686 break;
687 } while (true);
688
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000689 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000690 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000691 End = ActiveCommentLoc; // don't truncate a decl comment.
692 else
693 End = TheTok.getLocation();
694
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000695 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000696 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000697}
698
Chris Lattner2a6ee912010-11-17 07:05:50 +0000699/// AdvanceToTokenCharacter - Given a location that specifies the start of a
700/// token, return a new location that specifies a character within the token.
701SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
702 unsigned CharNo,
703 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000704 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000705 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000706 // character is. This needs to take into consideration newlines and
707 // trigraphs.
708 bool Invalid = false;
709 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
710
711 // If they request the first char of the token, we're trivially done.
712 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
713 return TokStart;
714
715 unsigned PhysOffset = 0;
716
717 // The usual case is that tokens don't contain anything interesting. Skip
718 // over the uninteresting characters. If a token only consists of simple
719 // chars, this method is extremely fast.
720 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
721 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000722 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000723 ++TokPtr;
724 --CharNo;
725 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000726 }
727
728 // If we have a character that may be a trigraph or escaped newline, use a
729 // lexer to parse it correctly.
730 for (; CharNo; --CharNo) {
731 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000732 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000733 TokPtr += Size;
734 PhysOffset += Size;
735 }
736
737 // Final detail: if we end up on an escaped newline, we want to return the
738 // location of the actual byte of the token. For example foo\<newline>bar
739 // advanced by 3 should return the location of b, not of \\. One compounding
740 // detail of this is that the escape may be made by a trigraph.
741 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
742 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
743
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000744 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000745}
746
747/// \brief Computes the source location just past the end of the
748/// token at this source location.
749///
750/// This routine can be used to produce a source location that
751/// points just past the end of the token referenced by \p Loc, and
752/// is generally used when a diagnostic needs to point just after a
753/// token where it expected something different that it received. If
754/// the returned source location would not be meaningful (e.g., if
755/// it points into a macro), this routine returns an invalid
756/// source location.
757///
758/// \param Offset an offset from the end of the token, where the source
759/// location should refer to. The default offset (0) produces a source
760/// location pointing just past the end of the token; an offset of 1 produces
761/// a source location pointing to the last character in the token, etc.
762SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
763 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000764 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000765 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000766 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000767
768 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000769 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000770 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000771 }
772
David Blaikiebbafb8a2012-03-11 07:00:24 +0000773 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000774 if (Len > Offset)
775 Len = Len - Offset;
776 else
777 return Loc;
778
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000779 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000780}
781
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000782/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000783/// token of the macro expansion.
784bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000785 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000786 const LangOptions &LangOpts,
787 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000788 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
789
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000790 SourceLocation expansionLoc;
791 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
792 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000793
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000794 if (expansionLoc.isFileID()) {
795 // No other macro expansions, this is the first.
796 if (MacroBegin)
797 *MacroBegin = expansionLoc;
798 return true;
799 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000800
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000801 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000802}
803
804/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000805/// token of the macro expansion.
806bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000807 const SourceManager &SM,
808 const LangOptions &LangOpts,
809 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000810 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
811
812 SourceLocation spellLoc = SM.getSpellingLoc(loc);
813 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
814 if (tokLen == 0)
815 return false;
816
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000817 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
818 SourceLocation expansionLoc;
819 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
820 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000821
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000822 if (expansionLoc.isFileID()) {
823 // No other macro expansions.
824 if (MacroEnd)
825 *MacroEnd = expansionLoc;
826 return true;
827 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000828
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000829 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000830}
831
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000832static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000833 const SourceManager &SM,
834 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000835 SourceLocation Begin = Range.getBegin();
836 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000837 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000838 if (Range.isTokenRange()) {
839 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
840 if (End.isInvalid())
841 return CharSourceRange();
842 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000843
844 // Break down the source locations.
845 FileID FID;
846 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000847 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000848 if (FID.isInvalid())
849 return CharSourceRange();
850
851 unsigned EndOffs;
852 if (!SM.isInFileID(End, FID, &EndOffs) ||
853 BeginOffs > EndOffs)
854 return CharSourceRange();
855
856 return CharSourceRange::getCharRange(Begin, End);
857}
858
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000859CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000860 const SourceManager &SM,
861 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000862 SourceLocation Begin = Range.getBegin();
863 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000864 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000865 return CharSourceRange();
866
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000867 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000868 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000869
870 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000871 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
872 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000873 Range.setBegin(Begin);
874 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000875 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000876
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000877 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000878 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
879 &End)) ||
880 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
881 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000882 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000883 Range.setEnd(End);
884 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000885 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000886
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000887 assert(Begin.isMacroID() && End.isMacroID());
888 SourceLocation MacroBegin, MacroEnd;
889 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000890 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
891 &MacroEnd)) ||
892 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
893 &MacroEnd)))) {
894 Range.setBegin(MacroBegin);
895 Range.setEnd(MacroEnd);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
897 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000898
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000899 bool Invalid = false;
900 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
901 &Invalid);
902 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000903 return CharSourceRange();
904
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000905 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
906 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
907 &Invalid);
908 if (Invalid)
909 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000910
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000911 if (EndEntry.getExpansion().isMacroArgExpansion() &&
912 BeginEntry.getExpansion().getExpansionLocStart() ==
913 EndEntry.getExpansion().getExpansionLocStart()) {
914 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
915 Range.setEnd(SM.getImmediateSpellingLoc(End));
916 return makeFileCharRange(Range, SM, LangOpts);
917 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000918 }
919
920 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000921}
922
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000923StringRef Lexer::getSourceText(CharSourceRange Range,
924 const SourceManager &SM,
925 const LangOptions &LangOpts,
926 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000927 Range = makeFileCharRange(Range, SM, LangOpts);
928 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000929 if (Invalid) *Invalid = true;
930 return StringRef();
931 }
932
933 // Break down the source location.
934 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
935 if (beginInfo.first.isInvalid()) {
936 if (Invalid) *Invalid = true;
937 return StringRef();
938 }
939
940 unsigned EndOffs;
941 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
942 beginInfo.second > EndOffs) {
943 if (Invalid) *Invalid = true;
944 return StringRef();
945 }
946
947 // Try to the load the file buffer.
948 bool invalidTemp = false;
949 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
950 if (invalidTemp) {
951 if (Invalid) *Invalid = true;
952 return StringRef();
953 }
954
955 if (Invalid) *Invalid = false;
956 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
957}
958
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000959StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
960 const SourceManager &SM,
961 const LangOptions &LangOpts) {
962 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000963
964 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000965 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000966 FileID FID = SM.getFileID(Loc);
967 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
968 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
969 Loc = Expansion.getExpansionLocStart();
970 if (!Expansion.isMacroArgExpansion())
971 break;
972
973 // For macro arguments we need to check that the argument did not come
974 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
975
976 // Loc points to the argument id of the macro definition, move to the
977 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000978 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000979 SourceLocation SpellLoc = Expansion.getSpellingLoc();
980 if (SpellLoc.isFileID())
981 break; // No inner macro.
982
983 // If spelling location resides in the same FileID as macro expansion
984 // location, it means there is no inner macro.
985 FileID MacroFID = SM.getFileID(Loc);
986 if (SM.isInFileID(SpellLoc, MacroFID))
987 break;
988
989 // Argument came from inner macro.
990 Loc = SpellLoc;
991 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000992
993 // Find the spelling location of the start of the non-argument expansion
994 // range. This is where the macro name was spelled in order to begin
995 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000996 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000997
998 // Dig out the buffer where the macro name was spelled and the extents of the
999 // name so that we can render it into the expansion note.
1000 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1001 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1002 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1003 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1004}
1005
Richard Trieu3a5c9582016-01-26 02:51:55 +00001006StringRef Lexer::getImmediateMacroNameForDiagnostics(
1007 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1008 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1009 // Walk past macro argument expanions.
1010 while (SM.isMacroArgExpansion(Loc))
1011 Loc = SM.getImmediateExpansionRange(Loc).first;
1012
1013 // If the macro's spelling has no FileID, then it's actually a token paste
1014 // or stringization (or similar) and not a macro at all.
1015 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1016 return StringRef();
1017
1018 // Find the spelling location of the start of the non-argument expansion
1019 // range. This is where the macro name was spelled in order to begin
1020 // expanding this macro.
1021 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1022
1023 // Dig out the buffer where the macro name was spelled and the extents of the
1024 // name so that we can render it into the expansion note.
1025 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1026 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1027 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1028 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1029}
1030
Jordan Rose288c4212012-06-07 01:10:31 +00001031bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001032 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001033}
1034
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001035StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1036 const SourceManager &SM) {
1037 if (Loc.isInvalid() || Loc.isMacroID())
1038 return "";
1039 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1040 if (LocInfo.first.isInvalid())
1041 return "";
1042 bool Invalid = false;
1043 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1044 if (Invalid)
1045 return "";
1046 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1047 if (!Line)
1048 return "";
1049 StringRef Rest = Buffer.substr(Line - Buffer.data());
1050 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1051 return NumWhitespaceChars == StringRef::npos
1052 ? ""
1053 : Rest.take_front(NumWhitespaceChars);
1054}
1055
Chris Lattner22eb9722006-06-18 05:43:12 +00001056//===----------------------------------------------------------------------===//
1057// Diagnostics forwarding code.
1058//===----------------------------------------------------------------------===//
1059
Chris Lattner619c1742007-07-22 18:38:25 +00001060/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001061/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001062/// This is currently only used for _Pragma implementation, so it is the slow
1063/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001064static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1065 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001066static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1067 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001068 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001069 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattner619c1742007-07-22 18:38:25 +00001071 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001072 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001073 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001074 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001076 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001077 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001078 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001079 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner9dc9c202009-02-15 20:52:18 +00001081 // Figure out the expansion loc range, which is the range covered by the
1082 // original _Pragma(...) sequence.
1083 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001084 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chandler Carruth115b0772011-07-26 03:03:05 +00001086 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001087}
1088
Chris Lattner22eb9722006-06-18 05:43:12 +00001089/// getSourceLocation - Return a source location identifier for the specified
1090/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001091SourceLocation Lexer::getSourceLocation(const char *Loc,
1092 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001093 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001094 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001095
1096 // In the normal case, we're just lexing from a simple file buffer, return
1097 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001098 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001099 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001100 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattnerd32480d2009-01-17 06:22:33 +00001102 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1103 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001104 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001105 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001106}
1107
Chris Lattner22eb9722006-06-18 05:43:12 +00001108/// Diag - Forwarding function for diagnostics. This translate a source
1109/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001110DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001111 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001112}
1113
1114//===----------------------------------------------------------------------===//
1115// Trigraph and Escaped Newline Handling Code.
1116//===----------------------------------------------------------------------===//
1117
1118/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1119/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1120static char GetTrigraphCharForLetter(char Letter) {
1121 switch (Letter) {
1122 default: return 0;
1123 case '=': return '#';
1124 case ')': return ']';
1125 case '(': return '[';
1126 case '!': return '|';
1127 case '\'': return '^';
1128 case '>': return '}';
1129 case '/': return '\\';
1130 case '<': return '{';
1131 case '-': return '~';
1132 }
1133}
1134
1135/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1136/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1137/// return the result character. Finally, emit a warning about trigraph use
1138/// whether trigraphs are enabled or not.
1139static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1140 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001141 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001142
David Blaikiebbafb8a2012-03-11 07:00:24 +00001143 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001144 if (!L->isLexingRawMode())
1145 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001146 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Chris Lattner6d27a162008-11-22 02:02:22 +00001149 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001150 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001151 return Res;
1152}
1153
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001154/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1155/// 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 +00001156/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001157unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1158 unsigned Size = 0;
1159 while (isWhitespace(Ptr[Size])) {
1160 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001162 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1163 continue;
1164
1165 // If this is a \r\n or \n\r, skip the other half.
1166 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1167 Ptr[Size-1] != Ptr[Size])
1168 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001170 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001171 }
1172
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001173 // Not an escaped newline, must be a \t or something else.
1174 return 0;
1175}
1176
Chris Lattner38b2cde2009-04-18 22:27:02 +00001177/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1178/// them), skip over them and return the first non-escaped-newline found,
1179/// otherwise return P.
1180const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001181 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001182 const char *AfterEscape;
1183 if (*P == '\\') {
1184 AfterEscape = P+1;
1185 } else if (*P == '?') {
1186 // If not a trigraph for escape, bail out.
1187 if (P[1] != '?' || P[2] != '/')
1188 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001189 // FIXME: Take LangOpts into account; the language might not
1190 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001191 AfterEscape = P+3;
1192 } else {
1193 return P;
1194 }
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattner38b2cde2009-04-18 22:27:02 +00001196 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1197 if (NewLineSize == 0) return P;
1198 P = AfterEscape+NewLineSize;
1199 }
1200}
1201
Anna Zaks59a3c802011-07-27 21:43:43 +00001202/// \brief Checks that the given token is the first token that occurs after the
1203/// given location (this excludes comments and whitespace). Returns the location
1204/// immediately after the specified token. If the token is not found or the
1205/// location is inside a macro, the returned source location will be invalid.
1206SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1207 tok::TokenKind TKind,
1208 const SourceManager &SM,
1209 const LangOptions &LangOpts,
1210 bool SkipTrailingWhitespaceAndNewLine) {
1211 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001212 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001213 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001214 }
1215 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1216
1217 // Break down the source location.
1218 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1219
1220 // Try to load the file buffer.
1221 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001222 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001223 if (InvalidTemp)
1224 return SourceLocation();
1225
1226 const char *TokenBegin = File.data() + LocInfo.second;
1227
1228 // Lex from the start of the given location.
1229 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1230 TokenBegin, File.end());
1231 // Find the token.
1232 Token Tok;
1233 lexer.LexFromRawLexer(Tok);
1234 if (Tok.isNot(TKind))
1235 return SourceLocation();
1236 SourceLocation TokenLoc = Tok.getLocation();
1237
1238 // Calculate how much whitespace needs to be skipped if any.
1239 unsigned NumWhitespaceChars = 0;
1240 if (SkipTrailingWhitespaceAndNewLine) {
1241 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1242 Tok.getLength();
1243 unsigned char C = *TokenEnd;
1244 while (isHorizontalWhitespace(C)) {
1245 C = *(++TokenEnd);
1246 NumWhitespaceChars++;
1247 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001248
1249 // Skip \r, \n, \r\n, or \n\r
1250 if (C == '\n' || C == '\r') {
1251 char PrevC = C;
1252 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001253 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001254 if ((C == '\n' || C == '\r') && C != PrevC)
1255 NumWhitespaceChars++;
1256 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001257 }
1258
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001259 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001260}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001261
Chris Lattner22eb9722006-06-18 05:43:12 +00001262/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1263/// get its size, and return it. This is tricky in several cases:
1264/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1265/// then either return the trigraph (skipping 3 chars) or the '?',
1266/// depending on whether trigraphs are enabled or not.
1267/// 2. If this is an escaped newline (potentially with whitespace between
1268/// the backslash and newline), implicitly skip the newline and return
1269/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001270///
1271/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1272/// know that we can accumulate into Size, and that we have already incremented
1273/// Ptr by Size bytes.
1274///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001275/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1276/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001277///
1278char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001279 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 // If we have a slash, look for an escaped newline.
1281 if (Ptr[0] == '\\') {
1282 ++Size;
1283 ++Ptr;
1284Slash:
1285 // Common case, backslash-char where the char is not whitespace.
1286 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001287
Chris Lattnerc1835952009-06-23 05:15:06 +00001288 // See if we have optional whitespace characters between the slash and
1289 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001290 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1291 // Remember that this token needs to be cleaned.
1292 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001293
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001294 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001295 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001296 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001298 // Found backslash<whitespace><newline>. Parse the char after it.
1299 Size += EscapedNewLineSize;
1300 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001301
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001302 // Use slow version to accumulate a correct size field.
1303 return getCharAndSizeSlow(Ptr, Size, Tok);
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattner22eb9722006-06-18 05:43:12 +00001306 // Otherwise, this is not an escaped newline, just return the slash.
1307 return '\\';
1308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // If this is a trigraph, process it.
1311 if (Ptr[0] == '?' && Ptr[1] == '?') {
1312 // If this is actually a legal trigraph (not something like "??x"), emit
1313 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001314 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001316 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001317
1318 Ptr += 3;
1319 Size += 3;
1320 if (C == '\\') goto Slash;
1321 return C;
1322 }
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 // If this is neither, return a single character.
1326 ++Size;
1327 return *Ptr;
1328}
1329
1330/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1331/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1332/// and that we have already incremented Ptr by Size bytes.
1333///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001334/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1335/// be updated to match.
1336char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001337 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // If we have a slash, look for an escaped newline.
1339 if (Ptr[0] == '\\') {
1340 ++Size;
1341 ++Ptr;
1342Slash:
1343 // Common case, backslash-char where the char is not whitespace.
1344 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001347 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1348 // Found backslash<whitespace><newline>. Parse the char after it.
1349 Size += EscapedNewLineSize;
1350 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001352 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001353 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001354 }
Mike Stump11289f42009-09-09 15:08:12 +00001355
Chris Lattner22eb9722006-06-18 05:43:12 +00001356 // Otherwise, this is not an escaped newline, just return the slash.
1357 return '\\';
1358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001361 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 // If this is actually a legal trigraph (not something like "??x"), return
1363 // it.
1364 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1365 Ptr += 3;
1366 Size += 3;
1367 if (C == '\\') goto Slash;
1368 return C;
1369 }
1370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
Chris Lattner22eb9722006-06-18 05:43:12 +00001372 // If this is neither, return a single character.
1373 ++Size;
1374 return *Ptr;
1375}
1376
Chris Lattner22eb9722006-06-18 05:43:12 +00001377//===----------------------------------------------------------------------===//
1378// Helper methods for lexing.
1379//===----------------------------------------------------------------------===//
1380
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001381/// \brief Routine that indiscriminately skips bytes in the source file.
1382void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1383 BufferPtr += Bytes;
1384 if (BufferPtr > BufferEnd)
1385 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001386 // FIXME: What exactly does the StartOfLine bit mean? There are two
1387 // possible meanings for the "start" of the line: the first token on the
1388 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001389 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001390 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001391}
1392
Jordan Rose58c61e02013-02-09 01:10:25 +00001393static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001394 if (LangOpts.AsmPreprocessor) {
1395 return false;
1396 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001397 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1398 C11AllowedIDCharRanges);
1399 return C11AllowedIDChars.contains(C);
1400 } else if (LangOpts.CPlusPlus) {
1401 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1402 CXX03AllowedIDCharRanges);
1403 return CXX03AllowedIDChars.contains(C);
1404 } else {
1405 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1406 C99AllowedIDCharRanges);
1407 return C99AllowedIDChars.contains(C);
1408 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001409}
1410
Jordan Rose58c61e02013-02-09 01:10:25 +00001411static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1412 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001413 if (LangOpts.AsmPreprocessor) {
1414 return false;
1415 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001416 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1417 C11DisallowedInitialIDCharRanges);
1418 return !C11DisallowedInitialIDChars.contains(C);
1419 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001420 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001421 } else {
1422 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1423 C99DisallowedInitialIDCharRanges);
1424 return !C99DisallowedInitialIDChars.contains(C);
1425 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001426}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001427
Jordan Rose58c61e02013-02-09 01:10:25 +00001428static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1429 const char *End) {
1430 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1431 L.getSourceLocation(End));
1432}
1433
1434static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1435 CharSourceRange Range, bool IsFirst) {
1436 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001437 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001438 enum {
1439 CannotAppearInIdentifier = 0,
1440 CannotStartIdentifier
1441 };
1442
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001443 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1444 C99AllowedIDCharRanges);
1445 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1446 C99DisallowedInitialIDCharRanges);
1447 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001448 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1449 << Range
1450 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001451 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001452 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1453 << Range
1454 << CannotStartIdentifier;
1455 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001456 }
1457
Jordan Rose58c61e02013-02-09 01:10:25 +00001458 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001459 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001460 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1461 CXX03AllowedIDCharRanges);
1462 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001463 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1464 << Range;
1465 }
1466 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001467}
1468
1469bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1470 Token &Result) {
1471 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001472 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001473 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1474 return false;
1475
1476 if (!isLexingRawMode())
1477 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1478 makeCharRange(*this, CurPtr, UCNPtr),
1479 /*IsFirst=*/false);
1480
1481 Result.setFlag(Token::HasUCN);
1482 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1483 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1484 CurPtr = UCNPtr;
1485 else
1486 while (CurPtr != UCNPtr)
1487 (void)getAndAdvanceChar(CurPtr, Result);
1488 return true;
1489}
1490
1491bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1492 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001493 llvm::UTF32 CodePoint;
1494 llvm::ConversionResult Result =
1495 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1496 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001497 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001498 llvm::strictConversion);
1499 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001500 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1501 return false;
1502
1503 if (!isLexingRawMode())
1504 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1505 makeCharRange(*this, CurPtr, UnicodePtr),
1506 /*IsFirst=*/false);
1507
1508 CurPtr = UnicodePtr;
1509 return true;
1510}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001511
Eli Friedman0834a4b2013-09-19 00:41:32 +00001512bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1514 unsigned Size;
1515 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001516 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001518
Chris Lattner22eb9722006-06-18 05:43:12 +00001519 --CurPtr; // Back up over the skipped character.
1520
1521 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1522 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001523 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001524 // TODO: Could merge these checks into an InfoTable flag to make the
1525 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001526 if (isASCII(C) && C != '\\' && C != '?' &&
1527 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001528FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001529 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001530 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1531 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Chris Lattner0f1f5052006-07-20 04:16:23 +00001533 // If we are in raw mode, return this identifier raw. There is no need to
1534 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001535 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001536 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001537
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001538 // Fill in Result.IdentifierInfo and update the token kind,
1539 // looking up the identifier in the identifier table.
1540 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattnerc5a00062006-06-18 16:41:01 +00001542 // Finally, now that we know we have an identifier, pass this off to the
1543 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001544 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001545 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001546
1547 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1548 && II->getPPKeywordID() == tok::pp_not_keyword
1549 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1550 // Return the code-completion token.
1551 Result.setKind(tok::code_completion);
1552 cutOffLexing();
1553 return true;
1554 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001555 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001556 }
Mike Stump11289f42009-09-09 15:08:12 +00001557
Chris Lattner22eb9722006-06-18 05:43:12 +00001558 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001561 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001562 if (C == '$') {
1563 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001564 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001565
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001567 if (!isLexingRawMode())
1568 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 CurPtr = ConsumeChar(CurPtr, Size, Result);
1570 C = getCharAndSize(CurPtr, Size);
1571 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001572
Richard Smith8b7258b2014-02-17 21:52:30 +00001573 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001574 C = getCharAndSize(CurPtr, Size);
1575 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001576 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001577 C = getCharAndSize(CurPtr, Size);
1578 continue;
1579 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001580 goto FinishIdentifier;
1581 }
1582
1583 // Otherwise, this character is good, consume it.
1584 CurPtr = ConsumeChar(CurPtr, Size, Result);
1585
1586 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001587 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001588 CurPtr = ConsumeChar(CurPtr, Size, Result);
1589 C = getCharAndSize(CurPtr, Size);
1590 }
1591 }
1592}
1593
Douglas Gregor759ef232010-08-30 14:50:47 +00001594/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001595/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001596bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001597 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001599 if (C1 != '0')
1600 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001601 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001602 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001603}
Chris Lattner22eb9722006-06-18 05:43:12 +00001604
Nate Begeman5eee9332008-04-14 02:26:39 +00001605/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001606/// constant. From[-1] is the first character lexed. Return the end of the
1607/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001608bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001609 unsigned Size;
1610 char C = getCharAndSize(CurPtr, Size);
1611 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001612 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001613 CurPtr = ConsumeChar(CurPtr, Size, Result);
1614 PrevCh = C;
1615 C = getCharAndSize(CurPtr, Size);
1616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
Chris Lattner22eb9722006-06-18 05:43:12 +00001618 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001619 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1620 // If we are in Microsoft mode, don't continue if the constant is hex.
1621 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001622 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001623 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1624 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001625
1626 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001627 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001628 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001629 // not-quite-conforming extension. Only do so if this looks like it's
1630 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1631 bool IsHexFloat = true;
1632 if (!LangOpts.C99) {
1633 if (!isHexaLiteral(BufferPtr, LangOpts))
1634 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001635 else if (!getLangOpts().CPlusPlus1z &&
1636 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001637 IsHexFloat = false;
1638 }
1639 if (IsHexFloat)
1640 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
Richard Smithfde94852013-09-26 03:33:06 +00001643 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001644 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001645 unsigned NextSize;
1646 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001647 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001648 if (!isLexingRawMode())
1649 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1650 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001651 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001652 return LexNumericConstant(Result, CurPtr);
1653 }
1654 }
1655
Richard Smith8b7258b2014-02-17 21:52:30 +00001656 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1657 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1658 return LexNumericConstant(Result, CurPtr);
1659 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1660 return LexNumericConstant(Result, CurPtr);
1661
Chris Lattnerd01e2912006-06-18 16:22:51 +00001662 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001663 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001664 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001665 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001666 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001667}
1668
Richard Smithe18f0fa2012-03-05 04:02:15 +00001669/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001670/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001671const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1672 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001674
Richard Smith8b7258b2014-02-17 21:52:30 +00001675 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001676 unsigned Size;
1677 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001678 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001679
Richard Smith8b7258b2014-02-17 21:52:30 +00001680 if (!isIdentifierHead(C)) {
1681 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1682 Consumed = true;
1683 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1684 Consumed = true;
1685 else
1686 return CurPtr;
1687 }
1688
1689 if (!getLangOpts().CPlusPlus11) {
1690 if (!isLexingRawMode())
1691 Diag(CurPtr,
1692 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1693 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1694 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1695 return CurPtr;
1696 }
1697
1698 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1699 // that does not start with an underscore is ill-formed. As a conforming
1700 // extension, we treat all such suffixes as if they had whitespace before
1701 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1702 // likely to be a ud-suffix than a macro, however, and accept that.
1703 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001704 bool IsUDSuffix = false;
1705 if (C == '_')
1706 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001707 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001708 // In C++1y, we need to look ahead a few characters to see if this is a
1709 // valid suffix for a string literal or a numeric literal (this could be
1710 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001711 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001712 char Buffer[MaxStandardSuffixLength] = { C };
1713 unsigned Consumed = Size;
1714 unsigned Chars = 1;
1715 while (true) {
1716 unsigned NextSize;
1717 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1718 getLangOpts());
1719 if (!isIdentifierBody(Next)) {
1720 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001721 const StringRef CompleteSuffix(Buffer, Chars);
1722 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1723 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001724 break;
1725 }
1726
1727 if (Chars == MaxStandardSuffixLength)
1728 // Too long: can't be a standard suffix.
1729 break;
1730
1731 Buffer[Chars++] = Next;
1732 Consumed += NextSize;
1733 }
Richard Smithf4198b72013-07-23 08:14:48 +00001734 }
1735
1736 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001737 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001738 Diag(CurPtr, getLangOpts().MSVCCompat
1739 ? diag::ext_ms_reserved_user_defined_literal
1740 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001741 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001742 return CurPtr;
1743 }
1744
Richard Smith8b7258b2014-02-17 21:52:30 +00001745 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001746 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001747
1748 Result.setFlag(Token::HasUDSuffix);
1749 while (true) {
1750 C = getCharAndSize(CurPtr, Size);
1751 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1752 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1753 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1754 else break;
1755 }
1756
Richard Smithe18f0fa2012-03-05 04:02:15 +00001757 return CurPtr;
1758}
1759
Chris Lattner22eb9722006-06-18 05:43:12 +00001760/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001761/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001762bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001763 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001764 // Does this string contain the \0 character?
1765 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001766
Richard Smithacd4d3d2011-10-15 01:18:56 +00001767 if (!isLexingRawMode() &&
1768 (Kind == tok::utf8_string_literal ||
1769 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001770 Kind == tok::utf32_string_literal))
1771 Diag(BufferPtr, getLangOpts().CPlusPlus
1772 ? diag::warn_cxx98_compat_unicode_literal
1773 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001774
Chris Lattner22eb9722006-06-18 05:43:12 +00001775 char C = getAndAdvanceChar(CurPtr, Result);
1776 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001777 // Skip escaped characters. Escaped newlines will already be processed by
1778 // getAndAdvanceChar.
1779 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001780 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001781
Chris Lattner52d96ac2010-05-30 23:27:38 +00001782 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001783 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001784 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001785 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001786 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001787 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001788 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001789
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001790 if (C == 0) {
1791 if (isCodeCompletionPoint(CurPtr-1)) {
1792 PP->CodeCompleteNaturalLanguage();
1793 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001794 cutOffLexing();
1795 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001796 }
1797
Chris Lattner52d96ac2010-05-30 23:27:38 +00001798 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001799 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001800 C = getAndAdvanceChar(CurPtr, Result);
1801 }
Mike Stump11289f42009-09-09 15:08:12 +00001802
Richard Smithe18f0fa2012-03-05 04:02:15 +00001803 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001804 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001805 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001806
Chris Lattner5a78a022006-07-20 06:02:19 +00001807 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001808 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001809 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001810
Chris Lattnerd01e2912006-06-18 16:22:51 +00001811 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001812 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001813 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001814 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001815 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001816}
1817
Craig Topper54edcca2011-08-11 04:06:15 +00001818/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1819/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001820bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001821 tok::TokenKind Kind) {
1822 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1823 // Between the initial and final double quote characters of the raw string,
1824 // any transformations performed in phases 1 and 2 (trigraphs,
1825 // universal-character-names, and line splicing) are reverted.
1826
Richard Smithacd4d3d2011-10-15 01:18:56 +00001827 if (!isLexingRawMode())
1828 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1829
Craig Topper54edcca2011-08-11 04:06:15 +00001830 unsigned PrefixLen = 0;
1831
1832 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1833 ++PrefixLen;
1834
1835 // If the last character was not a '(', then we didn't lex a valid delimiter.
1836 if (CurPtr[PrefixLen] != '(') {
1837 if (!isLexingRawMode()) {
1838 const char *PrefixEnd = &CurPtr[PrefixLen];
1839 if (PrefixLen == 16) {
1840 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1841 } else {
1842 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1843 << StringRef(PrefixEnd, 1);
1844 }
1845 }
1846
1847 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1848 // it's possible the '"' was intended to be part of the raw string, but
1849 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001850 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001851 char C = *CurPtr++;
1852
1853 if (C == '"')
1854 break;
1855 if (C == 0 && CurPtr-1 == BufferEnd) {
1856 --CurPtr;
1857 break;
1858 }
1859 }
1860
1861 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001862 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001863 }
1864
1865 // Save prefix and move CurPtr past it
1866 const char *Prefix = CurPtr;
1867 CurPtr += PrefixLen + 1; // skip over prefix and '('
1868
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001869 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001870 char C = *CurPtr++;
1871
1872 if (C == ')') {
1873 // Check for prefix match and closing quote.
1874 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1875 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1876 break;
1877 }
1878 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1879 if (!isLexingRawMode())
1880 Diag(BufferPtr, diag::err_unterminated_raw_string)
1881 << StringRef(Prefix, PrefixLen);
1882 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001883 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001884 }
1885 }
1886
Richard Smithe18f0fa2012-03-05 04:02:15 +00001887 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001888 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001889 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001890
Craig Topper54edcca2011-08-11 04:06:15 +00001891 // Update the location of token as well as BufferPtr.
1892 const char *TokStart = BufferPtr;
1893 FormTokenWithChars(Result, CurPtr, Kind);
1894 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001895 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001896}
1897
Chris Lattner22eb9722006-06-18 05:43:12 +00001898/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1899/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001900bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001901 // Does this string contain the \0 character?
1902 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001903 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 char C = getAndAdvanceChar(CurPtr, Result);
1905 while (C != '>') {
1906 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001907 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001909 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001911 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1912 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001913 // If the filename is unterminated, then it must just be a lone <
1914 // character. Return this as such.
1915 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001916 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 } else if (C == 0) {
1918 NulCharacter = CurPtr-1;
1919 }
1920 C = getAndAdvanceChar(CurPtr, Result);
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Chris Lattner5a78a022006-07-20 06:02:19 +00001923 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001924 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001925 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerd01e2912006-06-18 16:22:51 +00001927 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001928 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001929 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001930 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001931 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001932}
1933
Chris Lattner22eb9722006-06-18 05:43:12 +00001934/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001935/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001936bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001937 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001938 // Does this character contain the \0 character?
1939 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001940
Richard Smith3e3a7052014-11-08 06:08:42 +00001941 if (!isLexingRawMode()) {
1942 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1943 Diag(BufferPtr, getLangOpts().CPlusPlus
1944 ? diag::warn_cxx98_compat_unicode_literal
1945 : diag::warn_c99_compat_unicode_literal);
1946 else if (Kind == tok::utf8_char_constant)
1947 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1948 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001949
Chris Lattner22eb9722006-06-18 05:43:12 +00001950 char C = getAndAdvanceChar(CurPtr, Result);
1951 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001952 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001953 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001954 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001955 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001956 }
1957
1958 while (C != '\'') {
1959 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001960 if (C == '\\')
1961 C = getAndAdvanceChar(CurPtr, Result);
1962
1963 if (C == '\n' || C == '\r' || // Newline.
1964 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001965 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001966 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001967 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001968 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001969 }
1970
1971 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001972 if (isCodeCompletionPoint(CurPtr-1)) {
1973 PP->CodeCompleteNaturalLanguage();
1974 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001975 cutOffLexing();
1976 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001977 }
1978
Chris Lattner86851b82010-07-07 23:24:27 +00001979 NulCharacter = CurPtr-1;
1980 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001981 C = getAndAdvanceChar(CurPtr, Result);
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Richard Smithe18f0fa2012-03-05 04:02:15 +00001984 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001985 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001986 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001987
Chris Lattner86851b82010-07-07 23:24:27 +00001988 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001989 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001990 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001991
Chris Lattnerd01e2912006-06-18 16:22:51 +00001992 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001993 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001994 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001995 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001996 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001997}
1998
1999/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2000/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002001///
2002/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2003///
Eli Friedman0834a4b2013-09-19 00:41:32 +00002004bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2005 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002007 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2008
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002009 unsigned char Char = *CurPtr;
2010
2011 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002012 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002013 // Skip horizontal whitespace very aggressively.
2014 while (isHorizontalWhitespace(Char))
2015 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002017 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002018 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 break;
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 if (ParsingPreprocessorDirective) {
2022 // End of preprocessor directive line, let LexTokenInternal handle this.
2023 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002024 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002027 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002028 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 Char = *++CurPtr;
2030 }
2031
Chris Lattner4d963442008-10-12 04:05:48 +00002032 // If the client wants us to return whitespace, return it now.
2033 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002034 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002035 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002036 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002037 IsAtPhysicalStartOfLine = true;
2038 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002039 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002040 return true;
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002043 // If this isn't immediately after a newline, there is leading space.
2044 char PrevChar = CurPtr[-1];
2045 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2046
2047 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002048 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002049 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002050 TokAtPhysicalStartOfLine = true;
2051 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002052
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002054 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002055}
2056
Nico Weber158a31a2012-11-11 07:02:14 +00002057/// We have just read the // characters from input. Skip until we find the
2058/// newline character thats terminate the comment. Then update BufferPtr and
2059/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002060///
2061/// If we're in KeepCommentMode or any CommentHandler has inserted
2062/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002063bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2064 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002065 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002067 if (!LangOpts.LineComment && !isLexingRawMode()) {
2068 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002069
Chris Lattner22eb9722006-06-18 05:43:12 +00002070 // Mark them enabled so we only emit one warning for this translation
2071 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002072 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
Chris Lattner22eb9722006-06-18 05:43:12 +00002075 // Scan over the body of the comment. The common case, when scanning, is that
2076 // the comment contains normal ascii characters with nothing interesting in
2077 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002078 //
2079 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2080 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002081 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002082 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002084 // Skip over characters in the fast loop.
2085 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002086 C != '\n' && C != '\r') // Newline or DOS-style newline.
2087 C = *++CurPtr;
2088
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002089 const char *NextLine = CurPtr;
2090 if (C != 0) {
2091 // We found a newline, see if it's escaped.
2092 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002093 bool HasSpace = false;
2094 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002095 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002096 HasSpace = true;
2097 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002098
Richard Smith4c132e52017-04-18 21:45:04 +00002099 if (*EscapePtr == '\\')
2100 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002101 CurPtr = EscapePtr;
2102 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002103 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2104 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002105 CurPtr = EscapePtr-2;
2106 else
2107 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002108
2109 // If there was space between the backslash and newline, warn about it.
2110 if (HasSpace && !isLexingRawMode())
2111 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattner22eb9722006-06-18 05:43:12 +00002114 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002115 // properly decode the character. Read it in raw mode to avoid emitting
2116 // diagnostics about things like trigraphs. If we see an escaped newline,
2117 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002118 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002119 bool OldRawMode = isLexingRawMode();
2120 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002121 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002122 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002123
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002124 // If we only read only one character, then no special handling is needed.
2125 // We're done and can skip forward to the newline.
2126 if (C != 0 && CurPtr == OldPtr+1) {
2127 CurPtr = NextLine;
2128 break;
2129 }
2130
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002132 // \n, then we had an escaped newline within the comment. Emit diagnostic
2133 // unless the next line is also a // comment.
2134 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 for (; OldPtr != CurPtr; ++OldPtr)
2136 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002137 // Okay, we found a // comment that ends in a newline, if the next
2138 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002139 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002140 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002141 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002142 ++ForwardPtr;
2143 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2144 break;
2145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner6d27a162008-11-22 02:02:22 +00002147 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002148 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002149 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002150 }
2151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Richard Smith1d2ae942017-04-17 23:44:51 +00002153 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2154 --CurPtr;
2155 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002156 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002157
2158 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2159 PP->CodeCompleteNaturalLanguage();
2160 cutOffLexing();
2161 return false;
2162 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002163 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002164
Chris Lattner93ddf802010-02-03 21:06:21 +00002165 // Found but did not consume the newline. Notify comment handlers about the
2166 // comment unless we're in a #if 0 block.
2167 if (PP && !isLexingRawMode() &&
2168 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2169 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002170 BufferPtr = CurPtr;
2171 return true; // A token has to be returned.
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Chris Lattner457fc152006-07-29 06:30:25 +00002174 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002175 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002176 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002177
2178 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002179 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002180 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002181 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002182 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 }
Mike Stump11289f42009-09-09 15:08:12 +00002184
Chris Lattner22eb9722006-06-18 05:43:12 +00002185 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002186 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002187 // contribute to another token), it isn't needed for correctness. Note that
2188 // this is ok even in KeepWhitespaceMode, because we would have returned the
2189 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002190 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002191
Chris Lattner22eb9722006-06-18 05:43:12 +00002192 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002193 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002194 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002196 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002198 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002199}
Chris Lattner22eb9722006-06-18 05:43:12 +00002200
Nico Weber158a31a2012-11-11 07:02:14 +00002201/// If in save-comment mode, package up this Line comment in an appropriate
2202/// way and return it.
2203bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002204 // If we're not in a preprocessor directive, just return the // comment
2205 // directly.
2206 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002207
David Blaikied5321242012-06-06 18:52:13 +00002208 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002209 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002210
Nico Weber158a31a2012-11-11 07:02:14 +00002211 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002212 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002213 bool Invalid = false;
2214 std::string Spelling = PP->getSpelling(Result, &Invalid);
2215 if (Invalid)
2216 return true;
2217
Nico Weber158a31a2012-11-11 07:02:14 +00002218 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002219 Spelling[1] = '*'; // Change prefix to "/*".
2220 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002221
Chris Lattnerb11c3232008-10-12 04:51:35 +00002222 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002223 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002224 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002225 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002226}
2227
Chris Lattnercb283342006-06-18 06:48:37 +00002228/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002229/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2230/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002231static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002232 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002233 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002234
Chris Lattner22eb9722006-06-18 05:43:12 +00002235 // Back up off the newline.
2236 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattner22eb9722006-06-18 05:43:12 +00002238 // If this is a two-character newline sequence, skip the other character.
2239 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2240 // \n\n or \r\r -> not escaped newline.
2241 if (CurPtr[0] == CurPtr[1])
2242 return false;
2243 // \n\r or \r\n -> skip the newline.
2244 --CurPtr;
2245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 // If we have horizontal whitespace, skip over it. We allow whitespace
2248 // between the slash and newline.
2249 bool HasSpace = false;
2250 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2251 --CurPtr;
2252 HasSpace = true;
2253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
Chris Lattner22eb9722006-06-18 05:43:12 +00002255 // If we have a slash, we know this is an escaped newline.
2256 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002257 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 } else {
2259 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002260 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2261 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002262 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002263
Chris Lattnercb283342006-06-18 06:48:37 +00002264 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002265 CurPtr -= 2;
2266
2267 // If no trigraphs are enabled, warn that we ignored this trigraph and
2268 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002269 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002270 if (!L->isLexingRawMode())
2271 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002272 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002273 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002274 if (!L->isLexingRawMode())
2275 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002276 }
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattner22eb9722006-06-18 05:43:12 +00002278 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002279 if (!L->isLexingRawMode())
2280 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Chris Lattner22eb9722006-06-18 05:43:12 +00002282 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002283 if (HasSpace && !L->isLexingRawMode())
2284 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002285
Chris Lattnercb283342006-06-18 06:48:37 +00002286 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002287}
2288
Chris Lattneraded4a92006-10-27 04:42:31 +00002289#ifdef __SSE2__
2290#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002291#elif __ALTIVEC__
2292#include <altivec.h>
2293#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002294#endif
2295
James Dennettf442d242012-06-17 03:40:43 +00002296/// We have just read from input the / and * characters that started a comment.
2297/// Read until we find the * and / characters that terminate the comment.
2298/// Note that we don't bother decoding trigraphs or escaped newlines in block
2299/// comments, because they cannot cause the comment to end. The only thing
2300/// that can happen is the comment could end with an escaped newline between
2301/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002302///
Chris Lattner87d02082010-01-18 22:35:47 +00002303/// If we're in KeepCommentMode or any CommentHandler has inserted
2304/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002305bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2306 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002307 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002308 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002309 // optimization helps people who like to put a lot of * characters in their
2310 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002311
2312 // The first character we get with newlines and trigraphs skipped to handle
2313 // the degenerate /*/ case below correctly if the * has an escaped newline
2314 // after it.
2315 unsigned CharSize;
2316 unsigned char C = getCharAndSize(CurPtr, CharSize);
2317 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002319 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002320 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002321 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002322
Chris Lattner99e7d232008-10-12 04:19:49 +00002323 // KeepWhitespaceMode should return this broken comment as a token. Since
2324 // it isn't a well formed comment, just return it as an 'unknown' token.
2325 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002326 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002327 return true;
2328 }
Mike Stump11289f42009-09-09 15:08:12 +00002329
Chris Lattner99e7d232008-10-12 04:19:49 +00002330 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002331 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002332 }
Mike Stump11289f42009-09-09 15:08:12 +00002333
Chris Lattnerc850ad62007-07-21 23:43:37 +00002334 // Check to see if the first character after the '/*' is another /. If so,
2335 // then this slash does not end the block comment, it is part of it.
2336 if (C == '/')
2337 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002338
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002339 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002340 // Skip over all non-interesting characters until we find end of buffer or a
2341 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002342 if (CurPtr + 24 < BufferEnd &&
2343 // If there is a code-completion point avoid the fast scan because it
2344 // doesn't check for '\0'.
2345 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002346 // While not aligned to a 16-byte boundary.
2347 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2348 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002349
Chris Lattner6cc3e362006-10-27 04:12:35 +00002350 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002351
2352#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002353 __m128i Slashes = _mm_set1_epi8('/');
2354 while (CurPtr+16 <= BufferEnd) {
2355 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2356 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002357 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002358 // Adjust the pointer to point directly after the first slash. It's
2359 // not necessary to set C here, it will be overwritten at the end of
2360 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002361 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002362 goto FoundSlash;
2363 }
Roman Divacky61509902014-04-03 18:04:52 +00002364 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002365 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002366#elif __ALTIVEC__
2367 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002368 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002369 '/', '/', '/', '/', '/', '/', '/', '/'
2370 };
2371 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002372 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002373 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002374#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002375 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002376 while (CurPtr[0] != '/' &&
2377 CurPtr[1] != '/' &&
2378 CurPtr[2] != '/' &&
2379 CurPtr[3] != '/' &&
2380 CurPtr+4 < BufferEnd) {
2381 CurPtr += 4;
2382 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002383#endif
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattneraded4a92006-10-27 04:42:31 +00002385 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002386 C = *CurPtr++;
2387 }
Mike Stump11289f42009-09-09 15:08:12 +00002388
Chris Lattneraded4a92006-10-27 04:42:31 +00002389 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002390 while (C != '/' && C != '\0')
2391 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002392
Chris Lattner22eb9722006-06-18 05:43:12 +00002393 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002394 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002395 if (CurPtr[-2] == '*') // We found the final */. We're done!
2396 break;
Mike Stump11289f42009-09-09 15:08:12 +00002397
Chris Lattner22eb9722006-06-18 05:43:12 +00002398 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002399 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002400 // We found the final */, though it had an escaped newline between the
2401 // * and /. We're done!
2402 break;
2403 }
2404 }
2405 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2406 // If this is a /* inside of the comment, emit a warning. Don't do this
2407 // if this is a /*/, which will end the comment. This misses cases with
2408 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002409 if (!isLexingRawMode())
2410 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002411 }
2412 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002413 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002414 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002415 // Note: the user probably forgot a */. We could continue immediately
2416 // after the /*, but this would involve lexing a lot of what really is the
2417 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002418 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002419
Chris Lattner99e7d232008-10-12 04:19:49 +00002420 // KeepWhitespaceMode should return this broken comment as a token. Since
2421 // it isn't a well formed comment, just return it as an 'unknown' token.
2422 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002423 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002424 return true;
2425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
Chris Lattner99e7d232008-10-12 04:19:49 +00002427 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002428 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002429 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2430 PP->CodeCompleteNaturalLanguage();
2431 cutOffLexing();
2432 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002433 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002434
Chris Lattner22eb9722006-06-18 05:43:12 +00002435 C = *CurPtr++;
2436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437
Chris Lattner93ddf802010-02-03 21:06:21 +00002438 // Notify comment handlers about the comment unless we're in a #if 0 block.
2439 if (PP && !isLexingRawMode() &&
2440 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2441 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002442 BufferPtr = CurPtr;
2443 return true; // A token has to be returned.
2444 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002445
Chris Lattner457fc152006-07-29 06:30:25 +00002446 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002447 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002448 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002449 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002450 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002451
2452 // It is common for the tokens immediately after a /**/ comment to be
2453 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002454 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2455 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002456 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002457 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002458 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002459 }
2460
2461 // Otherwise, just return so that the next character will be lexed as a token.
2462 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002463 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002464 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002465}
2466
2467//===----------------------------------------------------------------------===//
2468// Primary Lexing Entry Points
2469//===----------------------------------------------------------------------===//
2470
Chris Lattner22eb9722006-06-18 05:43:12 +00002471/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2472/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002473void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002474 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2475 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002476 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002477
2478 // CurPtr - Cache BufferPtr in an automatic variable.
2479 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002480 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002481 char Char = getAndAdvanceChar(CurPtr, Tmp);
2482 switch (Char) {
2483 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002484 if (Result)
2485 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002486 break;
2487 case 0: // Null.
2488 // Found end of file?
2489 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002490 if (isCodeCompletionPoint(CurPtr-1)) {
2491 PP->CodeCompleteNaturalLanguage();
2492 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002493 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002494 }
2495
Chris Lattner22eb9722006-06-18 05:43:12 +00002496 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002497 if (Result)
2498 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002499 break;
2500 }
2501 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002502 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002503 case '\r':
2504 case '\n':
2505 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2506 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2507 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002509 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002510 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002511 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002512 if (PP)
2513 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002514 Lex(Tmp);
2515 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002516 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002517
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002518 // Finally, we're done;
2519 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002520 }
2521 }
2522}
2523
2524/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2525/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002526/// This returns true if Result contains a token, false if PP.Lex should be
2527/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002528bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002529 // If we hit the end of the file while parsing a preprocessor directive,
2530 // end the preprocessor directive first. The next token returned will
2531 // then be the end of file.
2532 if (ParsingPreprocessorDirective) {
2533 // Done parsing the "line".
2534 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002535 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002536 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002537
Chris Lattner457fc152006-07-29 06:30:25 +00002538 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002539 if (PP)
2540 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002541 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002542 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002543
Chris Lattner30a2fa12006-07-19 06:31:49 +00002544 // If we are in raw mode, return this event as an EOF token. Let the caller
2545 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002546 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002547 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002548 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002549 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002550 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002551 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002552
Erik Verbruggen795eee92017-07-05 09:44:07 +00002553 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002554 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2555 ConditionalStack.clear();
2556 }
2557
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002558 // Issue diagnostics for unterminated #if and missing newline.
2559
Chris Lattner30a2fa12006-07-19 06:31:49 +00002560 // If we are in a #if directive, emit an error.
2561 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002562 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002563 PP->Diag(ConditionalStack.back().IfLoc,
2564 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002565 ConditionalStack.pop_back();
2566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Chris Lattner8f96d042008-04-12 05:54:25 +00002568 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2569 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002570 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2571 DiagnosticsEngine &Diags = PP->getDiagnostics();
2572 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2573 unsigned DiagID;
2574
2575 if (LangOpts.CPlusPlus11) {
2576 // C++11 [lex.phases] 2.2 p2
2577 // Prefer the C++98 pedantic compatibility warning over the generic,
2578 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002579 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002580 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2581 } else {
2582 DiagID = diag::warn_no_newline_eof;
2583 }
2584 } else {
2585 DiagID = diag::ext_no_newline_eof;
2586 }
2587
2588 Diag(BufferEnd, DiagID)
2589 << FixItHint::CreateInsertion(EndLoc, "\n");
2590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Chris Lattner22eb9722006-06-18 05:43:12 +00002592 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002593
2594 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002595 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002596}
2597
Chris Lattner678c8802006-07-11 05:46:12 +00002598/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2599/// the specified lexer will return a tok::l_paren token, 0 if it is something
2600/// else and 2 if there are no more tokens in the buffer controlled by the
2601/// lexer.
2602unsigned Lexer::isNextPPTokenLParen() {
2603 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002604
Chris Lattner678c8802006-07-11 05:46:12 +00002605 // Switch to 'skipping' mode. This will ensure that we can lex a token
2606 // without emitting diagnostics, disables macro expansion, and will cause EOF
2607 // to return an EOF token instead of popping the include stack.
2608 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattner678c8802006-07-11 05:46:12 +00002610 // Save state that can be changed while lexing so that we can restore it.
2611 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002612 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002613 bool atStartOfLine = IsAtStartOfLine;
2614 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2615 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002616
Chris Lattner146762e2007-07-20 16:59:19 +00002617 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002618 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002619
Chris Lattner678c8802006-07-11 05:46:12 +00002620 // Restore state that may have changed.
2621 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002622 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002623 HasLeadingSpace = leadingSpace;
2624 IsAtStartOfLine = atStartOfLine;
2625 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002626
Chris Lattner678c8802006-07-11 05:46:12 +00002627 // Restore the lexer back to non-skipping mode.
2628 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002629
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002630 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002631 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002632 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002633}
2634
James Dennettf442d242012-06-17 03:40:43 +00002635/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002636static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2637 ConflictMarkerKind CMK) {
2638 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2639 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002640 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002641 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002643 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002644 if (Pos == 0 ||
2645 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002646 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2647 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002648 continue;
2649 }
2650 return RestOfBuffer.data()+Pos;
2651 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002652 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002653}
2654
2655/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2656/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2657/// and recover nicely. This returns true if it is a conflict marker and false
2658/// if not.
2659bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2660 // Only a conflict marker if it starts at the beginning of a line.
2661 if (CurPtr != BufferStart &&
2662 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2663 return false;
2664
Richard Smitha9e33d42011-10-12 00:37:51 +00002665 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002666 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2667 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002668 return false;
2669
2670 // If we have a situation where we don't care about conflict markers, ignore
2671 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002672 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002673 return false;
2674
Richard Smitha9e33d42011-10-12 00:37:51 +00002675 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2676
2677 // Check to see if there is an ending marker somewhere in the buffer at the
2678 // start of a line to terminate this conflict marker.
2679 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002680 // We found a match. We are really in a conflict marker.
2681 // Diagnose this, and ignore to the end of line.
2682 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002683 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002684
2685 // Skip ahead to the end of line. We know this exists because the
2686 // end-of-conflict marker starts with \r or \n.
2687 while (*CurPtr != '\r' && *CurPtr != '\n') {
2688 assert(CurPtr != BufferEnd && "Didn't find end of line");
2689 ++CurPtr;
2690 }
2691 BufferPtr = CurPtr;
2692 return true;
2693 }
2694
2695 // No end of conflict marker found.
2696 return false;
2697}
2698
Richard Smitha9e33d42011-10-12 00:37:51 +00002699/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2700/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2701/// is the end of a conflict marker. Handle it by ignoring up until the end of
2702/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002703bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2704 // Only a conflict marker if it starts at the beginning of a line.
2705 if (CurPtr != BufferStart &&
2706 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2707 return false;
2708
2709 // If we have a situation where we don't care about conflict markers, ignore
2710 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002711 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002712 return false;
2713
Richard Smitha9e33d42011-10-12 00:37:51 +00002714 // Check to see if we have the marker (4 characters in a row).
2715 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002716 if (CurPtr[i] != CurPtr[0])
2717 return false;
2718
2719 // If we do have it, search for the end of the conflict marker. This could
2720 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2721 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002722 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2723 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002724 CurPtr = End;
2725
2726 // Skip ahead to the end of line.
2727 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2728 ++CurPtr;
2729
2730 BufferPtr = CurPtr;
2731
2732 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002733 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002734 return true;
2735 }
2736
2737 return false;
2738}
2739
Alex Lorenz1be800c52017-04-19 08:58:56 +00002740static const char *findPlaceholderEnd(const char *CurPtr,
2741 const char *BufferEnd) {
2742 if (CurPtr == BufferEnd)
2743 return nullptr;
2744 BufferEnd -= 1; // Scan until the second last character.
2745 for (; CurPtr != BufferEnd; ++CurPtr) {
2746 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2747 return CurPtr + 2;
2748 }
2749 return nullptr;
2750}
2751
2752bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2753 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002754 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002755 return false;
2756 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2757 if (!End)
2758 return false;
2759 const char *Start = CurPtr - 1;
2760 if (!LangOpts.AllowEditorPlaceholders)
2761 Diag(Start, diag::err_placeholder_in_source);
2762 Result.startToken();
2763 FormTokenWithChars(Result, End, tok::raw_identifier);
2764 Result.setRawIdentifierData(Start);
2765 PP->LookUpIdentifierInfo(Result);
2766 Result.setFlag(Token::IsEditorPlaceholder);
2767 BufferPtr = End;
2768 return true;
2769}
2770
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002771bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2772 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002773 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002774 return Loc == PP->getCodeCompletionLoc();
2775 }
2776
2777 return false;
2778}
2779
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002780uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2781 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002782 unsigned CharSize;
2783 char Kind = getCharAndSize(StartPtr, CharSize);
2784
2785 unsigned NumHexDigits;
2786 if (Kind == 'u')
2787 NumHexDigits = 4;
2788 else if (Kind == 'U')
2789 NumHexDigits = 8;
2790 else
2791 return 0;
2792
Jordan Rosec0cba272013-01-27 20:12:04 +00002793 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002794 if (Result && !isLexingRawMode())
2795 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002796 return 0;
2797 }
2798
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002799 const char *CurPtr = StartPtr + CharSize;
2800 const char *KindLoc = &CurPtr[-1];
2801
2802 uint32_t CodePoint = 0;
2803 for (unsigned i = 0; i < NumHexDigits; ++i) {
2804 char C = getCharAndSize(CurPtr, CharSize);
2805
2806 unsigned Value = llvm::hexDigitValue(C);
2807 if (Value == -1U) {
2808 if (Result && !isLexingRawMode()) {
2809 if (i == 0) {
2810 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2811 << StringRef(KindLoc, 1);
2812 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002813 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002814
2815 // If the user wrote \U1234, suggest a fixit to \u.
2816 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002817 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002818 Diag(KindLoc, diag::note_ucn_four_not_eight)
2819 << FixItHint::CreateReplacement(URange, "u");
2820 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002821 }
2822 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002823
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002824 return 0;
2825 }
2826
2827 CodePoint <<= 4;
2828 CodePoint += Value;
2829
2830 CurPtr += CharSize;
2831 }
2832
2833 if (Result) {
2834 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002835 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002836 StartPtr = CurPtr;
2837 else
2838 while (StartPtr != CurPtr)
2839 (void)getAndAdvanceChar(StartPtr, *Result);
2840 } else {
2841 StartPtr = CurPtr;
2842 }
2843
Justin Bogner53535132013-10-21 05:02:28 +00002844 // Don't apply C family restrictions to UCNs in assembly mode
2845 if (LangOpts.AsmPreprocessor)
2846 return CodePoint;
2847
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002848 // C99 6.4.3p2: A universal character name shall not specify a character whose
2849 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2850 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2851 // C++11 [lex.charset]p2: If the hexadecimal value for a
2852 // universal-character-name corresponds to a surrogate code point (in the
2853 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2854 // if the hexadecimal value for a universal-character-name outside the
2855 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2856 // string literal corresponds to a control character (in either of the
2857 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2858 // basic source character set, the program is ill-formed.
2859 if (CodePoint < 0xA0) {
2860 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2861 return CodePoint;
2862
2863 // We don't use isLexingRawMode() here because we need to warn about bad
2864 // UCNs even when skipping preprocessing tokens in a #if block.
2865 if (Result && PP) {
2866 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2867 Diag(BufferPtr, diag::err_ucn_control_character);
2868 else {
2869 char C = static_cast<char>(CodePoint);
2870 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2871 }
2872 }
2873
2874 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002875
2876 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002877 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002878 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002879 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002880 if (Result && PP) {
2881 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2882 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2883 else
2884 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2885 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002886 return 0;
2887 }
2888
2889 return CodePoint;
2890}
2891
Eli Friedman0834a4b2013-09-19 00:41:32 +00002892bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2893 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002894 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2895 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002896 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002897 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002898 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002899 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002900
2901 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002902 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002903 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002904 return false;
2905}
Jordan Rose4246ae02013-01-24 20:50:50 +00002906
Eli Friedman0834a4b2013-09-19 00:41:32 +00002907bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002908 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2909 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2910 !PP->isPreprocessedOutput()) {
2911 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2912 makeCharRange(*this, BufferPtr, CurPtr),
2913 /*IsFirst=*/true);
2914 }
2915
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002916 MIOpt.ReadToken();
2917 return LexIdentifier(Result, CurPtr);
2918 }
2919
Jordan Rosecc538342013-01-31 19:48:48 +00002920 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2921 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002922 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002923 // Non-ASCII characters tend to creep into source code unintentionally.
2924 // Instead of letting the parser complain about the unknown token,
2925 // just drop the character.
2926 // Note that we can /only/ do this when the non-ASCII character is actually
2927 // spelled as Unicode, not written as a UCN. The standard requires that
2928 // we not throw away any possible preprocessor tokens, but there's a
2929 // loophole in the mapping of Unicode characters to basic character set
2930 // characters that allows us to map these particular characters to, say,
2931 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002932 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002933 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002934
2935 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002936 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002937 }
2938
2939 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2940 // up by accident.
2941 MIOpt.ReadToken();
2942 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002943 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002944}
2945
Eli Friedman0834a4b2013-09-19 00:41:32 +00002946void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2947 IsAtStartOfLine = Result.isAtStartOfLine();
2948 HasLeadingSpace = Result.hasLeadingSpace();
2949 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2950 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2951}
2952
2953bool Lexer::Lex(Token &Result) {
2954 // Start a new token.
2955 Result.startToken();
2956
2957 // Set up misc whitespace flags for LexTokenInternal.
2958 if (IsAtStartOfLine) {
2959 Result.setFlag(Token::StartOfLine);
2960 IsAtStartOfLine = false;
2961 }
2962
2963 if (HasLeadingSpace) {
2964 Result.setFlag(Token::LeadingSpace);
2965 HasLeadingSpace = false;
2966 }
2967
2968 if (HasLeadingEmptyMacro) {
2969 Result.setFlag(Token::LeadingEmptyMacro);
2970 HasLeadingEmptyMacro = false;
2971 }
2972
2973 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2974 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002975 bool isRawLex = isLexingRawMode();
2976 (void) isRawLex;
2977 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2978 // (After the LexTokenInternal call, the lexer might be destroyed.)
2979 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2980 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002981}
Chris Lattner22eb9722006-06-18 05:43:12 +00002982
2983/// LexTokenInternal - This implements a simple C family lexer. It is an
2984/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002985/// has a null character at the end of the file. This returns a preprocessing
2986/// token, not a normal token, as such, it is an internal interface. It assumes
2987/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002988bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002989LexNextToken:
2990 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002991 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002992 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Chris Lattner22eb9722006-06-18 05:43:12 +00002994 // CurPtr - Cache BufferPtr in an automatic variable.
2995 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002996
Chris Lattnereb54b592006-07-10 06:34:27 +00002997 // Small amounts of horizontal whitespace is very common between tokens.
2998 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2999 ++CurPtr;
3000 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3001 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003002
Chris Lattner4d963442008-10-12 04:05:48 +00003003 // If we are keeping whitespace and other tokens, just return what we just
3004 // skipped. The next lexer invocation will return the token after the
3005 // whitespace.
3006 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003007 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003008 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003009 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003010 }
Mike Stump11289f42009-09-09 15:08:12 +00003011
Chris Lattnereb54b592006-07-10 06:34:27 +00003012 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003013 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003014 }
Mike Stump11289f42009-09-09 15:08:12 +00003015
Chris Lattner22eb9722006-06-18 05:43:12 +00003016 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattner22eb9722006-06-18 05:43:12 +00003018 // Read a character, advancing over it.
3019 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003020 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Chris Lattner22eb9722006-06-18 05:43:12 +00003022 switch (Char) {
3023 case 0: // Null.
3024 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003025 if (CurPtr-1 == BufferEnd)
3026 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003027
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003028 // Check if we are performing code completion.
3029 if (isCodeCompletionPoint(CurPtr-1)) {
3030 // Return the code-completion token.
3031 Result.startToken();
3032 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003033 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003034 }
3035
Chris Lattner6d27a162008-11-22 02:02:22 +00003036 if (!isLexingRawMode())
3037 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003038 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003039 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3040 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003041
Eli Friedman0834a4b2013-09-19 00:41:32 +00003042 // We know the lexer hasn't changed, so just try again with this lexer.
3043 // (We manually eliminate the tail call to avoid recursion.)
3044 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003045
3046 case 26: // DOS & CP/M EOF: "^Z".
3047 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003048 if (LangOpts.MicrosoftExt) {
3049 if (!isLexingRawMode())
3050 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003051 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003052 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003053
Chris Lattner3dfff972009-12-17 05:29:40 +00003054 // If Microsoft extensions are disabled, this is just random garbage.
3055 Kind = tok::unknown;
3056 break;
3057
Chris Lattner22eb9722006-06-18 05:43:12 +00003058 case '\n':
3059 case '\r':
3060 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003061 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003062 if (ParsingPreprocessorDirective) {
3063 // Done parsing the "line".
3064 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003065
Chris Lattner457fc152006-07-29 06:30:25 +00003066 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003067 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003068 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003069
Chris Lattner22eb9722006-06-18 05:43:12 +00003070 // Since we consumed a newline, we are back at the start of a line.
3071 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003072 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003073
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003074 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003075 break;
3076 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003077
Chris Lattner22eb9722006-06-18 05:43:12 +00003078 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003079 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003080
Eli Friedman0834a4b2013-09-19 00:41:32 +00003081 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3082 return true; // KeepWhitespaceMode
3083
3084 // We only saw whitespace, so just try again with this lexer.
3085 // (We manually eliminate the tail call to avoid recursion.)
3086 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003087 case ' ':
3088 case '\t':
3089 case '\f':
3090 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003091 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003092 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003093 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3094 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003095
3096 SkipIgnoredUnits:
3097 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003098
Chris Lattnerb9b85972007-07-22 06:29:05 +00003099 // If the next token is obviously a // or /* */ comment, skip it efficiently
3100 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003101 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003102 LangOpts.LineComment &&
3103 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003104 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3105 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003106 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003107 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003108 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3109 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003110 goto SkipIgnoredUnits;
3111 } else if (isHorizontalWhitespace(*CurPtr)) {
3112 goto SkipHorizontalWhitespace;
3113 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003114 // We only saw whitespace, so just try again with this lexer.
3115 // (We manually eliminate the tail call to avoid recursion.)
3116 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003117
Chris Lattner2b15cf72008-01-03 17:58:54 +00003118 // C99 6.4.4.1: Integer Constants.
3119 // C99 6.4.4.2: Floating Constants.
3120 case '0': case '1': case '2': case '3': case '4':
3121 case '5': case '6': case '7': case '8': case '9':
3122 // Notify MIOpt that we read a non-whitespace/non-comment token.
3123 MIOpt.ReadToken();
3124 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003125
Richard Smith9b362092013-03-09 23:56:02 +00003126 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003127 // Notify MIOpt that we read a non-whitespace/non-comment token.
3128 MIOpt.ReadToken();
3129
Richard Smith9b362092013-03-09 23:56:02 +00003130 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003131 Char = getCharAndSize(CurPtr, SizeTmp);
3132
3133 // UTF-16 string literal
3134 if (Char == '"')
3135 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3136 tok::utf16_string_literal);
3137
3138 // UTF-16 character constant
3139 if (Char == '\'')
3140 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3141 tok::utf16_char_constant);
3142
Craig Topper54edcca2011-08-11 04:06:15 +00003143 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003144 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3145 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003146 return LexRawStringLiteral(Result,
3147 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3148 SizeTmp2, Result),
3149 tok::utf16_string_literal);
3150
3151 if (Char == '8') {
3152 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3153
3154 // UTF-8 string literal
3155 if (Char2 == '"')
3156 return LexStringLiteral(Result,
3157 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3158 SizeTmp2, Result),
3159 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003160 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3161 return LexCharConstant(
3162 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3163 SizeTmp2, Result),
3164 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003165
Richard Smith9b362092013-03-09 23:56:02 +00003166 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003167 unsigned SizeTmp3;
3168 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3169 // UTF-8 raw string literal
3170 if (Char3 == '"') {
3171 return LexRawStringLiteral(Result,
3172 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3173 SizeTmp2, Result),
3174 SizeTmp3, Result),
3175 tok::utf8_string_literal);
3176 }
3177 }
3178 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003179 }
3180
3181 // treat u like the start of an identifier.
3182 return LexIdentifier(Result, CurPtr);
3183
Richard Smith9b362092013-03-09 23:56:02 +00003184 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003185 // Notify MIOpt that we read a non-whitespace/non-comment token.
3186 MIOpt.ReadToken();
3187
Richard Smith9b362092013-03-09 23:56:02 +00003188 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003189 Char = getCharAndSize(CurPtr, SizeTmp);
3190
3191 // UTF-32 string literal
3192 if (Char == '"')
3193 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3194 tok::utf32_string_literal);
3195
3196 // UTF-32 character constant
3197 if (Char == '\'')
3198 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3199 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003200
3201 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003202 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3203 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003204 return LexRawStringLiteral(Result,
3205 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3206 SizeTmp2, Result),
3207 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003208 }
3209
3210 // treat U like the start of an identifier.
3211 return LexIdentifier(Result, CurPtr);
3212
Craig Topper54edcca2011-08-11 04:06:15 +00003213 case 'R': // Identifier or C++0x raw string literal
3214 // Notify MIOpt that we read a non-whitespace/non-comment token.
3215 MIOpt.ReadToken();
3216
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003217 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003218 Char = getCharAndSize(CurPtr, SizeTmp);
3219
3220 if (Char == '"')
3221 return LexRawStringLiteral(Result,
3222 ConsumeChar(CurPtr, SizeTmp, Result),
3223 tok::string_literal);
3224 }
3225
3226 // treat R like the start of an identifier.
3227 return LexIdentifier(Result, CurPtr);
3228
Chris Lattner2b15cf72008-01-03 17:58:54 +00003229 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003230 // Notify MIOpt that we read a non-whitespace/non-comment token.
3231 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003232 Char = getCharAndSize(CurPtr, SizeTmp);
3233
3234 // Wide string literal.
3235 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003236 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003237 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003238
Craig Topper54edcca2011-08-11 04:06:15 +00003239 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003240 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003241 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3242 return LexRawStringLiteral(Result,
3243 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3244 SizeTmp2, Result),
3245 tok::wide_string_literal);
3246
Chris Lattner22eb9722006-06-18 05:43:12 +00003247 // Wide character constant.
3248 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003249 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3250 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003252 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003253
Chris Lattner22eb9722006-06-18 05:43:12 +00003254 // C99 6.4.2: Identifiers.
3255 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3256 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003257 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003258 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3259 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3260 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003261 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003262 case 'v': case 'w': case 'x': case 'y': case 'z':
3263 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003264 // Notify MIOpt that we read a non-whitespace/non-comment token.
3265 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003267
3268 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003269 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003270 if (!isLexingRawMode())
3271 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003272 // Notify MIOpt that we read a non-whitespace/non-comment token.
3273 MIOpt.ReadToken();
3274 return LexIdentifier(Result, CurPtr);
3275 }
Mike Stump11289f42009-09-09 15:08:12 +00003276
Chris Lattnerb11c3232008-10-12 04:51:35 +00003277 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003278 break;
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattner22eb9722006-06-18 05:43:12 +00003280 // C99 6.4.4: Character Constants.
3281 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003282 // Notify MIOpt that we read a non-whitespace/non-comment token.
3283 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003284 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003285
3286 // C99 6.4.5: String Literals.
3287 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003288 // Notify MIOpt that we read a non-whitespace/non-comment token.
3289 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003290 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003291
3292 // C99 6.4.6: Punctuators.
3293 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003294 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 break;
3296 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003297 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 break;
3299 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003300 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 break;
3302 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003303 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003304 break;
3305 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003306 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003307 break;
3308 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003309 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003310 break;
3311 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003312 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003313 break;
3314 case '.':
3315 Char = getCharAndSize(CurPtr, SizeTmp);
3316 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003317 // Notify MIOpt that we read a non-whitespace/non-comment token.
3318 MIOpt.ReadToken();
3319
Chris Lattner22eb9722006-06-18 05:43:12 +00003320 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003321 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003322 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003323 CurPtr += SizeTmp;
3324 } else if (Char == '.' &&
3325 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003327 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3328 SizeTmp2, Result);
3329 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003330 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003331 }
3332 break;
3333 case '&':
3334 Char = getCharAndSize(CurPtr, SizeTmp);
3335 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003336 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003337 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3338 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003339 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003340 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3341 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003342 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003343 }
3344 break;
Mike Stump11289f42009-09-09 15:08:12 +00003345 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003346 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3349 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003350 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003351 }
3352 break;
3353 case '+':
3354 Char = getCharAndSize(CurPtr, SizeTmp);
3355 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003356 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003357 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003358 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003359 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003360 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003361 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003362 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003363 }
3364 break;
3365 case '-':
3366 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003367 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003368 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003369 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003370 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003371 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003372 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3373 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003374 Kind = tok::arrowstar;
3375 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003376 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::arrow;
3378 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003379 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003380 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003381 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003382 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003383 }
3384 break;
3385 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003386 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003387 break;
3388 case '!':
3389 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003390 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3392 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003393 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003394 }
3395 break;
3396 case '/':
3397 // 6.4.9: Comments
3398 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003399 if (Char == '/') { // Line comment.
3400 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003401 // want to lex this as a comment. There is one problem with this though,
3402 // that in one particular corner case, this can change the behavior of the
3403 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003404 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003405 // "foo". Check to see if the character after the second slash is a '*'.
3406 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003407 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003408 bool TreatAsComment = LangOpts.LineComment &&
3409 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003410 if (!TreatAsComment)
3411 if (!(PP && PP->isPreprocessedOutput()))
3412 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3413
3414 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003415 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3416 TokAtPhysicalStartOfLine))
3417 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003418
Chris Lattner58827712009-01-16 22:39:25 +00003419 // It is common for the tokens immediately after a // comment to be
3420 // whitespace (indentation for the next line). Instead of going through
3421 // the big switch, handle it efficiently now.
3422 goto SkipIgnoredUnits;
3423 }
3424 }
Mike Stump11289f42009-09-09 15:08:12 +00003425
Chris Lattner58827712009-01-16 22:39:25 +00003426 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003427 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3428 TokAtPhysicalStartOfLine))
3429 return true; // There is a token to return.
3430
3431 // We only saw whitespace, so just try again with this lexer.
3432 // (We manually eliminate the tail call to avoid recursion.)
3433 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Chris Lattner58827712009-01-16 22:39:25 +00003436 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003438 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003439 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003440 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003441 }
3442 break;
3443 case '%':
3444 Char = getCharAndSize(CurPtr, SizeTmp);
3445 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003446 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003448 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003449 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003451 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003452 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003453 Char = getCharAndSize(CurPtr, SizeTmp);
3454 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003455 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003456 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3457 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003458 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003460 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003461 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003462 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003463 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003464 // We parsed a # character. If this occurs at the start of the line,
3465 // it's actually the start of a preprocessing directive. Callback to
3466 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003467 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003468 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003469 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003470
Chris Lattner2534324a2009-03-18 20:58:27 +00003471 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003472 }
3473 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003474 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003475 }
3476 break;
3477 case '<':
3478 Char = getCharAndSize(CurPtr, SizeTmp);
3479 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003480 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003481 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003482 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3483 if (After == '=') {
3484 Kind = tok::lesslessequal;
3485 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3486 SizeTmp2, Result);
3487 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3488 // If this is actually a '<<<<<<<' version control conflict marker,
3489 // recognize it as such and recover nicely.
3490 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003491 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3492 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3493 // ignore it.
3494 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003495 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003496 Kind = tok::lesslessless;
3497 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3498 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003499 } else {
3500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3501 Kind = tok::lessless;
3502 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003503 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003504 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003505 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003506 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003507 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003508 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3509 // C++0x [lex.pptoken]p3:
3510 // Otherwise, if the next three characters are <:: and the subsequent
3511 // character is neither : nor >, the < is treated as a preprocessor
3512 // token by itself and not as the first character of the alternative
3513 // token <:.
3514 unsigned SizeTmp3;
3515 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3516 if (After != ':' && After != '>') {
3517 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003518 if (!isLexingRawMode())
3519 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003520 break;
3521 }
3522 }
3523
Chris Lattner22eb9722006-06-18 05:43:12 +00003524 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003525 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003526 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003527 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003528 Kind = tok::l_brace;
Alex Lorenz1be800c52017-04-19 08:58:56 +00003529 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3530 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003531 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003532 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003533 }
3534 break;
3535 case '>':
3536 Char = getCharAndSize(CurPtr, SizeTmp);
3537 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003539 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003540 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003541 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3542 if (After == '=') {
3543 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3544 SizeTmp2, Result);
3545 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003546 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3547 // If this is actually a '>>>>' conflict marker, recognize it as such
3548 // and recover nicely.
3549 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003550 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3551 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3552 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003553 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003554 Kind = tok::greatergreatergreater;
3555 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3556 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003557 } else {
3558 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3559 Kind = tok::greatergreater;
3560 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003561 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003562 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003563 }
3564 break;
3565 case '^':
3566 Char = getCharAndSize(CurPtr, SizeTmp);
3567 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003569 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003570 } else if (LangOpts.OpenCL && Char == '^') {
3571 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3572 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003573 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003574 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003575 }
3576 break;
3577 case '|':
3578 Char = getCharAndSize(CurPtr, SizeTmp);
3579 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003580 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003581 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3582 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003583 // If this is '|||||||' and we're in a conflict marker, ignore it.
3584 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3585 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003586 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3588 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003589 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003590 }
3591 break;
3592 case ':':
3593 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003595 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003597 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003598 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003599 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003600 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003601 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003602 }
3603 break;
3604 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003605 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003606 break;
3607 case '=':
3608 Char = getCharAndSize(CurPtr, SizeTmp);
3609 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003610 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003611 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3612 goto LexNextToken;
3613
Chris Lattnerb11c3232008-10-12 04:51:35 +00003614 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003616 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003617 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003618 }
3619 break;
3620 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003621 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003622 break;
3623 case '#':
3624 Char = getCharAndSize(CurPtr, SizeTmp);
3625 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003626 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003627 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003628 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003629 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003630 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003631 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003632 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003633 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003634 // We parsed a # character. If this occurs at the start of the line,
3635 // it's actually the start of a preprocessing directive. Callback to
3636 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003637 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003638 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003639 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003640
Chris Lattner2534324a2009-03-18 20:58:27 +00003641 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003642 }
3643 break;
3644
Chris Lattner2b15cf72008-01-03 17:58:54 +00003645 case '@':
3646 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003647 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003648 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003649 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003650 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003651 break;
Mike Stump11289f42009-09-09 15:08:12 +00003652
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003653 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003654 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003655 if (!LangOpts.AsmPreprocessor) {
3656 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3657 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3658 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3659 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003660
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003661 // We only saw whitespace, so just try again with this lexer.
3662 // (We manually eliminate the tail call to avoid recursion.)
3663 goto LexNextToken;
3664 }
3665
3666 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003667 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003668 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003669
Chris Lattnerb11c3232008-10-12 04:51:35 +00003670 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003671 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003672
3673 default: {
3674 if (isASCII(Char)) {
3675 Kind = tok::unknown;
3676 break;
3677 }
3678
Justin Lebar90910552016-09-30 00:38:45 +00003679 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003680
3681 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3682 // an escaped newline.
3683 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003684 llvm::ConversionResult Status =
3685 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3686 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003687 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003688 llvm::strictConversion);
3689 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003690 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3691 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3692 return true; // KeepWhitespaceMode
3693
3694 // We only saw whitespace, so just try again with this lexer.
3695 // (We manually eliminate the tail call to avoid recursion.)
3696 goto LexNextToken;
3697 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003698 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003699 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003700
Jordan Rosecc538342013-01-31 19:48:48 +00003701 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3702 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003703 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003704 Kind = tok::unknown;
3705 break;
3706 }
3707
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003708 // Non-ASCII characters tend to creep into source code unintentionally.
3709 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003710 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003711 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003712
3713 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003714 // We're pretending the character didn't exist, so just try again with
3715 // this lexer.
3716 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003717 goto LexNextToken;
3718 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003719 }
Mike Stump11289f42009-09-09 15:08:12 +00003720
Chris Lattner371ac8a2006-07-04 07:11:10 +00003721 // Notify MIOpt that we read a non-whitespace/non-comment token.
3722 MIOpt.ReadToken();
3723
Chris Lattnerd01e2912006-06-18 16:22:51 +00003724 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003725 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003726 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003727
3728HandleDirective:
3729 // We parsed a # character and it's the start of a preprocessing directive.
3730
3731 FormTokenWithChars(Result, CurPtr, tok::hash);
3732 PP->HandleDirective(Result);
3733
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003734 if (PP->hadModuleLoaderFatalFailure()) {
3735 // With a fatal failure in the module loader, we abort parsing.
3736 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003737 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003738 }
3739
Eli Friedman0834a4b2013-09-19 00:41:32 +00003740 // We parsed the directive; lex a token with the new state.
3741 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003742}