blob: 7d2869bb87cd60d5a986ad45b0ddd6ea09443362 [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//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000028#include "clang/Basic/CharInfo.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000029#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/CodeCompletionHandler.h"
31#include "clang/Lex/LexDiagnostic.h"
32#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Chris Lattner739e7392007-04-29 07:12:06 +000038#include "llvm/Support/MemoryBuffer.h"
Jordan Rose58c61e02013-02-09 01:10:25 +000039#include "UnicodeCharSets.h"
Craig Topper54edcca2011-08-11 04:06:15 +000040#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000041using namespace clang;
42
Chris Lattner4894f482007-10-07 08:47:24 +000043//===----------------------------------------------------------------------===//
44// Token Class Implementation
45//===----------------------------------------------------------------------===//
46
Mike Stump11289f42009-09-09 15:08:12 +000047/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000048bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000052}
53
54/// getObjCKeywordID - Return the ObjC keyword kind.
55tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 IdentifierInfo *specId = getIdentifierInfo();
57 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
58}
59
Chris Lattner67671ed2007-12-13 01:59:49 +000060
Chris Lattner4894f482007-10-07 08:47:24 +000061//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie68e081d2011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump11289f42009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattnerf76b9202009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000076
Eric Christopher7f36a792011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattnerf76b9202009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000093
Chris Lattnerf76b9202009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +000096
Chris Lattnerf76b9202009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000099
Chris Lattnerf76b9202009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattnerf76b9202009-01-17 06:55:17 +0000103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerf76b9202009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner5965a282009-01-17 07:56:59 +0000113/// Lexer constructor - Create a new lexer object for the specified buffer
114/// with the specified preprocessor managing the lexing process. This lexer
115/// assumes that the associated file buffer and Preprocessor objects will
116/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000121
Chris Lattner5965a282009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000124
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000125 resetExtendedTokenMode();
126}
127
128void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
132 else
133 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000134}
Chris Lattner4894f482007-10-07 08:47:24 +0000135
Chris Lattner02b436a2007-10-17 20:41:00 +0000136/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000137/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000138/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000139Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000140 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000141 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000142
Chris Lattnerf76b9202009-01-17 06:55:17 +0000143 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattner02b436a2007-10-17 20:41:00 +0000145 // We *are* in raw mode.
146 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000147}
148
Chris Lattner08354fe2009-01-17 07:35:14 +0000149/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000150/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000151/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000152Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000153 const SourceManager &SM, const LangOptions &langOpts)
154 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000155
Mike Stump11289f42009-09-09 15:08:12 +0000156 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000157 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000158
Chris Lattner08354fe2009-01-17 07:35:14 +0000159 // We *are* in raw mode.
160 LexingRawMode = true;
161}
162
Chris Lattner757169b2009-01-17 08:27:52 +0000163/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
164/// _Pragma expansion. This has a variety of magic semantics that this method
165/// sets up. It returns a new'd Lexer that must be delete'd when done.
166///
167/// On entrance to this routine, TokStartLoc is a macro location which has a
168/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000169/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000170/// "expanded from".
171///
172/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
173/// normal lexer that remaps tokens as they fly by. This would require making
174/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
175/// interface that could handle this stuff. This would pull GetMappedTokenLoc
176/// out of the critical path of the lexer!
177///
Mike Stump11289f42009-09-09 15:08:12 +0000178Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000179 SourceLocation ExpansionLocStart,
180 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000181 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000182 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000183
184 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000185 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000186 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
187 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner757169b2009-01-17 08:27:52 +0000189 // Now that the lexer is created, change the start/end locations so that we
190 // just lex the subsection of the file that we want. This is lexing from a
191 // scratch buffer.
192 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner757169b2009-01-17 08:27:52 +0000194 L->BufferPtr = StrData;
195 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000196 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000197
198 // Set the SourceLocation with the remapping information. This ensures that
199 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000200 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
201 ExpansionLocStart,
202 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner757169b2009-01-17 08:27:52 +0000204 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000205 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000206 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattner757169b2009-01-17 08:27:52 +0000208 // This lexer really is for _Pragma.
209 L->Is_PragmaLexer = true;
210 return L;
211}
212
Chris Lattner02b436a2007-10-17 20:41:00 +0000213
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000214/// Stringify - Convert the specified string into a C string, with surrounding
215/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000216std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000217 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000218 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000219 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000220 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000221 Result.insert(Result.begin()+i, '\\');
222 ++i; ++e;
223 }
224 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000225 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000226}
227
Chris Lattner4c4a2452007-07-24 06:57:14 +0000228/// Stringify - Convert the specified string into a C string by escaping '\'
229/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000230void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000231 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
232 if (Str[i] == '\\' || Str[i] == '"') {
233 Str.insert(Str.begin()+i, '\\');
234 ++i; ++e;
235 }
236 }
237}
238
Chris Lattner39720112010-11-17 07:26:20 +0000239//===----------------------------------------------------------------------===//
240// Token Spelling
241//===----------------------------------------------------------------------===//
242
Richard Smith9a67f472012-11-28 07:29:00 +0000243/// \brief Slow case of getSpelling. Extract the characters comprising the
244/// spelling of this token from the provided input buffer.
245static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
246 const LangOptions &LangOpts, char *Spelling) {
247 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
248
249 size_t Length = 0;
250 const char *BufEnd = BufPtr + Tok.getLength();
251
252 if (Tok.is(tok::string_literal)) {
253 // Munch the encoding-prefix and opening double-quote.
254 while (BufPtr < BufEnd) {
255 unsigned Size;
256 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
257 BufPtr += Size;
258
259 if (Spelling[Length - 1] == '"')
260 break;
261 }
262
263 // Raw string literals need special handling; trigraph expansion and line
264 // splicing do not occur within their d-char-sequence nor within their
265 // r-char-sequence.
266 if (Length >= 2 &&
267 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
268 // Search backwards from the end of the token to find the matching closing
269 // quote.
270 const char *RawEnd = BufEnd;
271 do --RawEnd; while (*RawEnd != '"');
272 size_t RawLength = RawEnd - BufPtr + 1;
273
274 // Everything between the quotes is included verbatim in the spelling.
275 memcpy(Spelling + Length, BufPtr, RawLength);
276 Length += RawLength;
277 BufPtr += RawLength;
278
279 // The rest of the token is lexed normally.
280 }
281 }
282
283 while (BufPtr < BufEnd) {
284 unsigned Size;
285 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
286 BufPtr += Size;
287 }
288
289 assert(Length < Tok.getLength() &&
290 "NeedsCleaning flag set on token that didn't need cleaning!");
291 return Length;
292}
293
Chris Lattner39720112010-11-17 07:26:20 +0000294/// getSpelling() - Return the 'spelling' of this token. The spelling of a
295/// token are the characters used to represent the token in the source file
296/// after trigraph expansion and escaped-newline folding. In particular, this
297/// wants to get the true, uncanonicalized, spelling of things like digraphs
298/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000300 SmallVectorImpl<char> &buffer,
301 const SourceManager &SM,
302 const LangOptions &options,
303 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000304 // Break down the source location.
305 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
306
307 // Try to the load the file buffer.
308 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000310 if (invalidTemp) {
311 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000313 }
314
315 const char *tokenBegin = file.data() + locInfo.second;
316
317 // Lex from the start of the given location.
318 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
319 file.begin(), tokenBegin, file.end());
320 Token token;
321 lexer.LexFromRawLexer(token);
322
323 unsigned length = token.getLength();
324
325 // Common case: no need for cleaning.
326 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000328
Richard Smith9a67f472012-11-28 07:29:00 +0000329 // Hard case, we need to relex the characters into the string.
330 buffer.resize(length);
331 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000333}
334
335/// getSpelling() - Return the 'spelling' of this token. The spelling of a
336/// token are the characters used to represent the token in the source file
337/// after trigraph expansion and escaped-newline folding. In particular, this
338/// wants to get the true, uncanonicalized, spelling of things like digraphs
339/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000340std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000341 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000342 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000343
Chris Lattner39720112010-11-17 07:26:20 +0000344 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000345 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000346 &CharDataInvalid);
347 if (Invalid)
348 *Invalid = CharDataInvalid;
349 if (CharDataInvalid)
350 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000351
352 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000353 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000354 return std::string(TokStart, TokStart + Tok.getLength());
355
Chris Lattner39720112010-11-17 07:26:20 +0000356 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000357 Result.resize(Tok.getLength());
358 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000359 return Result;
360}
361
362/// getSpelling - This method is used to get the spelling of a token into a
363/// preallocated buffer, instead of as an std::string. The caller is required
364/// to allocate enough space for the token, which is guaranteed to be at least
365/// Tok.getLength() bytes long. The actual length of the token is returned.
366///
367/// Note that this method may do two possible things: it may either fill in
368/// the buffer specified with characters, or it may *change the input pointer*
369/// to point to a constant buffer with the data already in it (avoiding a
370/// copy). The caller is not allowed to modify the returned buffer pointer
371/// if an internal buffer is returned.
372unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
373 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000374 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000375 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000376
377 const char *TokStart = 0;
378 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
379 if (Tok.is(tok::raw_identifier))
380 TokStart = Tok.getRawIdentifierData();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000381 else if (!Tok.hasUCN()) {
382 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
383 // Just return the string from the identifier table, which is very quick.
384 Buffer = II->getNameStart();
385 return II->getLength();
386 }
Chris Lattner39720112010-11-17 07:26:20 +0000387 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000388
389 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000390 if (Tok.isLiteral())
391 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392
Chris Lattner39720112010-11-17 07:26:20 +0000393 if (TokStart == 0) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000394 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000395 bool CharDataInvalid = false;
396 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
397 if (Invalid)
398 *Invalid = CharDataInvalid;
399 if (CharDataInvalid) {
400 Buffer = "";
401 return 0;
402 }
403 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000404
Chris Lattner39720112010-11-17 07:26:20 +0000405 // If this token contains nothing interesting, return it directly.
406 if (!Tok.needsCleaning()) {
407 Buffer = TokStart;
408 return Tok.getLength();
409 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000410
Chris Lattner39720112010-11-17 07:26:20 +0000411 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000412 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000413}
414
415
Chris Lattner8e129c22007-10-17 21:18:47 +0000416/// MeasureTokenLength - Relex the token at the specified location and return
417/// its length in bytes in the input file. If the token needs cleaning (e.g.
418/// includes a trigraph or an escaped newline) then this count includes bytes
419/// that are part of that.
420unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000423 Token TheTok;
424 if (getRawToken(Loc, TheTok, SM, LangOpts))
425 return 0;
426 return TheTok.getLength();
427}
428
429/// \brief Relex the token at the specified location.
430/// \returns true if there was a failure, false on success.
431bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
432 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000433 const LangOptions &LangOpts,
434 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000435 // TODO: this could be special cased for common tokens like identifiers, ')',
436 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000437 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000438 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
439 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000440
441 // If this comes from a macro expansion, we really do want the macro name, not
442 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000443 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000444 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000445 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000446 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000447 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000448 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000449
450 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000451
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000452 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000453 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000454
Chris Lattner8e129c22007-10-17 21:18:47 +0000455 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000456 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
457 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000458 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000459 TheLexer.LexFromRawLexer(Result);
460 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000461}
462
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000463static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
464 const SourceManager &SM,
465 const LangOptions &LangOpts) {
466 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000467 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000468 if (LocInfo.first.isInvalid())
469 return Loc;
470
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000471 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000472 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000473 if (Invalid)
474 return Loc;
475
476 // Back up from the current location until we hit the beginning of a line
477 // (or the buffer). We'll relex from that point.
478 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000479 if (LocInfo.second >= Buffer.size())
480 return Loc;
481
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000482 const char *StrData = BufStart+LocInfo.second;
483 if (StrData[0] == '\n' || StrData[0] == '\r')
484 return Loc;
485
486 const char *LexStart = StrData;
487 while (LexStart != BufStart) {
488 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
489 ++LexStart;
490 break;
491 }
492
493 --LexStart;
494 }
495
496 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000497 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000498 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
499 TheLexer.SetCommentRetentionState(true);
500
501 // Lex tokens until we find the token that contains the source location.
502 Token TheTok;
503 do {
504 TheLexer.LexFromRawLexer(TheTok);
505
506 if (TheLexer.getBufferLocation() > StrData) {
507 // Lexing this token has taken the lexer past the source location we're
508 // looking for. If the current token encompasses our source location,
509 // return the beginning of that token.
510 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
511 return TheTok.getLocation();
512
513 // We ended up skipping over the source location entirely, which means
514 // that it points into whitespace. We're done here.
515 break;
516 }
517 } while (TheTok.getKind() != tok::eof);
518
519 // We've passed our source location; just return the original source location.
520 return Loc;
521}
522
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000523SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
524 const SourceManager &SM,
525 const LangOptions &LangOpts) {
526 if (Loc.isFileID())
527 return getBeginningOfFileToken(Loc, SM, LangOpts);
528
529 if (!SM.isMacroArgExpansion(Loc))
530 return Loc;
531
532 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
533 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
534 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000535 std::pair<FileID, unsigned> BeginFileLocInfo
536 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000537 assert(FileLocInfo.first == BeginFileLocInfo.first &&
538 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000539 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000540}
541
Douglas Gregoraf82e352010-07-20 20:18:03 +0000542namespace {
543 enum PreambleDirectiveKind {
544 PDK_Skipped,
545 PDK_StartIf,
546 PDK_EndIf,
547 PDK_Unknown
548 };
549}
550
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000551std::pair<unsigned, bool>
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000552Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000554 // Create a lexer starting at the beginning of the file. Note that we use a
555 // "fake" file source location at offset 1 so that the lexer will track our
556 // position within the file.
557 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000558 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
559 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregoraf82e352010-07-20 20:18:03 +0000560 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000561 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000562
563 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
564 SourceLocation StartLoc = TheLexer.getSourceLocation();
565
Douglas Gregoraf82e352010-07-20 20:18:03 +0000566 bool InPreprocessorDirective = false;
567 Token TheTok;
568 Token IfStartTok;
569 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000570 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000571
572 unsigned MaxLineOffset = 0;
573 if (MaxLines) {
574 const char *CurPtr = Buffer->getBufferStart();
575 unsigned CurLine = 0;
576 while (CurPtr != Buffer->getBufferEnd()) {
577 char ch = *CurPtr++;
578 if (ch == '\n') {
579 ++CurLine;
580 if (CurLine == MaxLines)
581 break;
582 }
583 }
584 if (CurPtr != Buffer->getBufferEnd())
585 MaxLineOffset = CurPtr - Buffer->getBufferStart();
586 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000587
Douglas Gregoraf82e352010-07-20 20:18:03 +0000588 do {
589 TheLexer.LexFromRawLexer(TheTok);
590
591 if (InPreprocessorDirective) {
592 // If we've hit the end of the file, we're done.
593 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000594 break;
595 }
596
597 // If we haven't hit the end of the preprocessor directive, skip this
598 // token.
599 if (!TheTok.isAtStartOfLine())
600 continue;
601
602 // We've passed the end of the preprocessor directive, and will look
603 // at this token again below.
604 InPreprocessorDirective = false;
605 }
606
Douglas Gregor028d3e42010-08-09 20:45:32 +0000607 // Keep track of the # of lines in the preamble.
608 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000609 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000610
611 // If we were asked to limit the number of lines in the preamble,
612 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000613 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000614 break;
615 }
616
Douglas Gregoraf82e352010-07-20 20:18:03 +0000617 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000618 if (TheTok.getKind() == tok::comment) {
619 if (ActiveCommentLoc.isInvalid())
620 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000621 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000622 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000623
624 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
625 // This is the start of a preprocessor directive.
626 Token HashTok = TheTok;
627 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000628 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000629
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000630 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000631 // we don't have an identifier table available. Instead, just look at
632 // the raw identifier to recognize and categorize preprocessor directives.
633 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000634 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000635 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000636 TheTok.getLength());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000637 PreambleDirectiveKind PDK
638 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
639 .Case("include", PDK_Skipped)
640 .Case("__include_macros", PDK_Skipped)
641 .Case("define", PDK_Skipped)
642 .Case("undef", PDK_Skipped)
643 .Case("line", PDK_Skipped)
644 .Case("error", PDK_Skipped)
645 .Case("pragma", PDK_Skipped)
646 .Case("import", PDK_Skipped)
647 .Case("include_next", PDK_Skipped)
648 .Case("warning", PDK_Skipped)
649 .Case("ident", PDK_Skipped)
650 .Case("sccs", PDK_Skipped)
651 .Case("assert", PDK_Skipped)
652 .Case("unassert", PDK_Skipped)
653 .Case("if", PDK_StartIf)
654 .Case("ifdef", PDK_StartIf)
655 .Case("ifndef", PDK_StartIf)
656 .Case("elif", PDK_Skipped)
657 .Case("else", PDK_Skipped)
658 .Case("endif", PDK_EndIf)
659 .Default(PDK_Unknown);
660
661 switch (PDK) {
662 case PDK_Skipped:
663 continue;
664
665 case PDK_StartIf:
666 if (IfCount == 0)
667 IfStartTok = HashTok;
668
669 ++IfCount;
670 continue;
671
672 case PDK_EndIf:
673 // Mismatched #endif. The preamble ends here.
674 if (IfCount == 0)
675 break;
676
677 --IfCount;
678 continue;
679
680 case PDK_Unknown:
681 // We don't know what this directive is; stop at the '#'.
682 break;
683 }
684 }
685
686 // We only end up here if we didn't recognize the preprocessor
687 // directive or it was one that can't occur in the preamble at this
688 // point. Roll back the current token to the location of the '#'.
689 InPreprocessorDirective = false;
690 TheTok = HashTok;
691 }
692
Douglas Gregor028d3e42010-08-09 20:45:32 +0000693 // We hit a token that we don't recognize as being in the
694 // "preprocessing only" part of the file, so we're no longer in
695 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000696 break;
697 } while (true);
698
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000699 SourceLocation End;
700 if (IfCount)
701 End = IfStartTok.getLocation();
702 else if (ActiveCommentLoc.isValid())
703 End = ActiveCommentLoc; // don't truncate a decl comment.
704 else
705 End = TheTok.getLocation();
706
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000707 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
708 IfCount? IfStartTok.isAtStartOfLine()
709 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000710}
711
Chris Lattner2a6ee912010-11-17 07:05:50 +0000712
713/// AdvanceToTokenCharacter - Given a location that specifies the start of a
714/// token, return a new location that specifies a character within the token.
715SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
716 unsigned CharNo,
717 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000718 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000719 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000720 // character is. This needs to take into consideration newlines and
721 // trigraphs.
722 bool Invalid = false;
723 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
724
725 // If they request the first char of the token, we're trivially done.
726 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
727 return TokStart;
728
729 unsigned PhysOffset = 0;
730
731 // The usual case is that tokens don't contain anything interesting. Skip
732 // over the uninteresting characters. If a token only consists of simple
733 // chars, this method is extremely fast.
734 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
735 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000736 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000737 ++TokPtr, --CharNo, ++PhysOffset;
738 }
739
740 // If we have a character that may be a trigraph or escaped newline, use a
741 // lexer to parse it correctly.
742 for (; CharNo; --CharNo) {
743 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000745 TokPtr += Size;
746 PhysOffset += Size;
747 }
748
749 // Final detail: if we end up on an escaped newline, we want to return the
750 // location of the actual byte of the token. For example foo\<newline>bar
751 // advanced by 3 should return the location of b, not of \\. One compounding
752 // detail of this is that the escape may be made by a trigraph.
753 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
754 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
755
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000756 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000757}
758
759/// \brief Computes the source location just past the end of the
760/// token at this source location.
761///
762/// This routine can be used to produce a source location that
763/// points just past the end of the token referenced by \p Loc, and
764/// is generally used when a diagnostic needs to point just after a
765/// token where it expected something different that it received. If
766/// the returned source location would not be meaningful (e.g., if
767/// it points into a macro), this routine returns an invalid
768/// source location.
769///
770/// \param Offset an offset from the end of the token, where the source
771/// location should refer to. The default offset (0) produces a source
772/// location pointing just past the end of the token; an offset of 1 produces
773/// a source location pointing to the last character in the token, etc.
774SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
775 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000777 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000778 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000779
780 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000782 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000783 }
784
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000786 if (Len > Offset)
787 Len = Len - Offset;
788 else
789 return Loc;
790
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000791 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000792}
793
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000794/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000795/// token of the macro expansion.
796bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000797 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000798 const LangOptions &LangOpts,
799 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000800 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
801
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000802 SourceLocation expansionLoc;
803 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
804 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000805
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000806 if (expansionLoc.isFileID()) {
807 // No other macro expansions, this is the first.
808 if (MacroBegin)
809 *MacroBegin = expansionLoc;
810 return true;
811 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000812
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000813 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000814}
815
816/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000817/// token of the macro expansion.
818bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000819 const SourceManager &SM,
820 const LangOptions &LangOpts,
821 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000822 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
823
824 SourceLocation spellLoc = SM.getSpellingLoc(loc);
825 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
826 if (tokLen == 0)
827 return false;
828
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000829 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
830 SourceLocation expansionLoc;
831 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
832 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000833
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000834 if (expansionLoc.isFileID()) {
835 // No other macro expansions.
836 if (MacroEnd)
837 *MacroEnd = expansionLoc;
838 return true;
839 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000840
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000841 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000842}
843
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000844static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000845 const SourceManager &SM,
846 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000847 SourceLocation Begin = Range.getBegin();
848 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000849 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000850 if (Range.isTokenRange()) {
851 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
852 if (End.isInvalid())
853 return CharSourceRange();
854 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000855
856 // Break down the source locations.
857 FileID FID;
858 unsigned BeginOffs;
859 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
860 if (FID.isInvalid())
861 return CharSourceRange();
862
863 unsigned EndOffs;
864 if (!SM.isInFileID(End, FID, &EndOffs) ||
865 BeginOffs > EndOffs)
866 return CharSourceRange();
867
868 return CharSourceRange::getCharRange(Begin, End);
869}
870
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000872 const SourceManager &SM,
873 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000874 SourceLocation Begin = Range.getBegin();
875 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000877 return CharSourceRange();
878
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000879 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881
882 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000883 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
884 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000885 Range.setBegin(Begin);
886 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000887 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000888
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000889 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000890 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
891 &End)) ||
892 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
893 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000894 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000895 Range.setEnd(End);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000897 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000898
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000899 assert(Begin.isMacroID() && End.isMacroID());
900 SourceLocation MacroBegin, MacroEnd;
901 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000902 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
903 &MacroEnd)) ||
904 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
905 &MacroEnd)))) {
906 Range.setBegin(MacroBegin);
907 Range.setEnd(MacroEnd);
908 return makeRangeFromFileLocs(Range, SM, LangOpts);
909 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000910
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000911 bool Invalid = false;
912 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
913 &Invalid);
914 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000915 return CharSourceRange();
916
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000917 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
918 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
919 &Invalid);
920 if (Invalid)
921 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000922
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000923 if (EndEntry.getExpansion().isMacroArgExpansion() &&
924 BeginEntry.getExpansion().getExpansionLocStart() ==
925 EndEntry.getExpansion().getExpansionLocStart()) {
926 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
927 Range.setEnd(SM.getImmediateSpellingLoc(End));
928 return makeFileCharRange(Range, SM, LangOpts);
929 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000930 }
931
932 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000933}
934
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000935StringRef Lexer::getSourceText(CharSourceRange Range,
936 const SourceManager &SM,
937 const LangOptions &LangOpts,
938 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000939 Range = makeFileCharRange(Range, SM, LangOpts);
940 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000941 if (Invalid) *Invalid = true;
942 return StringRef();
943 }
944
945 // Break down the source location.
946 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
947 if (beginInfo.first.isInvalid()) {
948 if (Invalid) *Invalid = true;
949 return StringRef();
950 }
951
952 unsigned EndOffs;
953 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
954 beginInfo.second > EndOffs) {
955 if (Invalid) *Invalid = true;
956 return StringRef();
957 }
958
959 // Try to the load the file buffer.
960 bool invalidTemp = false;
961 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
962 if (invalidTemp) {
963 if (Invalid) *Invalid = true;
964 return StringRef();
965 }
966
967 if (Invalid) *Invalid = false;
968 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
969}
970
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000971StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
972 const SourceManager &SM,
973 const LangOptions &LangOpts) {
974 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000975
976 // Find the location of the immediate macro expansion.
977 while (1) {
978 FileID FID = SM.getFileID(Loc);
979 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
980 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
981 Loc = Expansion.getExpansionLocStart();
982 if (!Expansion.isMacroArgExpansion())
983 break;
984
985 // For macro arguments we need to check that the argument did not come
986 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
987
988 // Loc points to the argument id of the macro definition, move to the
989 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000990 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000991 SourceLocation SpellLoc = Expansion.getSpellingLoc();
992 if (SpellLoc.isFileID())
993 break; // No inner macro.
994
995 // If spelling location resides in the same FileID as macro expansion
996 // location, it means there is no inner macro.
997 FileID MacroFID = SM.getFileID(Loc);
998 if (SM.isInFileID(SpellLoc, MacroFID))
999 break;
1000
1001 // Argument came from inner macro.
1002 Loc = SpellLoc;
1003 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001004
1005 // Find the spelling location of the start of the non-argument expansion
1006 // range. This is where the macro name was spelled in order to begin
1007 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001008 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001009
1010 // Dig out the buffer where the macro name was spelled and the extents of the
1011 // name so that we can render it into the expansion note.
1012 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1013 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1014 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1015 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1016}
1017
Jordan Rose288c4212012-06-07 01:10:31 +00001018bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001019 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001020}
1021
Chris Lattnerd01e2912006-06-18 16:22:51 +00001022
Chris Lattner22eb9722006-06-18 05:43:12 +00001023//===----------------------------------------------------------------------===//
1024// Diagnostics forwarding code.
1025//===----------------------------------------------------------------------===//
1026
Chris Lattner619c1742007-07-22 18:38:25 +00001027/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001028/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001029/// This is currently only used for _Pragma implementation, so it is the slow
1030/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001031static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1032 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001033static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1034 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001035 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001036 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattner619c1742007-07-22 18:38:25 +00001038 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001039 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001040 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001041 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001043 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001044 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001045 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001046 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner9dc9c202009-02-15 20:52:18 +00001048 // Figure out the expansion loc range, which is the range covered by the
1049 // original _Pragma(...) sequence.
1050 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001051 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chandler Carruth115b0772011-07-26 03:03:05 +00001053 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001054}
1055
Chris Lattner22eb9722006-06-18 05:43:12 +00001056/// getSourceLocation - Return a source location identifier for the specified
1057/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001058SourceLocation Lexer::getSourceLocation(const char *Loc,
1059 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001060 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001061 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001062
1063 // In the normal case, we're just lexing from a simple file buffer, return
1064 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001065 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001066 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001067 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattnerd32480d2009-01-17 06:22:33 +00001069 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1070 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001071 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001072 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073}
1074
Chris Lattner22eb9722006-06-18 05:43:12 +00001075/// Diag - Forwarding function for diagnostics. This translate a source
1076/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001077DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001078 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001079}
1080
1081//===----------------------------------------------------------------------===//
1082// Trigraph and Escaped Newline Handling Code.
1083//===----------------------------------------------------------------------===//
1084
1085/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1086/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1087static char GetTrigraphCharForLetter(char Letter) {
1088 switch (Letter) {
1089 default: return 0;
1090 case '=': return '#';
1091 case ')': return ']';
1092 case '(': return '[';
1093 case '!': return '|';
1094 case '\'': return '^';
1095 case '>': return '}';
1096 case '/': return '\\';
1097 case '<': return '{';
1098 case '-': return '~';
1099 }
1100}
1101
1102/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1103/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1104/// return the result character. Finally, emit a warning about trigraph use
1105/// whether trigraphs are enabled or not.
1106static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1107 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001108 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001109
David Blaikiebbafb8a2012-03-11 07:00:24 +00001110 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001111 if (!L->isLexingRawMode())
1112 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001113 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattner6d27a162008-11-22 02:02:22 +00001116 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001117 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return Res;
1119}
1120
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001121/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1122/// 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 +00001123/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001124unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1125 unsigned Size = 0;
1126 while (isWhitespace(Ptr[Size])) {
1127 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001129 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1130 continue;
1131
1132 // If this is a \r\n or \n\r, skip the other half.
1133 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1134 Ptr[Size-1] != Ptr[Size])
1135 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001137 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001138 }
1139
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001140 // Not an escaped newline, must be a \t or something else.
1141 return 0;
1142}
1143
Chris Lattner38b2cde2009-04-18 22:27:02 +00001144/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1145/// them), skip over them and return the first non-escaped-newline found,
1146/// otherwise return P.
1147const char *Lexer::SkipEscapedNewLines(const char *P) {
1148 while (1) {
1149 const char *AfterEscape;
1150 if (*P == '\\') {
1151 AfterEscape = P+1;
1152 } else if (*P == '?') {
1153 // If not a trigraph for escape, bail out.
1154 if (P[1] != '?' || P[2] != '/')
1155 return P;
1156 AfterEscape = P+3;
1157 } else {
1158 return P;
1159 }
Mike Stump11289f42009-09-09 15:08:12 +00001160
Chris Lattner38b2cde2009-04-18 22:27:02 +00001161 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1162 if (NewLineSize == 0) return P;
1163 P = AfterEscape+NewLineSize;
1164 }
1165}
1166
Anna Zaks59a3c802011-07-27 21:43:43 +00001167/// \brief Checks that the given token is the first token that occurs after the
1168/// given location (this excludes comments and whitespace). Returns the location
1169/// immediately after the specified token. If the token is not found or the
1170/// location is inside a macro, the returned source location will be invalid.
1171SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1172 tok::TokenKind TKind,
1173 const SourceManager &SM,
1174 const LangOptions &LangOpts,
1175 bool SkipTrailingWhitespaceAndNewLine) {
1176 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001177 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001178 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001179 }
1180 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1181
1182 // Break down the source location.
1183 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1184
1185 // Try to load the file buffer.
1186 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001187 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001188 if (InvalidTemp)
1189 return SourceLocation();
1190
1191 const char *TokenBegin = File.data() + LocInfo.second;
1192
1193 // Lex from the start of the given location.
1194 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1195 TokenBegin, File.end());
1196 // Find the token.
1197 Token Tok;
1198 lexer.LexFromRawLexer(Tok);
1199 if (Tok.isNot(TKind))
1200 return SourceLocation();
1201 SourceLocation TokenLoc = Tok.getLocation();
1202
1203 // Calculate how much whitespace needs to be skipped if any.
1204 unsigned NumWhitespaceChars = 0;
1205 if (SkipTrailingWhitespaceAndNewLine) {
1206 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1207 Tok.getLength();
1208 unsigned char C = *TokenEnd;
1209 while (isHorizontalWhitespace(C)) {
1210 C = *(++TokenEnd);
1211 NumWhitespaceChars++;
1212 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001213
1214 // Skip \r, \n, \r\n, or \n\r
1215 if (C == '\n' || C == '\r') {
1216 char PrevC = C;
1217 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001218 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001219 if ((C == '\n' || C == '\r') && C != PrevC)
1220 NumWhitespaceChars++;
1221 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001222 }
1223
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001224 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001225}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001226
Chris Lattner22eb9722006-06-18 05:43:12 +00001227/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1228/// get its size, and return it. This is tricky in several cases:
1229/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1230/// then either return the trigraph (skipping 3 chars) or the '?',
1231/// depending on whether trigraphs are enabled or not.
1232/// 2. If this is an escaped newline (potentially with whitespace between
1233/// the backslash and newline), implicitly skip the newline and return
1234/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001235///
1236/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1237/// know that we can accumulate into Size, and that we have already incremented
1238/// Ptr by Size bytes.
1239///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001240/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1241/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001242///
1243char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001244 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 // If we have a slash, look for an escaped newline.
1246 if (Ptr[0] == '\\') {
1247 ++Size;
1248 ++Ptr;
1249Slash:
1250 // Common case, backslash-char where the char is not whitespace.
1251 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001252
Chris Lattnerc1835952009-06-23 05:15:06 +00001253 // See if we have optional whitespace characters between the slash and
1254 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001255 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1256 // Remember that this token needs to be cleaned.
1257 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001258
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001259 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001260 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001261 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001262
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001263 // Found backslash<whitespace><newline>. Parse the char after it.
1264 Size += EscapedNewLineSize;
1265 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001266
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001267 // If the char that we finally got was a \n, then we must have had
1268 // something like \<newline><newline>. We don't want to consume the
1269 // second newline.
1270 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1271 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001272
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001273 // Use slow version to accumulate a correct size field.
1274 return getCharAndSizeSlow(Ptr, Size, Tok);
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 // Otherwise, this is not an escaped newline, just return the slash.
1278 return '\\';
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 // If this is a trigraph, process it.
1282 if (Ptr[0] == '?' && Ptr[1] == '?') {
1283 // If this is actually a legal trigraph (not something like "??x"), emit
1284 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1285 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1286 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001287 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288
1289 Ptr += 3;
1290 Size += 3;
1291 if (C == '\\') goto Slash;
1292 return C;
1293 }
1294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 // If this is neither, return a single character.
1297 ++Size;
1298 return *Ptr;
1299}
1300
Chris Lattnerd01e2912006-06-18 16:22:51 +00001301
Chris Lattner22eb9722006-06-18 05:43:12 +00001302/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1303/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1304/// and that we have already incremented Ptr by Size bytes.
1305///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001306/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1307/// be updated to match.
1308char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001309 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // If we have a slash, look for an escaped newline.
1311 if (Ptr[0] == '\\') {
1312 ++Size;
1313 ++Ptr;
1314Slash:
1315 // Common case, backslash-char where the char is not whitespace.
1316 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001319 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1320 // Found backslash<whitespace><newline>. Parse the char after it.
1321 Size += EscapedNewLineSize;
1322 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001323
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001324 // If the char that we finally got was a \n, then we must have had
1325 // something like \<newline><newline>. We don't want to consume the
1326 // second newline.
1327 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1328 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001329
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001330 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 // Otherwise, this is not an escaped newline, just return the slash.
1335 return '\\';
1336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001339 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001340 // If this is actually a legal trigraph (not something like "??x"), return
1341 // it.
1342 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1343 Ptr += 3;
1344 Size += 3;
1345 if (C == '\\') goto Slash;
1346 return C;
1347 }
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 // If this is neither, return a single character.
1351 ++Size;
1352 return *Ptr;
1353}
1354
Chris Lattner22eb9722006-06-18 05:43:12 +00001355//===----------------------------------------------------------------------===//
1356// Helper methods for lexing.
1357//===----------------------------------------------------------------------===//
1358
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001359/// \brief Routine that indiscriminately skips bytes in the source file.
1360void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1361 BufferPtr += Bytes;
1362 if (BufferPtr > BufferEnd)
1363 BufferPtr = BufferEnd;
1364 IsAtStartOfLine = StartOfLine;
1365}
1366
Jordan Rose58c61e02013-02-09 01:10:25 +00001367static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001368 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1369 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1370 C11AllowedIDCharRanges);
1371 return C11AllowedIDChars.contains(C);
1372 } else if (LangOpts.CPlusPlus) {
1373 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1374 CXX03AllowedIDCharRanges);
1375 return CXX03AllowedIDChars.contains(C);
1376 } else {
1377 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1378 C99AllowedIDCharRanges);
1379 return C99AllowedIDChars.contains(C);
1380 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001381}
1382
Jordan Rose58c61e02013-02-09 01:10:25 +00001383static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1384 assert(isAllowedIDChar(C, LangOpts));
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001385 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1386 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1387 C11DisallowedInitialIDCharRanges);
1388 return !C11DisallowedInitialIDChars.contains(C);
1389 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001390 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001391 } else {
1392 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1393 C99DisallowedInitialIDCharRanges);
1394 return !C99DisallowedInitialIDChars.contains(C);
1395 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001396}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001397
Jordan Rose58c61e02013-02-09 01:10:25 +00001398static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1399 const char *End) {
1400 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1401 L.getSourceLocation(End));
1402}
1403
1404static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1405 CharSourceRange Range, bool IsFirst) {
1406 // Check C99 compatibility.
1407 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1408 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1409 enum {
1410 CannotAppearInIdentifier = 0,
1411 CannotStartIdentifier
1412 };
1413
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001414 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1415 C99AllowedIDCharRanges);
1416 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1417 C99DisallowedInitialIDCharRanges);
1418 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001419 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1420 << Range
1421 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001422 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001423 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1424 << Range
1425 << CannotStartIdentifier;
1426 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001427 }
1428
Jordan Rose58c61e02013-02-09 01:10:25 +00001429 // Check C++98 compatibility.
1430 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1431 Range.getBegin()) > DiagnosticsEngine::Ignored) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001432 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1433 CXX03AllowedIDCharRanges);
1434 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001435 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1436 << Range;
1437 }
1438 }
1439 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001440
Chris Lattner146762e2007-07-20 16:59:19 +00001441void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001442 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1443 unsigned Size;
1444 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001445 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001446 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001447
Chris Lattner22eb9722006-06-18 05:43:12 +00001448 --CurPtr; // Back up over the skipped character.
1449
1450 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1451 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001452 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001453 // TODO: Could merge these checks into an InfoTable flag to make the
1454 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001455 if (isASCII(C) && C != '\\' && C != '?' &&
1456 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001457FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001458 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001459 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1460 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chris Lattner0f1f5052006-07-20 04:16:23 +00001462 // If we are in raw mode, return this identifier raw. There is no need to
1463 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001464 if (LexingRawMode)
1465 return;
Mike Stump11289f42009-09-09 15:08:12 +00001466
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001467 // Fill in Result.IdentifierInfo and update the token kind,
1468 // looking up the identifier in the identifier table.
1469 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattnerc5a00062006-06-18 16:41:01 +00001471 // Finally, now that we know we have an identifier, pass this off to the
1472 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001473 if (II->isHandleIdentifierCase())
Chris Lattnerad89ec02009-01-21 07:43:11 +00001474 PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001475
Chris Lattnerad89ec02009-01-21 07:43:11 +00001476 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Chris Lattner22eb9722006-06-18 05:43:12 +00001479 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001480
Chris Lattner22eb9722006-06-18 05:43:12 +00001481 C = getCharAndSize(CurPtr, Size);
1482 while (1) {
1483 if (C == '$') {
1484 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001485 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001488 if (!isLexingRawMode())
1489 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001490 CurPtr = ConsumeChar(CurPtr, Size, Result);
1491 C = getCharAndSize(CurPtr, Size);
1492 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001493
1494 } else if (C == '\\') {
1495 const char *UCNPtr = CurPtr + Size;
1496 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Rose58c61e02013-02-09 01:10:25 +00001497 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001498 goto FinishIdentifier;
1499
Jordan Rose58c61e02013-02-09 01:10:25 +00001500 if (!isLexingRawMode()) {
1501 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1502 makeCharRange(*this, CurPtr, UCNPtr),
1503 /*IsFirst=*/false);
1504 }
1505
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001506 Result.setFlag(Token::HasUCN);
1507 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1508 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1509 CurPtr = UCNPtr;
1510 else
1511 while (CurPtr != UCNPtr)
1512 (void)getAndAdvanceChar(CurPtr, Result);
1513
1514 C = getCharAndSize(CurPtr, Size);
1515 continue;
1516 } else if (!isASCII(C)) {
1517 const char *UnicodePtr = CurPtr;
1518 UTF32 CodePoint;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00001519 ConversionResult Result =
1520 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1521 (const UTF8 *)BufferEnd,
1522 &CodePoint,
1523 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001524 if (Result != conversionOK ||
Jordan Rose58c61e02013-02-09 01:10:25 +00001525 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001526 goto FinishIdentifier;
1527
Jordan Rose58c61e02013-02-09 01:10:25 +00001528 if (!isLexingRawMode()) {
1529 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1530 makeCharRange(*this, CurPtr, UnicodePtr),
1531 /*IsFirst=*/false);
1532 }
1533
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001534 CurPtr = UnicodePtr;
1535 C = getCharAndSize(CurPtr, Size);
1536 continue;
1537 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 goto FinishIdentifier;
1539 }
1540
1541 // Otherwise, this character is good, consume it.
1542 CurPtr = ConsumeChar(CurPtr, Size, Result);
1543
1544 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001545 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 CurPtr = ConsumeChar(CurPtr, Size, Result);
1547 C = getCharAndSize(CurPtr, Size);
1548 }
1549 }
1550}
1551
Douglas Gregor759ef232010-08-30 14:50:47 +00001552/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001553/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001554bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001555 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001556 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001557 if (C1 != '0')
1558 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001559 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001560 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001561}
Chris Lattner22eb9722006-06-18 05:43:12 +00001562
Nate Begeman5eee9332008-04-14 02:26:39 +00001563/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001564/// constant. From[-1] is the first character lexed. Return the end of the
1565/// constant.
Chris Lattner146762e2007-07-20 16:59:19 +00001566void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001567 unsigned Size;
1568 char C = getCharAndSize(CurPtr, Size);
1569 char PrevCh = 0;
Jordan Rosea2100d72013-02-08 22:30:22 +00001570 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Chris Lattner22eb9722006-06-18 05:43:12 +00001571 CurPtr = ConsumeChar(CurPtr, Size, Result);
1572 PrevCh = C;
1573 C = getCharAndSize(CurPtr, Size);
1574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001577 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1578 // If we are in Microsoft mode, don't continue if the constant is hex.
1579 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001580 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001581 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1582 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001583
1584 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001585 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1586 // Outside C99, we accept hexadecimal floating point numbers as a
1587 // not-quite-conforming extension. Only do so if this looks like it's
1588 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1589 bool IsHexFloat = true;
1590 if (!LangOpts.C99) {
1591 if (!isHexaLiteral(BufferPtr, LangOpts))
1592 IsHexFloat = false;
1593 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1594 IsHexFloat = false;
1595 }
1596 if (IsHexFloat)
1597 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattnerd01e2912006-06-18 16:22:51 +00001600 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001601 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001602 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001603 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001604}
1605
Richard Smithe18f0fa2012-03-05 04:02:15 +00001606/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001607/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001608const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1609 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001611
1612 // Maximally munch an identifier. FIXME: UCNs.
1613 unsigned Size;
1614 char C = getCharAndSize(CurPtr, Size);
1615 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001616 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001617 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001618 Diag(CurPtr,
1619 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1620 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1621 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1622 return CurPtr;
1623 }
1624
1625 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1626 // that does not start with an underscore is ill-formed. As a conforming
1627 // extension, we treat all such suffixes as if they had whitespace before
1628 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001629 bool IsUDSuffix = false;
1630 if (C == '_')
1631 IsUDSuffix = true;
1632 else if (IsStringLiteral && C == 's' && getLangOpts().CPlusPlus1y) {
1633 // In C++1y, "s" is a valid ud-suffix for a string literal.
1634 unsigned NextSize;
1635 if (!isIdentifierBody(getCharAndSizeNoWarn(CurPtr + Size, NextSize,
1636 getLangOpts())))
1637 IsUDSuffix = true;
1638 }
1639
1640 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001641 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001642 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001643 diag::ext_ms_reserved_user_defined_literal :
1644 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001645 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1646 return CurPtr;
1647 }
1648
Richard Smithd67aea22012-03-06 03:21:47 +00001649 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001650 do {
1651 CurPtr = ConsumeChar(CurPtr, Size, Result);
1652 C = getCharAndSize(CurPtr, Size);
1653 } while (isIdentifierBody(C));
1654 }
1655 return CurPtr;
1656}
1657
Chris Lattner22eb9722006-06-18 05:43:12 +00001658/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001659/// either " or L" or u8" or u" or U".
1660void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1661 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001662 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001663
Richard Smithacd4d3d2011-10-15 01:18:56 +00001664 if (!isLexingRawMode() &&
1665 (Kind == tok::utf8_string_literal ||
1666 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001667 Kind == tok::utf32_string_literal))
1668 Diag(BufferPtr, getLangOpts().CPlusPlus
1669 ? diag::warn_cxx98_compat_unicode_literal
1670 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001671
Chris Lattner22eb9722006-06-18 05:43:12 +00001672 char C = getAndAdvanceChar(CurPtr, Result);
1673 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001674 // Skip escaped characters. Escaped newlines will already be processed by
1675 // getAndAdvanceChar.
1676 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001678
Chris Lattner52d96ac2010-05-30 23:27:38 +00001679 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001680 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001681 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001682 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001683 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001684 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001685 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001686
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001687 if (C == 0) {
1688 if (isCodeCompletionPoint(CurPtr-1)) {
1689 PP->CodeCompleteNaturalLanguage();
1690 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1691 return cutOffLexing();
1692 }
1693
Chris Lattner52d96ac2010-05-30 23:27:38 +00001694 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001695 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001696 C = getAndAdvanceChar(CurPtr, Result);
1697 }
Mike Stump11289f42009-09-09 15:08:12 +00001698
Richard Smithe18f0fa2012-03-05 04:02:15 +00001699 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001701 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001702
Chris Lattner5a78a022006-07-20 06:02:19 +00001703 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001704 if (NulCharacter && !isLexingRawMode())
1705 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001706
Chris Lattnerd01e2912006-06-18 16:22:51 +00001707 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001708 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001709 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001710 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001711}
1712
Craig Topper54edcca2011-08-11 04:06:15 +00001713/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1714/// having lexed R", LR", u8R", uR", or UR".
1715void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1716 tok::TokenKind Kind) {
1717 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1718 // Between the initial and final double quote characters of the raw string,
1719 // any transformations performed in phases 1 and 2 (trigraphs,
1720 // universal-character-names, and line splicing) are reverted.
1721
Richard Smithacd4d3d2011-10-15 01:18:56 +00001722 if (!isLexingRawMode())
1723 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1724
Craig Topper54edcca2011-08-11 04:06:15 +00001725 unsigned PrefixLen = 0;
1726
1727 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1728 ++PrefixLen;
1729
1730 // If the last character was not a '(', then we didn't lex a valid delimiter.
1731 if (CurPtr[PrefixLen] != '(') {
1732 if (!isLexingRawMode()) {
1733 const char *PrefixEnd = &CurPtr[PrefixLen];
1734 if (PrefixLen == 16) {
1735 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1736 } else {
1737 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1738 << StringRef(PrefixEnd, 1);
1739 }
1740 }
1741
1742 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1743 // it's possible the '"' was intended to be part of the raw string, but
1744 // there's not much we can do about that.
1745 while (1) {
1746 char C = *CurPtr++;
1747
1748 if (C == '"')
1749 break;
1750 if (C == 0 && CurPtr-1 == BufferEnd) {
1751 --CurPtr;
1752 break;
1753 }
1754 }
1755
1756 FormTokenWithChars(Result, CurPtr, tok::unknown);
1757 return;
1758 }
1759
1760 // Save prefix and move CurPtr past it
1761 const char *Prefix = CurPtr;
1762 CurPtr += PrefixLen + 1; // skip over prefix and '('
1763
1764 while (1) {
1765 char C = *CurPtr++;
1766
1767 if (C == ')') {
1768 // Check for prefix match and closing quote.
1769 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1770 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1771 break;
1772 }
1773 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1774 if (!isLexingRawMode())
1775 Diag(BufferPtr, diag::err_unterminated_raw_string)
1776 << StringRef(Prefix, PrefixLen);
1777 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1778 return;
1779 }
1780 }
1781
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
Craig Topper54edcca2011-08-11 04:06:15 +00001786 // Update the location of token as well as BufferPtr.
1787 const char *TokStart = BufferPtr;
1788 FormTokenWithChars(Result, CurPtr, Kind);
1789 Result.setLiteralData(TokStart);
1790}
1791
Chris Lattner22eb9722006-06-18 05:43:12 +00001792/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1793/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattner146762e2007-07-20 16:59:19 +00001794void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001795 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001796 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001797 char C = getAndAdvanceChar(CurPtr, Result);
1798 while (C != '>') {
1799 // Skip escaped characters.
1800 if (C == '\\') {
1801 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001802 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001803 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001804 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1805 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001806 // If the filename is unterminated, then it must just be a lone <
1807 // character. Return this as such.
1808 FormTokenWithChars(Result, AfterLessPos, tok::less);
Chris Lattner5a78a022006-07-20 06:02:19 +00001809 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001810 } else if (C == 0) {
1811 NulCharacter = CurPtr-1;
1812 }
1813 C = getAndAdvanceChar(CurPtr, Result);
1814 }
Mike Stump11289f42009-09-09 15:08:12 +00001815
Chris Lattner5a78a022006-07-20 06:02:19 +00001816 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001817 if (NulCharacter && !isLexingRawMode())
1818 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001819
Chris Lattnerd01e2912006-06-18 16:22:51 +00001820 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001821 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001822 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001823 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001824}
1825
1826
1827/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001828/// lexed either ' or L' or u' or U'.
1829void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1830 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001831 const char *NulCharacter = 0; // Does this character contain the \0 character?
1832
Richard Smithacd4d3d2011-10-15 01:18:56 +00001833 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001834 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1835 Diag(BufferPtr, getLangOpts().CPlusPlus
1836 ? diag::warn_cxx98_compat_unicode_literal
1837 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001838
Chris Lattner22eb9722006-06-18 05:43:12 +00001839 char C = getAndAdvanceChar(CurPtr, Result);
1840 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001841 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001842 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001843 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001844 return;
Chris Lattner86851b82010-07-07 23:24:27 +00001845 }
1846
1847 while (C != '\'') {
1848 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001849 if (C == '\\')
1850 C = getAndAdvanceChar(CurPtr, Result);
1851
1852 if (C == '\n' || C == '\r' || // Newline.
1853 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001854 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001855 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001856 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1857 return;
Nico Weber4e270382012-11-17 20:25:54 +00001858 }
1859
1860 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001861 if (isCodeCompletionPoint(CurPtr-1)) {
1862 PP->CodeCompleteNaturalLanguage();
1863 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1864 return cutOffLexing();
1865 }
1866
Chris Lattner86851b82010-07-07 23:24:27 +00001867 NulCharacter = CurPtr-1;
1868 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001869 C = getAndAdvanceChar(CurPtr, Result);
1870 }
Mike Stump11289f42009-09-09 15:08:12 +00001871
Richard Smithe18f0fa2012-03-05 04:02:15 +00001872 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001873 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001874 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001875
Chris Lattner86851b82010-07-07 23:24:27 +00001876 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001877 if (NulCharacter && !isLexingRawMode())
1878 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001879
Chris Lattnerd01e2912006-06-18 16:22:51 +00001880 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001881 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001882 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001883 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001884}
1885
1886/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1887/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001888///
1889/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1890///
1891bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001893 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1894
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001895 unsigned char Char = *CurPtr;
1896
1897 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 while (1) {
1899 // Skip horizontal whitespace very aggressively.
1900 while (isHorizontalWhitespace(Char))
1901 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001903 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001904 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001905 break;
Mike Stump11289f42009-09-09 15:08:12 +00001906
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 if (ParsingPreprocessorDirective) {
1908 // End of preprocessor directive line, let LexTokenInternal handle this.
1909 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001910 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001913 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001914 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001915 Char = *++CurPtr;
1916 }
1917
Chris Lattner4d963442008-10-12 04:05:48 +00001918 // If the client wants us to return whitespace, return it now.
1919 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001920 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001921 if (SawNewline)
1922 IsAtStartOfLine = true;
1923 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001924 return true;
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001927 // If this isn't immediately after a newline, there is leading space.
1928 char PrevChar = CurPtr[-1];
1929 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1930
1931 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1932 if (SawNewline)
1933 Result.setFlag(Token::StartOfLine);
1934
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001936 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001937}
1938
Nico Weber158a31a2012-11-11 07:02:14 +00001939/// We have just read the // characters from input. Skip until we find the
1940/// newline character thats terminate the comment. Then update BufferPtr and
1941/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001942///
1943/// If we're in KeepCommentMode or any CommentHandler has inserted
1944/// some tokens, this will store the first token and return true.
Nico Weber158a31a2012-11-11 07:02:14 +00001945bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1946 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00001947 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00001948 if (!LangOpts.LineComment && !isLexingRawMode()) {
1949 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattner22eb9722006-06-18 05:43:12 +00001951 // Mark them enabled so we only emit one warning for this translation
1952 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00001953 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattner22eb9722006-06-18 05:43:12 +00001956 // Scan over the body of the comment. The common case, when scanning, is that
1957 // the comment contains normal ascii characters with nothing interesting in
1958 // them. As such, optimize for this case with the inner loop.
1959 char C;
1960 do {
1961 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001962 // Skip over characters in the fast loop.
1963 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 C != '\n' && C != '\r') // Newline or DOS-style newline.
1965 C = *++CurPtr;
1966
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001967 const char *NextLine = CurPtr;
1968 if (C != 0) {
1969 // We found a newline, see if it's escaped.
1970 const char *EscapePtr = CurPtr-1;
1971 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1972 --EscapePtr;
1973
1974 if (*EscapePtr == '\\') // Escaped newline.
1975 CurPtr = EscapePtr;
1976 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1977 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1978 CurPtr = EscapePtr-2;
1979 else
1980 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00001984 // properly decode the character. Read it in raw mode to avoid emitting
1985 // diagnostics about things like trigraphs. If we see an escaped newline,
1986 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00001987 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00001988 bool OldRawMode = isLexingRawMode();
1989 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00001991 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00001992
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001993 // If we only read only one character, then no special handling is needed.
1994 // We're done and can skip forward to the newline.
1995 if (C != 0 && CurPtr == OldPtr+1) {
1996 CurPtr = NextLine;
1997 break;
1998 }
1999
Chris Lattner22eb9722006-06-18 05:43:12 +00002000 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002001 // \n, then we had an escaped newline within the comment. Emit diagnostic
2002 // unless the next line is also a // comment.
2003 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 for (; OldPtr != CurPtr; ++OldPtr)
2005 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002006 // Okay, we found a // comment that ends in a newline, if the next
2007 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002008 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002009 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002010 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002011 ++ForwardPtr;
2012 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2013 break;
2014 }
Mike Stump11289f42009-09-09 15:08:12 +00002015
Chris Lattner6d27a162008-11-22 02:02:22 +00002016 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002017 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002018 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 }
2020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor11583702010-08-25 17:04:25 +00002022 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002023 --CurPtr;
2024 break;
2025 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002026
2027 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2028 PP->CodeCompleteNaturalLanguage();
2029 cutOffLexing();
2030 return false;
2031 }
2032
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 } while (C != '\n' && C != '\r');
2034
Chris Lattner93ddf802010-02-03 21:06:21 +00002035 // Found but did not consume the newline. Notify comment handlers about the
2036 // comment unless we're in a #if 0 block.
2037 if (PP && !isLexingRawMode() &&
2038 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2039 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002040 BufferPtr = CurPtr;
2041 return true; // A token has to be returned.
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattner457fc152006-07-29 06:30:25 +00002044 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002045 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002046 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002047
2048 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002049 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002050 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002051 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002052 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Chris Lattner22eb9722006-06-18 05:43:12 +00002055 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002056 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002057 // contribute to another token), it isn't needed for correctness. Note that
2058 // this is ok even in KeepWhitespaceMode, because we would have returned the
2059 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002061
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002063 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002065 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002067 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002068}
Chris Lattner22eb9722006-06-18 05:43:12 +00002069
Nico Weber158a31a2012-11-11 07:02:14 +00002070/// If in save-comment mode, package up this Line comment in an appropriate
2071/// way and return it.
2072bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002073 // If we're not in a preprocessor directive, just return the // comment
2074 // directly.
2075 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002076
David Blaikied5321242012-06-06 18:52:13 +00002077 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002078 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002079
Nico Weber158a31a2012-11-11 07:02:14 +00002080 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002081 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002082 bool Invalid = false;
2083 std::string Spelling = PP->getSpelling(Result, &Invalid);
2084 if (Invalid)
2085 return true;
2086
Nico Weber158a31a2012-11-11 07:02:14 +00002087 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002088 Spelling[1] = '*'; // Change prefix to "/*".
2089 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002090
Chris Lattnerb11c3232008-10-12 04:51:35 +00002091 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002092 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002093 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002094 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002095}
2096
Chris Lattnercb283342006-06-18 06:48:37 +00002097/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002098/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2099/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002100static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002101 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002102 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattner22eb9722006-06-18 05:43:12 +00002104 // Back up off the newline.
2105 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner22eb9722006-06-18 05:43:12 +00002107 // If this is a two-character newline sequence, skip the other character.
2108 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2109 // \n\n or \r\r -> not escaped newline.
2110 if (CurPtr[0] == CurPtr[1])
2111 return false;
2112 // \n\r or \r\n -> skip the newline.
2113 --CurPtr;
2114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 // If we have horizontal whitespace, skip over it. We allow whitespace
2117 // between the slash and newline.
2118 bool HasSpace = false;
2119 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2120 --CurPtr;
2121 HasSpace = true;
2122 }
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattner22eb9722006-06-18 05:43:12 +00002124 // If we have a slash, we know this is an escaped newline.
2125 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002126 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002127 } else {
2128 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002129 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2130 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattnercb283342006-06-18 06:48:37 +00002133 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002134 CurPtr -= 2;
2135
2136 // If no trigraphs are enabled, warn that we ignored this trigraph and
2137 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002138 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002139 if (!L->isLexingRawMode())
2140 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002141 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002142 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002143 if (!L->isLexingRawMode())
2144 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002145 }
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattner22eb9722006-06-18 05:43:12 +00002147 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002148 if (!L->isLexingRawMode())
2149 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner22eb9722006-06-18 05:43:12 +00002151 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002152 if (HasSpace && !L->isLexingRawMode())
2153 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Chris Lattnercb283342006-06-18 06:48:37 +00002155 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002156}
2157
Chris Lattneraded4a92006-10-27 04:42:31 +00002158#ifdef __SSE2__
2159#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002160#elif __ALTIVEC__
2161#include <altivec.h>
2162#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002163#endif
2164
James Dennettf442d242012-06-17 03:40:43 +00002165/// We have just read from input the / and * characters that started a comment.
2166/// Read until we find the * and / characters that terminate the comment.
2167/// Note that we don't bother decoding trigraphs or escaped newlines in block
2168/// comments, because they cannot cause the comment to end. The only thing
2169/// that can happen is the comment could end with an escaped newline between
2170/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002171///
Chris Lattner87d02082010-01-18 22:35:47 +00002172/// If we're in KeepCommentMode or any CommentHandler has inserted
2173/// some tokens, this will store the first token and return true.
Chris Lattner146762e2007-07-20 16:59:19 +00002174bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002175 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002176 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002177 // optimization helps people who like to put a lot of * characters in their
2178 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002179
2180 // The first character we get with newlines and trigraphs skipped to handle
2181 // the degenerate /*/ case below correctly if the * has an escaped newline
2182 // after it.
2183 unsigned CharSize;
2184 unsigned char C = getCharAndSize(CurPtr, CharSize);
2185 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002186 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002187 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002188 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002189 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattner99e7d232008-10-12 04:19:49 +00002191 // KeepWhitespaceMode should return this broken comment as a token. Since
2192 // it isn't a well formed comment, just return it as an 'unknown' token.
2193 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002194 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002195 return true;
2196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattner99e7d232008-10-12 04:19:49 +00002198 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002199 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002200 }
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattnerc850ad62007-07-21 23:43:37 +00002202 // Check to see if the first character after the '/*' is another /. If so,
2203 // then this slash does not end the block comment, it is part of it.
2204 if (C == '/')
2205 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattner22eb9722006-06-18 05:43:12 +00002207 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002208 // Skip over all non-interesting characters until we find end of buffer or a
2209 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002210 if (CurPtr + 24 < BufferEnd &&
2211 // If there is a code-completion point avoid the fast scan because it
2212 // doesn't check for '\0'.
2213 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002214 // While not aligned to a 16-byte boundary.
2215 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2216 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002217
Chris Lattner6cc3e362006-10-27 04:12:35 +00002218 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002219
2220#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002221 __m128i Slashes = _mm_set1_epi8('/');
2222 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002223 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2224 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002225 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002226 // Adjust the pointer to point directly after the first slash. It's
2227 // not necessary to set C here, it will be overwritten at the end of
2228 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002229 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002230 goto FoundSlash;
2231 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002232 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002233 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002234#elif __ALTIVEC__
2235 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002236 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002237 '/', '/', '/', '/', '/', '/', '/', '/'
2238 };
2239 while (CurPtr+16 <= BufferEnd &&
2240 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2241 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002242#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002243 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002244 while (CurPtr[0] != '/' &&
2245 CurPtr[1] != '/' &&
2246 CurPtr[2] != '/' &&
2247 CurPtr[3] != '/' &&
2248 CurPtr+4 < BufferEnd) {
2249 CurPtr += 4;
2250 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002251#endif
Mike Stump11289f42009-09-09 15:08:12 +00002252
Chris Lattneraded4a92006-10-27 04:42:31 +00002253 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002254 C = *CurPtr++;
2255 }
Mike Stump11289f42009-09-09 15:08:12 +00002256
Chris Lattneraded4a92006-10-27 04:42:31 +00002257 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 while (C != '/' && C != '\0')
2259 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002262 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 if (CurPtr[-2] == '*') // We found the final */. We're done!
2264 break;
Mike Stump11289f42009-09-09 15:08:12 +00002265
Chris Lattner22eb9722006-06-18 05:43:12 +00002266 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002267 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002268 // We found the final */, though it had an escaped newline between the
2269 // * and /. We're done!
2270 break;
2271 }
2272 }
2273 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2274 // If this is a /* inside of the comment, emit a warning. Don't do this
2275 // if this is a /*/, which will end the comment. This misses cases with
2276 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002277 if (!isLexingRawMode())
2278 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002279 }
2280 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002281 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002282 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002283 // Note: the user probably forgot a */. We could continue immediately
2284 // after the /*, but this would involve lexing a lot of what really is the
2285 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002286 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattner99e7d232008-10-12 04:19:49 +00002288 // KeepWhitespaceMode should return this broken comment as a token. Since
2289 // it isn't a well formed comment, just return it as an 'unknown' token.
2290 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002291 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002292 return true;
2293 }
Mike Stump11289f42009-09-09 15:08:12 +00002294
Chris Lattner99e7d232008-10-12 04:19:49 +00002295 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002296 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002297 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2298 PP->CodeCompleteNaturalLanguage();
2299 cutOffLexing();
2300 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002301 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002302
Chris Lattner22eb9722006-06-18 05:43:12 +00002303 C = *CurPtr++;
2304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattner93ddf802010-02-03 21:06:21 +00002306 // Notify comment handlers about the comment unless we're in a #if 0 block.
2307 if (PP && !isLexingRawMode() &&
2308 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2309 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002310 BufferPtr = CurPtr;
2311 return true; // A token has to be returned.
2312 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002313
Chris Lattner457fc152006-07-29 06:30:25 +00002314 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002315 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002316 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002317 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002318 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002319
2320 // It is common for the tokens immediately after a /**/ comment to be
2321 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002322 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2323 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002324 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattner457fc152006-07-29 06:30:25 +00002325 SkipWhitespace(Result, CurPtr+1);
Chris Lattnere01e7582008-10-12 04:15:42 +00002326 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002327 }
2328
2329 // Otherwise, just return so that the next character will be lexed as a token.
2330 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002331 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002332 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002333}
2334
2335//===----------------------------------------------------------------------===//
2336// Primary Lexing Entry Points
2337//===----------------------------------------------------------------------===//
2338
Chris Lattner22eb9722006-06-18 05:43:12 +00002339/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2340/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002341void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002342 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2343 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002344 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002345
2346 // CurPtr - Cache BufferPtr in an automatic variable.
2347 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 while (1) {
2349 char Char = getAndAdvanceChar(CurPtr, Tmp);
2350 switch (Char) {
2351 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002352 if (Result)
2353 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002354 break;
2355 case 0: // Null.
2356 // Found end of file?
2357 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002358 if (isCodeCompletionPoint(CurPtr-1)) {
2359 PP->CodeCompleteNaturalLanguage();
2360 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002361 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002362 }
2363
Chris Lattner22eb9722006-06-18 05:43:12 +00002364 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002365 if (Result)
2366 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002367 break;
2368 }
2369 // FALL THROUGH.
2370 case '\r':
2371 case '\n':
2372 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2373 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2374 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002375
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002376 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002377 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002378 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002379 if (PP)
2380 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002381 Lex(Tmp);
2382 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002383 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002384
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002385 // Finally, we're done;
2386 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002387 }
2388 }
2389}
2390
2391/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2392/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002393/// This returns true if Result contains a token, false if PP.Lex should be
2394/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002395bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002396 // If we hit the end of the file while parsing a preprocessor directive,
2397 // end the preprocessor directive first. The next token returned will
2398 // then be the end of file.
2399 if (ParsingPreprocessorDirective) {
2400 // Done parsing the "line".
2401 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002402 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002403 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Chris Lattner457fc152006-07-29 06:30:25 +00002405 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002406 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002407 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002408 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002409
Chris Lattner30a2fa12006-07-19 06:31:49 +00002410 // If we are in raw mode, return this event as an EOF token. Let the caller
2411 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002412 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002413 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002414 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002415 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002416 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002417 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002418
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002419 // Issue diagnostics for unterminated #if and missing newline.
2420
Chris Lattner30a2fa12006-07-19 06:31:49 +00002421 // If we are in a #if directive, emit an error.
2422 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002423 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002424 PP->Diag(ConditionalStack.back().IfLoc,
2425 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002426 ConditionalStack.pop_back();
2427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattner8f96d042008-04-12 05:54:25 +00002429 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2430 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002431 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2432 DiagnosticsEngine &Diags = PP->getDiagnostics();
2433 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2434 unsigned DiagID;
2435
2436 if (LangOpts.CPlusPlus11) {
2437 // C++11 [lex.phases] 2.2 p2
2438 // Prefer the C++98 pedantic compatibility warning over the generic,
2439 // non-extension, user-requested "missing newline at EOF" warning.
2440 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_no_newline_eof,
2441 EndLoc) != DiagnosticsEngine::Ignored) {
2442 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2443 } else {
2444 DiagID = diag::warn_no_newline_eof;
2445 }
2446 } else {
2447 DiagID = diag::ext_no_newline_eof;
2448 }
2449
2450 Diag(BufferEnd, DiagID)
2451 << FixItHint::CreateInsertion(EndLoc, "\n");
2452 }
Mike Stump11289f42009-09-09 15:08:12 +00002453
Chris Lattner22eb9722006-06-18 05:43:12 +00002454 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002455
2456 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002457 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002458}
2459
Chris Lattner678c8802006-07-11 05:46:12 +00002460/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2461/// the specified lexer will return a tok::l_paren token, 0 if it is something
2462/// else and 2 if there are no more tokens in the buffer controlled by the
2463/// lexer.
2464unsigned Lexer::isNextPPTokenLParen() {
2465 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattner678c8802006-07-11 05:46:12 +00002467 // Switch to 'skipping' mode. This will ensure that we can lex a token
2468 // without emitting diagnostics, disables macro expansion, and will cause EOF
2469 // to return an EOF token instead of popping the include stack.
2470 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Chris Lattner678c8802006-07-11 05:46:12 +00002472 // Save state that can be changed while lexing so that we can restore it.
2473 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002474 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Chris Lattner146762e2007-07-20 16:59:19 +00002476 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +00002477 Tok.startToken();
Chris Lattner678c8802006-07-11 05:46:12 +00002478 LexTokenInternal(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002479
Chris Lattner678c8802006-07-11 05:46:12 +00002480 // Restore state that may have changed.
2481 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002482 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump11289f42009-09-09 15:08:12 +00002483
Chris Lattner678c8802006-07-11 05:46:12 +00002484 // Restore the lexer back to non-skipping mode.
2485 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002486
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002487 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002488 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002489 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002490}
2491
James Dennettf442d242012-06-17 03:40:43 +00002492/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002493static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2494 ConflictMarkerKind CMK) {
2495 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2496 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2497 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2498 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002499 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002500 // Must occur at start of line.
2501 if (RestOfBuffer[Pos-1] != '\r' &&
2502 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002503 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2504 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002505 continue;
2506 }
2507 return RestOfBuffer.data()+Pos;
2508 }
2509 return 0;
2510}
2511
2512/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2513/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2514/// and recover nicely. This returns true if it is a conflict marker and false
2515/// if not.
2516bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2517 // Only a conflict marker if it starts at the beginning of a line.
2518 if (CurPtr != BufferStart &&
2519 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2520 return false;
2521
Richard Smitha9e33d42011-10-12 00:37:51 +00002522 // Check to see if we have <<<<<<< or >>>>.
2523 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2524 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002525 return false;
2526
2527 // If we have a situation where we don't care about conflict markers, ignore
2528 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002529 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002530 return false;
2531
Richard Smitha9e33d42011-10-12 00:37:51 +00002532 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2533
2534 // Check to see if there is an ending marker somewhere in the buffer at the
2535 // start of a line to terminate this conflict marker.
2536 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002537 // We found a match. We are really in a conflict marker.
2538 // Diagnose this, and ignore to the end of line.
2539 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002540 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002541
2542 // Skip ahead to the end of line. We know this exists because the
2543 // end-of-conflict marker starts with \r or \n.
2544 while (*CurPtr != '\r' && *CurPtr != '\n') {
2545 assert(CurPtr != BufferEnd && "Didn't find end of line");
2546 ++CurPtr;
2547 }
2548 BufferPtr = CurPtr;
2549 return true;
2550 }
2551
2552 // No end of conflict marker found.
2553 return false;
2554}
2555
2556
Richard Smitha9e33d42011-10-12 00:37:51 +00002557/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2558/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2559/// is the end of a conflict marker. Handle it by ignoring up until the end of
2560/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002561bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2562 // Only a conflict marker if it starts at the beginning of a line.
2563 if (CurPtr != BufferStart &&
2564 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2565 return false;
2566
2567 // If we have a situation where we don't care about conflict markers, ignore
2568 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002569 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002570 return false;
2571
Richard Smitha9e33d42011-10-12 00:37:51 +00002572 // Check to see if we have the marker (4 characters in a row).
2573 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002574 if (CurPtr[i] != CurPtr[0])
2575 return false;
2576
2577 // If we do have it, search for the end of the conflict marker. This could
2578 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2579 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002580 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2581 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002582 CurPtr = End;
2583
2584 // Skip ahead to the end of line.
2585 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2586 ++CurPtr;
2587
2588 BufferPtr = CurPtr;
2589
2590 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002591 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002592 return true;
2593 }
2594
2595 return false;
2596}
2597
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002598bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2599 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002600 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002601 return Loc == PP->getCodeCompletionLoc();
2602 }
2603
2604 return false;
2605}
2606
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002607uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2608 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002609 unsigned CharSize;
2610 char Kind = getCharAndSize(StartPtr, CharSize);
2611
2612 unsigned NumHexDigits;
2613 if (Kind == 'u')
2614 NumHexDigits = 4;
2615 else if (Kind == 'U')
2616 NumHexDigits = 8;
2617 else
2618 return 0;
2619
Jordan Rosec0cba272013-01-27 20:12:04 +00002620 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002621 if (Result && !isLexingRawMode())
2622 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002623 return 0;
2624 }
2625
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002626 const char *CurPtr = StartPtr + CharSize;
2627 const char *KindLoc = &CurPtr[-1];
2628
2629 uint32_t CodePoint = 0;
2630 for (unsigned i = 0; i < NumHexDigits; ++i) {
2631 char C = getCharAndSize(CurPtr, CharSize);
2632
2633 unsigned Value = llvm::hexDigitValue(C);
2634 if (Value == -1U) {
2635 if (Result && !isLexingRawMode()) {
2636 if (i == 0) {
2637 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2638 << StringRef(KindLoc, 1);
2639 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002640 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002641
2642 // If the user wrote \U1234, suggest a fixit to \u.
2643 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002644 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002645 Diag(KindLoc, diag::note_ucn_four_not_eight)
2646 << FixItHint::CreateReplacement(URange, "u");
2647 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002648 }
2649 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002650
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002651 return 0;
2652 }
2653
2654 CodePoint <<= 4;
2655 CodePoint += Value;
2656
2657 CurPtr += CharSize;
2658 }
2659
2660 if (Result) {
2661 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002662 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002663 StartPtr = CurPtr;
2664 else
2665 while (StartPtr != CurPtr)
2666 (void)getAndAdvanceChar(StartPtr, *Result);
2667 } else {
2668 StartPtr = CurPtr;
2669 }
2670
2671 // C99 6.4.3p2: A universal character name shall not specify a character whose
2672 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2673 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2674 // C++11 [lex.charset]p2: If the hexadecimal value for a
2675 // universal-character-name corresponds to a surrogate code point (in the
2676 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2677 // if the hexadecimal value for a universal-character-name outside the
2678 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2679 // string literal corresponds to a control character (in either of the
2680 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2681 // basic source character set, the program is ill-formed.
2682 if (CodePoint < 0xA0) {
2683 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2684 return CodePoint;
2685
2686 // We don't use isLexingRawMode() here because we need to warn about bad
2687 // UCNs even when skipping preprocessing tokens in a #if block.
2688 if (Result && PP) {
2689 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2690 Diag(BufferPtr, diag::err_ucn_control_character);
2691 else {
2692 char C = static_cast<char>(CodePoint);
2693 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2694 }
2695 }
2696
2697 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002698
2699 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002700 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002701 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002702 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002703 if (Result && PP) {
2704 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2705 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2706 else
2707 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2708 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002709 return 0;
2710 }
2711
2712 return CodePoint;
2713}
2714
2715void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002716 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2717 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002718 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002719 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002720 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002721 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002722
2723 Result.setFlag(Token::LeadingSpace);
2724 if (SkipWhitespace(Result, CurPtr))
2725 return; // KeepWhitespaceMode
2726
2727 return LexTokenInternal(Result);
2728 }
2729
Jordan Rose58c61e02013-02-09 01:10:25 +00002730 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2731 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2732 !PP->isPreprocessedOutput()) {
2733 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2734 makeCharRange(*this, BufferPtr, CurPtr),
2735 /*IsFirst=*/true);
2736 }
2737
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002738 MIOpt.ReadToken();
2739 return LexIdentifier(Result, CurPtr);
2740 }
2741
Jordan Rosecc538342013-01-31 19:48:48 +00002742 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2743 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002744 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002745 // Non-ASCII characters tend to creep into source code unintentionally.
2746 // Instead of letting the parser complain about the unknown token,
2747 // just drop the character.
2748 // Note that we can /only/ do this when the non-ASCII character is actually
2749 // spelled as Unicode, not written as a UCN. The standard requires that
2750 // we not throw away any possible preprocessor tokens, but there's a
2751 // loophole in the mapping of Unicode characters to basic character set
2752 // characters that allows us to map these particular characters to, say,
2753 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002754 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002755 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002756
2757 BufferPtr = CurPtr;
2758 return LexTokenInternal(Result);
2759 }
2760
2761 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2762 // up by accident.
2763 MIOpt.ReadToken();
2764 FormTokenWithChars(Result, CurPtr, tok::unknown);
2765}
2766
Chris Lattner22eb9722006-06-18 05:43:12 +00002767
2768/// LexTokenInternal - This implements a simple C family lexer. It is an
2769/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002770/// has a null character at the end of the file. This returns a preprocessing
2771/// token, not a normal token, as such, it is an internal interface. It assumes
2772/// that the Flags of result have been cleared before calling this.
Chris Lattner146762e2007-07-20 16:59:19 +00002773void Lexer::LexTokenInternal(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002774LexNextToken:
2775 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002776 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002777 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002778
Chris Lattner22eb9722006-06-18 05:43:12 +00002779 // CurPtr - Cache BufferPtr in an automatic variable.
2780 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002781
Chris Lattnereb54b592006-07-10 06:34:27 +00002782 // Small amounts of horizontal whitespace is very common between tokens.
2783 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2784 ++CurPtr;
2785 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2786 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Chris Lattner4d963442008-10-12 04:05:48 +00002788 // If we are keeping whitespace and other tokens, just return what we just
2789 // skipped. The next lexer invocation will return the token after the
2790 // whitespace.
2791 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002792 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002793 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002794 return;
2795 }
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattnereb54b592006-07-10 06:34:27 +00002797 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002798 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002799 }
Mike Stump11289f42009-09-09 15:08:12 +00002800
Chris Lattner22eb9722006-06-18 05:43:12 +00002801 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002802
Chris Lattner22eb9722006-06-18 05:43:12 +00002803 // Read a character, advancing over it.
2804 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002805 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002806
Chris Lattner22eb9722006-06-18 05:43:12 +00002807 switch (Char) {
2808 case 0: // Null.
2809 // Found end of file?
Chris Lattner2183a6e2006-07-18 06:36:12 +00002810 if (CurPtr-1 == BufferEnd) {
2811 // Read the PP instance variable into an automatic variable, because
2812 // LexEndOfFile will often delete 'this'.
Chris Lattner02b436a2007-10-17 20:41:00 +00002813 Preprocessor *PPCache = PP;
Chris Lattner2183a6e2006-07-18 06:36:12 +00002814 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2815 return; // Got a token to return.
Chris Lattner02b436a2007-10-17 20:41:00 +00002816 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2817 return PPCache->Lex(Result);
Chris Lattner2183a6e2006-07-18 06:36:12 +00002818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002820 // Check if we are performing code completion.
2821 if (isCodeCompletionPoint(CurPtr-1)) {
2822 // Return the code-completion token.
2823 Result.startToken();
2824 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2825 return;
2826 }
2827
Chris Lattner6d27a162008-11-22 02:02:22 +00002828 if (!isLexingRawMode())
2829 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002830 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002831 if (SkipWhitespace(Result, CurPtr))
2832 return; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002833
Chris Lattner22eb9722006-06-18 05:43:12 +00002834 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002835
2836 case 26: // DOS & CP/M EOF: "^Z".
2837 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002838 if (LangOpts.MicrosoftExt) {
Chris Lattner3dfff972009-12-17 05:29:40 +00002839 // Read the PP instance variable into an automatic variable, because
2840 // LexEndOfFile will often delete 'this'.
2841 Preprocessor *PPCache = PP;
2842 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2843 return; // Got a token to return.
2844 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2845 return PPCache->Lex(Result);
2846 }
2847 // If Microsoft extensions are disabled, this is just random garbage.
2848 Kind = tok::unknown;
2849 break;
2850
Chris Lattner22eb9722006-06-18 05:43:12 +00002851 case '\n':
2852 case '\r':
2853 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002854 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002855 if (ParsingPreprocessorDirective) {
2856 // Done parsing the "line".
2857 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002858
Chris Lattner457fc152006-07-29 06:30:25 +00002859 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002860 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002861 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002862
Chris Lattner22eb9722006-06-18 05:43:12 +00002863 // Since we consumed a newline, we are back at the start of a line.
2864 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002865
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002866 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002867 break;
2868 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002869
Chris Lattner22eb9722006-06-18 05:43:12 +00002870 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002871 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002872
Chris Lattner4d963442008-10-12 04:05:48 +00002873 if (SkipWhitespace(Result, CurPtr))
2874 return; // KeepWhitespaceMode
Chris Lattner22eb9722006-06-18 05:43:12 +00002875 goto LexNextToken; // GCC isn't tail call eliminating.
2876 case ' ':
2877 case '\t':
2878 case '\f':
2879 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002880 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002881 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002882 if (SkipWhitespace(Result, CurPtr))
2883 return; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002884
2885 SkipIgnoredUnits:
2886 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002887
Chris Lattnerb9b85972007-07-22 06:29:05 +00002888 // If the next token is obviously a // or /* */ comment, skip it efficiently
2889 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002890 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00002891 LangOpts.LineComment &&
2892 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Nico Weber158a31a2012-11-11 07:02:14 +00002893 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner87d02082010-01-18 22:35:47 +00002894 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002895 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002896 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner87d02082010-01-18 22:35:47 +00002897 if (SkipBlockComment(Result, CurPtr+2))
2898 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002899 goto SkipIgnoredUnits;
2900 } else if (isHorizontalWhitespace(*CurPtr)) {
2901 goto SkipHorizontalWhitespace;
2902 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002903 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002904
Chris Lattner2b15cf72008-01-03 17:58:54 +00002905 // C99 6.4.4.1: Integer Constants.
2906 // C99 6.4.4.2: Floating Constants.
2907 case '0': case '1': case '2': case '3': case '4':
2908 case '5': case '6': case '7': case '8': case '9':
2909 // Notify MIOpt that we read a non-whitespace/non-comment token.
2910 MIOpt.ReadToken();
2911 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00002912
Richard Smith9b362092013-03-09 23:56:02 +00002913 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002914 // Notify MIOpt that we read a non-whitespace/non-comment token.
2915 MIOpt.ReadToken();
2916
Richard Smith9b362092013-03-09 23:56:02 +00002917 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002918 Char = getCharAndSize(CurPtr, SizeTmp);
2919
2920 // UTF-16 string literal
2921 if (Char == '"')
2922 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2923 tok::utf16_string_literal);
2924
2925 // UTF-16 character constant
2926 if (Char == '\'')
2927 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2928 tok::utf16_char_constant);
2929
Craig Topper54edcca2011-08-11 04:06:15 +00002930 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002931 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2932 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002933 return LexRawStringLiteral(Result,
2934 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2935 SizeTmp2, Result),
2936 tok::utf16_string_literal);
2937
2938 if (Char == '8') {
2939 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2940
2941 // UTF-8 string literal
2942 if (Char2 == '"')
2943 return LexStringLiteral(Result,
2944 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2945 SizeTmp2, Result),
2946 tok::utf8_string_literal);
2947
Richard Smith9b362092013-03-09 23:56:02 +00002948 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00002949 unsigned SizeTmp3;
2950 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2951 // UTF-8 raw string literal
2952 if (Char3 == '"') {
2953 return LexRawStringLiteral(Result,
2954 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2955 SizeTmp2, Result),
2956 SizeTmp3, Result),
2957 tok::utf8_string_literal);
2958 }
2959 }
2960 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00002961 }
2962
2963 // treat u like the start of an identifier.
2964 return LexIdentifier(Result, CurPtr);
2965
Richard Smith9b362092013-03-09 23:56:02 +00002966 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002967 // Notify MIOpt that we read a non-whitespace/non-comment token.
2968 MIOpt.ReadToken();
2969
Richard Smith9b362092013-03-09 23:56:02 +00002970 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002971 Char = getCharAndSize(CurPtr, SizeTmp);
2972
2973 // UTF-32 string literal
2974 if (Char == '"')
2975 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2976 tok::utf32_string_literal);
2977
2978 // UTF-32 character constant
2979 if (Char == '\'')
2980 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2981 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00002982
2983 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002984 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2985 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002986 return LexRawStringLiteral(Result,
2987 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2988 SizeTmp2, Result),
2989 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00002990 }
2991
2992 // treat U like the start of an identifier.
2993 return LexIdentifier(Result, CurPtr);
2994
Craig Topper54edcca2011-08-11 04:06:15 +00002995 case 'R': // Identifier or C++0x raw string literal
2996 // Notify MIOpt that we read a non-whitespace/non-comment token.
2997 MIOpt.ReadToken();
2998
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002999 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003000 Char = getCharAndSize(CurPtr, SizeTmp);
3001
3002 if (Char == '"')
3003 return LexRawStringLiteral(Result,
3004 ConsumeChar(CurPtr, SizeTmp, Result),
3005 tok::string_literal);
3006 }
3007
3008 // treat R like the start of an identifier.
3009 return LexIdentifier(Result, CurPtr);
3010
Chris Lattner2b15cf72008-01-03 17:58:54 +00003011 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003012 // Notify MIOpt that we read a non-whitespace/non-comment token.
3013 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003014 Char = getCharAndSize(CurPtr, SizeTmp);
3015
3016 // Wide string literal.
3017 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003018 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003019 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003020
Craig Topper54edcca2011-08-11 04:06:15 +00003021 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003022 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003023 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3024 return LexRawStringLiteral(Result,
3025 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3026 SizeTmp2, Result),
3027 tok::wide_string_literal);
3028
Chris Lattner22eb9722006-06-18 05:43:12 +00003029 // Wide character constant.
3030 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003031 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3032 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003033 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003034
Chris Lattner22eb9722006-06-18 05:43:12 +00003035 // C99 6.4.2: Identifiers.
3036 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3037 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003038 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003039 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3040 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3041 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003042 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003043 case 'v': case 'w': case 'x': case 'y': case 'z':
3044 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003045 // Notify MIOpt that we read a non-whitespace/non-comment token.
3046 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003047 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003048
3049 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003050 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003051 if (!isLexingRawMode())
3052 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003053 // Notify MIOpt that we read a non-whitespace/non-comment token.
3054 MIOpt.ReadToken();
3055 return LexIdentifier(Result, CurPtr);
3056 }
Mike Stump11289f42009-09-09 15:08:12 +00003057
Chris Lattnerb11c3232008-10-12 04:51:35 +00003058 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003059 break;
Mike Stump11289f42009-09-09 15:08:12 +00003060
Chris Lattner22eb9722006-06-18 05:43:12 +00003061 // C99 6.4.4: Character Constants.
3062 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003063 // Notify MIOpt that we read a non-whitespace/non-comment token.
3064 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003065 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003066
3067 // C99 6.4.5: String Literals.
3068 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003069 // Notify MIOpt that we read a non-whitespace/non-comment token.
3070 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003071 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003072
3073 // C99 6.4.6: Punctuators.
3074 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003075 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003076 break;
3077 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003078 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003079 break;
3080 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003081 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003082 break;
3083 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003084 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003085 break;
3086 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003087 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003088 break;
3089 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003090 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003091 break;
3092 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003093 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003094 break;
3095 case '.':
3096 Char = getCharAndSize(CurPtr, SizeTmp);
3097 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003098 // Notify MIOpt that we read a non-whitespace/non-comment token.
3099 MIOpt.ReadToken();
3100
Chris Lattner22eb9722006-06-18 05:43:12 +00003101 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003102 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003103 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003104 CurPtr += SizeTmp;
3105 } else if (Char == '.' &&
3106 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003107 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003108 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3109 SizeTmp2, Result);
3110 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003111 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003112 }
3113 break;
3114 case '&':
3115 Char = getCharAndSize(CurPtr, SizeTmp);
3116 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003117 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003118 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3119 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003120 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003121 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3122 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003123 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003124 }
3125 break;
Mike Stump11289f42009-09-09 15:08:12 +00003126 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003127 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003128 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003129 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3130 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003131 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003132 }
3133 break;
3134 case '+':
3135 Char = getCharAndSize(CurPtr, SizeTmp);
3136 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003137 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003138 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003139 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003140 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003141 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003142 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003143 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003144 }
3145 break;
3146 case '-':
3147 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003148 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003149 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003150 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003151 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003152 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003153 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3154 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003155 Kind = tok::arrowstar;
3156 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003157 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003158 Kind = tok::arrow;
3159 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003160 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003161 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003162 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003163 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003164 }
3165 break;
3166 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003167 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003168 break;
3169 case '!':
3170 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003171 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003172 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3173 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003174 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003175 }
3176 break;
3177 case '/':
3178 // 6.4.9: Comments
3179 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003180 if (Char == '/') { // Line comment.
3181 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003182 // want to lex this as a comment. There is one problem with this though,
3183 // that in one particular corner case, this can change the behavior of the
3184 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003185 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003186 // "foo". Check to see if the character after the second slash is a '*'.
3187 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003188 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003189 bool TreatAsComment = LangOpts.LineComment &&
3190 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003191 if (!TreatAsComment)
3192 if (!(PP && PP->isPreprocessedOutput()))
3193 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3194
3195 if (TreatAsComment) {
Nico Weber158a31a2012-11-11 07:02:14 +00003196 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003197 return; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003198
Chris Lattner58827712009-01-16 22:39:25 +00003199 // It is common for the tokens immediately after a // comment to be
3200 // whitespace (indentation for the next line). Instead of going through
3201 // the big switch, handle it efficiently now.
3202 goto SkipIgnoredUnits;
3203 }
3204 }
Mike Stump11289f42009-09-09 15:08:12 +00003205
Chris Lattner58827712009-01-16 22:39:25 +00003206 if (Char == '*') { // /**/ comment.
Chris Lattner457fc152006-07-29 06:30:25 +00003207 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003208 return; // There is a token to return.
Chris Lattnere01e7582008-10-12 04:15:42 +00003209 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner58827712009-01-16 22:39:25 +00003210 }
Mike Stump11289f42009-09-09 15:08:12 +00003211
Chris Lattner58827712009-01-16 22:39:25 +00003212 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003213 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003214 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003215 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003216 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003217 }
3218 break;
3219 case '%':
3220 Char = getCharAndSize(CurPtr, SizeTmp);
3221 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003222 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003223 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003224 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003225 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003226 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003227 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003228 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003229 Char = getCharAndSize(CurPtr, SizeTmp);
3230 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003231 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003232 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3233 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003234 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003235 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003236 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003237 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003238 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003239 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003240 // We parsed a # character. If this occurs at the start of the line,
3241 // it's actually the start of a preprocessing directive. Callback to
3242 // the preprocessor to handle it.
3243 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003244 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3245 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003246
Chris Lattner2534324a2009-03-18 20:58:27 +00003247 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003248 }
3249 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003250 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 }
3252 break;
3253 case '<':
3254 Char = getCharAndSize(CurPtr, SizeTmp);
3255 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003256 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003257 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003258 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3259 if (After == '=') {
3260 Kind = tok::lesslessequal;
3261 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3262 SizeTmp2, Result);
3263 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3264 // If this is actually a '<<<<<<<' version control conflict marker,
3265 // recognize it as such and recover nicely.
3266 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003267 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3268 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3269 // ignore it.
3270 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003271 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003272 Kind = tok::lesslessless;
3273 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3274 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003275 } else {
3276 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3277 Kind = tok::lessless;
3278 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003279 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003280 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003281 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003282 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003283 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003284 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3285 // C++0x [lex.pptoken]p3:
3286 // Otherwise, if the next three characters are <:: and the subsequent
3287 // character is neither : nor >, the < is treated as a preprocessor
3288 // token by itself and not as the first character of the alternative
3289 // token <:.
3290 unsigned SizeTmp3;
3291 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3292 if (After != ':' && After != '>') {
3293 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003294 if (!isLexingRawMode())
3295 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003296 break;
3297 }
3298 }
3299
Chris Lattner22eb9722006-06-18 05:43:12 +00003300 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003301 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003302 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003304 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003305 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003306 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003307 }
3308 break;
3309 case '>':
3310 Char = getCharAndSize(CurPtr, SizeTmp);
3311 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003312 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003313 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003314 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003315 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3316 if (After == '=') {
3317 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3318 SizeTmp2, Result);
3319 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003320 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3321 // If this is actually a '>>>>' conflict marker, recognize it as such
3322 // and recover nicely.
3323 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003324 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3325 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3326 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003327 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003328 Kind = tok::greatergreatergreater;
3329 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3330 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003331 } else {
3332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3333 Kind = tok::greatergreater;
3334 }
3335
Chris Lattner22eb9722006-06-18 05:43:12 +00003336 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003337 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003338 }
3339 break;
3340 case '^':
3341 Char = getCharAndSize(CurPtr, SizeTmp);
3342 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003343 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003344 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003345 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003346 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003347 }
3348 break;
3349 case '|':
3350 Char = getCharAndSize(CurPtr, SizeTmp);
3351 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003352 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003353 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3354 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003355 // If this is '|||||||' and we're in a conflict marker, ignore it.
3356 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3357 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003358 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003359 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3360 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003361 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003362 }
3363 break;
3364 case ':':
3365 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003366 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003367 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003368 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003369 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003370 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003371 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003372 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003373 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003374 }
3375 break;
3376 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003378 break;
3379 case '=':
3380 Char = getCharAndSize(CurPtr, SizeTmp);
3381 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003382 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003383 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3384 goto LexNextToken;
3385
Chris Lattnerb11c3232008-10-12 04:51:35 +00003386 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003387 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003388 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003389 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003390 }
3391 break;
3392 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003393 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003394 break;
3395 case '#':
3396 Char = getCharAndSize(CurPtr, SizeTmp);
3397 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003398 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003399 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003400 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003401 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003402 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003403 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003404 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003405 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003406 // We parsed a # character. If this occurs at the start of the line,
3407 // it's actually the start of a preprocessing directive. Callback to
3408 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003409 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003410 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3411 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003412
Chris Lattner2534324a2009-03-18 20:58:27 +00003413 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003414 }
3415 break;
3416
Chris Lattner2b15cf72008-01-03 17:58:54 +00003417 case '@':
3418 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003419 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003420 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003421 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003422 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003423 break;
Mike Stump11289f42009-09-09 15:08:12 +00003424
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003425 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 case '\\':
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003427 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3428 return LexUnicode(Result, CodePoint, CurPtr);
3429
Chris Lattnerb11c3232008-10-12 04:51:35 +00003430 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003431 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003432
3433 default: {
3434 if (isASCII(Char)) {
3435 Kind = tok::unknown;
3436 break;
3437 }
3438
3439 UTF32 CodePoint;
3440
3441 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3442 // an escaped newline.
3443 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003444 ConversionResult Status =
3445 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3446 (const UTF8 *)BufferEnd,
3447 &CodePoint,
3448 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003449 if (Status == conversionOK)
3450 return LexUnicode(Result, CodePoint, CurPtr);
3451
Jordan Rosecc538342013-01-31 19:48:48 +00003452 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3453 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003454 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003455 Kind = tok::unknown;
3456 break;
3457 }
3458
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003459 // Non-ASCII characters tend to creep into source code unintentionally.
3460 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003461 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003462 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003463
3464 BufferPtr = CurPtr+1;
3465 goto LexNextToken;
3466 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003467 }
Mike Stump11289f42009-09-09 15:08:12 +00003468
Chris Lattner371ac8a2006-07-04 07:11:10 +00003469 // Notify MIOpt that we read a non-whitespace/non-comment token.
3470 MIOpt.ReadToken();
3471
Chris Lattnerd01e2912006-06-18 16:22:51 +00003472 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003473 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003474 return;
3475
3476HandleDirective:
3477 // We parsed a # character and it's the start of a preprocessing directive.
3478
3479 FormTokenWithChars(Result, CurPtr, tok::hash);
3480 PP->HandleDirective(Result);
3481
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003482 if (PP->hadModuleLoaderFatalFailure()) {
3483 // With a fatal failure in the module loader, we abort parsing.
3484 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3485 return;
3486 }
3487
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003488 // As an optimization, if the preprocessor didn't switch lexers, tail
3489 // recurse.
3490 if (PP->isCurrentLexer(this)) {
3491 // Start a new token. If this is a #include or something, the PP may
3492 // want us starting at the beginning of the line again. If so, set
3493 // the StartOfLine flag and clear LeadingSpace.
3494 if (IsAtStartOfLine) {
3495 Result.setFlag(Token::StartOfLine);
3496 Result.clearFlag(Token::LeadingSpace);
3497 IsAtStartOfLine = false;
3498 }
3499 goto LexNextToken; // GCC isn't tail call eliminating.
3500 }
3501 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003502}