blob: 88e7b247806c70d9f3b76aadbb3d1554306271b1 [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)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000146 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
147 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000148
Chris Lattner757169b2009-01-17 08:27:52 +0000149/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
150/// _Pragma expansion. This has a variety of magic semantics that this method
151/// sets up. It returns a new'd Lexer that must be delete'd when done.
152///
153/// On entrance to this routine, TokStartLoc is a macro location which has a
154/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000155/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000156/// "expanded from".
157///
Alp Toker7755aff2014-05-18 18:37:59 +0000158/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000159/// normal lexer that remaps tokens as they fly by. This would require making
160/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
161/// interface that could handle this stuff. This would pull GetMappedTokenLoc
162/// out of the critical path of the lexer!
163///
Mike Stump11289f42009-09-09 15:08:12 +0000164Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000165 SourceLocation ExpansionLocStart,
166 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000167 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000168 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000169
170 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000171 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000172 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
173 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner757169b2009-01-17 08:27:52 +0000175 // Now that the lexer is created, change the start/end locations so that we
176 // just lex the subsection of the file that we want. This is lexing from a
177 // scratch buffer.
178 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner757169b2009-01-17 08:27:52 +0000180 L->BufferPtr = StrData;
181 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000182 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000183
184 // Set the SourceLocation with the remapping information. This ensures that
185 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000186 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
187 ExpansionLocStart,
188 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattner757169b2009-01-17 08:27:52 +0000190 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000191 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000192 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner757169b2009-01-17 08:27:52 +0000194 // This lexer really is for _Pragma.
195 L->Is_PragmaLexer = true;
196 return L;
197}
198
Chris Lattner02b436a2007-10-17 20:41:00 +0000199
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000200/// Stringify - Convert the specified string into a C string, with surrounding
201/// ""'s, and with escaped \ and " characters.
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000202std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000203 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000204 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000205 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000206 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000207 Result.insert(Result.begin()+i, '\\');
208 ++i; ++e;
209 }
210 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000211 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000212}
213
Chris Lattner4c4a2452007-07-24 06:57:14 +0000214/// Stringify - Convert the specified string into a C string by escaping '\'
215/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000216void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000217 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
218 if (Str[i] == '\\' || Str[i] == '"') {
219 Str.insert(Str.begin()+i, '\\');
220 ++i; ++e;
221 }
222 }
223}
224
Chris Lattner39720112010-11-17 07:26:20 +0000225//===----------------------------------------------------------------------===//
226// Token Spelling
227//===----------------------------------------------------------------------===//
228
Richard Smith9a67f472012-11-28 07:29:00 +0000229/// \brief Slow case of getSpelling. Extract the characters comprising the
230/// spelling of this token from the provided input buffer.
231static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
232 const LangOptions &LangOpts, char *Spelling) {
233 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
234
235 size_t Length = 0;
236 const char *BufEnd = BufPtr + Tok.getLength();
237
Craig Toppera6324c92015-10-22 15:35:21 +0000238 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000239 // Munch the encoding-prefix and opening double-quote.
240 while (BufPtr < BufEnd) {
241 unsigned Size;
242 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
243 BufPtr += Size;
244
245 if (Spelling[Length - 1] == '"')
246 break;
247 }
248
249 // Raw string literals need special handling; trigraph expansion and line
250 // splicing do not occur within their d-char-sequence nor within their
251 // r-char-sequence.
252 if (Length >= 2 &&
253 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
254 // Search backwards from the end of the token to find the matching closing
255 // quote.
256 const char *RawEnd = BufEnd;
257 do --RawEnd; while (*RawEnd != '"');
258 size_t RawLength = RawEnd - BufPtr + 1;
259
260 // Everything between the quotes is included verbatim in the spelling.
261 memcpy(Spelling + Length, BufPtr, RawLength);
262 Length += RawLength;
263 BufPtr += RawLength;
264
265 // The rest of the token is lexed normally.
266 }
267 }
268
269 while (BufPtr < BufEnd) {
270 unsigned Size;
271 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
272 BufPtr += Size;
273 }
274
275 assert(Length < Tok.getLength() &&
276 "NeedsCleaning flag set on token that didn't need cleaning!");
277 return Length;
278}
279
Chris Lattner39720112010-11-17 07:26:20 +0000280/// getSpelling() - Return the 'spelling' of this token. The spelling of a
281/// token are the characters used to represent the token in the source file
282/// after trigraph expansion and escaped-newline folding. In particular, this
283/// wants to get the true, uncanonicalized, spelling of things like digraphs
284/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000285StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000286 SmallVectorImpl<char> &buffer,
287 const SourceManager &SM,
288 const LangOptions &options,
289 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000290 // Break down the source location.
291 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
292
293 // Try to the load the file buffer.
294 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000296 if (invalidTemp) {
297 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000298 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000299 }
300
301 const char *tokenBegin = file.data() + locInfo.second;
302
303 // Lex from the start of the given location.
304 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
305 file.begin(), tokenBegin, file.end());
306 Token token;
307 lexer.LexFromRawLexer(token);
308
309 unsigned length = token.getLength();
310
311 // Common case: no need for cleaning.
312 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000313 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000314
Richard Smith9a67f472012-11-28 07:29:00 +0000315 // Hard case, we need to relex the characters into the string.
316 buffer.resize(length);
317 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000319}
320
321/// getSpelling() - Return the 'spelling' of this token. The spelling of a
322/// token are the characters used to represent the token in the source file
323/// after trigraph expansion and escaped-newline folding. In particular, this
324/// wants to get the true, uncanonicalized, spelling of things like digraphs
325/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000326std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000327 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000328 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000329
Chris Lattner39720112010-11-17 07:26:20 +0000330 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000331 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000332 &CharDataInvalid);
333 if (Invalid)
334 *Invalid = CharDataInvalid;
335 if (CharDataInvalid)
336 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000337
338 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000339 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000340 return std::string(TokStart, TokStart + Tok.getLength());
341
Chris Lattner39720112010-11-17 07:26:20 +0000342 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000343 Result.resize(Tok.getLength());
344 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000345 return Result;
346}
347
348/// getSpelling - This method is used to get the spelling of a token into a
349/// preallocated buffer, instead of as an std::string. The caller is required
350/// to allocate enough space for the token, which is guaranteed to be at least
351/// Tok.getLength() bytes long. The actual length of the token is returned.
352///
353/// Note that this method may do two possible things: it may either fill in
354/// the buffer specified with characters, or it may *change the input pointer*
355/// to point to a constant buffer with the data already in it (avoiding a
356/// copy). The caller is not allowed to modify the returned buffer pointer
357/// if an internal buffer is returned.
358unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
359 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000360 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000361 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000362
Craig Topperd2d442c2014-05-17 23:10:59 +0000363 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000364 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
365 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000366 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000367 else if (!Tok.hasUCN()) {
368 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
369 // Just return the string from the identifier table, which is very quick.
370 Buffer = II->getNameStart();
371 return II->getLength();
372 }
Chris Lattner39720112010-11-17 07:26:20 +0000373 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000374
375 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000376 if (Tok.isLiteral())
377 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000378
Craig Topperd2d442c2014-05-17 23:10:59 +0000379 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000380 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000381 bool CharDataInvalid = false;
382 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
383 if (Invalid)
384 *Invalid = CharDataInvalid;
385 if (CharDataInvalid) {
386 Buffer = "";
387 return 0;
388 }
389 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000390
Chris Lattner39720112010-11-17 07:26:20 +0000391 // If this token contains nothing interesting, return it directly.
392 if (!Tok.needsCleaning()) {
393 Buffer = TokStart;
394 return Tok.getLength();
395 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000396
Chris Lattner39720112010-11-17 07:26:20 +0000397 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000398 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000399}
400
401
Chris Lattner8e129c22007-10-17 21:18:47 +0000402/// MeasureTokenLength - Relex the token at the specified location and return
403/// its length in bytes in the input file. If the token needs cleaning (e.g.
404/// includes a trigraph or an escaped newline) then this count includes bytes
405/// that are part of that.
406unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000407 const SourceManager &SM,
408 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000409 Token TheTok;
410 if (getRawToken(Loc, TheTok, SM, LangOpts))
411 return 0;
412 return TheTok.getLength();
413}
414
415/// \brief Relex the token at the specified location.
416/// \returns true if there was a failure, false on success.
417bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
418 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000419 const LangOptions &LangOpts,
420 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000421 // TODO: this could be special cased for common tokens like identifiers, ')',
422 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000423 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000424 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
425 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000426
427 // If this comes from a macro expansion, we really do want the macro name, not
428 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000429 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000430 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000431 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000432 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000433 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000434 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000435
436 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000437
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000438 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000439 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000440
Chris Lattner8e129c22007-10-17 21:18:47 +0000441 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000442 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
443 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000444 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000445 TheLexer.LexFromRawLexer(Result);
446 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000447}
448
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000449static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
450 const SourceManager &SM,
451 const LangOptions &LangOpts) {
452 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000453 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000454 if (LocInfo.first.isInvalid())
455 return Loc;
456
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000457 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000459 if (Invalid)
460 return Loc;
461
462 // Back up from the current location until we hit the beginning of a line
463 // (or the buffer). We'll relex from that point.
464 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000465 if (LocInfo.second >= Buffer.size())
466 return Loc;
467
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000468 const char *StrData = BufStart+LocInfo.second;
469 if (StrData[0] == '\n' || StrData[0] == '\r')
470 return Loc;
471
472 const char *LexStart = StrData;
473 while (LexStart != BufStart) {
474 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
475 ++LexStart;
476 break;
477 }
478
479 --LexStart;
480 }
481
482 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000483 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000484 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
485 TheLexer.SetCommentRetentionState(true);
486
487 // Lex tokens until we find the token that contains the source location.
488 Token TheTok;
489 do {
490 TheLexer.LexFromRawLexer(TheTok);
491
492 if (TheLexer.getBufferLocation() > StrData) {
493 // Lexing this token has taken the lexer past the source location we're
494 // looking for. If the current token encompasses our source location,
495 // return the beginning of that token.
496 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
497 return TheTok.getLocation();
498
499 // We ended up skipping over the source location entirely, which means
500 // that it points into whitespace. We're done here.
501 break;
502 }
503 } while (TheTok.getKind() != tok::eof);
504
505 // We've passed our source location; just return the original source location.
506 return Loc;
507}
508
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000509SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
510 const SourceManager &SM,
511 const LangOptions &LangOpts) {
512 if (Loc.isFileID())
513 return getBeginningOfFileToken(Loc, SM, LangOpts);
514
515 if (!SM.isMacroArgExpansion(Loc))
516 return Loc;
517
518 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
519 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
520 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000521 std::pair<FileID, unsigned> BeginFileLocInfo
522 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000523 assert(FileLocInfo.first == BeginFileLocInfo.first &&
524 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000525 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000526}
527
Douglas Gregoraf82e352010-07-20 20:18:03 +0000528namespace {
529 enum PreambleDirectiveKind {
530 PDK_Skipped,
531 PDK_StartIf,
532 PDK_EndIf,
533 PDK_Unknown
534 };
535}
536
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000537std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000538 const LangOptions &LangOpts,
539 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000540 // Create a lexer starting at the beginning of the file. Note that we use a
541 // "fake" file source location at offset 1 so that the lexer will track our
542 // position within the file.
543 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000544 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000545 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
546 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000547 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000548
549 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
550 SourceLocation StartLoc = TheLexer.getSourceLocation();
551
Douglas Gregoraf82e352010-07-20 20:18:03 +0000552 bool InPreprocessorDirective = false;
553 Token TheTok;
554 Token IfStartTok;
555 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000556 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000557
558 unsigned MaxLineOffset = 0;
559 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000560 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000561 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000562 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000563 char ch = *CurPtr++;
564 if (ch == '\n') {
565 ++CurLine;
566 if (CurLine == MaxLines)
567 break;
568 }
569 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000570 if (CurPtr != Buffer.end())
571 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000572 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000573
Douglas Gregoraf82e352010-07-20 20:18:03 +0000574 do {
575 TheLexer.LexFromRawLexer(TheTok);
576
577 if (InPreprocessorDirective) {
578 // If we've hit the end of the file, we're done.
579 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000580 break;
581 }
582
583 // If we haven't hit the end of the preprocessor directive, skip this
584 // token.
585 if (!TheTok.isAtStartOfLine())
586 continue;
587
588 // We've passed the end of the preprocessor directive, and will look
589 // at this token again below.
590 InPreprocessorDirective = false;
591 }
592
Douglas Gregor028d3e42010-08-09 20:45:32 +0000593 // Keep track of the # of lines in the preamble.
594 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000595 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000596
597 // If we were asked to limit the number of lines in the preamble,
598 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000599 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000600 break;
601 }
602
Douglas Gregoraf82e352010-07-20 20:18:03 +0000603 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000604 if (TheTok.getKind() == tok::comment) {
605 if (ActiveCommentLoc.isInvalid())
606 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000607 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000608 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000609
610 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
611 // This is the start of a preprocessor directive.
612 Token HashTok = TheTok;
613 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000614 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000616 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000617 // we don't have an identifier table available. Instead, just look at
618 // the raw identifier to recognize and categorize preprocessor directives.
619 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000620 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000621 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622 PreambleDirectiveKind PDK
623 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
624 .Case("include", PDK_Skipped)
625 .Case("__include_macros", PDK_Skipped)
626 .Case("define", PDK_Skipped)
627 .Case("undef", PDK_Skipped)
628 .Case("line", PDK_Skipped)
629 .Case("error", PDK_Skipped)
630 .Case("pragma", PDK_Skipped)
631 .Case("import", PDK_Skipped)
632 .Case("include_next", PDK_Skipped)
633 .Case("warning", PDK_Skipped)
634 .Case("ident", PDK_Skipped)
635 .Case("sccs", PDK_Skipped)
636 .Case("assert", PDK_Skipped)
637 .Case("unassert", PDK_Skipped)
638 .Case("if", PDK_StartIf)
639 .Case("ifdef", PDK_StartIf)
640 .Case("ifndef", PDK_StartIf)
641 .Case("elif", PDK_Skipped)
642 .Case("else", PDK_Skipped)
643 .Case("endif", PDK_EndIf)
644 .Default(PDK_Unknown);
645
646 switch (PDK) {
647 case PDK_Skipped:
648 continue;
649
650 case PDK_StartIf:
651 if (IfCount == 0)
652 IfStartTok = HashTok;
653
654 ++IfCount;
655 continue;
656
657 case PDK_EndIf:
658 // Mismatched #endif. The preamble ends here.
659 if (IfCount == 0)
660 break;
661
662 --IfCount;
663 continue;
664
665 case PDK_Unknown:
666 // We don't know what this directive is; stop at the '#'.
667 break;
668 }
669 }
670
671 // We only end up here if we didn't recognize the preprocessor
672 // directive or it was one that can't occur in the preamble at this
673 // point. Roll back the current token to the location of the '#'.
674 InPreprocessorDirective = false;
675 TheTok = HashTok;
676 }
677
Douglas Gregor028d3e42010-08-09 20:45:32 +0000678 // We hit a token that we don't recognize as being in the
679 // "preprocessing only" part of the file, so we're no longer in
680 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000681 break;
682 } while (true);
683
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000684 SourceLocation End;
685 if (IfCount)
686 End = IfStartTok.getLocation();
687 else if (ActiveCommentLoc.isValid())
688 End = ActiveCommentLoc; // don't truncate a decl comment.
689 else
690 End = TheTok.getLocation();
691
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000692 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
693 IfCount? IfStartTok.isAtStartOfLine()
694 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000695}
696
Chris Lattner2a6ee912010-11-17 07:05:50 +0000697
698/// AdvanceToTokenCharacter - Given a location that specifies the start of a
699/// token, return a new location that specifies a character within the token.
700SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
701 unsigned CharNo,
702 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000703 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000704 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000705 // character is. This needs to take into consideration newlines and
706 // trigraphs.
707 bool Invalid = false;
708 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
709
710 // If they request the first char of the token, we're trivially done.
711 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
712 return TokStart;
713
714 unsigned PhysOffset = 0;
715
716 // The usual case is that tokens don't contain anything interesting. Skip
717 // over the uninteresting characters. If a token only consists of simple
718 // chars, this method is extremely fast.
719 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
720 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000721 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000722 ++TokPtr, --CharNo, ++PhysOffset;
723 }
724
725 // If we have a character that may be a trigraph or escaped newline, use a
726 // lexer to parse it correctly.
727 for (; CharNo; --CharNo) {
728 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000730 TokPtr += Size;
731 PhysOffset += Size;
732 }
733
734 // Final detail: if we end up on an escaped newline, we want to return the
735 // location of the actual byte of the token. For example foo\<newline>bar
736 // advanced by 3 should return the location of b, not of \\. One compounding
737 // detail of this is that the escape may be made by a trigraph.
738 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
739 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
740
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000741 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000742}
743
744/// \brief Computes the source location just past the end of the
745/// token at this source location.
746///
747/// This routine can be used to produce a source location that
748/// points just past the end of the token referenced by \p Loc, and
749/// is generally used when a diagnostic needs to point just after a
750/// token where it expected something different that it received. If
751/// the returned source location would not be meaningful (e.g., if
752/// it points into a macro), this routine returns an invalid
753/// source location.
754///
755/// \param Offset an offset from the end of the token, where the source
756/// location should refer to. The default offset (0) produces a source
757/// location pointing just past the end of the token; an offset of 1 produces
758/// a source location pointing to the last character in the token, etc.
759SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
760 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000762 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000763 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000764
765 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000767 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000768 }
769
David Blaikiebbafb8a2012-03-11 07:00:24 +0000770 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000771 if (Len > Offset)
772 Len = Len - Offset;
773 else
774 return Loc;
775
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000776 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000777}
778
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000779/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000780/// token of the macro expansion.
781bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000782 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000783 const LangOptions &LangOpts,
784 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000785 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
786
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000787 SourceLocation expansionLoc;
788 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
789 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000790
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000791 if (expansionLoc.isFileID()) {
792 // No other macro expansions, this is the first.
793 if (MacroBegin)
794 *MacroBegin = expansionLoc;
795 return true;
796 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000797
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000798 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799}
800
801/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000802/// token of the macro expansion.
803bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000804 const SourceManager &SM,
805 const LangOptions &LangOpts,
806 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000807 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
808
809 SourceLocation spellLoc = SM.getSpellingLoc(loc);
810 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
811 if (tokLen == 0)
812 return false;
813
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000814 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
815 SourceLocation expansionLoc;
816 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
817 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000818
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000819 if (expansionLoc.isFileID()) {
820 // No other macro expansions.
821 if (MacroEnd)
822 *MacroEnd = expansionLoc;
823 return true;
824 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000825
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000826 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827}
828
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000829static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000830 const SourceManager &SM,
831 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000832 SourceLocation Begin = Range.getBegin();
833 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000834 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000835 if (Range.isTokenRange()) {
836 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
837 if (End.isInvalid())
838 return CharSourceRange();
839 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000840
841 // Break down the source locations.
842 FileID FID;
843 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000844 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000845 if (FID.isInvalid())
846 return CharSourceRange();
847
848 unsigned EndOffs;
849 if (!SM.isInFileID(End, FID, &EndOffs) ||
850 BeginOffs > EndOffs)
851 return CharSourceRange();
852
853 return CharSourceRange::getCharRange(Begin, End);
854}
855
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000856CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000857 const SourceManager &SM,
858 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000859 SourceLocation Begin = Range.getBegin();
860 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000861 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000862 return CharSourceRange();
863
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000864 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000865 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000866
867 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000868 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
869 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000870 Range.setBegin(Begin);
871 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000872 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000873
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000874 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000875 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
876 &End)) ||
877 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
878 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000879 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880 Range.setEnd(End);
881 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000882 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000883
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 assert(Begin.isMacroID() && End.isMacroID());
885 SourceLocation MacroBegin, MacroEnd;
886 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000887 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
888 &MacroEnd)) ||
889 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
890 &MacroEnd)))) {
891 Range.setBegin(MacroBegin);
892 Range.setEnd(MacroEnd);
893 return makeRangeFromFileLocs(Range, SM, LangOpts);
894 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000895
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000896 bool Invalid = false;
897 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
898 &Invalid);
899 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000900 return CharSourceRange();
901
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000902 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
903 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
904 &Invalid);
905 if (Invalid)
906 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000907
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000908 if (EndEntry.getExpansion().isMacroArgExpansion() &&
909 BeginEntry.getExpansion().getExpansionLocStart() ==
910 EndEntry.getExpansion().getExpansionLocStart()) {
911 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
912 Range.setEnd(SM.getImmediateSpellingLoc(End));
913 return makeFileCharRange(Range, SM, LangOpts);
914 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000915 }
916
917 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000918}
919
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000920StringRef Lexer::getSourceText(CharSourceRange Range,
921 const SourceManager &SM,
922 const LangOptions &LangOpts,
923 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000924 Range = makeFileCharRange(Range, SM, LangOpts);
925 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000926 if (Invalid) *Invalid = true;
927 return StringRef();
928 }
929
930 // Break down the source location.
931 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
932 if (beginInfo.first.isInvalid()) {
933 if (Invalid) *Invalid = true;
934 return StringRef();
935 }
936
937 unsigned EndOffs;
938 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
939 beginInfo.second > EndOffs) {
940 if (Invalid) *Invalid = true;
941 return StringRef();
942 }
943
944 // Try to the load the file buffer.
945 bool invalidTemp = false;
946 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
947 if (invalidTemp) {
948 if (Invalid) *Invalid = true;
949 return StringRef();
950 }
951
952 if (Invalid) *Invalid = false;
953 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
954}
955
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000956StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
957 const SourceManager &SM,
958 const LangOptions &LangOpts) {
959 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000960
961 // Find the location of the immediate macro expansion.
962 while (1) {
963 FileID FID = SM.getFileID(Loc);
964 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
965 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
966 Loc = Expansion.getExpansionLocStart();
967 if (!Expansion.isMacroArgExpansion())
968 break;
969
970 // For macro arguments we need to check that the argument did not come
971 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
972
973 // Loc points to the argument id of the macro definition, move to the
974 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000975 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000976 SourceLocation SpellLoc = Expansion.getSpellingLoc();
977 if (SpellLoc.isFileID())
978 break; // No inner macro.
979
980 // If spelling location resides in the same FileID as macro expansion
981 // location, it means there is no inner macro.
982 FileID MacroFID = SM.getFileID(Loc);
983 if (SM.isInFileID(SpellLoc, MacroFID))
984 break;
985
986 // Argument came from inner macro.
987 Loc = SpellLoc;
988 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000989
990 // Find the spelling location of the start of the non-argument expansion
991 // range. This is where the macro name was spelled in order to begin
992 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000993 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000994
995 // Dig out the buffer where the macro name was spelled and the extents of the
996 // name so that we can render it into the expansion note.
997 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
998 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
999 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1000 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1001}
1002
Richard Trieu3a5c9582016-01-26 02:51:55 +00001003StringRef Lexer::getImmediateMacroNameForDiagnostics(
1004 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1005 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1006 // Walk past macro argument expanions.
1007 while (SM.isMacroArgExpansion(Loc))
1008 Loc = SM.getImmediateExpansionRange(Loc).first;
1009
1010 // If the macro's spelling has no FileID, then it's actually a token paste
1011 // or stringization (or similar) and not a macro at all.
1012 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1013 return StringRef();
1014
1015 // Find the spelling location of the start of the non-argument expansion
1016 // range. This is where the macro name was spelled in order to begin
1017 // expanding this macro.
1018 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1019
1020 // Dig out the buffer where the macro name was spelled and the extents of the
1021 // name so that we can render it into the expansion note.
1022 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1023 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1024 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1025 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1026}
1027
Jordan Rose288c4212012-06-07 01:10:31 +00001028bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001029 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001030}
1031
Chris Lattnerd01e2912006-06-18 16:22:51 +00001032
Chris Lattner22eb9722006-06-18 05:43:12 +00001033//===----------------------------------------------------------------------===//
1034// Diagnostics forwarding code.
1035//===----------------------------------------------------------------------===//
1036
Chris Lattner619c1742007-07-22 18:38:25 +00001037/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001038/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001039/// This is currently only used for _Pragma implementation, so it is the slow
1040/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001041static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1042 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001043static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1044 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001045 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001046 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner619c1742007-07-22 18:38:25 +00001048 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001049 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001050 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001051 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001053 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001054 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001055 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001056 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner9dc9c202009-02-15 20:52:18 +00001058 // Figure out the expansion loc range, which is the range covered by the
1059 // original _Pragma(...) sequence.
1060 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001061 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001062
Chandler Carruth115b0772011-07-26 03:03:05 +00001063 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001064}
1065
Chris Lattner22eb9722006-06-18 05:43:12 +00001066/// getSourceLocation - Return a source location identifier for the specified
1067/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001068SourceLocation Lexer::getSourceLocation(const char *Loc,
1069 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001070 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001071 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001072
1073 // In the normal case, we're just lexing from a simple file buffer, return
1074 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001075 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001076 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001077 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattnerd32480d2009-01-17 06:22:33 +00001079 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1080 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001081 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001082 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001083}
1084
Chris Lattner22eb9722006-06-18 05:43:12 +00001085/// Diag - Forwarding function for diagnostics. This translate a source
1086/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001087DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001088 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001089}
1090
1091//===----------------------------------------------------------------------===//
1092// Trigraph and Escaped Newline Handling Code.
1093//===----------------------------------------------------------------------===//
1094
1095/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1096/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1097static char GetTrigraphCharForLetter(char Letter) {
1098 switch (Letter) {
1099 default: return 0;
1100 case '=': return '#';
1101 case ')': return ']';
1102 case '(': return '[';
1103 case '!': return '|';
1104 case '\'': return '^';
1105 case '>': return '}';
1106 case '/': return '\\';
1107 case '<': return '{';
1108 case '-': return '~';
1109 }
1110}
1111
1112/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1113/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1114/// return the result character. Finally, emit a warning about trigraph use
1115/// whether trigraphs are enabled or not.
1116static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1117 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001118 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001119
David Blaikiebbafb8a2012-03-11 07:00:24 +00001120 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001121 if (!L->isLexingRawMode())
1122 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001123 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner6d27a162008-11-22 02:02:22 +00001126 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001127 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001128 return Res;
1129}
1130
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001131/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1132/// 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 +00001133/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001134unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1135 unsigned Size = 0;
1136 while (isWhitespace(Ptr[Size])) {
1137 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001138
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001139 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1140 continue;
1141
1142 // If this is a \r\n or \n\r, skip the other half.
1143 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1144 Ptr[Size-1] != Ptr[Size])
1145 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001147 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001148 }
1149
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001150 // Not an escaped newline, must be a \t or something else.
1151 return 0;
1152}
1153
Chris Lattner38b2cde2009-04-18 22:27:02 +00001154/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1155/// them), skip over them and return the first non-escaped-newline found,
1156/// otherwise return P.
1157const char *Lexer::SkipEscapedNewLines(const char *P) {
1158 while (1) {
1159 const char *AfterEscape;
1160 if (*P == '\\') {
1161 AfterEscape = P+1;
1162 } else if (*P == '?') {
1163 // If not a trigraph for escape, bail out.
1164 if (P[1] != '?' || P[2] != '/')
1165 return P;
1166 AfterEscape = P+3;
1167 } else {
1168 return P;
1169 }
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattner38b2cde2009-04-18 22:27:02 +00001171 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1172 if (NewLineSize == 0) return P;
1173 P = AfterEscape+NewLineSize;
1174 }
1175}
1176
Anna Zaks59a3c802011-07-27 21:43:43 +00001177/// \brief Checks that the given token is the first token that occurs after the
1178/// given location (this excludes comments and whitespace). Returns the location
1179/// immediately after the specified token. If the token is not found or the
1180/// location is inside a macro, the returned source location will be invalid.
1181SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1182 tok::TokenKind TKind,
1183 const SourceManager &SM,
1184 const LangOptions &LangOpts,
1185 bool SkipTrailingWhitespaceAndNewLine) {
1186 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001187 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001188 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001189 }
1190 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1191
1192 // Break down the source location.
1193 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1194
1195 // Try to load the file buffer.
1196 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001197 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001198 if (InvalidTemp)
1199 return SourceLocation();
1200
1201 const char *TokenBegin = File.data() + LocInfo.second;
1202
1203 // Lex from the start of the given location.
1204 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1205 TokenBegin, File.end());
1206 // Find the token.
1207 Token Tok;
1208 lexer.LexFromRawLexer(Tok);
1209 if (Tok.isNot(TKind))
1210 return SourceLocation();
1211 SourceLocation TokenLoc = Tok.getLocation();
1212
1213 // Calculate how much whitespace needs to be skipped if any.
1214 unsigned NumWhitespaceChars = 0;
1215 if (SkipTrailingWhitespaceAndNewLine) {
1216 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1217 Tok.getLength();
1218 unsigned char C = *TokenEnd;
1219 while (isHorizontalWhitespace(C)) {
1220 C = *(++TokenEnd);
1221 NumWhitespaceChars++;
1222 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001223
1224 // Skip \r, \n, \r\n, or \n\r
1225 if (C == '\n' || C == '\r') {
1226 char PrevC = C;
1227 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001228 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001229 if ((C == '\n' || C == '\r') && C != PrevC)
1230 NumWhitespaceChars++;
1231 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001232 }
1233
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001234 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001235}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001236
Chris Lattner22eb9722006-06-18 05:43:12 +00001237/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1238/// get its size, and return it. This is tricky in several cases:
1239/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1240/// then either return the trigraph (skipping 3 chars) or the '?',
1241/// depending on whether trigraphs are enabled or not.
1242/// 2. If this is an escaped newline (potentially with whitespace between
1243/// the backslash and newline), implicitly skip the newline and return
1244/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001245///
1246/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1247/// know that we can accumulate into Size, and that we have already incremented
1248/// Ptr by Size bytes.
1249///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001250/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1251/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001252///
1253char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001254 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001255 // If we have a slash, look for an escaped newline.
1256 if (Ptr[0] == '\\') {
1257 ++Size;
1258 ++Ptr;
1259Slash:
1260 // Common case, backslash-char where the char is not whitespace.
1261 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001262
Chris Lattnerc1835952009-06-23 05:15:06 +00001263 // See if we have optional whitespace characters between the slash and
1264 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001265 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1266 // Remember that this token needs to be cleaned.
1267 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001268
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001269 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001270 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001271 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001273 // Found backslash<whitespace><newline>. Parse the char after it.
1274 Size += EscapedNewLineSize;
1275 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001276
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001277 // If the char that we finally got was a \n, then we must have had
1278 // something like \<newline><newline>. We don't want to consume the
1279 // second newline.
1280 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1281 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001282
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001283 // Use slow version to accumulate a correct size field.
1284 return getCharAndSizeSlow(Ptr, Size, Tok);
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattner22eb9722006-06-18 05:43:12 +00001287 // Otherwise, this is not an escaped newline, just return the slash.
1288 return '\\';
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 // If this is a trigraph, process it.
1292 if (Ptr[0] == '?' && Ptr[1] == '?') {
1293 // If this is actually a legal trigraph (not something like "??x"), emit
1294 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001295 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001297 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001298
1299 Ptr += 3;
1300 Size += 3;
1301 if (C == '\\') goto Slash;
1302 return C;
1303 }
1304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattner22eb9722006-06-18 05:43:12 +00001306 // If this is neither, return a single character.
1307 ++Size;
1308 return *Ptr;
1309}
1310
Chris Lattnerd01e2912006-06-18 16:22:51 +00001311
Chris Lattner22eb9722006-06-18 05:43:12 +00001312/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1313/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1314/// and that we have already incremented Ptr by Size bytes.
1315///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001316/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1317/// be updated to match.
1318char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001319 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001320 // If we have a slash, look for an escaped newline.
1321 if (Ptr[0] == '\\') {
1322 ++Size;
1323 ++Ptr;
1324Slash:
1325 // Common case, backslash-char where the char is not whitespace.
1326 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001327
Chris Lattner22eb9722006-06-18 05:43:12 +00001328 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001329 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1330 // Found backslash<whitespace><newline>. Parse the char after it.
1331 Size += EscapedNewLineSize;
1332 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001333
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001334 // If the char that we finally got was a \n, then we must have had
1335 // something like \<newline><newline>. We don't want to consume the
1336 // second newline.
1337 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1338 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001339
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001340 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001341 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 // Otherwise, this is not an escaped newline, just return the slash.
1345 return '\\';
1346 }
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattner22eb9722006-06-18 05:43:12 +00001348 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001349 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 // If this is actually a legal trigraph (not something like "??x"), return
1351 // it.
1352 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1353 Ptr += 3;
1354 Size += 3;
1355 if (C == '\\') goto Slash;
1356 return C;
1357 }
1358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 // If this is neither, return a single character.
1361 ++Size;
1362 return *Ptr;
1363}
1364
Chris Lattner22eb9722006-06-18 05:43:12 +00001365//===----------------------------------------------------------------------===//
1366// Helper methods for lexing.
1367//===----------------------------------------------------------------------===//
1368
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001369/// \brief Routine that indiscriminately skips bytes in the source file.
1370void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1371 BufferPtr += Bytes;
1372 if (BufferPtr > BufferEnd)
1373 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001374 // FIXME: What exactly does the StartOfLine bit mean? There are two
1375 // possible meanings for the "start" of the line: the first token on the
1376 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001377 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001378 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001379}
1380
Jordan Rose58c61e02013-02-09 01:10:25 +00001381static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001382 if (LangOpts.AsmPreprocessor) {
1383 return false;
1384 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001385 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1386 C11AllowedIDCharRanges);
1387 return C11AllowedIDChars.contains(C);
1388 } else if (LangOpts.CPlusPlus) {
1389 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1390 CXX03AllowedIDCharRanges);
1391 return CXX03AllowedIDChars.contains(C);
1392 } else {
1393 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1394 C99AllowedIDCharRanges);
1395 return C99AllowedIDChars.contains(C);
1396 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001397}
1398
Jordan Rose58c61e02013-02-09 01:10:25 +00001399static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1400 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001401 if (LangOpts.AsmPreprocessor) {
1402 return false;
1403 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001404 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1405 C11DisallowedInitialIDCharRanges);
1406 return !C11DisallowedInitialIDChars.contains(C);
1407 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001408 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001409 } else {
1410 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1411 C99DisallowedInitialIDCharRanges);
1412 return !C99DisallowedInitialIDChars.contains(C);
1413 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001414}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001415
Jordan Rose58c61e02013-02-09 01:10:25 +00001416static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1417 const char *End) {
1418 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1419 L.getSourceLocation(End));
1420}
1421
1422static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1423 CharSourceRange Range, bool IsFirst) {
1424 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001425 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001426 enum {
1427 CannotAppearInIdentifier = 0,
1428 CannotStartIdentifier
1429 };
1430
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001431 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1432 C99AllowedIDCharRanges);
1433 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1434 C99DisallowedInitialIDCharRanges);
1435 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001436 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1437 << Range
1438 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001439 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001440 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1441 << Range
1442 << CannotStartIdentifier;
1443 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001444 }
1445
Jordan Rose58c61e02013-02-09 01:10:25 +00001446 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001447 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001448 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1449 CXX03AllowedIDCharRanges);
1450 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001451 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1452 << Range;
1453 }
1454 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001455}
1456
1457bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1458 Token &Result) {
1459 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001460 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001461 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1462 return false;
1463
1464 if (!isLexingRawMode())
1465 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1466 makeCharRange(*this, CurPtr, UCNPtr),
1467 /*IsFirst=*/false);
1468
1469 Result.setFlag(Token::HasUCN);
1470 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1471 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1472 CurPtr = UCNPtr;
1473 else
1474 while (CurPtr != UCNPtr)
1475 (void)getAndAdvanceChar(CurPtr, Result);
1476 return true;
1477}
1478
1479bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1480 const char *UnicodePtr = CurPtr;
1481 UTF32 CodePoint;
1482 ConversionResult Result =
1483 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1484 (const UTF8 *)BufferEnd,
1485 &CodePoint,
1486 strictConversion);
1487 if (Result != conversionOK ||
1488 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1489 return false;
1490
1491 if (!isLexingRawMode())
1492 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1493 makeCharRange(*this, CurPtr, UnicodePtr),
1494 /*IsFirst=*/false);
1495
1496 CurPtr = UnicodePtr;
1497 return true;
1498}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001499
Eli Friedman0834a4b2013-09-19 00:41:32 +00001500bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001501 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1502 unsigned Size;
1503 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001504 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001505 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001506
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 --CurPtr; // Back up over the skipped character.
1508
1509 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1510 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001511 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001512 // TODO: Could merge these checks into an InfoTable flag to make the
1513 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001514 if (isASCII(C) && C != '\\' && C != '?' &&
1515 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001516FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001517 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001518 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1519 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattner0f1f5052006-07-20 04:16:23 +00001521 // If we are in raw mode, return this identifier raw. There is no need to
1522 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001523 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001524 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001525
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001526 // Fill in Result.IdentifierInfo and update the token kind,
1527 // looking up the identifier in the identifier table.
1528 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001529
Chris Lattnerc5a00062006-06-18 16:41:01 +00001530 // Finally, now that we know we have an identifier, pass this off to the
1531 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001532 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001533 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001534
Eli Friedman0834a4b2013-09-19 00:41:32 +00001535 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001539
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 C = getCharAndSize(CurPtr, Size);
1541 while (1) {
1542 if (C == '$') {
1543 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001544 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001547 if (!isLexingRawMode())
1548 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 CurPtr = ConsumeChar(CurPtr, Size, Result);
1550 C = getCharAndSize(CurPtr, Size);
1551 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001552
Richard Smith8b7258b2014-02-17 21:52:30 +00001553 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001554 C = getCharAndSize(CurPtr, Size);
1555 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001556 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001557 C = getCharAndSize(CurPtr, Size);
1558 continue;
1559 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 goto FinishIdentifier;
1561 }
1562
1563 // Otherwise, this character is good, consume it.
1564 CurPtr = ConsumeChar(CurPtr, Size, Result);
1565
1566 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001567 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001568 CurPtr = ConsumeChar(CurPtr, Size, Result);
1569 C = getCharAndSize(CurPtr, Size);
1570 }
1571 }
1572}
1573
Douglas Gregor759ef232010-08-30 14:50:47 +00001574/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001575/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001576bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001577 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001579 if (C1 != '0')
1580 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001581 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001582 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001583}
Chris Lattner22eb9722006-06-18 05:43:12 +00001584
Nate Begeman5eee9332008-04-14 02:26:39 +00001585/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001586/// constant. From[-1] is the first character lexed. Return the end of the
1587/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001588bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001589 unsigned Size;
1590 char C = getCharAndSize(CurPtr, Size);
1591 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001592 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001593 CurPtr = ConsumeChar(CurPtr, Size, Result);
1594 PrevCh = C;
1595 C = getCharAndSize(CurPtr, Size);
1596 }
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattner22eb9722006-06-18 05:43:12 +00001598 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001599 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1600 // If we are in Microsoft mode, don't continue if the constant is hex.
1601 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001602 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001603 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1604 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001605
1606 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001607 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1608 // Outside C99, we accept hexadecimal floating point numbers as a
1609 // not-quite-conforming extension. Only do so if this looks like it's
1610 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1611 bool IsHexFloat = true;
1612 if (!LangOpts.C99) {
1613 if (!isHexaLiteral(BufferPtr, LangOpts))
1614 IsHexFloat = false;
1615 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1616 IsHexFloat = false;
1617 }
1618 if (IsHexFloat)
1619 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
Richard Smithfde94852013-09-26 03:33:06 +00001622 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001623 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001624 unsigned NextSize;
1625 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001626 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001627 if (!isLexingRawMode())
1628 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1629 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001630 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001631 return LexNumericConstant(Result, CurPtr);
1632 }
1633 }
1634
Richard Smith8b7258b2014-02-17 21:52:30 +00001635 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1636 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1637 return LexNumericConstant(Result, CurPtr);
1638 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1639 return LexNumericConstant(Result, CurPtr);
1640
Chris Lattnerd01e2912006-06-18 16:22:51 +00001641 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001642 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001643 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001644 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001645 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001646}
1647
Richard Smithe18f0fa2012-03-05 04:02:15 +00001648/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001649/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001650const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1651 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001652 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001653
Richard Smith8b7258b2014-02-17 21:52:30 +00001654 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001655 unsigned Size;
1656 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001657 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001658
Richard Smith8b7258b2014-02-17 21:52:30 +00001659 if (!isIdentifierHead(C)) {
1660 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1661 Consumed = true;
1662 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1663 Consumed = true;
1664 else
1665 return CurPtr;
1666 }
1667
1668 if (!getLangOpts().CPlusPlus11) {
1669 if (!isLexingRawMode())
1670 Diag(CurPtr,
1671 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1672 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1673 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1674 return CurPtr;
1675 }
1676
1677 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1678 // that does not start with an underscore is ill-formed. As a conforming
1679 // extension, we treat all such suffixes as if they had whitespace before
1680 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1681 // likely to be a ud-suffix than a macro, however, and accept that.
1682 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001683 bool IsUDSuffix = false;
1684 if (C == '_')
1685 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001686 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001687 // In C++1y, we need to look ahead a few characters to see if this is a
1688 // valid suffix for a string literal or a numeric literal (this could be
1689 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001690 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001691 char Buffer[MaxStandardSuffixLength] = { C };
1692 unsigned Consumed = Size;
1693 unsigned Chars = 1;
1694 while (true) {
1695 unsigned NextSize;
1696 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1697 getLangOpts());
1698 if (!isIdentifierBody(Next)) {
1699 // End of suffix. Check whether this is on the whitelist.
1700 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1701 NumericLiteralParser::isValidUDSuffix(
1702 getLangOpts(), StringRef(Buffer, Chars));
1703 break;
1704 }
1705
1706 if (Chars == MaxStandardSuffixLength)
1707 // Too long: can't be a standard suffix.
1708 break;
1709
1710 Buffer[Chars++] = Next;
1711 Consumed += NextSize;
1712 }
Richard Smithf4198b72013-07-23 08:14:48 +00001713 }
1714
1715 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001716 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001717 Diag(CurPtr, getLangOpts().MSVCCompat
1718 ? diag::ext_ms_reserved_user_defined_literal
1719 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001720 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001721 return CurPtr;
1722 }
1723
Richard Smith8b7258b2014-02-17 21:52:30 +00001724 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001725 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001726
1727 Result.setFlag(Token::HasUDSuffix);
1728 while (true) {
1729 C = getCharAndSize(CurPtr, Size);
1730 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1731 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1732 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1733 else break;
1734 }
1735
Richard Smithe18f0fa2012-03-05 04:02:15 +00001736 return CurPtr;
1737}
1738
Chris Lattner22eb9722006-06-18 05:43:12 +00001739/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001740/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001741bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001742 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001743 // Does this string contain the \0 character?
1744 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Richard Smithacd4d3d2011-10-15 01:18:56 +00001746 if (!isLexingRawMode() &&
1747 (Kind == tok::utf8_string_literal ||
1748 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001749 Kind == tok::utf32_string_literal))
1750 Diag(BufferPtr, getLangOpts().CPlusPlus
1751 ? diag::warn_cxx98_compat_unicode_literal
1752 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001753
Chris Lattner22eb9722006-06-18 05:43:12 +00001754 char C = getAndAdvanceChar(CurPtr, Result);
1755 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001756 // Skip escaped characters. Escaped newlines will already be processed by
1757 // getAndAdvanceChar.
1758 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001759 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001760
Chris Lattner52d96ac2010-05-30 23:27:38 +00001761 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001762 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001763 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001764 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001765 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001766 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001767 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001768
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001769 if (C == 0) {
1770 if (isCodeCompletionPoint(CurPtr-1)) {
1771 PP->CodeCompleteNaturalLanguage();
1772 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001773 cutOffLexing();
1774 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001775 }
1776
Chris Lattner52d96ac2010-05-30 23:27:38 +00001777 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001778 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001779 C = getAndAdvanceChar(CurPtr, Result);
1780 }
Mike Stump11289f42009-09-09 15:08:12 +00001781
Richard Smithe18f0fa2012-03-05 04:02:15 +00001782 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001784 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001785
Chris Lattner5a78a022006-07-20 06:02:19 +00001786 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001787 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001788 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001789
Chris Lattnerd01e2912006-06-18 16:22:51 +00001790 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001791 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001792 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001793 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001794 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001795}
1796
Craig Topper54edcca2011-08-11 04:06:15 +00001797/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1798/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001799bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001800 tok::TokenKind Kind) {
1801 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1802 // Between the initial and final double quote characters of the raw string,
1803 // any transformations performed in phases 1 and 2 (trigraphs,
1804 // universal-character-names, and line splicing) are reverted.
1805
Richard Smithacd4d3d2011-10-15 01:18:56 +00001806 if (!isLexingRawMode())
1807 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1808
Craig Topper54edcca2011-08-11 04:06:15 +00001809 unsigned PrefixLen = 0;
1810
1811 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1812 ++PrefixLen;
1813
1814 // If the last character was not a '(', then we didn't lex a valid delimiter.
1815 if (CurPtr[PrefixLen] != '(') {
1816 if (!isLexingRawMode()) {
1817 const char *PrefixEnd = &CurPtr[PrefixLen];
1818 if (PrefixLen == 16) {
1819 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1820 } else {
1821 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1822 << StringRef(PrefixEnd, 1);
1823 }
1824 }
1825
1826 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1827 // it's possible the '"' was intended to be part of the raw string, but
1828 // there's not much we can do about that.
1829 while (1) {
1830 char C = *CurPtr++;
1831
1832 if (C == '"')
1833 break;
1834 if (C == 0 && CurPtr-1 == BufferEnd) {
1835 --CurPtr;
1836 break;
1837 }
1838 }
1839
1840 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001841 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001842 }
1843
1844 // Save prefix and move CurPtr past it
1845 const char *Prefix = CurPtr;
1846 CurPtr += PrefixLen + 1; // skip over prefix and '('
1847
1848 while (1) {
1849 char C = *CurPtr++;
1850
1851 if (C == ')') {
1852 // Check for prefix match and closing quote.
1853 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1854 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1855 break;
1856 }
1857 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1858 if (!isLexingRawMode())
1859 Diag(BufferPtr, diag::err_unterminated_raw_string)
1860 << StringRef(Prefix, PrefixLen);
1861 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001862 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001863 }
1864 }
1865
Richard Smithe18f0fa2012-03-05 04:02:15 +00001866 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001867 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001868 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001869
Craig Topper54edcca2011-08-11 04:06:15 +00001870 // Update the location of token as well as BufferPtr.
1871 const char *TokStart = BufferPtr;
1872 FormTokenWithChars(Result, CurPtr, Kind);
1873 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001874 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001875}
1876
Chris Lattner22eb9722006-06-18 05:43:12 +00001877/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1878/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001879bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001880 // Does this string contain the \0 character?
1881 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001882 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001883 char C = getAndAdvanceChar(CurPtr, Result);
1884 while (C != '>') {
1885 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001886 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001887 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001888 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001890 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1891 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001892 // If the filename is unterminated, then it must just be a lone <
1893 // character. Return this as such.
1894 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001895 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001896 } else if (C == 0) {
1897 NulCharacter = CurPtr-1;
1898 }
1899 C = getAndAdvanceChar(CurPtr, Result);
1900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
Chris Lattner5a78a022006-07-20 06:02:19 +00001902 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001903 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001904 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Chris Lattnerd01e2912006-06-18 16:22:51 +00001906 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001907 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001908 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001909 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001910 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001911}
1912
1913
1914/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001915/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001916bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001917 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001918 // Does this character contain the \0 character?
1919 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
Richard Smith3e3a7052014-11-08 06:08:42 +00001921 if (!isLexingRawMode()) {
1922 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1923 Diag(BufferPtr, getLangOpts().CPlusPlus
1924 ? diag::warn_cxx98_compat_unicode_literal
1925 : diag::warn_c99_compat_unicode_literal);
1926 else if (Kind == tok::utf8_char_constant)
1927 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1928 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001929
Chris Lattner22eb9722006-06-18 05:43:12 +00001930 char C = getAndAdvanceChar(CurPtr, Result);
1931 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001932 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001933 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001934 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001935 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001936 }
1937
1938 while (C != '\'') {
1939 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001940 if (C == '\\')
1941 C = getAndAdvanceChar(CurPtr, Result);
1942
1943 if (C == '\n' || C == '\r' || // Newline.
1944 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001945 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001946 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001947 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001948 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001949 }
1950
1951 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001952 if (isCodeCompletionPoint(CurPtr-1)) {
1953 PP->CodeCompleteNaturalLanguage();
1954 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001955 cutOffLexing();
1956 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001957 }
1958
Chris Lattner86851b82010-07-07 23:24:27 +00001959 NulCharacter = CurPtr-1;
1960 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 C = getAndAdvanceChar(CurPtr, Result);
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Richard Smithe18f0fa2012-03-05 04:02:15 +00001964 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001965 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001966 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001967
Chris Lattner86851b82010-07-07 23:24:27 +00001968 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001969 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001970 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001971
Chris Lattnerd01e2912006-06-18 16:22:51 +00001972 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001973 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001974 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001975 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001976 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001977}
1978
1979/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1980/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001981///
1982/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1983///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001984bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1985 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001986 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001987 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1988
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001989 unsigned char Char = *CurPtr;
1990
1991 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001992 while (1) {
1993 // Skip horizontal whitespace very aggressively.
1994 while (isHorizontalWhitespace(Char))
1995 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001997 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001998 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 break;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 if (ParsingPreprocessorDirective) {
2002 // End of preprocessor directive line, let LexTokenInternal handle this.
2003 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002004 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002007 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002008 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002009 Char = *++CurPtr;
2010 }
2011
Chris Lattner4d963442008-10-12 04:05:48 +00002012 // If the client wants us to return whitespace, return it now.
2013 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002014 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002015 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002016 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002017 IsAtPhysicalStartOfLine = true;
2018 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002019 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002020 return true;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002023 // If this isn't immediately after a newline, there is leading space.
2024 char PrevChar = CurPtr[-1];
2025 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2026
2027 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002028 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002029 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002030 TokAtPhysicalStartOfLine = true;
2031 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002032
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002034 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002035}
2036
Nico Weber158a31a2012-11-11 07:02:14 +00002037/// We have just read the // characters from input. Skip until we find the
2038/// newline character thats terminate the comment. Then update BufferPtr and
2039/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002040///
2041/// If we're in KeepCommentMode or any CommentHandler has inserted
2042/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002043bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2044 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002045 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002047 if (!LangOpts.LineComment && !isLexingRawMode()) {
2048 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Chris Lattner22eb9722006-06-18 05:43:12 +00002050 // Mark them enabled so we only emit one warning for this translation
2051 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002052 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Chris Lattner22eb9722006-06-18 05:43:12 +00002055 // Scan over the body of the comment. The common case, when scanning, is that
2056 // the comment contains normal ascii characters with nothing interesting in
2057 // them. As such, optimize for this case with the inner loop.
2058 char C;
2059 do {
2060 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002061 // Skip over characters in the fast loop.
2062 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002063 C != '\n' && C != '\r') // Newline or DOS-style newline.
2064 C = *++CurPtr;
2065
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002066 const char *NextLine = CurPtr;
2067 if (C != 0) {
2068 // We found a newline, see if it's escaped.
2069 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002070 bool HasSpace = false;
2071 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002072 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002073 HasSpace = true;
2074 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002075
2076 if (*EscapePtr == '\\') // Escaped newline.
2077 CurPtr = EscapePtr;
2078 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2079 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2080 CurPtr = EscapePtr-2;
2081 else
2082 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002083
2084 // If there was space between the backslash and newline, warn about it.
2085 if (HasSpace && !isLexingRawMode())
2086 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner22eb9722006-06-18 05:43:12 +00002089 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002090 // properly decode the character. Read it in raw mode to avoid emitting
2091 // diagnostics about things like trigraphs. If we see an escaped newline,
2092 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002093 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002094 bool OldRawMode = isLexingRawMode();
2095 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002097 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002098
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002099 // If we only read only one character, then no special handling is needed.
2100 // We're done and can skip forward to the newline.
2101 if (C != 0 && CurPtr == OldPtr+1) {
2102 CurPtr = NextLine;
2103 break;
2104 }
2105
Chris Lattner22eb9722006-06-18 05:43:12 +00002106 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002107 // \n, then we had an escaped newline within the comment. Emit diagnostic
2108 // unless the next line is also a // comment.
2109 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002110 for (; OldPtr != CurPtr; ++OldPtr)
2111 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002112 // Okay, we found a // comment that ends in a newline, if the next
2113 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002114 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002115 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002116 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002117 ++ForwardPtr;
2118 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2119 break;
2120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattner6d27a162008-11-22 02:02:22 +00002122 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002123 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002124 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002125 }
2126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
Douglas Gregor11583702010-08-25 17:04:25 +00002128 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002129 --CurPtr;
2130 break;
2131 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002132
2133 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2134 PP->CodeCompleteNaturalLanguage();
2135 cutOffLexing();
2136 return false;
2137 }
2138
Chris Lattner22eb9722006-06-18 05:43:12 +00002139 } while (C != '\n' && C != '\r');
2140
Chris Lattner93ddf802010-02-03 21:06:21 +00002141 // Found but did not consume the newline. Notify comment handlers about the
2142 // comment unless we're in a #if 0 block.
2143 if (PP && !isLexingRawMode() &&
2144 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2145 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002146 BufferPtr = CurPtr;
2147 return true; // A token has to be returned.
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattner457fc152006-07-29 06:30:25 +00002150 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002151 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002152 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002153
2154 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002155 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002156 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002157 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002158 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Chris Lattner22eb9722006-06-18 05:43:12 +00002161 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002162 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002163 // contribute to another token), it isn't needed for correctness. Note that
2164 // this is ok even in KeepWhitespaceMode, because we would have returned the
2165 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002166 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002169 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002170 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002172 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002173 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002174 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002175}
Chris Lattner22eb9722006-06-18 05:43:12 +00002176
Nico Weber158a31a2012-11-11 07:02:14 +00002177/// If in save-comment mode, package up this Line comment in an appropriate
2178/// way and return it.
2179bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002180 // If we're not in a preprocessor directive, just return the // comment
2181 // directly.
2182 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002183
David Blaikied5321242012-06-06 18:52:13 +00002184 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002185 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002186
Nico Weber158a31a2012-11-11 07:02:14 +00002187 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002188 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002189 bool Invalid = false;
2190 std::string Spelling = PP->getSpelling(Result, &Invalid);
2191 if (Invalid)
2192 return true;
2193
Nico Weber158a31a2012-11-11 07:02:14 +00002194 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002195 Spelling[1] = '*'; // Change prefix to "/*".
2196 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattnerb11c3232008-10-12 04:51:35 +00002198 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002199 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002200 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002201 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002202}
2203
Chris Lattnercb283342006-06-18 06:48:37 +00002204/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002205/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2206/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002207static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002208 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002209 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattner22eb9722006-06-18 05:43:12 +00002211 // Back up off the newline.
2212 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattner22eb9722006-06-18 05:43:12 +00002214 // If this is a two-character newline sequence, skip the other character.
2215 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2216 // \n\n or \r\r -> not escaped newline.
2217 if (CurPtr[0] == CurPtr[1])
2218 return false;
2219 // \n\r or \r\n -> skip the newline.
2220 --CurPtr;
2221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 // If we have horizontal whitespace, skip over it. We allow whitespace
2224 // between the slash and newline.
2225 bool HasSpace = false;
2226 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2227 --CurPtr;
2228 HasSpace = true;
2229 }
Mike Stump11289f42009-09-09 15:08:12 +00002230
Chris Lattner22eb9722006-06-18 05:43:12 +00002231 // If we have a slash, we know this is an escaped newline.
2232 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002233 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002234 } else {
2235 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002236 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2237 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002238 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002239
Chris Lattnercb283342006-06-18 06:48:37 +00002240 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002241 CurPtr -= 2;
2242
2243 // If no trigraphs are enabled, warn that we ignored this trigraph and
2244 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002245 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002246 if (!L->isLexingRawMode())
2247 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002248 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002249 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002250 if (!L->isLexingRawMode())
2251 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002252 }
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattner22eb9722006-06-18 05:43:12 +00002254 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002255 if (!L->isLexingRawMode())
2256 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002257
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002259 if (HasSpace && !L->isLexingRawMode())
2260 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattnercb283342006-06-18 06:48:37 +00002262 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002263}
2264
Chris Lattneraded4a92006-10-27 04:42:31 +00002265#ifdef __SSE2__
2266#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002267#elif __ALTIVEC__
2268#include <altivec.h>
2269#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002270#endif
2271
James Dennettf442d242012-06-17 03:40:43 +00002272/// We have just read from input the / and * characters that started a comment.
2273/// Read until we find the * and / characters that terminate the comment.
2274/// Note that we don't bother decoding trigraphs or escaped newlines in block
2275/// comments, because they cannot cause the comment to end. The only thing
2276/// that can happen is the comment could end with an escaped newline between
2277/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002278///
Chris Lattner87d02082010-01-18 22:35:47 +00002279/// If we're in KeepCommentMode or any CommentHandler has inserted
2280/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002281bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2282 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002283 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002284 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002285 // optimization helps people who like to put a lot of * characters in their
2286 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002287
2288 // The first character we get with newlines and trigraphs skipped to handle
2289 // the degenerate /*/ case below correctly if the * has an escaped newline
2290 // after it.
2291 unsigned CharSize;
2292 unsigned char C = getCharAndSize(CurPtr, CharSize);
2293 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002295 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002296 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002297 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002298
Chris Lattner99e7d232008-10-12 04:19:49 +00002299 // KeepWhitespaceMode should return this broken comment as a token. Since
2300 // it isn't a well formed comment, just return it as an 'unknown' token.
2301 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002302 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002303 return true;
2304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattner99e7d232008-10-12 04:19:49 +00002306 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002307 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 }
Mike Stump11289f42009-09-09 15:08:12 +00002309
Chris Lattnerc850ad62007-07-21 23:43:37 +00002310 // Check to see if the first character after the '/*' is another /. If so,
2311 // then this slash does not end the block comment, it is part of it.
2312 if (C == '/')
2313 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattner22eb9722006-06-18 05:43:12 +00002315 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002316 // Skip over all non-interesting characters until we find end of buffer or a
2317 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002318 if (CurPtr + 24 < BufferEnd &&
2319 // If there is a code-completion point avoid the fast scan because it
2320 // doesn't check for '\0'.
2321 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002322 // While not aligned to a 16-byte boundary.
2323 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2324 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002325
Chris Lattner6cc3e362006-10-27 04:12:35 +00002326 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002327
2328#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002329 __m128i Slashes = _mm_set1_epi8('/');
2330 while (CurPtr+16 <= BufferEnd) {
2331 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2332 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002333 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002334 // Adjust the pointer to point directly after the first slash. It's
2335 // not necessary to set C here, it will be overwritten at the end of
2336 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002337 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002338 goto FoundSlash;
2339 }
Roman Divacky61509902014-04-03 18:04:52 +00002340 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002341 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002342#elif __ALTIVEC__
2343 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002344 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002345 '/', '/', '/', '/', '/', '/', '/', '/'
2346 };
2347 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002348 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002349 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002350#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002351 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002352 while (CurPtr[0] != '/' &&
2353 CurPtr[1] != '/' &&
2354 CurPtr[2] != '/' &&
2355 CurPtr[3] != '/' &&
2356 CurPtr+4 < BufferEnd) {
2357 CurPtr += 4;
2358 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002359#endif
Mike Stump11289f42009-09-09 15:08:12 +00002360
Chris Lattneraded4a92006-10-27 04:42:31 +00002361 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002362 C = *CurPtr++;
2363 }
Mike Stump11289f42009-09-09 15:08:12 +00002364
Chris Lattneraded4a92006-10-27 04:42:31 +00002365 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002366 while (C != '/' && C != '\0')
2367 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002368
Chris Lattner22eb9722006-06-18 05:43:12 +00002369 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002370 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002371 if (CurPtr[-2] == '*') // We found the final */. We're done!
2372 break;
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattner22eb9722006-06-18 05:43:12 +00002374 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002375 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002376 // We found the final */, though it had an escaped newline between the
2377 // * and /. We're done!
2378 break;
2379 }
2380 }
2381 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2382 // If this is a /* inside of the comment, emit a warning. Don't do this
2383 // if this is a /*/, which will end the comment. This misses cases with
2384 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002385 if (!isLexingRawMode())
2386 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002387 }
2388 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002389 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002390 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002391 // Note: the user probably forgot a */. We could continue immediately
2392 // after the /*, but this would involve lexing a lot of what really is the
2393 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002394 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattner99e7d232008-10-12 04:19:49 +00002396 // KeepWhitespaceMode should return this broken comment as a token. Since
2397 // it isn't a well formed comment, just return it as an 'unknown' token.
2398 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002399 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002400 return true;
2401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattner99e7d232008-10-12 04:19:49 +00002403 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002404 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002405 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2406 PP->CodeCompleteNaturalLanguage();
2407 cutOffLexing();
2408 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002409 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002410
Chris Lattner22eb9722006-06-18 05:43:12 +00002411 C = *CurPtr++;
2412 }
Mike Stump11289f42009-09-09 15:08:12 +00002413
Chris Lattner93ddf802010-02-03 21:06:21 +00002414 // Notify comment handlers about the comment unless we're in a #if 0 block.
2415 if (PP && !isLexingRawMode() &&
2416 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2417 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002418 BufferPtr = CurPtr;
2419 return true; // A token has to be returned.
2420 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002421
Chris Lattner457fc152006-07-29 06:30:25 +00002422 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002423 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002424 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002425 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002426 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002427
2428 // It is common for the tokens immediately after a /**/ comment to be
2429 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002430 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2431 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002432 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002433 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002434 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002435 }
2436
2437 // Otherwise, just return so that the next character will be lexed as a token.
2438 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002439 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002440 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002441}
2442
2443//===----------------------------------------------------------------------===//
2444// Primary Lexing Entry Points
2445//===----------------------------------------------------------------------===//
2446
Chris Lattner22eb9722006-06-18 05:43:12 +00002447/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2448/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002449void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002450 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2451 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002452 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002453
2454 // CurPtr - Cache BufferPtr in an automatic variable.
2455 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002456 while (1) {
2457 char Char = getAndAdvanceChar(CurPtr, Tmp);
2458 switch (Char) {
2459 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002460 if (Result)
2461 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002462 break;
2463 case 0: // Null.
2464 // Found end of file?
2465 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002466 if (isCodeCompletionPoint(CurPtr-1)) {
2467 PP->CodeCompleteNaturalLanguage();
2468 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002469 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002470 }
2471
Chris Lattner22eb9722006-06-18 05:43:12 +00002472 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002473 if (Result)
2474 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002475 break;
2476 }
2477 // FALL THROUGH.
2478 case '\r':
2479 case '\n':
2480 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2481 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2482 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002483
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002484 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002485 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002486 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002487 if (PP)
2488 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002489 Lex(Tmp);
2490 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002491 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002492
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002493 // Finally, we're done;
2494 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002495 }
2496 }
2497}
2498
2499/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2500/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002501/// This returns true if Result contains a token, false if PP.Lex should be
2502/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002503bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002504 // If we hit the end of the file while parsing a preprocessor directive,
2505 // end the preprocessor directive first. The next token returned will
2506 // then be the end of file.
2507 if (ParsingPreprocessorDirective) {
2508 // Done parsing the "line".
2509 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002510 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002511 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Chris Lattner457fc152006-07-29 06:30:25 +00002513 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002514 if (PP)
2515 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002516 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002517 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002518
Chris Lattner30a2fa12006-07-19 06:31:49 +00002519 // If we are in raw mode, return this event as an EOF token. Let the caller
2520 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002521 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002522 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002523 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002524 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002525 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002526 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002527
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002528 // Issue diagnostics for unterminated #if and missing newline.
2529
Chris Lattner30a2fa12006-07-19 06:31:49 +00002530 // If we are in a #if directive, emit an error.
2531 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002532 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002533 PP->Diag(ConditionalStack.back().IfLoc,
2534 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002535 ConditionalStack.pop_back();
2536 }
Mike Stump11289f42009-09-09 15:08:12 +00002537
Chris Lattner8f96d042008-04-12 05:54:25 +00002538 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2539 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002540 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2541 DiagnosticsEngine &Diags = PP->getDiagnostics();
2542 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2543 unsigned DiagID;
2544
2545 if (LangOpts.CPlusPlus11) {
2546 // C++11 [lex.phases] 2.2 p2
2547 // Prefer the C++98 pedantic compatibility warning over the generic,
2548 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002549 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002550 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2551 } else {
2552 DiagID = diag::warn_no_newline_eof;
2553 }
2554 } else {
2555 DiagID = diag::ext_no_newline_eof;
2556 }
2557
2558 Diag(BufferEnd, DiagID)
2559 << FixItHint::CreateInsertion(EndLoc, "\n");
2560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Chris Lattner22eb9722006-06-18 05:43:12 +00002562 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002563
2564 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002565 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002566}
2567
Chris Lattner678c8802006-07-11 05:46:12 +00002568/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2569/// the specified lexer will return a tok::l_paren token, 0 if it is something
2570/// else and 2 if there are no more tokens in the buffer controlled by the
2571/// lexer.
2572unsigned Lexer::isNextPPTokenLParen() {
2573 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002574
Chris Lattner678c8802006-07-11 05:46:12 +00002575 // Switch to 'skipping' mode. This will ensure that we can lex a token
2576 // without emitting diagnostics, disables macro expansion, and will cause EOF
2577 // to return an EOF token instead of popping the include stack.
2578 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002579
Chris Lattner678c8802006-07-11 05:46:12 +00002580 // Save state that can be changed while lexing so that we can restore it.
2581 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002582 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002583 bool atStartOfLine = IsAtStartOfLine;
2584 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2585 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Chris Lattner146762e2007-07-20 16:59:19 +00002587 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002588 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002589
Chris Lattner678c8802006-07-11 05:46:12 +00002590 // Restore state that may have changed.
2591 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002592 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002593 HasLeadingSpace = leadingSpace;
2594 IsAtStartOfLine = atStartOfLine;
2595 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002596
Chris Lattner678c8802006-07-11 05:46:12 +00002597 // Restore the lexer back to non-skipping mode.
2598 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002599
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002600 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002601 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002602 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002603}
2604
James Dennettf442d242012-06-17 03:40:43 +00002605/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002606static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2607 ConflictMarkerKind CMK) {
2608 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2609 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2610 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2611 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002612 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002613 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002614 if (Pos == 0 ||
2615 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002616 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2617 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002618 continue;
2619 }
2620 return RestOfBuffer.data()+Pos;
2621 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002622 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002623}
2624
2625/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2626/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2627/// and recover nicely. This returns true if it is a conflict marker and false
2628/// if not.
2629bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2630 // Only a conflict marker if it starts at the beginning of a line.
2631 if (CurPtr != BufferStart &&
2632 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2633 return false;
2634
Richard Smitha9e33d42011-10-12 00:37:51 +00002635 // Check to see if we have <<<<<<< or >>>>.
2636 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2637 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002638 return false;
2639
2640 // If we have a situation where we don't care about conflict markers, ignore
2641 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002642 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002643 return false;
2644
Richard Smitha9e33d42011-10-12 00:37:51 +00002645 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2646
2647 // Check to see if there is an ending marker somewhere in the buffer at the
2648 // start of a line to terminate this conflict marker.
2649 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002650 // We found a match. We are really in a conflict marker.
2651 // Diagnose this, and ignore to the end of line.
2652 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002653 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002654
2655 // Skip ahead to the end of line. We know this exists because the
2656 // end-of-conflict marker starts with \r or \n.
2657 while (*CurPtr != '\r' && *CurPtr != '\n') {
2658 assert(CurPtr != BufferEnd && "Didn't find end of line");
2659 ++CurPtr;
2660 }
2661 BufferPtr = CurPtr;
2662 return true;
2663 }
2664
2665 // No end of conflict marker found.
2666 return false;
2667}
2668
2669
Richard Smitha9e33d42011-10-12 00:37:51 +00002670/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2671/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2672/// is the end of a conflict marker. Handle it by ignoring up until the end of
2673/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002674bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2675 // Only a conflict marker if it starts at the beginning of a line.
2676 if (CurPtr != BufferStart &&
2677 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2678 return false;
2679
2680 // If we have a situation where we don't care about conflict markers, ignore
2681 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002682 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002683 return false;
2684
Richard Smitha9e33d42011-10-12 00:37:51 +00002685 // Check to see if we have the marker (4 characters in a row).
2686 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002687 if (CurPtr[i] != CurPtr[0])
2688 return false;
2689
2690 // If we do have it, search for the end of the conflict marker. This could
2691 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2692 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002693 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2694 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002695 CurPtr = End;
2696
2697 // Skip ahead to the end of line.
2698 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2699 ++CurPtr;
2700
2701 BufferPtr = CurPtr;
2702
2703 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002704 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002705 return true;
2706 }
2707
2708 return false;
2709}
2710
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002711bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2712 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002713 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002714 return Loc == PP->getCodeCompletionLoc();
2715 }
2716
2717 return false;
2718}
2719
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002720uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2721 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002722 unsigned CharSize;
2723 char Kind = getCharAndSize(StartPtr, CharSize);
2724
2725 unsigned NumHexDigits;
2726 if (Kind == 'u')
2727 NumHexDigits = 4;
2728 else if (Kind == 'U')
2729 NumHexDigits = 8;
2730 else
2731 return 0;
2732
Jordan Rosec0cba272013-01-27 20:12:04 +00002733 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002734 if (Result && !isLexingRawMode())
2735 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002736 return 0;
2737 }
2738
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002739 const char *CurPtr = StartPtr + CharSize;
2740 const char *KindLoc = &CurPtr[-1];
2741
2742 uint32_t CodePoint = 0;
2743 for (unsigned i = 0; i < NumHexDigits; ++i) {
2744 char C = getCharAndSize(CurPtr, CharSize);
2745
2746 unsigned Value = llvm::hexDigitValue(C);
2747 if (Value == -1U) {
2748 if (Result && !isLexingRawMode()) {
2749 if (i == 0) {
2750 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2751 << StringRef(KindLoc, 1);
2752 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002753 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002754
2755 // If the user wrote \U1234, suggest a fixit to \u.
2756 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002757 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002758 Diag(KindLoc, diag::note_ucn_four_not_eight)
2759 << FixItHint::CreateReplacement(URange, "u");
2760 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002761 }
2762 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002763
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002764 return 0;
2765 }
2766
2767 CodePoint <<= 4;
2768 CodePoint += Value;
2769
2770 CurPtr += CharSize;
2771 }
2772
2773 if (Result) {
2774 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002775 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002776 StartPtr = CurPtr;
2777 else
2778 while (StartPtr != CurPtr)
2779 (void)getAndAdvanceChar(StartPtr, *Result);
2780 } else {
2781 StartPtr = CurPtr;
2782 }
2783
Justin Bogner53535132013-10-21 05:02:28 +00002784 // Don't apply C family restrictions to UCNs in assembly mode
2785 if (LangOpts.AsmPreprocessor)
2786 return CodePoint;
2787
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002788 // C99 6.4.3p2: A universal character name shall not specify a character whose
2789 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2790 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2791 // C++11 [lex.charset]p2: If the hexadecimal value for a
2792 // universal-character-name corresponds to a surrogate code point (in the
2793 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2794 // if the hexadecimal value for a universal-character-name outside the
2795 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2796 // string literal corresponds to a control character (in either of the
2797 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2798 // basic source character set, the program is ill-formed.
2799 if (CodePoint < 0xA0) {
2800 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2801 return CodePoint;
2802
2803 // We don't use isLexingRawMode() here because we need to warn about bad
2804 // UCNs even when skipping preprocessing tokens in a #if block.
2805 if (Result && PP) {
2806 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2807 Diag(BufferPtr, diag::err_ucn_control_character);
2808 else {
2809 char C = static_cast<char>(CodePoint);
2810 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2811 }
2812 }
2813
2814 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002815
2816 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002817 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002818 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002819 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002820 if (Result && PP) {
2821 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2822 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2823 else
2824 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2825 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002826 return 0;
2827 }
2828
2829 return CodePoint;
2830}
2831
Eli Friedman0834a4b2013-09-19 00:41:32 +00002832bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2833 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002834 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2835 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002836 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002837 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002838 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002839 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002840
2841 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002842 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002843 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002844 return false;
2845}
Jordan Rose4246ae02013-01-24 20:50:50 +00002846
Eli Friedman0834a4b2013-09-19 00:41:32 +00002847bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002848 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2849 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2850 !PP->isPreprocessedOutput()) {
2851 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2852 makeCharRange(*this, BufferPtr, CurPtr),
2853 /*IsFirst=*/true);
2854 }
2855
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002856 MIOpt.ReadToken();
2857 return LexIdentifier(Result, CurPtr);
2858 }
2859
Jordan Rosecc538342013-01-31 19:48:48 +00002860 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2861 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002862 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002863 // Non-ASCII characters tend to creep into source code unintentionally.
2864 // Instead of letting the parser complain about the unknown token,
2865 // just drop the character.
2866 // Note that we can /only/ do this when the non-ASCII character is actually
2867 // spelled as Unicode, not written as a UCN. The standard requires that
2868 // we not throw away any possible preprocessor tokens, but there's a
2869 // loophole in the mapping of Unicode characters to basic character set
2870 // characters that allows us to map these particular characters to, say,
2871 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002872 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002873 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002874
2875 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002876 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002877 }
2878
2879 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2880 // up by accident.
2881 MIOpt.ReadToken();
2882 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002883 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002884}
2885
Eli Friedman0834a4b2013-09-19 00:41:32 +00002886void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2887 IsAtStartOfLine = Result.isAtStartOfLine();
2888 HasLeadingSpace = Result.hasLeadingSpace();
2889 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2890 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2891}
2892
2893bool Lexer::Lex(Token &Result) {
2894 // Start a new token.
2895 Result.startToken();
2896
2897 // Set up misc whitespace flags for LexTokenInternal.
2898 if (IsAtStartOfLine) {
2899 Result.setFlag(Token::StartOfLine);
2900 IsAtStartOfLine = false;
2901 }
2902
2903 if (HasLeadingSpace) {
2904 Result.setFlag(Token::LeadingSpace);
2905 HasLeadingSpace = false;
2906 }
2907
2908 if (HasLeadingEmptyMacro) {
2909 Result.setFlag(Token::LeadingEmptyMacro);
2910 HasLeadingEmptyMacro = false;
2911 }
2912
2913 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2914 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002915 bool isRawLex = isLexingRawMode();
2916 (void) isRawLex;
2917 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2918 // (After the LexTokenInternal call, the lexer might be destroyed.)
2919 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2920 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002921}
Chris Lattner22eb9722006-06-18 05:43:12 +00002922
2923/// LexTokenInternal - This implements a simple C family lexer. It is an
2924/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002925/// has a null character at the end of the file. This returns a preprocessing
2926/// token, not a normal token, as such, it is an internal interface. It assumes
2927/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002928bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002929LexNextToken:
2930 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002931 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002932 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002933
Chris Lattner22eb9722006-06-18 05:43:12 +00002934 // CurPtr - Cache BufferPtr in an automatic variable.
2935 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002936
Chris Lattnereb54b592006-07-10 06:34:27 +00002937 // Small amounts of horizontal whitespace is very common between tokens.
2938 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2939 ++CurPtr;
2940 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2941 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Chris Lattner4d963442008-10-12 04:05:48 +00002943 // If we are keeping whitespace and other tokens, just return what we just
2944 // skipped. The next lexer invocation will return the token after the
2945 // whitespace.
2946 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002947 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002948 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002949 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002950 }
Mike Stump11289f42009-09-09 15:08:12 +00002951
Chris Lattnereb54b592006-07-10 06:34:27 +00002952 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002953 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Chris Lattner22eb9722006-06-18 05:43:12 +00002956 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002957
Chris Lattner22eb9722006-06-18 05:43:12 +00002958 // Read a character, advancing over it.
2959 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002960 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002961
Chris Lattner22eb9722006-06-18 05:43:12 +00002962 switch (Char) {
2963 case 0: // Null.
2964 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002965 if (CurPtr-1 == BufferEnd)
2966 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002968 // Check if we are performing code completion.
2969 if (isCodeCompletionPoint(CurPtr-1)) {
2970 // Return the code-completion token.
2971 Result.startToken();
2972 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002973 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002974 }
2975
Chris Lattner6d27a162008-11-22 02:02:22 +00002976 if (!isLexingRawMode())
2977 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002978 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002979 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2980 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002981
Eli Friedman0834a4b2013-09-19 00:41:32 +00002982 // We know the lexer hasn't changed, so just try again with this lexer.
2983 // (We manually eliminate the tail call to avoid recursion.)
2984 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002985
2986 case 26: // DOS & CP/M EOF: "^Z".
2987 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00002988 if (LangOpts.MicrosoftExt) {
2989 if (!isLexingRawMode())
2990 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002991 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00002992 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002993
Chris Lattner3dfff972009-12-17 05:29:40 +00002994 // If Microsoft extensions are disabled, this is just random garbage.
2995 Kind = tok::unknown;
2996 break;
2997
Chris Lattner22eb9722006-06-18 05:43:12 +00002998 case '\n':
2999 case '\r':
3000 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003001 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003002 if (ParsingPreprocessorDirective) {
3003 // Done parsing the "line".
3004 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattner457fc152006-07-29 06:30:25 +00003006 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003007 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003008 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003009
Chris Lattner22eb9722006-06-18 05:43:12 +00003010 // Since we consumed a newline, we are back at the start of a line.
3011 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003012 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003013
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003014 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003015 break;
3016 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003017
Chris Lattner22eb9722006-06-18 05:43:12 +00003018 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003019 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003020
Eli Friedman0834a4b2013-09-19 00:41:32 +00003021 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3022 return true; // KeepWhitespaceMode
3023
3024 // We only saw whitespace, so just try again with this lexer.
3025 // (We manually eliminate the tail call to avoid recursion.)
3026 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003027 case ' ':
3028 case '\t':
3029 case '\f':
3030 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003031 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003032 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003033 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3034 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003035
3036 SkipIgnoredUnits:
3037 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003038
Chris Lattnerb9b85972007-07-22 06:29:05 +00003039 // If the next token is obviously a // or /* */ comment, skip it efficiently
3040 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003041 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003042 LangOpts.LineComment &&
3043 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003044 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3045 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003046 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003047 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003048 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3049 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003050 goto SkipIgnoredUnits;
3051 } else if (isHorizontalWhitespace(*CurPtr)) {
3052 goto SkipHorizontalWhitespace;
3053 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003054 // We only saw whitespace, so just try again with this lexer.
3055 // (We manually eliminate the tail call to avoid recursion.)
3056 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003057
Chris Lattner2b15cf72008-01-03 17:58:54 +00003058 // C99 6.4.4.1: Integer Constants.
3059 // C99 6.4.4.2: Floating Constants.
3060 case '0': case '1': case '2': case '3': case '4':
3061 case '5': case '6': case '7': case '8': case '9':
3062 // Notify MIOpt that we read a non-whitespace/non-comment token.
3063 MIOpt.ReadToken();
3064 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003065
Richard Smith9b362092013-03-09 23:56:02 +00003066 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003067 // Notify MIOpt that we read a non-whitespace/non-comment token.
3068 MIOpt.ReadToken();
3069
Richard Smith9b362092013-03-09 23:56:02 +00003070 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003071 Char = getCharAndSize(CurPtr, SizeTmp);
3072
3073 // UTF-16 string literal
3074 if (Char == '"')
3075 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3076 tok::utf16_string_literal);
3077
3078 // UTF-16 character constant
3079 if (Char == '\'')
3080 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3081 tok::utf16_char_constant);
3082
Craig Topper54edcca2011-08-11 04:06:15 +00003083 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003084 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3085 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003086 return LexRawStringLiteral(Result,
3087 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3088 SizeTmp2, Result),
3089 tok::utf16_string_literal);
3090
3091 if (Char == '8') {
3092 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3093
3094 // UTF-8 string literal
3095 if (Char2 == '"')
3096 return LexStringLiteral(Result,
3097 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3098 SizeTmp2, Result),
3099 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003100 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3101 return LexCharConstant(
3102 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3103 SizeTmp2, Result),
3104 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003105
Richard Smith9b362092013-03-09 23:56:02 +00003106 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003107 unsigned SizeTmp3;
3108 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3109 // UTF-8 raw string literal
3110 if (Char3 == '"') {
3111 return LexRawStringLiteral(Result,
3112 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3113 SizeTmp2, Result),
3114 SizeTmp3, Result),
3115 tok::utf8_string_literal);
3116 }
3117 }
3118 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003119 }
3120
3121 // treat u like the start of an identifier.
3122 return LexIdentifier(Result, CurPtr);
3123
Richard Smith9b362092013-03-09 23:56:02 +00003124 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003125 // Notify MIOpt that we read a non-whitespace/non-comment token.
3126 MIOpt.ReadToken();
3127
Richard Smith9b362092013-03-09 23:56:02 +00003128 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003129 Char = getCharAndSize(CurPtr, SizeTmp);
3130
3131 // UTF-32 string literal
3132 if (Char == '"')
3133 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3134 tok::utf32_string_literal);
3135
3136 // UTF-32 character constant
3137 if (Char == '\'')
3138 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3139 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003140
3141 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003142 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3143 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003144 return LexRawStringLiteral(Result,
3145 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3146 SizeTmp2, Result),
3147 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003148 }
3149
3150 // treat U like the start of an identifier.
3151 return LexIdentifier(Result, CurPtr);
3152
Craig Topper54edcca2011-08-11 04:06:15 +00003153 case 'R': // Identifier or C++0x raw string literal
3154 // Notify MIOpt that we read a non-whitespace/non-comment token.
3155 MIOpt.ReadToken();
3156
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003157 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003158 Char = getCharAndSize(CurPtr, SizeTmp);
3159
3160 if (Char == '"')
3161 return LexRawStringLiteral(Result,
3162 ConsumeChar(CurPtr, SizeTmp, Result),
3163 tok::string_literal);
3164 }
3165
3166 // treat R like the start of an identifier.
3167 return LexIdentifier(Result, CurPtr);
3168
Chris Lattner2b15cf72008-01-03 17:58:54 +00003169 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003170 // Notify MIOpt that we read a non-whitespace/non-comment token.
3171 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003172 Char = getCharAndSize(CurPtr, SizeTmp);
3173
3174 // Wide string literal.
3175 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003176 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003177 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003178
Craig Topper54edcca2011-08-11 04:06:15 +00003179 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003180 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003181 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3182 return LexRawStringLiteral(Result,
3183 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3184 SizeTmp2, Result),
3185 tok::wide_string_literal);
3186
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 // Wide character constant.
3188 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003189 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3190 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003191 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003192
Chris Lattner22eb9722006-06-18 05:43:12 +00003193 // C99 6.4.2: Identifiers.
3194 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3195 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003196 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003197 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3198 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3199 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003200 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003201 case 'v': case 'w': case 'x': case 'y': case 'z':
3202 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003203 // Notify MIOpt that we read a non-whitespace/non-comment token.
3204 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003205 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003206
3207 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003208 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003209 if (!isLexingRawMode())
3210 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003211 // Notify MIOpt that we read a non-whitespace/non-comment token.
3212 MIOpt.ReadToken();
3213 return LexIdentifier(Result, CurPtr);
3214 }
Mike Stump11289f42009-09-09 15:08:12 +00003215
Chris Lattnerb11c3232008-10-12 04:51:35 +00003216 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003217 break;
Mike Stump11289f42009-09-09 15:08:12 +00003218
Chris Lattner22eb9722006-06-18 05:43:12 +00003219 // C99 6.4.4: Character Constants.
3220 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003221 // Notify MIOpt that we read a non-whitespace/non-comment token.
3222 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003223 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003224
3225 // C99 6.4.5: String Literals.
3226 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003227 // Notify MIOpt that we read a non-whitespace/non-comment token.
3228 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003229 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003230
3231 // C99 6.4.6: Punctuators.
3232 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003233 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003234 break;
3235 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003236 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003237 break;
3238 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003239 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003240 break;
3241 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003242 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003243 break;
3244 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003245 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003246 break;
3247 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003248 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003249 break;
3250 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003251 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003252 break;
3253 case '.':
3254 Char = getCharAndSize(CurPtr, SizeTmp);
3255 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003256 // Notify MIOpt that we read a non-whitespace/non-comment token.
3257 MIOpt.ReadToken();
3258
Chris Lattner22eb9722006-06-18 05:43:12 +00003259 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003260 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003261 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003262 CurPtr += SizeTmp;
3263 } else if (Char == '.' &&
3264 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003265 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3267 SizeTmp2, Result);
3268 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003269 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003270 }
3271 break;
3272 case '&':
3273 Char = getCharAndSize(CurPtr, SizeTmp);
3274 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003275 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003276 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3277 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003278 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003279 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3280 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003281 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003282 }
3283 break;
Mike Stump11289f42009-09-09 15:08:12 +00003284 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003285 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003286 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003287 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3288 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003289 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003290 }
3291 break;
3292 case '+':
3293 Char = getCharAndSize(CurPtr, SizeTmp);
3294 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003296 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003297 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003299 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003300 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003301 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003302 }
3303 break;
3304 case '-':
3305 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003306 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003307 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003308 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003309 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003310 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003311 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3312 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003313 Kind = tok::arrowstar;
3314 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003315 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003316 Kind = tok::arrow;
3317 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003319 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003320 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003321 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003322 }
3323 break;
3324 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003325 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003326 break;
3327 case '!':
3328 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3331 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003332 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003333 }
3334 break;
3335 case '/':
3336 // 6.4.9: Comments
3337 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003338 if (Char == '/') { // Line comment.
3339 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003340 // want to lex this as a comment. There is one problem with this though,
3341 // that in one particular corner case, this can change the behavior of the
3342 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003343 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003344 // "foo". Check to see if the character after the second slash is a '*'.
3345 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003346 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003347 bool TreatAsComment = LangOpts.LineComment &&
3348 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003349 if (!TreatAsComment)
3350 if (!(PP && PP->isPreprocessedOutput()))
3351 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3352
3353 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003354 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3355 TokAtPhysicalStartOfLine))
3356 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003357
Chris Lattner58827712009-01-16 22:39:25 +00003358 // It is common for the tokens immediately after a // comment to be
3359 // whitespace (indentation for the next line). Instead of going through
3360 // the big switch, handle it efficiently now.
3361 goto SkipIgnoredUnits;
3362 }
3363 }
Mike Stump11289f42009-09-09 15:08:12 +00003364
Chris Lattner58827712009-01-16 22:39:25 +00003365 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003366 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3367 TokAtPhysicalStartOfLine))
3368 return true; // There is a token to return.
3369
3370 // We only saw whitespace, so just try again with this lexer.
3371 // (We manually eliminate the tail call to avoid recursion.)
3372 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003373 }
Mike Stump11289f42009-09-09 15:08:12 +00003374
Chris Lattner58827712009-01-16 22:39:25 +00003375 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003376 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003378 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003379 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003380 }
3381 break;
3382 case '%':
3383 Char = getCharAndSize(CurPtr, SizeTmp);
3384 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003385 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003387 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003388 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003390 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003392 Char = getCharAndSize(CurPtr, SizeTmp);
3393 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003394 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003395 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3396 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003397 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003398 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003399 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003400 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003401 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003402 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003403 // We parsed a # character. If this occurs at the start of the line,
3404 // it's actually the start of a preprocessing directive. Callback to
3405 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003406 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003407 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003408 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Chris Lattner2534324a2009-03-18 20:58:27 +00003410 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 }
3412 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003413 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003414 }
3415 break;
3416 case '<':
3417 Char = getCharAndSize(CurPtr, SizeTmp);
3418 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003419 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003420 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003421 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3422 if (After == '=') {
3423 Kind = tok::lesslessequal;
3424 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3425 SizeTmp2, Result);
3426 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3427 // If this is actually a '<<<<<<<' version control conflict marker,
3428 // recognize it as such and recover nicely.
3429 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003430 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3431 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3432 // ignore it.
3433 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003434 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003435 Kind = tok::lesslessless;
3436 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3437 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003438 } else {
3439 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3440 Kind = tok::lessless;
3441 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003442 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003443 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003444 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003445 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003446 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003447 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3448 // C++0x [lex.pptoken]p3:
3449 // Otherwise, if the next three characters are <:: and the subsequent
3450 // character is neither : nor >, the < is treated as a preprocessor
3451 // token by itself and not as the first character of the alternative
3452 // token <:.
3453 unsigned SizeTmp3;
3454 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3455 if (After != ':' && After != '>') {
3456 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003457 if (!isLexingRawMode())
3458 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003459 break;
3460 }
3461 }
3462
Chris Lattner22eb9722006-06-18 05:43:12 +00003463 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003464 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003465 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003467 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003468 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003469 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003470 }
3471 break;
3472 case '>':
3473 Char = getCharAndSize(CurPtr, SizeTmp);
3474 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003475 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003476 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003477 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003478 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3479 if (After == '=') {
3480 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3481 SizeTmp2, Result);
3482 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003483 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3484 // If this is actually a '>>>>' conflict marker, recognize it as such
3485 // and recover nicely.
3486 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003487 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3488 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3489 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003490 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003491 Kind = tok::greatergreatergreater;
3492 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3493 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003494 } else {
3495 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3496 Kind = tok::greatergreater;
3497 }
3498
Chris Lattner22eb9722006-06-18 05:43:12 +00003499 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003500 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003501 }
3502 break;
3503 case '^':
3504 Char = getCharAndSize(CurPtr, SizeTmp);
3505 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003506 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003507 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003508 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003509 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003510 }
3511 break;
3512 case '|':
3513 Char = getCharAndSize(CurPtr, SizeTmp);
3514 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003515 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3517 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003518 // If this is '|||||||' and we're in a conflict marker, ignore it.
3519 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3520 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003521 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3523 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003524 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003525 }
3526 break;
3527 case ':':
3528 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003529 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003530 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003531 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003532 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003533 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003534 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003535 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003536 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003537 }
3538 break;
3539 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003540 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003541 break;
3542 case '=':
3543 Char = getCharAndSize(CurPtr, SizeTmp);
3544 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003545 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003546 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3547 goto LexNextToken;
3548
Chris Lattnerb11c3232008-10-12 04:51:35 +00003549 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003550 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003551 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003552 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003553 }
3554 break;
3555 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003556 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003557 break;
3558 case '#':
3559 Char = getCharAndSize(CurPtr, SizeTmp);
3560 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003561 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003563 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003564 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003565 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003566 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003567 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003568 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003569 // We parsed a # character. If this occurs at the start of the line,
3570 // it's actually the start of a preprocessing directive. Callback to
3571 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003572 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003573 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003574 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003575
Chris Lattner2534324a2009-03-18 20:58:27 +00003576 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003577 }
3578 break;
3579
Chris Lattner2b15cf72008-01-03 17:58:54 +00003580 case '@':
3581 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003582 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003583 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003584 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003585 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003586 break;
Mike Stump11289f42009-09-09 15:08:12 +00003587
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003588 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003589 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003590 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3591 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3592 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3593 return true; // KeepWhitespaceMode
3594
3595 // We only saw whitespace, so just try again with this lexer.
3596 // (We manually eliminate the tail call to avoid recursion.)
3597 goto LexNextToken;
3598 }
3599
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003600 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003601 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003602
Chris Lattnerb11c3232008-10-12 04:51:35 +00003603 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003604 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003605
3606 default: {
3607 if (isASCII(Char)) {
3608 Kind = tok::unknown;
3609 break;
3610 }
3611
3612 UTF32 CodePoint;
3613
3614 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3615 // an escaped newline.
3616 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003617 ConversionResult Status =
3618 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3619 (const UTF8 *)BufferEnd,
3620 &CodePoint,
3621 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003622 if (Status == conversionOK) {
3623 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3624 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3625 return true; // KeepWhitespaceMode
3626
3627 // We only saw whitespace, so just try again with this lexer.
3628 // (We manually eliminate the tail call to avoid recursion.)
3629 goto LexNextToken;
3630 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003631 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003632 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003633
Jordan Rosecc538342013-01-31 19:48:48 +00003634 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3635 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003636 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003637 Kind = tok::unknown;
3638 break;
3639 }
3640
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003641 // Non-ASCII characters tend to creep into source code unintentionally.
3642 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003643 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003644 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003645
3646 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003647 // We're pretending the character didn't exist, so just try again with
3648 // this lexer.
3649 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003650 goto LexNextToken;
3651 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003652 }
Mike Stump11289f42009-09-09 15:08:12 +00003653
Chris Lattner371ac8a2006-07-04 07:11:10 +00003654 // Notify MIOpt that we read a non-whitespace/non-comment token.
3655 MIOpt.ReadToken();
3656
Chris Lattnerd01e2912006-06-18 16:22:51 +00003657 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003658 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003659 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003660
3661HandleDirective:
3662 // We parsed a # character and it's the start of a preprocessing directive.
3663
3664 FormTokenWithChars(Result, CurPtr, tok::hash);
3665 PP->HandleDirective(Result);
3666
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003667 if (PP->hadModuleLoaderFatalFailure()) {
3668 // With a fatal failure in the module loader, we abort parsing.
3669 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003670 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003671 }
3672
Eli Friedman0834a4b2013-09-19 00:41:32 +00003673 // We parsed the directive; lex a token with the new state.
3674 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003675}