blob: efee609fc101c4a20fdffc7bb32a81d065fc19f2 [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"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#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"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000022#include "llvm/ADT/STLExtras.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"
Chris Lattner739e7392007-04-29 07:12:06 +000027#include "llvm/Support/MemoryBuffer.h"
Craig Topper54edcca2011-08-11 04:06:15 +000028#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000029using namespace clang;
30
Chris Lattner4894f482007-10-07 08:47:24 +000031//===----------------------------------------------------------------------===//
32// Token Class Implementation
33//===----------------------------------------------------------------------===//
34
Mike Stump11289f42009-09-09 15:08:12 +000035/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000036bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000037 if (IdentifierInfo *II = getIdentifierInfo())
38 return II->getObjCKeywordID() == objcKey;
39 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000040}
41
42/// getObjCKeywordID - Return the ObjC keyword kind.
43tok::ObjCKeywordKind Token::getObjCKeywordID() const {
44 IdentifierInfo *specId = getIdentifierInfo();
45 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
46}
47
Chris Lattner67671ed2007-12-13 01:59:49 +000048
Chris Lattner4894f482007-10-07 08:47:24 +000049//===----------------------------------------------------------------------===//
50// Lexer Class Implementation
51//===----------------------------------------------------------------------===//
52
David Blaikie68e081d2011-12-20 02:48:34 +000053void Lexer::anchor() { }
54
Mike Stump11289f42009-09-09 15:08:12 +000055void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000056 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000057 BufferStart = BufStart;
58 BufferPtr = BufPtr;
59 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnerf76b9202009-01-17 06:55:17 +000061 assert(BufEnd[0] == 0 &&
62 "We assume that the input buffer has a null character at the end"
63 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000064
Eric Christopher7f36a792011-04-09 00:01:04 +000065 // Check whether we have a BOM in the beginning of the buffer. If yes - act
66 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
67 // skip the UTF-8 BOM if it's present.
68 if (BufferStart == BufferPtr) {
69 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000071 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000072 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
73 .Default(0);
74
75 // Skip the BOM.
76 BufferPtr += BOMLength;
77 }
78
Chris Lattnerf76b9202009-01-17 06:55:17 +000079 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000080 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000081
Chris Lattnerf76b9202009-01-17 06:55:17 +000082 // Start of the file is a start of line.
83 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000084 IsAtPhysicalStartOfLine = true;
85
86 HasLeadingSpace = false;
87 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +000088
Chris Lattnerf76b9202009-01-17 06:55:17 +000089 // We are not after parsing a #.
90 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattnerf76b9202009-01-17 06:55:17 +000092 // We are not after parsing #include.
93 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattnerf76b9202009-01-17 06:55:17 +000095 // We are not in raw mode. Raw mode disables diagnostics and interpretation
96 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
97 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
98 // or otherwise skipping over tokens.
99 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattnerf76b9202009-01-17 06:55:17 +0000101 // Default to not keeping comments.
102 ExtendedTokenMode = 0;
103}
104
Chris Lattner5965a282009-01-17 07:56:59 +0000105/// Lexer constructor - Create a new lexer object for the specified buffer
106/// with the specified preprocessor managing the lexing process. This lexer
107/// assumes that the associated file buffer and Preprocessor objects will
108/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000109Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000110 : PreprocessorLexer(&PP, FID),
111 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000112 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner5965a282009-01-17 07:56:59 +0000114 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
115 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000116
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000117 resetExtendedTokenMode();
118}
119
120void Lexer::resetExtendedTokenMode() {
121 assert(PP && "Cannot reset token mode without a preprocessor");
122 if (LangOpts.TraditionalCPP)
123 SetKeepWhitespaceMode(true);
124 else
125 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000126}
Chris Lattner4894f482007-10-07 08:47:24 +0000127
Chris Lattner02b436a2007-10-17 20:41:00 +0000128/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000129/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000130/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000132 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000133 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000134
Chris Lattnerf76b9202009-01-17 06:55:17 +0000135 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattner02b436a2007-10-17 20:41:00 +0000137 // We *are* in raw mode.
138 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000139}
140
Chris Lattner08354fe2009-01-17 07:35:14 +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 Lattner08354fe2009-01-17 07:35:14 +0000143/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000144Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 const SourceManager &SM, const LangOptions &langOpts)
146 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000147
Mike Stump11289f42009-09-09 15:08:12 +0000148 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000149 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000150
Chris Lattner08354fe2009-01-17 07:35:14 +0000151 // We *are* in raw mode.
152 LexingRawMode = true;
153}
154
Chris Lattner757169b2009-01-17 08:27:52 +0000155/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
156/// _Pragma expansion. This has a variety of magic semantics that this method
157/// sets up. It returns a new'd Lexer that must be delete'd when done.
158///
159/// On entrance to this routine, TokStartLoc is a macro location which has a
160/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000161/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000162/// "expanded from".
163///
Alp Toker7755aff2014-05-18 18:37:59 +0000164/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000165/// normal lexer that remaps tokens as they fly by. This would require making
166/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
167/// interface that could handle this stuff. This would pull GetMappedTokenLoc
168/// out of the critical path of the lexer!
169///
Mike Stump11289f42009-09-09 15:08:12 +0000170Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000171 SourceLocation ExpansionLocStart,
172 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000173 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000174 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000175
176 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000177 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000178 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
179 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner757169b2009-01-17 08:27:52 +0000181 // Now that the lexer is created, change the start/end locations so that we
182 // just lex the subsection of the file that we want. This is lexing from a
183 // scratch buffer.
184 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattner757169b2009-01-17 08:27:52 +0000186 L->BufferPtr = StrData;
187 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000188 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000189
190 // Set the SourceLocation with the remapping information. This ensures that
191 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000192 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
193 ExpansionLocStart,
194 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000195
Chris Lattner757169b2009-01-17 08:27:52 +0000196 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000197 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000198 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000199
Chris Lattner757169b2009-01-17 08:27:52 +0000200 // This lexer really is for _Pragma.
201 L->Is_PragmaLexer = true;
202 return L;
203}
204
Chris Lattner02b436a2007-10-17 20:41:00 +0000205
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000206/// Stringify - Convert the specified string into a C string, with surrounding
207/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000208std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000209 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000210 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000211 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000212 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000213 Result.insert(Result.begin()+i, '\\');
214 ++i; ++e;
215 }
216 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000217 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000218}
219
Chris Lattner4c4a2452007-07-24 06:57:14 +0000220/// Stringify - Convert the specified string into a C string by escaping '\'
221/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000222void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000223 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
224 if (Str[i] == '\\' || Str[i] == '"') {
225 Str.insert(Str.begin()+i, '\\');
226 ++i; ++e;
227 }
228 }
229}
230
Chris Lattner39720112010-11-17 07:26:20 +0000231//===----------------------------------------------------------------------===//
232// Token Spelling
233//===----------------------------------------------------------------------===//
234
Richard Smith9a67f472012-11-28 07:29:00 +0000235/// \brief Slow case of getSpelling. Extract the characters comprising the
236/// spelling of this token from the provided input buffer.
237static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
238 const LangOptions &LangOpts, char *Spelling) {
239 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
240
241 size_t Length = 0;
242 const char *BufEnd = BufPtr + Tok.getLength();
243
244 if (Tok.is(tok::string_literal)) {
245 // Munch the encoding-prefix and opening double-quote.
246 while (BufPtr < BufEnd) {
247 unsigned Size;
248 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
249 BufPtr += Size;
250
251 if (Spelling[Length - 1] == '"')
252 break;
253 }
254
255 // Raw string literals need special handling; trigraph expansion and line
256 // splicing do not occur within their d-char-sequence nor within their
257 // r-char-sequence.
258 if (Length >= 2 &&
259 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
260 // Search backwards from the end of the token to find the matching closing
261 // quote.
262 const char *RawEnd = BufEnd;
263 do --RawEnd; while (*RawEnd != '"');
264 size_t RawLength = RawEnd - BufPtr + 1;
265
266 // Everything between the quotes is included verbatim in the spelling.
267 memcpy(Spelling + Length, BufPtr, RawLength);
268 Length += RawLength;
269 BufPtr += RawLength;
270
271 // The rest of the token is lexed normally.
272 }
273 }
274
275 while (BufPtr < BufEnd) {
276 unsigned Size;
277 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
278 BufPtr += Size;
279 }
280
281 assert(Length < Tok.getLength() &&
282 "NeedsCleaning flag set on token that didn't need cleaning!");
283 return Length;
284}
285
Chris Lattner39720112010-11-17 07:26:20 +0000286/// getSpelling() - Return the 'spelling' of this token. The spelling of a
287/// token are the characters used to represent the token in the source file
288/// after trigraph expansion and escaped-newline folding. In particular, this
289/// wants to get the true, uncanonicalized, spelling of things like digraphs
290/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000291StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000292 SmallVectorImpl<char> &buffer,
293 const SourceManager &SM,
294 const LangOptions &options,
295 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000296 // Break down the source location.
297 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
298
299 // Try to the load the file buffer.
300 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000301 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000302 if (invalidTemp) {
303 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000305 }
306
307 const char *tokenBegin = file.data() + locInfo.second;
308
309 // Lex from the start of the given location.
310 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
311 file.begin(), tokenBegin, file.end());
312 Token token;
313 lexer.LexFromRawLexer(token);
314
315 unsigned length = token.getLength();
316
317 // Common case: no need for cleaning.
318 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000320
Richard Smith9a67f472012-11-28 07:29:00 +0000321 // Hard case, we need to relex the characters into the string.
322 buffer.resize(length);
323 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000325}
326
327/// getSpelling() - Return the 'spelling' of this token. The spelling of a
328/// token are the characters used to represent the token in the source file
329/// after trigraph expansion and escaped-newline folding. In particular, this
330/// wants to get the true, uncanonicalized, spelling of things like digraphs
331/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000332std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000333 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000334 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000335
Chris Lattner39720112010-11-17 07:26:20 +0000336 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000337 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000338 &CharDataInvalid);
339 if (Invalid)
340 *Invalid = CharDataInvalid;
341 if (CharDataInvalid)
342 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000343
344 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000345 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000346 return std::string(TokStart, TokStart + Tok.getLength());
347
Chris Lattner39720112010-11-17 07:26:20 +0000348 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000349 Result.resize(Tok.getLength());
350 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000351 return Result;
352}
353
354/// getSpelling - This method is used to get the spelling of a token into a
355/// preallocated buffer, instead of as an std::string. The caller is required
356/// to allocate enough space for the token, which is guaranteed to be at least
357/// Tok.getLength() bytes long. The actual length of the token is returned.
358///
359/// Note that this method may do two possible things: it may either fill in
360/// the buffer specified with characters, or it may *change the input pointer*
361/// to point to a constant buffer with the data already in it (avoiding a
362/// copy). The caller is not allowed to modify the returned buffer pointer
363/// if an internal buffer is returned.
364unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
365 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000366 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000367 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000368
Craig Topperd2d442c2014-05-17 23:10:59 +0000369 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000370 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
371 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000372 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000373 else if (!Tok.hasUCN()) {
374 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
375 // Just return the string from the identifier table, which is very quick.
376 Buffer = II->getNameStart();
377 return II->getLength();
378 }
Chris Lattner39720112010-11-17 07:26:20 +0000379 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000380
381 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000382 if (Tok.isLiteral())
383 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000384
Craig Topperd2d442c2014-05-17 23:10:59 +0000385 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000386 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000387 bool CharDataInvalid = false;
388 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
389 if (Invalid)
390 *Invalid = CharDataInvalid;
391 if (CharDataInvalid) {
392 Buffer = "";
393 return 0;
394 }
395 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000396
Chris Lattner39720112010-11-17 07:26:20 +0000397 // If this token contains nothing interesting, return it directly.
398 if (!Tok.needsCleaning()) {
399 Buffer = TokStart;
400 return Tok.getLength();
401 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000402
Chris Lattner39720112010-11-17 07:26:20 +0000403 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000404 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000405}
406
407
Chris Lattner8e129c22007-10-17 21:18:47 +0000408/// MeasureTokenLength - Relex the token at the specified location and return
409/// its length in bytes in the input file. If the token needs cleaning (e.g.
410/// includes a trigraph or an escaped newline) then this count includes bytes
411/// that are part of that.
412unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000413 const SourceManager &SM,
414 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000415 Token TheTok;
416 if (getRawToken(Loc, TheTok, SM, LangOpts))
417 return 0;
418 return TheTok.getLength();
419}
420
421/// \brief Relex the token at the specified location.
422/// \returns true if there was a failure, false on success.
423bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000425 const LangOptions &LangOpts,
426 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000429 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
431 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000432
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000435 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000437 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000439 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000440 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000441
442 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000443
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000445 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000446
Chris Lattner8e129c22007-10-17 21:18:47 +0000447 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000450 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000451 TheLexer.LexFromRawLexer(Result);
452 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000453}
454
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000455static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
456 const SourceManager &SM,
457 const LangOptions &LangOpts) {
458 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000460 if (LocInfo.first.isInvalid())
461 return Loc;
462
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000463 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000465 if (Invalid)
466 return Loc;
467
468 // Back up from the current location until we hit the beginning of a line
469 // (or the buffer). We'll relex from that point.
470 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000471 if (LocInfo.second >= Buffer.size())
472 return Loc;
473
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000474 const char *StrData = BufStart+LocInfo.second;
475 if (StrData[0] == '\n' || StrData[0] == '\r')
476 return Loc;
477
478 const char *LexStart = StrData;
479 while (LexStart != BufStart) {
480 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
481 ++LexStart;
482 break;
483 }
484
485 --LexStart;
486 }
487
488 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000489 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000490 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
491 TheLexer.SetCommentRetentionState(true);
492
493 // Lex tokens until we find the token that contains the source location.
494 Token TheTok;
495 do {
496 TheLexer.LexFromRawLexer(TheTok);
497
498 if (TheLexer.getBufferLocation() > StrData) {
499 // Lexing this token has taken the lexer past the source location we're
500 // looking for. If the current token encompasses our source location,
501 // return the beginning of that token.
502 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
503 return TheTok.getLocation();
504
505 // We ended up skipping over the source location entirely, which means
506 // that it points into whitespace. We're done here.
507 break;
508 }
509 } while (TheTok.getKind() != tok::eof);
510
511 // We've passed our source location; just return the original source location.
512 return Loc;
513}
514
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000515SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
516 const SourceManager &SM,
517 const LangOptions &LangOpts) {
518 if (Loc.isFileID())
519 return getBeginningOfFileToken(Loc, SM, LangOpts);
520
521 if (!SM.isMacroArgExpansion(Loc))
522 return Loc;
523
524 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
525 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
526 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000527 std::pair<FileID, unsigned> BeginFileLocInfo
528 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000529 assert(FileLocInfo.first == BeginFileLocInfo.first &&
530 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000531 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000532}
533
Douglas Gregoraf82e352010-07-20 20:18:03 +0000534namespace {
535 enum PreambleDirectiveKind {
536 PDK_Skipped,
537 PDK_StartIf,
538 PDK_EndIf,
539 PDK_Unknown
540 };
541}
542
David Blaikie3d95d852014-08-11 22:08:06 +0000543std::pair<unsigned, bool> Lexer::ComputePreamble(llvm::MemoryBuffer &Buffer,
544 const LangOptions &LangOpts,
545 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000546 // Create a lexer starting at the beginning of the file. Note that we use a
547 // "fake" file source location at offset 1 so that the lexer will track our
548 // position within the file.
549 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000550 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
David Blaikie3d95d852014-08-11 22:08:06 +0000551 Lexer TheLexer(FileLoc, LangOpts, Buffer.getBufferStart(),
552 Buffer.getBufferStart(), Buffer.getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000553 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000554
555 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
556 SourceLocation StartLoc = TheLexer.getSourceLocation();
557
Douglas Gregoraf82e352010-07-20 20:18:03 +0000558 bool InPreprocessorDirective = false;
559 Token TheTok;
560 Token IfStartTok;
561 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000562 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000563
564 unsigned MaxLineOffset = 0;
565 if (MaxLines) {
David Blaikie3d95d852014-08-11 22:08:06 +0000566 const char *CurPtr = Buffer.getBufferStart();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000567 unsigned CurLine = 0;
David Blaikie3d95d852014-08-11 22:08:06 +0000568 while (CurPtr != Buffer.getBufferEnd()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000569 char ch = *CurPtr++;
570 if (ch == '\n') {
571 ++CurLine;
572 if (CurLine == MaxLines)
573 break;
574 }
575 }
David Blaikie3d95d852014-08-11 22:08:06 +0000576 if (CurPtr != Buffer.getBufferEnd())
577 MaxLineOffset = CurPtr - Buffer.getBufferStart();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000578 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000579
Douglas Gregoraf82e352010-07-20 20:18:03 +0000580 do {
581 TheLexer.LexFromRawLexer(TheTok);
582
583 if (InPreprocessorDirective) {
584 // If we've hit the end of the file, we're done.
585 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000586 break;
587 }
588
589 // If we haven't hit the end of the preprocessor directive, skip this
590 // token.
591 if (!TheTok.isAtStartOfLine())
592 continue;
593
594 // We've passed the end of the preprocessor directive, and will look
595 // at this token again below.
596 InPreprocessorDirective = false;
597 }
598
Douglas Gregor028d3e42010-08-09 20:45:32 +0000599 // Keep track of the # of lines in the preamble.
600 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000601 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000602
603 // If we were asked to limit the number of lines in the preamble,
604 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000605 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000606 break;
607 }
608
Douglas Gregoraf82e352010-07-20 20:18:03 +0000609 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000610 if (TheTok.getKind() == tok::comment) {
611 if (ActiveCommentLoc.isInvalid())
612 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000613 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000614 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615
616 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
617 // This is the start of a preprocessor directive.
618 Token HashTok = TheTok;
619 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000620 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000621
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000622 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000623 // we don't have an identifier table available. Instead, just look at
624 // the raw identifier to recognize and categorize preprocessor directives.
625 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000626 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000627 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000628 PreambleDirectiveKind PDK
629 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
630 .Case("include", PDK_Skipped)
631 .Case("__include_macros", PDK_Skipped)
632 .Case("define", PDK_Skipped)
633 .Case("undef", PDK_Skipped)
634 .Case("line", PDK_Skipped)
635 .Case("error", PDK_Skipped)
636 .Case("pragma", PDK_Skipped)
637 .Case("import", PDK_Skipped)
638 .Case("include_next", PDK_Skipped)
639 .Case("warning", PDK_Skipped)
640 .Case("ident", PDK_Skipped)
641 .Case("sccs", PDK_Skipped)
642 .Case("assert", PDK_Skipped)
643 .Case("unassert", PDK_Skipped)
644 .Case("if", PDK_StartIf)
645 .Case("ifdef", PDK_StartIf)
646 .Case("ifndef", PDK_StartIf)
647 .Case("elif", PDK_Skipped)
648 .Case("else", PDK_Skipped)
649 .Case("endif", PDK_EndIf)
650 .Default(PDK_Unknown);
651
652 switch (PDK) {
653 case PDK_Skipped:
654 continue;
655
656 case PDK_StartIf:
657 if (IfCount == 0)
658 IfStartTok = HashTok;
659
660 ++IfCount;
661 continue;
662
663 case PDK_EndIf:
664 // Mismatched #endif. The preamble ends here.
665 if (IfCount == 0)
666 break;
667
668 --IfCount;
669 continue;
670
671 case PDK_Unknown:
672 // We don't know what this directive is; stop at the '#'.
673 break;
674 }
675 }
676
677 // We only end up here if we didn't recognize the preprocessor
678 // directive or it was one that can't occur in the preamble at this
679 // point. Roll back the current token to the location of the '#'.
680 InPreprocessorDirective = false;
681 TheTok = HashTok;
682 }
683
Douglas Gregor028d3e42010-08-09 20:45:32 +0000684 // We hit a token that we don't recognize as being in the
685 // "preprocessing only" part of the file, so we're no longer in
686 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000687 break;
688 } while (true);
689
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000690 SourceLocation End;
691 if (IfCount)
692 End = IfStartTok.getLocation();
693 else if (ActiveCommentLoc.isValid())
694 End = ActiveCommentLoc; // don't truncate a decl comment.
695 else
696 End = TheTok.getLocation();
697
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000698 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
699 IfCount? IfStartTok.isAtStartOfLine()
700 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000701}
702
Chris Lattner2a6ee912010-11-17 07:05:50 +0000703
704/// AdvanceToTokenCharacter - Given a location that specifies the start of a
705/// token, return a new location that specifies a character within the token.
706SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
707 unsigned CharNo,
708 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000709 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000710 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000711 // character is. This needs to take into consideration newlines and
712 // trigraphs.
713 bool Invalid = false;
714 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
715
716 // If they request the first char of the token, we're trivially done.
717 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
718 return TokStart;
719
720 unsigned PhysOffset = 0;
721
722 // The usual case is that tokens don't contain anything interesting. Skip
723 // over the uninteresting characters. If a token only consists of simple
724 // chars, this method is extremely fast.
725 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
726 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000727 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000728 ++TokPtr, --CharNo, ++PhysOffset;
729 }
730
731 // If we have a character that may be a trigraph or escaped newline, use a
732 // lexer to parse it correctly.
733 for (; CharNo; --CharNo) {
734 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000735 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000736 TokPtr += Size;
737 PhysOffset += Size;
738 }
739
740 // Final detail: if we end up on an escaped newline, we want to return the
741 // location of the actual byte of the token. For example foo\<newline>bar
742 // advanced by 3 should return the location of b, not of \\. One compounding
743 // detail of this is that the escape may be made by a trigraph.
744 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
745 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
746
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000747 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000748}
749
750/// \brief Computes the source location just past the end of the
751/// token at this source location.
752///
753/// This routine can be used to produce a source location that
754/// points just past the end of the token referenced by \p Loc, and
755/// is generally used when a diagnostic needs to point just after a
756/// token where it expected something different that it received. If
757/// the returned source location would not be meaningful (e.g., if
758/// it points into a macro), this routine returns an invalid
759/// source location.
760///
761/// \param Offset an offset from the end of the token, where the source
762/// location should refer to. The default offset (0) produces a source
763/// location pointing just past the end of the token; an offset of 1 produces
764/// a source location pointing to the last character in the token, etc.
765SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
766 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000767 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000768 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000769 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000770
771 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000772 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000773 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000774 }
775
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000777 if (Len > Offset)
778 Len = Len - Offset;
779 else
780 return Loc;
781
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000782 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000783}
784
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000785/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000786/// token of the macro expansion.
787bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000788 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000789 const LangOptions &LangOpts,
790 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000791 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
792
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000793 SourceLocation expansionLoc;
794 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
795 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000796
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000797 if (expansionLoc.isFileID()) {
798 // No other macro expansions, this is the first.
799 if (MacroBegin)
800 *MacroBegin = expansionLoc;
801 return true;
802 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000803
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000804 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000805}
806
807/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000808/// token of the macro expansion.
809bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000810 const SourceManager &SM,
811 const LangOptions &LangOpts,
812 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000813 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
814
815 SourceLocation spellLoc = SM.getSpellingLoc(loc);
816 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
817 if (tokLen == 0)
818 return false;
819
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000820 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
821 SourceLocation expansionLoc;
822 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
823 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000824
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000825 if (expansionLoc.isFileID()) {
826 // No other macro expansions.
827 if (MacroEnd)
828 *MacroEnd = expansionLoc;
829 return true;
830 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000831
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000832 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000833}
834
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000835static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000836 const SourceManager &SM,
837 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000838 SourceLocation Begin = Range.getBegin();
839 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000840 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000841 if (Range.isTokenRange()) {
842 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
843 if (End.isInvalid())
844 return CharSourceRange();
845 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000846
847 // Break down the source locations.
848 FileID FID;
849 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000850 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000851 if (FID.isInvalid())
852 return CharSourceRange();
853
854 unsigned EndOffs;
855 if (!SM.isInFileID(End, FID, &EndOffs) ||
856 BeginOffs > EndOffs)
857 return CharSourceRange();
858
859 return CharSourceRange::getCharRange(Begin, End);
860}
861
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000862CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000863 const SourceManager &SM,
864 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000865 SourceLocation Begin = Range.getBegin();
866 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000867 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000868 return CharSourceRange();
869
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000870 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000872
873 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000874 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
875 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000876 Range.setBegin(Begin);
877 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000878 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000879
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000880 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000881 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
882 &End)) ||
883 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
884 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000885 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000886 Range.setEnd(End);
887 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000888 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000889
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000890 assert(Begin.isMacroID() && End.isMacroID());
891 SourceLocation MacroBegin, MacroEnd;
892 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000893 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
894 &MacroEnd)) ||
895 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
896 &MacroEnd)))) {
897 Range.setBegin(MacroBegin);
898 Range.setEnd(MacroEnd);
899 return makeRangeFromFileLocs(Range, SM, LangOpts);
900 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000901
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000902 bool Invalid = false;
903 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
904 &Invalid);
905 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000906 return CharSourceRange();
907
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000908 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
909 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
910 &Invalid);
911 if (Invalid)
912 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000913
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000914 if (EndEntry.getExpansion().isMacroArgExpansion() &&
915 BeginEntry.getExpansion().getExpansionLocStart() ==
916 EndEntry.getExpansion().getExpansionLocStart()) {
917 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
918 Range.setEnd(SM.getImmediateSpellingLoc(End));
919 return makeFileCharRange(Range, SM, LangOpts);
920 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000921 }
922
923 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000924}
925
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000926StringRef Lexer::getSourceText(CharSourceRange Range,
927 const SourceManager &SM,
928 const LangOptions &LangOpts,
929 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000930 Range = makeFileCharRange(Range, SM, LangOpts);
931 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000932 if (Invalid) *Invalid = true;
933 return StringRef();
934 }
935
936 // Break down the source location.
937 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
938 if (beginInfo.first.isInvalid()) {
939 if (Invalid) *Invalid = true;
940 return StringRef();
941 }
942
943 unsigned EndOffs;
944 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
945 beginInfo.second > EndOffs) {
946 if (Invalid) *Invalid = true;
947 return StringRef();
948 }
949
950 // Try to the load the file buffer.
951 bool invalidTemp = false;
952 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
953 if (invalidTemp) {
954 if (Invalid) *Invalid = true;
955 return StringRef();
956 }
957
958 if (Invalid) *Invalid = false;
959 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
960}
961
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000962StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
963 const SourceManager &SM,
964 const LangOptions &LangOpts) {
965 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000966
967 // Find the location of the immediate macro expansion.
968 while (1) {
969 FileID FID = SM.getFileID(Loc);
970 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
971 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
972 Loc = Expansion.getExpansionLocStart();
973 if (!Expansion.isMacroArgExpansion())
974 break;
975
976 // For macro arguments we need to check that the argument did not come
977 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
978
979 // Loc points to the argument id of the macro definition, move to the
980 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000981 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000982 SourceLocation SpellLoc = Expansion.getSpellingLoc();
983 if (SpellLoc.isFileID())
984 break; // No inner macro.
985
986 // If spelling location resides in the same FileID as macro expansion
987 // location, it means there is no inner macro.
988 FileID MacroFID = SM.getFileID(Loc);
989 if (SM.isInFileID(SpellLoc, MacroFID))
990 break;
991
992 // Argument came from inner macro.
993 Loc = SpellLoc;
994 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000995
996 // Find the spelling location of the start of the non-argument expansion
997 // range. This is where the macro name was spelled in order to begin
998 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000999 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001000
1001 // Dig out the buffer where the macro name was spelled and the extents of the
1002 // name so that we can render it into the expansion note.
1003 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1004 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1005 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1006 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1007}
1008
Jordan Rose288c4212012-06-07 01:10:31 +00001009bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001010 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001011}
1012
Chris Lattnerd01e2912006-06-18 16:22:51 +00001013
Chris Lattner22eb9722006-06-18 05:43:12 +00001014//===----------------------------------------------------------------------===//
1015// Diagnostics forwarding code.
1016//===----------------------------------------------------------------------===//
1017
Chris Lattner619c1742007-07-22 18:38:25 +00001018/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001019/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001020/// This is currently only used for _Pragma implementation, so it is the slow
1021/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001022static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1023 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001024static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1025 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001026 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001027 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001028
Chris Lattner619c1742007-07-22 18:38:25 +00001029 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001030 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001031 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001032 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001034 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001035 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001036 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001037 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001038
Chris Lattner9dc9c202009-02-15 20:52:18 +00001039 // Figure out the expansion loc range, which is the range covered by the
1040 // original _Pragma(...) sequence.
1041 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001042 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chandler Carruth115b0772011-07-26 03:03:05 +00001044 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001045}
1046
Chris Lattner22eb9722006-06-18 05:43:12 +00001047/// getSourceLocation - Return a source location identifier for the specified
1048/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001049SourceLocation Lexer::getSourceLocation(const char *Loc,
1050 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001051 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001052 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001053
1054 // In the normal case, we're just lexing from a simple file buffer, return
1055 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001056 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001057 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001058 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattnerd32480d2009-01-17 06:22:33 +00001060 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1061 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001062 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001063 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001064}
1065
Chris Lattner22eb9722006-06-18 05:43:12 +00001066/// Diag - Forwarding function for diagnostics. This translate a source
1067/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001068DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001069 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001070}
1071
1072//===----------------------------------------------------------------------===//
1073// Trigraph and Escaped Newline Handling Code.
1074//===----------------------------------------------------------------------===//
1075
1076/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1077/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1078static char GetTrigraphCharForLetter(char Letter) {
1079 switch (Letter) {
1080 default: return 0;
1081 case '=': return '#';
1082 case ')': return ']';
1083 case '(': return '[';
1084 case '!': return '|';
1085 case '\'': return '^';
1086 case '>': return '}';
1087 case '/': return '\\';
1088 case '<': return '{';
1089 case '-': return '~';
1090 }
1091}
1092
1093/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1094/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1095/// return the result character. Finally, emit a warning about trigraph use
1096/// whether trigraphs are enabled or not.
1097static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1098 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001099 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001100
David Blaikiebbafb8a2012-03-11 07:00:24 +00001101 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001102 if (!L->isLexingRawMode())
1103 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001104 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chris Lattner6d27a162008-11-22 02:02:22 +00001107 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001108 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001109 return Res;
1110}
1111
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001112/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1113/// 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 +00001114/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001115unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1116 unsigned Size = 0;
1117 while (isWhitespace(Ptr[Size])) {
1118 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001119
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001120 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1121 continue;
1122
1123 // If this is a \r\n or \n\r, skip the other half.
1124 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1125 Ptr[Size-1] != Ptr[Size])
1126 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001128 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001129 }
1130
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001131 // Not an escaped newline, must be a \t or something else.
1132 return 0;
1133}
1134
Chris Lattner38b2cde2009-04-18 22:27:02 +00001135/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1136/// them), skip over them and return the first non-escaped-newline found,
1137/// otherwise return P.
1138const char *Lexer::SkipEscapedNewLines(const char *P) {
1139 while (1) {
1140 const char *AfterEscape;
1141 if (*P == '\\') {
1142 AfterEscape = P+1;
1143 } else if (*P == '?') {
1144 // If not a trigraph for escape, bail out.
1145 if (P[1] != '?' || P[2] != '/')
1146 return P;
1147 AfterEscape = P+3;
1148 } else {
1149 return P;
1150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattner38b2cde2009-04-18 22:27:02 +00001152 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1153 if (NewLineSize == 0) return P;
1154 P = AfterEscape+NewLineSize;
1155 }
1156}
1157
Anna Zaks59a3c802011-07-27 21:43:43 +00001158/// \brief Checks that the given token is the first token that occurs after the
1159/// given location (this excludes comments and whitespace). Returns the location
1160/// immediately after the specified token. If the token is not found or the
1161/// location is inside a macro, the returned source location will be invalid.
1162SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1163 tok::TokenKind TKind,
1164 const SourceManager &SM,
1165 const LangOptions &LangOpts,
1166 bool SkipTrailingWhitespaceAndNewLine) {
1167 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001168 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001169 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001170 }
1171 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1172
1173 // Break down the source location.
1174 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1175
1176 // Try to load the file buffer.
1177 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001178 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001179 if (InvalidTemp)
1180 return SourceLocation();
1181
1182 const char *TokenBegin = File.data() + LocInfo.second;
1183
1184 // Lex from the start of the given location.
1185 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1186 TokenBegin, File.end());
1187 // Find the token.
1188 Token Tok;
1189 lexer.LexFromRawLexer(Tok);
1190 if (Tok.isNot(TKind))
1191 return SourceLocation();
1192 SourceLocation TokenLoc = Tok.getLocation();
1193
1194 // Calculate how much whitespace needs to be skipped if any.
1195 unsigned NumWhitespaceChars = 0;
1196 if (SkipTrailingWhitespaceAndNewLine) {
1197 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1198 Tok.getLength();
1199 unsigned char C = *TokenEnd;
1200 while (isHorizontalWhitespace(C)) {
1201 C = *(++TokenEnd);
1202 NumWhitespaceChars++;
1203 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001204
1205 // Skip \r, \n, \r\n, or \n\r
1206 if (C == '\n' || C == '\r') {
1207 char PrevC = C;
1208 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001209 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001210 if ((C == '\n' || C == '\r') && C != PrevC)
1211 NumWhitespaceChars++;
1212 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001213 }
1214
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001215 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001216}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001217
Chris Lattner22eb9722006-06-18 05:43:12 +00001218/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1219/// get its size, and return it. This is tricky in several cases:
1220/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1221/// then either return the trigraph (skipping 3 chars) or the '?',
1222/// depending on whether trigraphs are enabled or not.
1223/// 2. If this is an escaped newline (potentially with whitespace between
1224/// the backslash and newline), implicitly skip the newline and return
1225/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001226///
1227/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1228/// know that we can accumulate into Size, and that we have already incremented
1229/// Ptr by Size bytes.
1230///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001231/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1232/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001233///
1234char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001235 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001236 // If we have a slash, look for an escaped newline.
1237 if (Ptr[0] == '\\') {
1238 ++Size;
1239 ++Ptr;
1240Slash:
1241 // Common case, backslash-char where the char is not whitespace.
1242 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001243
Chris Lattnerc1835952009-06-23 05:15:06 +00001244 // See if we have optional whitespace characters between the slash and
1245 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001246 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1247 // Remember that this token needs to be cleaned.
1248 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001249
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001250 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001251 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001252 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001254 // Found backslash<whitespace><newline>. Parse the char after it.
1255 Size += EscapedNewLineSize;
1256 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001257
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001258 // If the char that we finally got was a \n, then we must have had
1259 // something like \<newline><newline>. We don't want to consume the
1260 // second newline.
1261 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1262 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001263
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001264 // Use slow version to accumulate a correct size field.
1265 return getCharAndSizeSlow(Ptr, Size, Tok);
1266 }
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattner22eb9722006-06-18 05:43:12 +00001268 // Otherwise, this is not an escaped newline, just return the slash.
1269 return '\\';
1270 }
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattner22eb9722006-06-18 05:43:12 +00001272 // If this is a trigraph, process it.
1273 if (Ptr[0] == '?' && Ptr[1] == '?') {
1274 // If this is actually a legal trigraph (not something like "??x"), emit
1275 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001276 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001278 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001279
1280 Ptr += 3;
1281 Size += 3;
1282 if (C == '\\') goto Slash;
1283 return C;
1284 }
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 // If this is neither, return a single character.
1288 ++Size;
1289 return *Ptr;
1290}
1291
Chris Lattnerd01e2912006-06-18 16:22:51 +00001292
Chris Lattner22eb9722006-06-18 05:43:12 +00001293/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1294/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1295/// and that we have already incremented Ptr by Size bytes.
1296///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001297/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1298/// be updated to match.
1299char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001300 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 // If we have a slash, look for an escaped newline.
1302 if (Ptr[0] == '\\') {
1303 ++Size;
1304 ++Ptr;
1305Slash:
1306 // Common case, backslash-char where the char is not whitespace.
1307 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001310 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1311 // Found backslash<whitespace><newline>. Parse the char after it.
1312 Size += EscapedNewLineSize;
1313 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001315 // If the char that we finally got was a \n, then we must have had
1316 // something like \<newline><newline>. We don't want to consume the
1317 // second newline.
1318 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1319 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001320
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001321 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001322 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 // Otherwise, this is not an escaped newline, just return the slash.
1326 return '\\';
1327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattner22eb9722006-06-18 05:43:12 +00001329 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001330 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 // If this is actually a legal trigraph (not something like "??x"), return
1332 // it.
1333 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1334 Ptr += 3;
1335 Size += 3;
1336 if (C == '\\') goto Slash;
1337 return C;
1338 }
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // If this is neither, return a single character.
1342 ++Size;
1343 return *Ptr;
1344}
1345
Chris Lattner22eb9722006-06-18 05:43:12 +00001346//===----------------------------------------------------------------------===//
1347// Helper methods for lexing.
1348//===----------------------------------------------------------------------===//
1349
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001350/// \brief Routine that indiscriminately skips bytes in the source file.
1351void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1352 BufferPtr += Bytes;
1353 if (BufferPtr > BufferEnd)
1354 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001355 // FIXME: What exactly does the StartOfLine bit mean? There are two
1356 // possible meanings for the "start" of the line: the first token on the
1357 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001358 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001359 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001360}
1361
Jordan Rose58c61e02013-02-09 01:10:25 +00001362static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001363 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1364 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1365 C11AllowedIDCharRanges);
1366 return C11AllowedIDChars.contains(C);
1367 } else if (LangOpts.CPlusPlus) {
1368 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1369 CXX03AllowedIDCharRanges);
1370 return CXX03AllowedIDChars.contains(C);
1371 } else {
1372 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1373 C99AllowedIDCharRanges);
1374 return C99AllowedIDChars.contains(C);
1375 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001376}
1377
Jordan Rose58c61e02013-02-09 01:10:25 +00001378static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1379 assert(isAllowedIDChar(C, LangOpts));
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001380 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1381 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1382 C11DisallowedInitialIDCharRanges);
1383 return !C11DisallowedInitialIDChars.contains(C);
1384 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001385 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001386 } else {
1387 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1388 C99DisallowedInitialIDCharRanges);
1389 return !C99DisallowedInitialIDChars.contains(C);
1390 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001391}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001392
Jordan Rose58c61e02013-02-09 01:10:25 +00001393static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1394 const char *End) {
1395 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1396 L.getSourceLocation(End));
1397}
1398
1399static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1400 CharSourceRange Range, bool IsFirst) {
1401 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001402 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001403 enum {
1404 CannotAppearInIdentifier = 0,
1405 CannotStartIdentifier
1406 };
1407
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001408 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1409 C99AllowedIDCharRanges);
1410 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1411 C99DisallowedInitialIDCharRanges);
1412 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001413 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1414 << Range
1415 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001416 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001417 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1418 << Range
1419 << CannotStartIdentifier;
1420 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001421 }
1422
Jordan Rose58c61e02013-02-09 01:10:25 +00001423 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001424 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001425 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1426 CXX03AllowedIDCharRanges);
1427 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001428 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1429 << Range;
1430 }
1431 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001432}
1433
1434bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1435 Token &Result) {
1436 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001437 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001438 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1439 return false;
1440
1441 if (!isLexingRawMode())
1442 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1443 makeCharRange(*this, CurPtr, UCNPtr),
1444 /*IsFirst=*/false);
1445
1446 Result.setFlag(Token::HasUCN);
1447 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1448 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1449 CurPtr = UCNPtr;
1450 else
1451 while (CurPtr != UCNPtr)
1452 (void)getAndAdvanceChar(CurPtr, Result);
1453 return true;
1454}
1455
1456bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1457 const char *UnicodePtr = CurPtr;
1458 UTF32 CodePoint;
1459 ConversionResult Result =
1460 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1461 (const UTF8 *)BufferEnd,
1462 &CodePoint,
1463 strictConversion);
1464 if (Result != conversionOK ||
1465 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1466 return false;
1467
1468 if (!isLexingRawMode())
1469 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1470 makeCharRange(*this, CurPtr, UnicodePtr),
1471 /*IsFirst=*/false);
1472
1473 CurPtr = UnicodePtr;
1474 return true;
1475}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001476
Eli Friedman0834a4b2013-09-19 00:41:32 +00001477bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1479 unsigned Size;
1480 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001481 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001482 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001483
Chris Lattner22eb9722006-06-18 05:43:12 +00001484 --CurPtr; // Back up over the skipped character.
1485
1486 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1487 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001488 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001489 // TODO: Could merge these checks into an InfoTable flag to make the
1490 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001491 if (isASCII(C) && C != '\\' && C != '?' &&
1492 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001493FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001494 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001495 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1496 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattner0f1f5052006-07-20 04:16:23 +00001498 // If we are in raw mode, return this identifier raw. There is no need to
1499 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001500 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001501 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001502
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001503 // Fill in Result.IdentifierInfo and update the token kind,
1504 // looking up the identifier in the identifier table.
1505 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattnerc5a00062006-06-18 16:41:01 +00001507 // Finally, now that we know we have an identifier, pass this off to the
1508 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001509 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001510 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001511
Eli Friedman0834a4b2013-09-19 00:41:32 +00001512 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
Chris Lattner22eb9722006-06-18 05:43:12 +00001515 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001516
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 C = getCharAndSize(CurPtr, Size);
1518 while (1) {
1519 if (C == '$') {
1520 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001521 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattner22eb9722006-06-18 05:43:12 +00001523 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001524 if (!isLexingRawMode())
1525 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001526 CurPtr = ConsumeChar(CurPtr, Size, Result);
1527 C = getCharAndSize(CurPtr, Size);
1528 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001529
Richard Smith8b7258b2014-02-17 21:52:30 +00001530 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001531 C = getCharAndSize(CurPtr, Size);
1532 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001533 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001534 C = getCharAndSize(CurPtr, Size);
1535 continue;
1536 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001537 goto FinishIdentifier;
1538 }
1539
1540 // Otherwise, this character is good, consume it.
1541 CurPtr = ConsumeChar(CurPtr, Size, Result);
1542
1543 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001544 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 CurPtr = ConsumeChar(CurPtr, Size, Result);
1546 C = getCharAndSize(CurPtr, Size);
1547 }
1548 }
1549}
1550
Douglas Gregor759ef232010-08-30 14:50:47 +00001551/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001552/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001553bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001554 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001556 if (C1 != '0')
1557 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001559 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001560}
Chris Lattner22eb9722006-06-18 05:43:12 +00001561
Nate Begeman5eee9332008-04-14 02:26:39 +00001562/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001563/// constant. From[-1] is the first character lexed. Return the end of the
1564/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001565bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001566 unsigned Size;
1567 char C = getCharAndSize(CurPtr, Size);
1568 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001569 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 CurPtr = ConsumeChar(CurPtr, Size, Result);
1571 PrevCh = C;
1572 C = getCharAndSize(CurPtr, Size);
1573 }
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001576 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1577 // If we are in Microsoft mode, don't continue if the constant is hex.
1578 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001579 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001580 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1581 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001582
1583 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001584 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1585 // Outside C99, we accept hexadecimal floating point numbers as a
1586 // not-quite-conforming extension. Only do so if this looks like it's
1587 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1588 bool IsHexFloat = true;
1589 if (!LangOpts.C99) {
1590 if (!isHexaLiteral(BufferPtr, LangOpts))
1591 IsHexFloat = false;
1592 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1593 IsHexFloat = false;
1594 }
1595 if (IsHexFloat)
1596 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1597 }
Mike Stump11289f42009-09-09 15:08:12 +00001598
Richard Smithfde94852013-09-26 03:33:06 +00001599 // If we have a digit separator, continue.
1600 if (C == '\'' && getLangOpts().CPlusPlus1y) {
1601 unsigned NextSize;
1602 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001603 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001604 if (!isLexingRawMode())
1605 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1606 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001607 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001608 return LexNumericConstant(Result, CurPtr);
1609 }
1610 }
1611
Richard Smith8b7258b2014-02-17 21:52:30 +00001612 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1613 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1614 return LexNumericConstant(Result, CurPtr);
1615 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1616 return LexNumericConstant(Result, CurPtr);
1617
Chris Lattnerd01e2912006-06-18 16:22:51 +00001618 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001619 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001620 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001621 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001622 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001623}
1624
Richard Smithe18f0fa2012-03-05 04:02:15 +00001625/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001626/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001627const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1628 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001629 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001630
Richard Smith8b7258b2014-02-17 21:52:30 +00001631 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001632 unsigned Size;
1633 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001634 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001635
Richard Smith8b7258b2014-02-17 21:52:30 +00001636 if (!isIdentifierHead(C)) {
1637 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1638 Consumed = true;
1639 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1640 Consumed = true;
1641 else
1642 return CurPtr;
1643 }
1644
1645 if (!getLangOpts().CPlusPlus11) {
1646 if (!isLexingRawMode())
1647 Diag(CurPtr,
1648 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1649 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1650 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1651 return CurPtr;
1652 }
1653
1654 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1655 // that does not start with an underscore is ill-formed. As a conforming
1656 // extension, we treat all such suffixes as if they had whitespace before
1657 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1658 // likely to be a ud-suffix than a macro, however, and accept that.
1659 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001660 bool IsUDSuffix = false;
1661 if (C == '_')
1662 IsUDSuffix = true;
Richard Smith2a988622013-09-24 04:06:10 +00001663 else if (IsStringLiteral && getLangOpts().CPlusPlus1y) {
1664 // In C++1y, we need to look ahead a few characters to see if this is a
1665 // valid suffix for a string literal or a numeric literal (this could be
1666 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001667 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001668 char Buffer[MaxStandardSuffixLength] = { C };
1669 unsigned Consumed = Size;
1670 unsigned Chars = 1;
1671 while (true) {
1672 unsigned NextSize;
1673 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1674 getLangOpts());
1675 if (!isIdentifierBody(Next)) {
1676 // End of suffix. Check whether this is on the whitelist.
1677 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1678 NumericLiteralParser::isValidUDSuffix(
1679 getLangOpts(), StringRef(Buffer, Chars));
1680 break;
1681 }
1682
1683 if (Chars == MaxStandardSuffixLength)
1684 // Too long: can't be a standard suffix.
1685 break;
1686
1687 Buffer[Chars++] = Next;
1688 Consumed += NextSize;
1689 }
Richard Smithf4198b72013-07-23 08:14:48 +00001690 }
1691
1692 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001693 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001694 Diag(CurPtr, getLangOpts().MSVCCompat
1695 ? diag::ext_ms_reserved_user_defined_literal
1696 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001697 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001698 return CurPtr;
1699 }
1700
Richard Smith8b7258b2014-02-17 21:52:30 +00001701 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001702 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001703
1704 Result.setFlag(Token::HasUDSuffix);
1705 while (true) {
1706 C = getCharAndSize(CurPtr, Size);
1707 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1708 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1709 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1710 else break;
1711 }
1712
Richard Smithe18f0fa2012-03-05 04:02:15 +00001713 return CurPtr;
1714}
1715
Chris Lattner22eb9722006-06-18 05:43:12 +00001716/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001717/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001718bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001719 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001720 // Does this string contain the \0 character?
1721 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Richard Smithacd4d3d2011-10-15 01:18:56 +00001723 if (!isLexingRawMode() &&
1724 (Kind == tok::utf8_string_literal ||
1725 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001726 Kind == tok::utf32_string_literal))
1727 Diag(BufferPtr, getLangOpts().CPlusPlus
1728 ? diag::warn_cxx98_compat_unicode_literal
1729 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001730
Chris Lattner22eb9722006-06-18 05:43:12 +00001731 char C = getAndAdvanceChar(CurPtr, Result);
1732 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001733 // Skip escaped characters. Escaped newlines will already be processed by
1734 // getAndAdvanceChar.
1735 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001736 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001737
Chris Lattner52d96ac2010-05-30 23:27:38 +00001738 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001739 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001740 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001741 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001742 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001743 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001744 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001745
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001746 if (C == 0) {
1747 if (isCodeCompletionPoint(CurPtr-1)) {
1748 PP->CodeCompleteNaturalLanguage();
1749 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001750 cutOffLexing();
1751 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001752 }
1753
Chris Lattner52d96ac2010-05-30 23:27:38 +00001754 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001755 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001756 C = getAndAdvanceChar(CurPtr, Result);
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
Richard Smithe18f0fa2012-03-05 04:02:15 +00001759 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001760 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001761 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001762
Chris Lattner5a78a022006-07-20 06:02:19 +00001763 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001764 if (NulCharacter && !isLexingRawMode())
1765 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001766
Chris Lattnerd01e2912006-06-18 16:22:51 +00001767 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001768 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001769 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001770 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001771 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001772}
1773
Craig Topper54edcca2011-08-11 04:06:15 +00001774/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1775/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001776bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001777 tok::TokenKind Kind) {
1778 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1779 // Between the initial and final double quote characters of the raw string,
1780 // any transformations performed in phases 1 and 2 (trigraphs,
1781 // universal-character-names, and line splicing) are reverted.
1782
Richard Smithacd4d3d2011-10-15 01:18:56 +00001783 if (!isLexingRawMode())
1784 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1785
Craig Topper54edcca2011-08-11 04:06:15 +00001786 unsigned PrefixLen = 0;
1787
1788 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1789 ++PrefixLen;
1790
1791 // If the last character was not a '(', then we didn't lex a valid delimiter.
1792 if (CurPtr[PrefixLen] != '(') {
1793 if (!isLexingRawMode()) {
1794 const char *PrefixEnd = &CurPtr[PrefixLen];
1795 if (PrefixLen == 16) {
1796 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1797 } else {
1798 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1799 << StringRef(PrefixEnd, 1);
1800 }
1801 }
1802
1803 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1804 // it's possible the '"' was intended to be part of the raw string, but
1805 // there's not much we can do about that.
1806 while (1) {
1807 char C = *CurPtr++;
1808
1809 if (C == '"')
1810 break;
1811 if (C == 0 && CurPtr-1 == BufferEnd) {
1812 --CurPtr;
1813 break;
1814 }
1815 }
1816
1817 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001818 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001819 }
1820
1821 // Save prefix and move CurPtr past it
1822 const char *Prefix = CurPtr;
1823 CurPtr += PrefixLen + 1; // skip over prefix and '('
1824
1825 while (1) {
1826 char C = *CurPtr++;
1827
1828 if (C == ')') {
1829 // Check for prefix match and closing quote.
1830 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1831 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1832 break;
1833 }
1834 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1835 if (!isLexingRawMode())
1836 Diag(BufferPtr, diag::err_unterminated_raw_string)
1837 << StringRef(Prefix, PrefixLen);
1838 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001839 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001840 }
1841 }
1842
Richard Smithe18f0fa2012-03-05 04:02:15 +00001843 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001844 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001845 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001846
Craig Topper54edcca2011-08-11 04:06:15 +00001847 // Update the location of token as well as BufferPtr.
1848 const char *TokStart = BufferPtr;
1849 FormTokenWithChars(Result, CurPtr, Kind);
1850 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001851 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001852}
1853
Chris Lattner22eb9722006-06-18 05:43:12 +00001854/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1855/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001856bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001857 // Does this string contain the \0 character?
1858 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001859 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 char C = getAndAdvanceChar(CurPtr, Result);
1861 while (C != '>') {
1862 // Skip escaped characters.
1863 if (C == '\\') {
1864 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001865 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001866 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001867 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1868 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001869 // If the filename is unterminated, then it must just be a lone <
1870 // character. Return this as such.
1871 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001872 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001873 } else if (C == 0) {
1874 NulCharacter = CurPtr-1;
1875 }
1876 C = getAndAdvanceChar(CurPtr, Result);
1877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattner5a78a022006-07-20 06:02:19 +00001879 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001880 if (NulCharacter && !isLexingRawMode())
1881 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattnerd01e2912006-06-18 16:22:51 +00001883 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001884 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001885 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001886 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001887 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001888}
1889
1890
1891/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001892/// lexed either ' or L' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001893bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001894 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001895 // Does this character contain the \0 character?
1896 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001897
Richard Smithacd4d3d2011-10-15 01:18:56 +00001898 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001899 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1900 Diag(BufferPtr, getLangOpts().CPlusPlus
1901 ? diag::warn_cxx98_compat_unicode_literal
1902 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001903
Chris Lattner22eb9722006-06-18 05:43:12 +00001904 char C = getAndAdvanceChar(CurPtr, Result);
1905 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001906 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001907 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001908 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001909 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001910 }
1911
1912 while (C != '\'') {
1913 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001914 if (C == '\\')
1915 C = getAndAdvanceChar(CurPtr, Result);
1916
1917 if (C == '\n' || C == '\r' || // Newline.
1918 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001919 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001920 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001921 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001922 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001923 }
1924
1925 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001926 if (isCodeCompletionPoint(CurPtr-1)) {
1927 PP->CodeCompleteNaturalLanguage();
1928 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001929 cutOffLexing();
1930 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001931 }
1932
Chris Lattner86851b82010-07-07 23:24:27 +00001933 NulCharacter = CurPtr-1;
1934 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 C = getAndAdvanceChar(CurPtr, Result);
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Richard Smithe18f0fa2012-03-05 04:02:15 +00001938 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001939 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001940 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001941
Chris Lattner86851b82010-07-07 23:24:27 +00001942 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001943 if (NulCharacter && !isLexingRawMode())
1944 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001945
Chris Lattnerd01e2912006-06-18 16:22:51 +00001946 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001947 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001948 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001949 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001950 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001951}
1952
1953/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1954/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001955///
1956/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1957///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001958bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1959 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001960 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001961 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1962
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001963 unsigned char Char = *CurPtr;
1964
1965 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001966 while (1) {
1967 // Skip horizontal whitespace very aggressively.
1968 while (isHorizontalWhitespace(Char))
1969 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001971 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001972 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001973 break;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Chris Lattner22eb9722006-06-18 05:43:12 +00001975 if (ParsingPreprocessorDirective) {
1976 // End of preprocessor directive line, let LexTokenInternal handle this.
1977 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001978 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001981 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001982 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 Char = *++CurPtr;
1984 }
1985
Chris Lattner4d963442008-10-12 04:05:48 +00001986 // If the client wants us to return whitespace, return it now.
1987 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001988 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001989 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001990 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001991 IsAtPhysicalStartOfLine = true;
1992 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001993 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001994 return true;
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001997 // If this isn't immediately after a newline, there is leading space.
1998 char PrevChar = CurPtr[-1];
1999 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2000
2001 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002002 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002003 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002004 TokAtPhysicalStartOfLine = true;
2005 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002006
Chris Lattner22eb9722006-06-18 05:43:12 +00002007 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002008 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002009}
2010
Nico Weber158a31a2012-11-11 07:02:14 +00002011/// We have just read the // characters from input. Skip until we find the
2012/// newline character thats terminate the comment. Then update BufferPtr and
2013/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002014///
2015/// If we're in KeepCommentMode or any CommentHandler has inserted
2016/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002017bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2018 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002019 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002021 if (!LangOpts.LineComment && !isLexingRawMode()) {
2022 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002023
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 // Mark them enabled so we only emit one warning for this translation
2025 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002026 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Chris Lattner22eb9722006-06-18 05:43:12 +00002029 // Scan over the body of the comment. The common case, when scanning, is that
2030 // the comment contains normal ascii characters with nothing interesting in
2031 // them. As such, optimize for this case with the inner loop.
2032 char C;
2033 do {
2034 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 // Skip over characters in the fast loop.
2036 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002037 C != '\n' && C != '\r') // Newline or DOS-style newline.
2038 C = *++CurPtr;
2039
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002040 const char *NextLine = CurPtr;
2041 if (C != 0) {
2042 // We found a newline, see if it's escaped.
2043 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002044 bool HasSpace = false;
2045 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002046 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002047 HasSpace = true;
2048 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002049
2050 if (*EscapePtr == '\\') // Escaped newline.
2051 CurPtr = EscapePtr;
2052 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2053 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2054 CurPtr = EscapePtr-2;
2055 else
2056 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002057
2058 // If there was space between the backslash and newline, warn about it.
2059 if (HasSpace && !isLexingRawMode())
2060 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
Chris Lattner22eb9722006-06-18 05:43:12 +00002063 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002064 // properly decode the character. Read it in raw mode to avoid emitting
2065 // diagnostics about things like trigraphs. If we see an escaped newline,
2066 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002067 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002068 bool OldRawMode = isLexingRawMode();
2069 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002070 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002071 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002072
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002073 // If we only read only one character, then no special handling is needed.
2074 // We're done and can skip forward to the newline.
2075 if (C != 0 && CurPtr == OldPtr+1) {
2076 CurPtr = NextLine;
2077 break;
2078 }
2079
Chris Lattner22eb9722006-06-18 05:43:12 +00002080 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002081 // \n, then we had an escaped newline within the comment. Emit diagnostic
2082 // unless the next line is also a // comment.
2083 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002084 for (; OldPtr != CurPtr; ++OldPtr)
2085 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002086 // Okay, we found a // comment that ends in a newline, if the next
2087 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002088 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002089 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002090 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002091 ++ForwardPtr;
2092 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2093 break;
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattner6d27a162008-11-22 02:02:22 +00002096 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002097 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002098 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002099 }
2100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor11583702010-08-25 17:04:25 +00002102 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002103 --CurPtr;
2104 break;
2105 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002106
2107 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2108 PP->CodeCompleteNaturalLanguage();
2109 cutOffLexing();
2110 return false;
2111 }
2112
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 } while (C != '\n' && C != '\r');
2114
Chris Lattner93ddf802010-02-03 21:06:21 +00002115 // Found but did not consume the newline. Notify comment handlers about the
2116 // comment unless we're in a #if 0 block.
2117 if (PP && !isLexingRawMode() &&
2118 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2119 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002120 BufferPtr = CurPtr;
2121 return true; // A token has to be returned.
2122 }
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattner457fc152006-07-29 06:30:25 +00002124 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002125 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002126 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002127
2128 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002129 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002130 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002132 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002133 }
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002136 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002137 // contribute to another token), it isn't needed for correctness. Note that
2138 // this is ok even in KeepWhitespaceMode, because we would have returned the
2139 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002140 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattner22eb9722006-06-18 05:43:12 +00002142 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002143 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002144 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002145 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002146 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002147 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002148 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002149}
Chris Lattner22eb9722006-06-18 05:43:12 +00002150
Nico Weber158a31a2012-11-11 07:02:14 +00002151/// If in save-comment mode, package up this Line comment in an appropriate
2152/// way and return it.
2153bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002154 // If we're not in a preprocessor directive, just return the // comment
2155 // directly.
2156 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002157
David Blaikied5321242012-06-06 18:52:13 +00002158 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002159 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002160
Nico Weber158a31a2012-11-11 07:02:14 +00002161 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002162 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002163 bool Invalid = false;
2164 std::string Spelling = PP->getSpelling(Result, &Invalid);
2165 if (Invalid)
2166 return true;
2167
Nico Weber158a31a2012-11-11 07:02:14 +00002168 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002169 Spelling[1] = '*'; // Change prefix to "/*".
2170 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattnerb11c3232008-10-12 04:51:35 +00002172 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002173 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002174 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002175 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002176}
2177
Chris Lattnercb283342006-06-18 06:48:37 +00002178/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002179/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2180/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002181static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002182 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002184
Chris Lattner22eb9722006-06-18 05:43:12 +00002185 // Back up off the newline.
2186 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattner22eb9722006-06-18 05:43:12 +00002188 // If this is a two-character newline sequence, skip the other character.
2189 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2190 // \n\n or \r\r -> not escaped newline.
2191 if (CurPtr[0] == CurPtr[1])
2192 return false;
2193 // \n\r or \r\n -> skip the newline.
2194 --CurPtr;
2195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Chris Lattner22eb9722006-06-18 05:43:12 +00002197 // If we have horizontal whitespace, skip over it. We allow whitespace
2198 // between the slash and newline.
2199 bool HasSpace = false;
2200 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2201 --CurPtr;
2202 HasSpace = true;
2203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Chris Lattner22eb9722006-06-18 05:43:12 +00002205 // If we have a slash, we know this is an escaped newline.
2206 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002207 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002208 } else {
2209 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002210 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2211 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002212 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattnercb283342006-06-18 06:48:37 +00002214 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002215 CurPtr -= 2;
2216
2217 // If no trigraphs are enabled, warn that we ignored this trigraph and
2218 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002219 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002220 if (!L->isLexingRawMode())
2221 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002222 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002224 if (!L->isLexingRawMode())
2225 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002226 }
Mike Stump11289f42009-09-09 15:08:12 +00002227
Chris Lattner22eb9722006-06-18 05:43:12 +00002228 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002229 if (!L->isLexingRawMode())
2230 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattner22eb9722006-06-18 05:43:12 +00002232 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002233 if (HasSpace && !L->isLexingRawMode())
2234 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattnercb283342006-06-18 06:48:37 +00002236 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002237}
2238
Chris Lattneraded4a92006-10-27 04:42:31 +00002239#ifdef __SSE2__
2240#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002241#elif __ALTIVEC__
2242#include <altivec.h>
2243#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002244#endif
2245
James Dennettf442d242012-06-17 03:40:43 +00002246/// We have just read from input the / and * characters that started a comment.
2247/// Read until we find the * and / characters that terminate the comment.
2248/// Note that we don't bother decoding trigraphs or escaped newlines in block
2249/// comments, because they cannot cause the comment to end. The only thing
2250/// that can happen is the comment could end with an escaped newline between
2251/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002252///
Chris Lattner87d02082010-01-18 22:35:47 +00002253/// If we're in KeepCommentMode or any CommentHandler has inserted
2254/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002255bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2256 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002257 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002258 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002259 // optimization helps people who like to put a lot of * characters in their
2260 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002261
2262 // The first character we get with newlines and trigraphs skipped to handle
2263 // the degenerate /*/ case below correctly if the * has an escaped newline
2264 // after it.
2265 unsigned CharSize;
2266 unsigned char C = getCharAndSize(CurPtr, CharSize);
2267 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002268 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002269 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002270 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002271 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Chris Lattner99e7d232008-10-12 04:19:49 +00002273 // KeepWhitespaceMode should return this broken comment as a token. Since
2274 // it isn't a well formed comment, just return it as an 'unknown' token.
2275 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002276 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002277 return true;
2278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattner99e7d232008-10-12 04:19:49 +00002280 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002281 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
Chris Lattnerc850ad62007-07-21 23:43:37 +00002284 // Check to see if the first character after the '/*' is another /. If so,
2285 // then this slash does not end the block comment, it is part of it.
2286 if (C == '/')
2287 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002288
Chris Lattner22eb9722006-06-18 05:43:12 +00002289 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002290 // Skip over all non-interesting characters until we find end of buffer or a
2291 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002292 if (CurPtr + 24 < BufferEnd &&
2293 // If there is a code-completion point avoid the fast scan because it
2294 // doesn't check for '\0'.
2295 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002296 // While not aligned to a 16-byte boundary.
2297 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2298 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattner6cc3e362006-10-27 04:12:35 +00002300 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002301
2302#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002303 __m128i Slashes = _mm_set1_epi8('/');
2304 while (CurPtr+16 <= BufferEnd) {
2305 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2306 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002307 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002308 // Adjust the pointer to point directly after the first slash. It's
2309 // not necessary to set C here, it will be overwritten at the end of
2310 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002311 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002312 goto FoundSlash;
2313 }
Roman Divacky61509902014-04-03 18:04:52 +00002314 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002315 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002316#elif __ALTIVEC__
2317 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002318 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002319 '/', '/', '/', '/', '/', '/', '/', '/'
2320 };
2321 while (CurPtr+16 <= BufferEnd &&
2322 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2323 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002324#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002325 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002326 while (CurPtr[0] != '/' &&
2327 CurPtr[1] != '/' &&
2328 CurPtr[2] != '/' &&
2329 CurPtr[3] != '/' &&
2330 CurPtr+4 < BufferEnd) {
2331 CurPtr += 4;
2332 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002333#endif
Mike Stump11289f42009-09-09 15:08:12 +00002334
Chris Lattneraded4a92006-10-27 04:42:31 +00002335 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002336 C = *CurPtr++;
2337 }
Mike Stump11289f42009-09-09 15:08:12 +00002338
Chris Lattneraded4a92006-10-27 04:42:31 +00002339 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002340 while (C != '/' && C != '\0')
2341 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002342
Chris Lattner22eb9722006-06-18 05:43:12 +00002343 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002344 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002345 if (CurPtr[-2] == '*') // We found the final */. We're done!
2346 break;
Mike Stump11289f42009-09-09 15:08:12 +00002347
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002349 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002350 // We found the final */, though it had an escaped newline between the
2351 // * and /. We're done!
2352 break;
2353 }
2354 }
2355 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2356 // If this is a /* inside of the comment, emit a warning. Don't do this
2357 // if this is a /*/, which will end the comment. This misses cases with
2358 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002359 if (!isLexingRawMode())
2360 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002361 }
2362 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002363 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002364 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002365 // Note: the user probably forgot a */. We could continue immediately
2366 // after the /*, but this would involve lexing a lot of what really is the
2367 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002368 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattner99e7d232008-10-12 04:19:49 +00002370 // KeepWhitespaceMode should return this broken comment as a token. Since
2371 // it isn't a well formed comment, just return it as an 'unknown' token.
2372 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002373 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002374 return true;
2375 }
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattner99e7d232008-10-12 04:19:49 +00002377 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002378 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002379 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2380 PP->CodeCompleteNaturalLanguage();
2381 cutOffLexing();
2382 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002383 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002384
Chris Lattner22eb9722006-06-18 05:43:12 +00002385 C = *CurPtr++;
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Chris Lattner93ddf802010-02-03 21:06:21 +00002388 // Notify comment handlers about the comment unless we're in a #if 0 block.
2389 if (PP && !isLexingRawMode() &&
2390 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2391 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002392 BufferPtr = CurPtr;
2393 return true; // A token has to be returned.
2394 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002395
Chris Lattner457fc152006-07-29 06:30:25 +00002396 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002397 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002398 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002399 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002400 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002401
2402 // It is common for the tokens immediately after a /**/ comment to be
2403 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002404 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2405 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002406 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002407 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002408 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002409 }
2410
2411 // Otherwise, just return so that the next character will be lexed as a token.
2412 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002413 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002414 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002415}
2416
2417//===----------------------------------------------------------------------===//
2418// Primary Lexing Entry Points
2419//===----------------------------------------------------------------------===//
2420
Chris Lattner22eb9722006-06-18 05:43:12 +00002421/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2422/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002423void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002424 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2425 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002426 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002427
2428 // CurPtr - Cache BufferPtr in an automatic variable.
2429 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002430 while (1) {
2431 char Char = getAndAdvanceChar(CurPtr, Tmp);
2432 switch (Char) {
2433 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002434 if (Result)
2435 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002436 break;
2437 case 0: // Null.
2438 // Found end of file?
2439 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002440 if (isCodeCompletionPoint(CurPtr-1)) {
2441 PP->CodeCompleteNaturalLanguage();
2442 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002443 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002444 }
2445
Chris Lattner22eb9722006-06-18 05:43:12 +00002446 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002447 if (Result)
2448 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002449 break;
2450 }
2451 // FALL THROUGH.
2452 case '\r':
2453 case '\n':
2454 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2455 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2456 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002457
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002458 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002459 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002460 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002461 if (PP)
2462 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002463 Lex(Tmp);
2464 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002465 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002466
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002467 // Finally, we're done;
2468 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002469 }
2470 }
2471}
2472
2473/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2474/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002475/// This returns true if Result contains a token, false if PP.Lex should be
2476/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002477bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002478 // If we hit the end of the file while parsing a preprocessor directive,
2479 // end the preprocessor directive first. The next token returned will
2480 // then be the end of file.
2481 if (ParsingPreprocessorDirective) {
2482 // Done parsing the "line".
2483 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002484 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002485 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002486
Chris Lattner457fc152006-07-29 06:30:25 +00002487 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002488 if (PP)
2489 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002490 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002491 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002492
Chris Lattner30a2fa12006-07-19 06:31:49 +00002493 // If we are in raw mode, return this event as an EOF token. Let the caller
2494 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002495 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002496 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002497 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002498 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002499 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002500 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002501
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002502 // Issue diagnostics for unterminated #if and missing newline.
2503
Chris Lattner30a2fa12006-07-19 06:31:49 +00002504 // If we are in a #if directive, emit an error.
2505 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002506 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002507 PP->Diag(ConditionalStack.back().IfLoc,
2508 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002509 ConditionalStack.pop_back();
2510 }
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattner8f96d042008-04-12 05:54:25 +00002512 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2513 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002514 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2515 DiagnosticsEngine &Diags = PP->getDiagnostics();
2516 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2517 unsigned DiagID;
2518
2519 if (LangOpts.CPlusPlus11) {
2520 // C++11 [lex.phases] 2.2 p2
2521 // Prefer the C++98 pedantic compatibility warning over the generic,
2522 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002523 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002524 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2525 } else {
2526 DiagID = diag::warn_no_newline_eof;
2527 }
2528 } else {
2529 DiagID = diag::ext_no_newline_eof;
2530 }
2531
2532 Diag(BufferEnd, DiagID)
2533 << FixItHint::CreateInsertion(EndLoc, "\n");
2534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
Chris Lattner22eb9722006-06-18 05:43:12 +00002536 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002537
2538 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002539 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002540}
2541
Chris Lattner678c8802006-07-11 05:46:12 +00002542/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2543/// the specified lexer will return a tok::l_paren token, 0 if it is something
2544/// else and 2 if there are no more tokens in the buffer controlled by the
2545/// lexer.
2546unsigned Lexer::isNextPPTokenLParen() {
2547 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner678c8802006-07-11 05:46:12 +00002549 // Switch to 'skipping' mode. This will ensure that we can lex a token
2550 // without emitting diagnostics, disables macro expansion, and will cause EOF
2551 // to return an EOF token instead of popping the include stack.
2552 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002553
Chris Lattner678c8802006-07-11 05:46:12 +00002554 // Save state that can be changed while lexing so that we can restore it.
2555 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002556 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002557 bool atStartOfLine = IsAtStartOfLine;
2558 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2559 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002560
Chris Lattner146762e2007-07-20 16:59:19 +00002561 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002562 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002563
Chris Lattner678c8802006-07-11 05:46:12 +00002564 // Restore state that may have changed.
2565 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002566 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002567 HasLeadingSpace = leadingSpace;
2568 IsAtStartOfLine = atStartOfLine;
2569 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner678c8802006-07-11 05:46:12 +00002571 // Restore the lexer back to non-skipping mode.
2572 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002573
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002574 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002575 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002576 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002577}
2578
James Dennettf442d242012-06-17 03:40:43 +00002579/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002580static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2581 ConflictMarkerKind CMK) {
2582 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2583 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2584 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2585 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002587 // Must occur at start of line.
2588 if (RestOfBuffer[Pos-1] != '\r' &&
2589 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002590 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2591 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002592 continue;
2593 }
2594 return RestOfBuffer.data()+Pos;
2595 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002596 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002597}
2598
2599/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2600/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2601/// and recover nicely. This returns true if it is a conflict marker and false
2602/// if not.
2603bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2604 // Only a conflict marker if it starts at the beginning of a line.
2605 if (CurPtr != BufferStart &&
2606 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2607 return false;
2608
Richard Smitha9e33d42011-10-12 00:37:51 +00002609 // Check to see if we have <<<<<<< or >>>>.
2610 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2611 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002612 return false;
2613
2614 // If we have a situation where we don't care about conflict markers, ignore
2615 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002616 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002617 return false;
2618
Richard Smitha9e33d42011-10-12 00:37:51 +00002619 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2620
2621 // Check to see if there is an ending marker somewhere in the buffer at the
2622 // start of a line to terminate this conflict marker.
2623 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002624 // We found a match. We are really in a conflict marker.
2625 // Diagnose this, and ignore to the end of line.
2626 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002627 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002628
2629 // Skip ahead to the end of line. We know this exists because the
2630 // end-of-conflict marker starts with \r or \n.
2631 while (*CurPtr != '\r' && *CurPtr != '\n') {
2632 assert(CurPtr != BufferEnd && "Didn't find end of line");
2633 ++CurPtr;
2634 }
2635 BufferPtr = CurPtr;
2636 return true;
2637 }
2638
2639 // No end of conflict marker found.
2640 return false;
2641}
2642
2643
Richard Smitha9e33d42011-10-12 00:37:51 +00002644/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2645/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2646/// is the end of a conflict marker. Handle it by ignoring up until the end of
2647/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002648bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2649 // Only a conflict marker if it starts at the beginning of a line.
2650 if (CurPtr != BufferStart &&
2651 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2652 return false;
2653
2654 // If we have a situation where we don't care about conflict markers, ignore
2655 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002656 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002657 return false;
2658
Richard Smitha9e33d42011-10-12 00:37:51 +00002659 // Check to see if we have the marker (4 characters in a row).
2660 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002661 if (CurPtr[i] != CurPtr[0])
2662 return false;
2663
2664 // If we do have it, search for the end of the conflict marker. This could
2665 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2666 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002667 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2668 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002669 CurPtr = End;
2670
2671 // Skip ahead to the end of line.
2672 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2673 ++CurPtr;
2674
2675 BufferPtr = CurPtr;
2676
2677 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002678 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002679 return true;
2680 }
2681
2682 return false;
2683}
2684
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002685bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2686 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002687 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002688 return Loc == PP->getCodeCompletionLoc();
2689 }
2690
2691 return false;
2692}
2693
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002694uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2695 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002696 unsigned CharSize;
2697 char Kind = getCharAndSize(StartPtr, CharSize);
2698
2699 unsigned NumHexDigits;
2700 if (Kind == 'u')
2701 NumHexDigits = 4;
2702 else if (Kind == 'U')
2703 NumHexDigits = 8;
2704 else
2705 return 0;
2706
Jordan Rosec0cba272013-01-27 20:12:04 +00002707 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002708 if (Result && !isLexingRawMode())
2709 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002710 return 0;
2711 }
2712
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002713 const char *CurPtr = StartPtr + CharSize;
2714 const char *KindLoc = &CurPtr[-1];
2715
2716 uint32_t CodePoint = 0;
2717 for (unsigned i = 0; i < NumHexDigits; ++i) {
2718 char C = getCharAndSize(CurPtr, CharSize);
2719
2720 unsigned Value = llvm::hexDigitValue(C);
2721 if (Value == -1U) {
2722 if (Result && !isLexingRawMode()) {
2723 if (i == 0) {
2724 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2725 << StringRef(KindLoc, 1);
2726 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002727 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002728
2729 // If the user wrote \U1234, suggest a fixit to \u.
2730 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002731 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002732 Diag(KindLoc, diag::note_ucn_four_not_eight)
2733 << FixItHint::CreateReplacement(URange, "u");
2734 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002735 }
2736 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002737
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002738 return 0;
2739 }
2740
2741 CodePoint <<= 4;
2742 CodePoint += Value;
2743
2744 CurPtr += CharSize;
2745 }
2746
2747 if (Result) {
2748 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002749 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002750 StartPtr = CurPtr;
2751 else
2752 while (StartPtr != CurPtr)
2753 (void)getAndAdvanceChar(StartPtr, *Result);
2754 } else {
2755 StartPtr = CurPtr;
2756 }
2757
Justin Bogner53535132013-10-21 05:02:28 +00002758 // Don't apply C family restrictions to UCNs in assembly mode
2759 if (LangOpts.AsmPreprocessor)
2760 return CodePoint;
2761
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002762 // C99 6.4.3p2: A universal character name shall not specify a character whose
2763 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2764 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2765 // C++11 [lex.charset]p2: If the hexadecimal value for a
2766 // universal-character-name corresponds to a surrogate code point (in the
2767 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2768 // if the hexadecimal value for a universal-character-name outside the
2769 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2770 // string literal corresponds to a control character (in either of the
2771 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2772 // basic source character set, the program is ill-formed.
2773 if (CodePoint < 0xA0) {
2774 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2775 return CodePoint;
2776
2777 // We don't use isLexingRawMode() here because we need to warn about bad
2778 // UCNs even when skipping preprocessing tokens in a #if block.
2779 if (Result && PP) {
2780 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2781 Diag(BufferPtr, diag::err_ucn_control_character);
2782 else {
2783 char C = static_cast<char>(CodePoint);
2784 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2785 }
2786 }
2787
2788 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002789
2790 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002791 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002792 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002793 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002794 if (Result && PP) {
2795 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2796 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2797 else
2798 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2799 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002800 return 0;
2801 }
2802
2803 return CodePoint;
2804}
2805
Eli Friedman0834a4b2013-09-19 00:41:32 +00002806bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2807 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002808 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2809 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002810 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002811 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002812 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002813 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002814
2815 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002816 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002817 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002818 return false;
2819}
Jordan Rose4246ae02013-01-24 20:50:50 +00002820
Eli Friedman0834a4b2013-09-19 00:41:32 +00002821bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002822 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2823 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2824 !PP->isPreprocessedOutput()) {
2825 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2826 makeCharRange(*this, BufferPtr, CurPtr),
2827 /*IsFirst=*/true);
2828 }
2829
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002830 MIOpt.ReadToken();
2831 return LexIdentifier(Result, CurPtr);
2832 }
2833
Jordan Rosecc538342013-01-31 19:48:48 +00002834 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2835 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002836 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002837 // Non-ASCII characters tend to creep into source code unintentionally.
2838 // Instead of letting the parser complain about the unknown token,
2839 // just drop the character.
2840 // Note that we can /only/ do this when the non-ASCII character is actually
2841 // spelled as Unicode, not written as a UCN. The standard requires that
2842 // we not throw away any possible preprocessor tokens, but there's a
2843 // loophole in the mapping of Unicode characters to basic character set
2844 // characters that allows us to map these particular characters to, say,
2845 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002846 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002847 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002848
2849 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002850 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002851 }
2852
2853 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2854 // up by accident.
2855 MIOpt.ReadToken();
2856 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002857 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002858}
2859
Eli Friedman0834a4b2013-09-19 00:41:32 +00002860void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2861 IsAtStartOfLine = Result.isAtStartOfLine();
2862 HasLeadingSpace = Result.hasLeadingSpace();
2863 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2864 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2865}
2866
2867bool Lexer::Lex(Token &Result) {
2868 // Start a new token.
2869 Result.startToken();
2870
2871 // Set up misc whitespace flags for LexTokenInternal.
2872 if (IsAtStartOfLine) {
2873 Result.setFlag(Token::StartOfLine);
2874 IsAtStartOfLine = false;
2875 }
2876
2877 if (HasLeadingSpace) {
2878 Result.setFlag(Token::LeadingSpace);
2879 HasLeadingSpace = false;
2880 }
2881
2882 if (HasLeadingEmptyMacro) {
2883 Result.setFlag(Token::LeadingEmptyMacro);
2884 HasLeadingEmptyMacro = false;
2885 }
2886
2887 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2888 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002889 bool isRawLex = isLexingRawMode();
2890 (void) isRawLex;
2891 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2892 // (After the LexTokenInternal call, the lexer might be destroyed.)
2893 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2894 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002895}
Chris Lattner22eb9722006-06-18 05:43:12 +00002896
2897/// LexTokenInternal - This implements a simple C family lexer. It is an
2898/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002899/// has a null character at the end of the file. This returns a preprocessing
2900/// token, not a normal token, as such, it is an internal interface. It assumes
2901/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002902bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002903LexNextToken:
2904 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002905 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002906 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002907
Chris Lattner22eb9722006-06-18 05:43:12 +00002908 // CurPtr - Cache BufferPtr in an automatic variable.
2909 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002910
Chris Lattnereb54b592006-07-10 06:34:27 +00002911 // Small amounts of horizontal whitespace is very common between tokens.
2912 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2913 ++CurPtr;
2914 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2915 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Chris Lattner4d963442008-10-12 04:05:48 +00002917 // If we are keeping whitespace and other tokens, just return what we just
2918 // skipped. The next lexer invocation will return the token after the
2919 // whitespace.
2920 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002921 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002922 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002923 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002924 }
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chris Lattnereb54b592006-07-10 06:34:27 +00002926 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002927 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Chris Lattner22eb9722006-06-18 05:43:12 +00002930 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002931
Chris Lattner22eb9722006-06-18 05:43:12 +00002932 // Read a character, advancing over it.
2933 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002934 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattner22eb9722006-06-18 05:43:12 +00002936 switch (Char) {
2937 case 0: // Null.
2938 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002939 if (CurPtr-1 == BufferEnd)
2940 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002942 // Check if we are performing code completion.
2943 if (isCodeCompletionPoint(CurPtr-1)) {
2944 // Return the code-completion token.
2945 Result.startToken();
2946 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002947 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002948 }
2949
Chris Lattner6d27a162008-11-22 02:02:22 +00002950 if (!isLexingRawMode())
2951 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002952 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002953 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2954 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002955
Eli Friedman0834a4b2013-09-19 00:41:32 +00002956 // We know the lexer hasn't changed, so just try again with this lexer.
2957 // (We manually eliminate the tail call to avoid recursion.)
2958 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002959
2960 case 26: // DOS & CP/M EOF: "^Z".
2961 // If we're in Microsoft extensions mode, treat this as end of file.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002962 if (LangOpts.MicrosoftExt)
2963 return LexEndOfFile(Result, CurPtr-1);
2964
Chris Lattner3dfff972009-12-17 05:29:40 +00002965 // If Microsoft extensions are disabled, this is just random garbage.
2966 Kind = tok::unknown;
2967 break;
2968
Chris Lattner22eb9722006-06-18 05:43:12 +00002969 case '\n':
2970 case '\r':
2971 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002972 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002973 if (ParsingPreprocessorDirective) {
2974 // Done parsing the "line".
2975 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002976
Chris Lattner457fc152006-07-29 06:30:25 +00002977 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002978 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002979 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002980
Chris Lattner22eb9722006-06-18 05:43:12 +00002981 // Since we consumed a newline, we are back at the start of a line.
2982 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002983 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002984
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002985 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002986 break;
2987 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002988
Chris Lattner22eb9722006-06-18 05:43:12 +00002989 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002990 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Eli Friedman0834a4b2013-09-19 00:41:32 +00002992 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2993 return true; // KeepWhitespaceMode
2994
2995 // We only saw whitespace, so just try again with this lexer.
2996 // (We manually eliminate the tail call to avoid recursion.)
2997 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00002998 case ' ':
2999 case '\t':
3000 case '\f':
3001 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003002 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003003 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003004 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3005 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003006
3007 SkipIgnoredUnits:
3008 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003009
Chris Lattnerb9b85972007-07-22 06:29:05 +00003010 // If the next token is obviously a // or /* */ comment, skip it efficiently
3011 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003012 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003013 LangOpts.LineComment &&
3014 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003015 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3016 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003017 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003018 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003019 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3020 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003021 goto SkipIgnoredUnits;
3022 } else if (isHorizontalWhitespace(*CurPtr)) {
3023 goto SkipHorizontalWhitespace;
3024 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003025 // We only saw whitespace, so just try again with this lexer.
3026 // (We manually eliminate the tail call to avoid recursion.)
3027 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003028
Chris Lattner2b15cf72008-01-03 17:58:54 +00003029 // C99 6.4.4.1: Integer Constants.
3030 // C99 6.4.4.2: Floating Constants.
3031 case '0': case '1': case '2': case '3': case '4':
3032 case '5': case '6': case '7': case '8': case '9':
3033 // Notify MIOpt that we read a non-whitespace/non-comment token.
3034 MIOpt.ReadToken();
3035 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003036
Richard Smith9b362092013-03-09 23:56:02 +00003037 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003038 // Notify MIOpt that we read a non-whitespace/non-comment token.
3039 MIOpt.ReadToken();
3040
Richard Smith9b362092013-03-09 23:56:02 +00003041 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003042 Char = getCharAndSize(CurPtr, SizeTmp);
3043
3044 // UTF-16 string literal
3045 if (Char == '"')
3046 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3047 tok::utf16_string_literal);
3048
3049 // UTF-16 character constant
3050 if (Char == '\'')
3051 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3052 tok::utf16_char_constant);
3053
Craig Topper54edcca2011-08-11 04:06:15 +00003054 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003055 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3056 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003057 return LexRawStringLiteral(Result,
3058 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3059 SizeTmp2, Result),
3060 tok::utf16_string_literal);
3061
3062 if (Char == '8') {
3063 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3064
3065 // UTF-8 string literal
3066 if (Char2 == '"')
3067 return LexStringLiteral(Result,
3068 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3069 SizeTmp2, Result),
3070 tok::utf8_string_literal);
3071
Richard Smith9b362092013-03-09 23:56:02 +00003072 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003073 unsigned SizeTmp3;
3074 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3075 // UTF-8 raw string literal
3076 if (Char3 == '"') {
3077 return LexRawStringLiteral(Result,
3078 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3079 SizeTmp2, Result),
3080 SizeTmp3, Result),
3081 tok::utf8_string_literal);
3082 }
3083 }
3084 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003085 }
3086
3087 // treat u like the start of an identifier.
3088 return LexIdentifier(Result, CurPtr);
3089
Richard Smith9b362092013-03-09 23:56:02 +00003090 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003091 // Notify MIOpt that we read a non-whitespace/non-comment token.
3092 MIOpt.ReadToken();
3093
Richard Smith9b362092013-03-09 23:56:02 +00003094 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003095 Char = getCharAndSize(CurPtr, SizeTmp);
3096
3097 // UTF-32 string literal
3098 if (Char == '"')
3099 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3100 tok::utf32_string_literal);
3101
3102 // UTF-32 character constant
3103 if (Char == '\'')
3104 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3105 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003106
3107 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003108 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3109 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003110 return LexRawStringLiteral(Result,
3111 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3112 SizeTmp2, Result),
3113 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003114 }
3115
3116 // treat U like the start of an identifier.
3117 return LexIdentifier(Result, CurPtr);
3118
Craig Topper54edcca2011-08-11 04:06:15 +00003119 case 'R': // Identifier or C++0x raw string literal
3120 // Notify MIOpt that we read a non-whitespace/non-comment token.
3121 MIOpt.ReadToken();
3122
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003123 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003124 Char = getCharAndSize(CurPtr, SizeTmp);
3125
3126 if (Char == '"')
3127 return LexRawStringLiteral(Result,
3128 ConsumeChar(CurPtr, SizeTmp, Result),
3129 tok::string_literal);
3130 }
3131
3132 // treat R like the start of an identifier.
3133 return LexIdentifier(Result, CurPtr);
3134
Chris Lattner2b15cf72008-01-03 17:58:54 +00003135 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003136 // Notify MIOpt that we read a non-whitespace/non-comment token.
3137 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003138 Char = getCharAndSize(CurPtr, SizeTmp);
3139
3140 // Wide string literal.
3141 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003142 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003143 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003144
Craig Topper54edcca2011-08-11 04:06:15 +00003145 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003146 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003147 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3148 return LexRawStringLiteral(Result,
3149 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3150 SizeTmp2, Result),
3151 tok::wide_string_literal);
3152
Chris Lattner22eb9722006-06-18 05:43:12 +00003153 // Wide character constant.
3154 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003155 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3156 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003157 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003158
Chris Lattner22eb9722006-06-18 05:43:12 +00003159 // C99 6.4.2: Identifiers.
3160 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3161 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003162 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003163 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3164 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3165 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003166 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003167 case 'v': case 'w': case 'x': case 'y': case 'z':
3168 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003169 // Notify MIOpt that we read a non-whitespace/non-comment token.
3170 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003171 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003172
3173 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003174 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003175 if (!isLexingRawMode())
3176 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003177 // Notify MIOpt that we read a non-whitespace/non-comment token.
3178 MIOpt.ReadToken();
3179 return LexIdentifier(Result, CurPtr);
3180 }
Mike Stump11289f42009-09-09 15:08:12 +00003181
Chris Lattnerb11c3232008-10-12 04:51:35 +00003182 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003183 break;
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattner22eb9722006-06-18 05:43:12 +00003185 // C99 6.4.4: Character Constants.
3186 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003187 // Notify MIOpt that we read a non-whitespace/non-comment token.
3188 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003189 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003190
3191 // C99 6.4.5: String Literals.
3192 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003193 // Notify MIOpt that we read a non-whitespace/non-comment token.
3194 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003195 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003196
3197 // C99 6.4.6: Punctuators.
3198 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003199 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 break;
3201 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003202 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003203 break;
3204 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003205 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003206 break;
3207 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003208 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003209 break;
3210 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003211 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003212 break;
3213 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003214 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003215 break;
3216 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003217 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003218 break;
3219 case '.':
3220 Char = getCharAndSize(CurPtr, SizeTmp);
3221 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003222 // Notify MIOpt that we read a non-whitespace/non-comment token.
3223 MIOpt.ReadToken();
3224
Chris Lattner22eb9722006-06-18 05:43:12 +00003225 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003226 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003227 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003228 CurPtr += SizeTmp;
3229 } else if (Char == '.' &&
3230 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003231 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003232 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3233 SizeTmp2, Result);
3234 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003235 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003236 }
3237 break;
3238 case '&':
3239 Char = getCharAndSize(CurPtr, SizeTmp);
3240 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003241 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003242 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3243 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003244 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003245 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3246 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003247 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003248 }
3249 break;
Mike Stump11289f42009-09-09 15:08:12 +00003250 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003252 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003253 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3254 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003255 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003256 }
3257 break;
3258 case '+':
3259 Char = getCharAndSize(CurPtr, SizeTmp);
3260 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003261 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003262 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003263 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003265 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003267 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003268 }
3269 break;
3270 case '-':
3271 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003272 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003273 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003274 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003275 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003276 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003277 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3278 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003279 Kind = tok::arrowstar;
3280 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003281 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003282 Kind = tok::arrow;
3283 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003284 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003285 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003286 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003287 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003288 }
3289 break;
3290 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003291 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003292 break;
3293 case '!':
3294 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003295 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003296 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3297 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003298 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003299 }
3300 break;
3301 case '/':
3302 // 6.4.9: Comments
3303 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003304 if (Char == '/') { // Line comment.
3305 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003306 // want to lex this as a comment. There is one problem with this though,
3307 // that in one particular corner case, this can change the behavior of the
3308 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003309 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003310 // "foo". Check to see if the character after the second slash is a '*'.
3311 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003312 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003313 bool TreatAsComment = LangOpts.LineComment &&
3314 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003315 if (!TreatAsComment)
3316 if (!(PP && PP->isPreprocessedOutput()))
3317 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3318
3319 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003320 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3321 TokAtPhysicalStartOfLine))
3322 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003323
Chris Lattner58827712009-01-16 22:39:25 +00003324 // It is common for the tokens immediately after a // comment to be
3325 // whitespace (indentation for the next line). Instead of going through
3326 // the big switch, handle it efficiently now.
3327 goto SkipIgnoredUnits;
3328 }
3329 }
Mike Stump11289f42009-09-09 15:08:12 +00003330
Chris Lattner58827712009-01-16 22:39:25 +00003331 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003332 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3333 TokAtPhysicalStartOfLine))
3334 return true; // There is a token to return.
3335
3336 // We only saw whitespace, so just try again with this lexer.
3337 // (We manually eliminate the tail call to avoid recursion.)
3338 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003339 }
Mike Stump11289f42009-09-09 15:08:12 +00003340
Chris Lattner58827712009-01-16 22:39:25 +00003341 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003342 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003343 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003344 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003345 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003346 }
3347 break;
3348 case '%':
3349 Char = getCharAndSize(CurPtr, SizeTmp);
3350 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003351 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003352 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003353 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003354 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003355 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003356 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003357 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003358 Char = getCharAndSize(CurPtr, SizeTmp);
3359 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003360 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003361 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3362 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003363 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003364 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003365 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003366 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003367 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003368 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003369 // We parsed a # character. If this occurs at the start of the line,
3370 // it's actually the start of a preprocessing directive. Callback to
3371 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003372 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003373 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003374 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003375
Chris Lattner2534324a2009-03-18 20:58:27 +00003376 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003377 }
3378 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003379 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003380 }
3381 break;
3382 case '<':
3383 Char = getCharAndSize(CurPtr, SizeTmp);
3384 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003385 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003387 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3388 if (After == '=') {
3389 Kind = tok::lesslessequal;
3390 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3391 SizeTmp2, Result);
3392 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3393 // If this is actually a '<<<<<<<' version control conflict marker,
3394 // recognize it as such and recover nicely.
3395 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003396 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3397 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3398 // ignore it.
3399 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003400 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003401 Kind = tok::lesslessless;
3402 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3403 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003404 } else {
3405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3406 Kind = tok::lessless;
3407 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003408 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003409 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003410 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003411 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003412 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003413 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3414 // C++0x [lex.pptoken]p3:
3415 // Otherwise, if the next three characters are <:: and the subsequent
3416 // character is neither : nor >, the < is treated as a preprocessor
3417 // token by itself and not as the first character of the alternative
3418 // token <:.
3419 unsigned SizeTmp3;
3420 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3421 if (After != ':' && After != '>') {
3422 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003423 if (!isLexingRawMode())
3424 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003425 break;
3426 }
3427 }
3428
Chris Lattner22eb9722006-06-18 05:43:12 +00003429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003430 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003431 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003432 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003433 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003434 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003435 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003436 }
3437 break;
3438 case '>':
3439 Char = getCharAndSize(CurPtr, SizeTmp);
3440 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003441 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003442 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003443 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003444 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3445 if (After == '=') {
3446 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3447 SizeTmp2, Result);
3448 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003449 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3450 // If this is actually a '>>>>' conflict marker, recognize it as such
3451 // and recover nicely.
3452 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003453 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3454 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3455 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003456 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003457 Kind = tok::greatergreatergreater;
3458 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3459 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003460 } else {
3461 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3462 Kind = tok::greatergreater;
3463 }
3464
Chris Lattner22eb9722006-06-18 05:43:12 +00003465 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003466 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003467 }
3468 break;
3469 case '^':
3470 Char = getCharAndSize(CurPtr, SizeTmp);
3471 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003473 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 }
3477 break;
3478 case '|':
3479 Char = getCharAndSize(CurPtr, SizeTmp);
3480 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003481 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003482 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3483 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003484 // If this is '|||||||' and we're in a conflict marker, ignore it.
3485 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3486 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003487 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003488 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3489 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003490 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003491 }
3492 break;
3493 case ':':
3494 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003495 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003496 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003497 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003498 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003499 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003501 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003502 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003503 }
3504 break;
3505 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003506 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003507 break;
3508 case '=':
3509 Char = getCharAndSize(CurPtr, SizeTmp);
3510 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003511 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003512 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3513 goto LexNextToken;
3514
Chris Lattnerb11c3232008-10-12 04:51:35 +00003515 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003517 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003518 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003519 }
3520 break;
3521 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003522 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003523 break;
3524 case '#':
3525 Char = getCharAndSize(CurPtr, SizeTmp);
3526 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003527 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003529 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003530 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003531 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003532 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003533 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003534 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003535 // We parsed a # character. If this occurs at the start of the line,
3536 // it's actually the start of a preprocessing directive. Callback to
3537 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003538 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003539 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003540 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Chris Lattner2534324a2009-03-18 20:58:27 +00003542 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003543 }
3544 break;
3545
Chris Lattner2b15cf72008-01-03 17:58:54 +00003546 case '@':
3547 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003548 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003549 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003550 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003551 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003552 break;
Mike Stump11289f42009-09-09 15:08:12 +00003553
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003554 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003555 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003556 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3557 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3558 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3559 return true; // KeepWhitespaceMode
3560
3561 // We only saw whitespace, so just try again with this lexer.
3562 // (We manually eliminate the tail call to avoid recursion.)
3563 goto LexNextToken;
3564 }
3565
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003566 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003567 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003568
Chris Lattnerb11c3232008-10-12 04:51:35 +00003569 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003570 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003571
3572 default: {
3573 if (isASCII(Char)) {
3574 Kind = tok::unknown;
3575 break;
3576 }
3577
3578 UTF32 CodePoint;
3579
3580 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3581 // an escaped newline.
3582 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003583 ConversionResult Status =
3584 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3585 (const UTF8 *)BufferEnd,
3586 &CodePoint,
3587 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003588 if (Status == conversionOK) {
3589 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3590 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3591 return true; // KeepWhitespaceMode
3592
3593 // We only saw whitespace, so just try again with this lexer.
3594 // (We manually eliminate the tail call to avoid recursion.)
3595 goto LexNextToken;
3596 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003597 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003598 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003599
Jordan Rosecc538342013-01-31 19:48:48 +00003600 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3601 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003602 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003603 Kind = tok::unknown;
3604 break;
3605 }
3606
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003607 // Non-ASCII characters tend to creep into source code unintentionally.
3608 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003609 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003610 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003611
3612 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003613 // We're pretending the character didn't exist, so just try again with
3614 // this lexer.
3615 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003616 goto LexNextToken;
3617 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Chris Lattner371ac8a2006-07-04 07:11:10 +00003620 // Notify MIOpt that we read a non-whitespace/non-comment token.
3621 MIOpt.ReadToken();
3622
Chris Lattnerd01e2912006-06-18 16:22:51 +00003623 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003624 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003625 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003626
3627HandleDirective:
3628 // We parsed a # character and it's the start of a preprocessing directive.
3629
3630 FormTokenWithChars(Result, CurPtr, tok::hash);
3631 PP->HandleDirective(Result);
3632
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003633 if (PP->hadModuleLoaderFatalFailure()) {
3634 // With a fatal failure in the module loader, we abort parsing.
3635 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003636 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003637 }
3638
Eli Friedman0834a4b2013-09-19 00:41:32 +00003639 // We parsed the directive; lex a token with the new state.
3640 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003641}