blob: 71db68a58c029a622f3f2f1d96abb11c4c4b31a2 [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,
433 const LangOptions &LangOpts) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000434 // TODO: this could be special cased for common tokens like identifiers, ')',
435 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000436 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000437 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
438 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000439
440 // If this comes from a macro expansion, we really do want the macro name, not
441 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000442 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000443 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000444 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000445 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000446 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000447 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000448
449 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000450
Douglas Gregor562c1f92010-01-22 19:49:59 +0000451 if (isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000452 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000453
Chris Lattner8e129c22007-10-17 21:18:47 +0000454 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000455 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
456 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000457 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000458 TheLexer.LexFromRawLexer(Result);
459 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000460}
461
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000462static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
463 const SourceManager &SM,
464 const LangOptions &LangOpts) {
465 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000466 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000467 if (LocInfo.first.isInvalid())
468 return Loc;
469
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000470 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000472 if (Invalid)
473 return Loc;
474
475 // Back up from the current location until we hit the beginning of a line
476 // (or the buffer). We'll relex from that point.
477 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000478 if (LocInfo.second >= Buffer.size())
479 return Loc;
480
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000481 const char *StrData = BufStart+LocInfo.second;
482 if (StrData[0] == '\n' || StrData[0] == '\r')
483 return Loc;
484
485 const char *LexStart = StrData;
486 while (LexStart != BufStart) {
487 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
488 ++LexStart;
489 break;
490 }
491
492 --LexStart;
493 }
494
495 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000496 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000497 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
498 TheLexer.SetCommentRetentionState(true);
499
500 // Lex tokens until we find the token that contains the source location.
501 Token TheTok;
502 do {
503 TheLexer.LexFromRawLexer(TheTok);
504
505 if (TheLexer.getBufferLocation() > StrData) {
506 // Lexing this token has taken the lexer past the source location we're
507 // looking for. If the current token encompasses our source location,
508 // return the beginning of that token.
509 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
510 return TheTok.getLocation();
511
512 // We ended up skipping over the source location entirely, which means
513 // that it points into whitespace. We're done here.
514 break;
515 }
516 } while (TheTok.getKind() != tok::eof);
517
518 // We've passed our source location; just return the original source location.
519 return Loc;
520}
521
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000522SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
523 const SourceManager &SM,
524 const LangOptions &LangOpts) {
525 if (Loc.isFileID())
526 return getBeginningOfFileToken(Loc, SM, LangOpts);
527
528 if (!SM.isMacroArgExpansion(Loc))
529 return Loc;
530
531 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
532 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
533 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000534 std::pair<FileID, unsigned> BeginFileLocInfo
535 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000536 assert(FileLocInfo.first == BeginFileLocInfo.first &&
537 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000538 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000539}
540
Douglas Gregoraf82e352010-07-20 20:18:03 +0000541namespace {
542 enum PreambleDirectiveKind {
543 PDK_Skipped,
544 PDK_StartIf,
545 PDK_EndIf,
546 PDK_Unknown
547 };
548}
549
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000550std::pair<unsigned, bool>
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000551Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000552 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000553 // Create a lexer starting at the beginning of the file. Note that we use a
554 // "fake" file source location at offset 1 so that the lexer will track our
555 // position within the file.
556 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000557 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
558 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregoraf82e352010-07-20 20:18:03 +0000559 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000560 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000561
562 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
563 SourceLocation StartLoc = TheLexer.getSourceLocation();
564
Douglas Gregoraf82e352010-07-20 20:18:03 +0000565 bool InPreprocessorDirective = false;
566 Token TheTok;
567 Token IfStartTok;
568 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000569 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000570
571 unsigned MaxLineOffset = 0;
572 if (MaxLines) {
573 const char *CurPtr = Buffer->getBufferStart();
574 unsigned CurLine = 0;
575 while (CurPtr != Buffer->getBufferEnd()) {
576 char ch = *CurPtr++;
577 if (ch == '\n') {
578 ++CurLine;
579 if (CurLine == MaxLines)
580 break;
581 }
582 }
583 if (CurPtr != Buffer->getBufferEnd())
584 MaxLineOffset = CurPtr - Buffer->getBufferStart();
585 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000586
Douglas Gregoraf82e352010-07-20 20:18:03 +0000587 do {
588 TheLexer.LexFromRawLexer(TheTok);
589
590 if (InPreprocessorDirective) {
591 // If we've hit the end of the file, we're done.
592 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000593 break;
594 }
595
596 // If we haven't hit the end of the preprocessor directive, skip this
597 // token.
598 if (!TheTok.isAtStartOfLine())
599 continue;
600
601 // We've passed the end of the preprocessor directive, and will look
602 // at this token again below.
603 InPreprocessorDirective = false;
604 }
605
Douglas Gregor028d3e42010-08-09 20:45:32 +0000606 // Keep track of the # of lines in the preamble.
607 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000608 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000609
610 // If we were asked to limit the number of lines in the preamble,
611 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000612 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000613 break;
614 }
615
Douglas Gregoraf82e352010-07-20 20:18:03 +0000616 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000617 if (TheTok.getKind() == tok::comment) {
618 if (ActiveCommentLoc.isInvalid())
619 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000620 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000621 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622
623 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
624 // This is the start of a preprocessor directive.
625 Token HashTok = TheTok;
626 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000627 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000628
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000629 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000630 // we don't have an identifier table available. Instead, just look at
631 // the raw identifier to recognize and categorize preprocessor directives.
632 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000633 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000634 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000635 TheTok.getLength());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000636 PreambleDirectiveKind PDK
637 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
638 .Case("include", PDK_Skipped)
639 .Case("__include_macros", PDK_Skipped)
640 .Case("define", PDK_Skipped)
641 .Case("undef", PDK_Skipped)
642 .Case("line", PDK_Skipped)
643 .Case("error", PDK_Skipped)
644 .Case("pragma", PDK_Skipped)
645 .Case("import", PDK_Skipped)
646 .Case("include_next", PDK_Skipped)
647 .Case("warning", PDK_Skipped)
648 .Case("ident", PDK_Skipped)
649 .Case("sccs", PDK_Skipped)
650 .Case("assert", PDK_Skipped)
651 .Case("unassert", PDK_Skipped)
652 .Case("if", PDK_StartIf)
653 .Case("ifdef", PDK_StartIf)
654 .Case("ifndef", PDK_StartIf)
655 .Case("elif", PDK_Skipped)
656 .Case("else", PDK_Skipped)
657 .Case("endif", PDK_EndIf)
658 .Default(PDK_Unknown);
659
660 switch (PDK) {
661 case PDK_Skipped:
662 continue;
663
664 case PDK_StartIf:
665 if (IfCount == 0)
666 IfStartTok = HashTok;
667
668 ++IfCount;
669 continue;
670
671 case PDK_EndIf:
672 // Mismatched #endif. The preamble ends here.
673 if (IfCount == 0)
674 break;
675
676 --IfCount;
677 continue;
678
679 case PDK_Unknown:
680 // We don't know what this directive is; stop at the '#'.
681 break;
682 }
683 }
684
685 // We only end up here if we didn't recognize the preprocessor
686 // directive or it was one that can't occur in the preamble at this
687 // point. Roll back the current token to the location of the '#'.
688 InPreprocessorDirective = false;
689 TheTok = HashTok;
690 }
691
Douglas Gregor028d3e42010-08-09 20:45:32 +0000692 // We hit a token that we don't recognize as being in the
693 // "preprocessing only" part of the file, so we're no longer in
694 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000695 break;
696 } while (true);
697
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000698 SourceLocation End;
699 if (IfCount)
700 End = IfStartTok.getLocation();
701 else if (ActiveCommentLoc.isValid())
702 End = ActiveCommentLoc; // don't truncate a decl comment.
703 else
704 End = TheTok.getLocation();
705
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000706 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
707 IfCount? IfStartTok.isAtStartOfLine()
708 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000709}
710
Chris Lattner2a6ee912010-11-17 07:05:50 +0000711
712/// AdvanceToTokenCharacter - Given a location that specifies the start of a
713/// token, return a new location that specifies a character within the token.
714SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
715 unsigned CharNo,
716 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000717 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000718 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000719 // character is. This needs to take into consideration newlines and
720 // trigraphs.
721 bool Invalid = false;
722 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
723
724 // If they request the first char of the token, we're trivially done.
725 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
726 return TokStart;
727
728 unsigned PhysOffset = 0;
729
730 // The usual case is that tokens don't contain anything interesting. Skip
731 // over the uninteresting characters. If a token only consists of simple
732 // chars, this method is extremely fast.
733 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
734 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000735 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000736 ++TokPtr, --CharNo, ++PhysOffset;
737 }
738
739 // If we have a character that may be a trigraph or escaped newline, use a
740 // lexer to parse it correctly.
741 for (; CharNo; --CharNo) {
742 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000743 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000744 TokPtr += Size;
745 PhysOffset += Size;
746 }
747
748 // Final detail: if we end up on an escaped newline, we want to return the
749 // location of the actual byte of the token. For example foo\<newline>bar
750 // advanced by 3 should return the location of b, not of \\. One compounding
751 // detail of this is that the escape may be made by a trigraph.
752 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
753 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
754
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000755 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000756}
757
758/// \brief Computes the source location just past the end of the
759/// token at this source location.
760///
761/// This routine can be used to produce a source location that
762/// points just past the end of the token referenced by \p Loc, and
763/// is generally used when a diagnostic needs to point just after a
764/// token where it expected something different that it received. If
765/// the returned source location would not be meaningful (e.g., if
766/// it points into a macro), this routine returns an invalid
767/// source location.
768///
769/// \param Offset an offset from the end of the token, where the source
770/// location should refer to. The default offset (0) produces a source
771/// location pointing just past the end of the token; an offset of 1 produces
772/// a source location pointing to the last character in the token, etc.
773SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
774 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000776 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000777 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000778
779 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000781 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000782 }
783
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000785 if (Len > Offset)
786 Len = Len - Offset;
787 else
788 return Loc;
789
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000790 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000791}
792
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000793/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000794/// token of the macro expansion.
795bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000796 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000797 const LangOptions &LangOpts,
798 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
800
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000801 SourceLocation expansionLoc;
802 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
803 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000804
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000805 if (expansionLoc.isFileID()) {
806 // No other macro expansions, this is the first.
807 if (MacroBegin)
808 *MacroBegin = expansionLoc;
809 return true;
810 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000811
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000812 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000813}
814
815/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000816/// token of the macro expansion.
817bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000818 const SourceManager &SM,
819 const LangOptions &LangOpts,
820 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000821 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
822
823 SourceLocation spellLoc = SM.getSpellingLoc(loc);
824 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
825 if (tokLen == 0)
826 return false;
827
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000828 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
829 SourceLocation expansionLoc;
830 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
831 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000832
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000833 if (expansionLoc.isFileID()) {
834 // No other macro expansions.
835 if (MacroEnd)
836 *MacroEnd = expansionLoc;
837 return true;
838 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000839
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000840 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000841}
842
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000843static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000844 const SourceManager &SM,
845 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000846 SourceLocation Begin = Range.getBegin();
847 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000848 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000849 if (Range.isTokenRange()) {
850 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
851 if (End.isInvalid())
852 return CharSourceRange();
853 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000854
855 // Break down the source locations.
856 FileID FID;
857 unsigned BeginOffs;
858 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
859 if (FID.isInvalid())
860 return CharSourceRange();
861
862 unsigned EndOffs;
863 if (!SM.isInFileID(End, FID, &EndOffs) ||
864 BeginOffs > EndOffs)
865 return CharSourceRange();
866
867 return CharSourceRange::getCharRange(Begin, End);
868}
869
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000870CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000871 const SourceManager &SM,
872 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000873 SourceLocation Begin = Range.getBegin();
874 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000875 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000876 return CharSourceRange();
877
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000878 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000879 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000880
881 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000882 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
883 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000884 Range.setBegin(Begin);
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000887
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000888 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
890 &End)) ||
891 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
892 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000893 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000894 Range.setEnd(End);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000896 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000897
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000898 assert(Begin.isMacroID() && End.isMacroID());
899 SourceLocation MacroBegin, MacroEnd;
900 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000901 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
902 &MacroEnd)) ||
903 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
904 &MacroEnd)))) {
905 Range.setBegin(MacroBegin);
906 Range.setEnd(MacroEnd);
907 return makeRangeFromFileLocs(Range, SM, LangOpts);
908 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000909
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000910 bool Invalid = false;
911 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
912 &Invalid);
913 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000914 return CharSourceRange();
915
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000916 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
917 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
918 &Invalid);
919 if (Invalid)
920 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000921
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000922 if (EndEntry.getExpansion().isMacroArgExpansion() &&
923 BeginEntry.getExpansion().getExpansionLocStart() ==
924 EndEntry.getExpansion().getExpansionLocStart()) {
925 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
926 Range.setEnd(SM.getImmediateSpellingLoc(End));
927 return makeFileCharRange(Range, SM, LangOpts);
928 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000929 }
930
931 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000932}
933
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000934StringRef Lexer::getSourceText(CharSourceRange Range,
935 const SourceManager &SM,
936 const LangOptions &LangOpts,
937 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000938 Range = makeFileCharRange(Range, SM, LangOpts);
939 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000940 if (Invalid) *Invalid = true;
941 return StringRef();
942 }
943
944 // Break down the source location.
945 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
946 if (beginInfo.first.isInvalid()) {
947 if (Invalid) *Invalid = true;
948 return StringRef();
949 }
950
951 unsigned EndOffs;
952 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
953 beginInfo.second > EndOffs) {
954 if (Invalid) *Invalid = true;
955 return StringRef();
956 }
957
958 // Try to the load the file buffer.
959 bool invalidTemp = false;
960 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
961 if (invalidTemp) {
962 if (Invalid) *Invalid = true;
963 return StringRef();
964 }
965
966 if (Invalid) *Invalid = false;
967 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
968}
969
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000970StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
971 const SourceManager &SM,
972 const LangOptions &LangOpts) {
973 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000974
975 // Find the location of the immediate macro expansion.
976 while (1) {
977 FileID FID = SM.getFileID(Loc);
978 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
979 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
980 Loc = Expansion.getExpansionLocStart();
981 if (!Expansion.isMacroArgExpansion())
982 break;
983
984 // For macro arguments we need to check that the argument did not come
985 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
986
987 // Loc points to the argument id of the macro definition, move to the
988 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000989 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000990 SourceLocation SpellLoc = Expansion.getSpellingLoc();
991 if (SpellLoc.isFileID())
992 break; // No inner macro.
993
994 // If spelling location resides in the same FileID as macro expansion
995 // location, it means there is no inner macro.
996 FileID MacroFID = SM.getFileID(Loc);
997 if (SM.isInFileID(SpellLoc, MacroFID))
998 break;
999
1000 // Argument came from inner macro.
1001 Loc = SpellLoc;
1002 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001003
1004 // Find the spelling location of the start of the non-argument expansion
1005 // range. This is where the macro name was spelled in order to begin
1006 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001007 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001008
1009 // Dig out the buffer where the macro name was spelled and the extents of the
1010 // name so that we can render it into the expansion note.
1011 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1012 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1013 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1014 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1015}
1016
Jordan Rose288c4212012-06-07 01:10:31 +00001017bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001018 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001019}
1020
Chris Lattnerd01e2912006-06-18 16:22:51 +00001021
Chris Lattner22eb9722006-06-18 05:43:12 +00001022//===----------------------------------------------------------------------===//
1023// Diagnostics forwarding code.
1024//===----------------------------------------------------------------------===//
1025
Chris Lattner619c1742007-07-22 18:38:25 +00001026/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001027/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001028/// This is currently only used for _Pragma implementation, so it is the slow
1029/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001030static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1031 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001032static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1033 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001034 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001035 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattner619c1742007-07-22 18:38:25 +00001037 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001038 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001039 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001040 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001042 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001043 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001044 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001045 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner9dc9c202009-02-15 20:52:18 +00001047 // Figure out the expansion loc range, which is the range covered by the
1048 // original _Pragma(...) sequence.
1049 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001050 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chandler Carruth115b0772011-07-26 03:03:05 +00001052 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001053}
1054
Chris Lattner22eb9722006-06-18 05:43:12 +00001055/// getSourceLocation - Return a source location identifier for the specified
1056/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001057SourceLocation Lexer::getSourceLocation(const char *Loc,
1058 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001059 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001060 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001061
1062 // In the normal case, we're just lexing from a simple file buffer, return
1063 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001064 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001065 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001066 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattnerd32480d2009-01-17 06:22:33 +00001068 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1069 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001070 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001071 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001072}
1073
Chris Lattner22eb9722006-06-18 05:43:12 +00001074/// Diag - Forwarding function for diagnostics. This translate a source
1075/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001076DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001077 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078}
1079
1080//===----------------------------------------------------------------------===//
1081// Trigraph and Escaped Newline Handling Code.
1082//===----------------------------------------------------------------------===//
1083
1084/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1085/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1086static char GetTrigraphCharForLetter(char Letter) {
1087 switch (Letter) {
1088 default: return 0;
1089 case '=': return '#';
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 }
1099}
1100
1101/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1102/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1103/// return the result character. Finally, emit a warning about trigraph use
1104/// whether trigraphs are enabled or not.
1105static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1106 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001107 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001108
David Blaikiebbafb8a2012-03-11 07:00:24 +00001109 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001110 if (!L->isLexingRawMode())
1111 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001112 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001113 }
Mike Stump11289f42009-09-09 15:08:12 +00001114
Chris Lattner6d27a162008-11-22 02:02:22 +00001115 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001116 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001117 return Res;
1118}
1119
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001120/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1121/// 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 +00001122/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001123unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1124 unsigned Size = 0;
1125 while (isWhitespace(Ptr[Size])) {
1126 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001128 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1129 continue;
1130
1131 // If this is a \r\n or \n\r, skip the other half.
1132 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1133 Ptr[Size-1] != Ptr[Size])
1134 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001136 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001137 }
1138
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001139 // Not an escaped newline, must be a \t or something else.
1140 return 0;
1141}
1142
Chris Lattner38b2cde2009-04-18 22:27:02 +00001143/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1144/// them), skip over them and return the first non-escaped-newline found,
1145/// otherwise return P.
1146const char *Lexer::SkipEscapedNewLines(const char *P) {
1147 while (1) {
1148 const char *AfterEscape;
1149 if (*P == '\\') {
1150 AfterEscape = P+1;
1151 } else if (*P == '?') {
1152 // If not a trigraph for escape, bail out.
1153 if (P[1] != '?' || P[2] != '/')
1154 return P;
1155 AfterEscape = P+3;
1156 } else {
1157 return P;
1158 }
Mike Stump11289f42009-09-09 15:08:12 +00001159
Chris Lattner38b2cde2009-04-18 22:27:02 +00001160 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1161 if (NewLineSize == 0) return P;
1162 P = AfterEscape+NewLineSize;
1163 }
1164}
1165
Anna Zaks59a3c802011-07-27 21:43:43 +00001166/// \brief Checks that the given token is the first token that occurs after the
1167/// given location (this excludes comments and whitespace). Returns the location
1168/// immediately after the specified token. If the token is not found or the
1169/// location is inside a macro, the returned source location will be invalid.
1170SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1171 tok::TokenKind TKind,
1172 const SourceManager &SM,
1173 const LangOptions &LangOpts,
1174 bool SkipTrailingWhitespaceAndNewLine) {
1175 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001176 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001177 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001178 }
1179 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1180
1181 // Break down the source location.
1182 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1183
1184 // Try to load the file buffer.
1185 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001186 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001187 if (InvalidTemp)
1188 return SourceLocation();
1189
1190 const char *TokenBegin = File.data() + LocInfo.second;
1191
1192 // Lex from the start of the given location.
1193 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1194 TokenBegin, File.end());
1195 // Find the token.
1196 Token Tok;
1197 lexer.LexFromRawLexer(Tok);
1198 if (Tok.isNot(TKind))
1199 return SourceLocation();
1200 SourceLocation TokenLoc = Tok.getLocation();
1201
1202 // Calculate how much whitespace needs to be skipped if any.
1203 unsigned NumWhitespaceChars = 0;
1204 if (SkipTrailingWhitespaceAndNewLine) {
1205 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1206 Tok.getLength();
1207 unsigned char C = *TokenEnd;
1208 while (isHorizontalWhitespace(C)) {
1209 C = *(++TokenEnd);
1210 NumWhitespaceChars++;
1211 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001212
1213 // Skip \r, \n, \r\n, or \n\r
1214 if (C == '\n' || C == '\r') {
1215 char PrevC = C;
1216 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001217 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001218 if ((C == '\n' || C == '\r') && C != PrevC)
1219 NumWhitespaceChars++;
1220 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001221 }
1222
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001223 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001224}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001225
Chris Lattner22eb9722006-06-18 05:43:12 +00001226/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1227/// get its size, and return it. This is tricky in several cases:
1228/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1229/// then either return the trigraph (skipping 3 chars) or the '?',
1230/// depending on whether trigraphs are enabled or not.
1231/// 2. If this is an escaped newline (potentially with whitespace between
1232/// the backslash and newline), implicitly skip the newline and return
1233/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001234///
1235/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1236/// know that we can accumulate into Size, and that we have already incremented
1237/// Ptr by Size bytes.
1238///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001239/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1240/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001241///
1242char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001243 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001244 // If we have a slash, look for an escaped newline.
1245 if (Ptr[0] == '\\') {
1246 ++Size;
1247 ++Ptr;
1248Slash:
1249 // Common case, backslash-char where the char is not whitespace.
1250 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattnerc1835952009-06-23 05:15:06 +00001252 // See if we have optional whitespace characters between the slash and
1253 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001254 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1255 // Remember that this token needs to be cleaned.
1256 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001257
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001258 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001259 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001260 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001262 // Found backslash<whitespace><newline>. Parse the char after it.
1263 Size += EscapedNewLineSize;
1264 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001265
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001266 // If the char that we finally got was a \n, then we must have had
1267 // something like \<newline><newline>. We don't want to consume the
1268 // second newline.
1269 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1270 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001271
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001272 // Use slow version to accumulate a correct size field.
1273 return getCharAndSizeSlow(Ptr, Size, Tok);
1274 }
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattner22eb9722006-06-18 05:43:12 +00001276 // Otherwise, this is not an escaped newline, just return the slash.
1277 return '\\';
1278 }
Mike Stump11289f42009-09-09 15:08:12 +00001279
Chris Lattner22eb9722006-06-18 05:43:12 +00001280 // If this is a trigraph, process it.
1281 if (Ptr[0] == '?' && Ptr[1] == '?') {
1282 // If this is actually a legal trigraph (not something like "??x"), emit
1283 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1284 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1285 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001286 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001287
1288 Ptr += 3;
1289 Size += 3;
1290 if (C == '\\') goto Slash;
1291 return C;
1292 }
1293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 // If this is neither, return a single character.
1296 ++Size;
1297 return *Ptr;
1298}
1299
Chris Lattnerd01e2912006-06-18 16:22:51 +00001300
Chris Lattner22eb9722006-06-18 05:43:12 +00001301/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1302/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1303/// and that we have already incremented Ptr by Size bytes.
1304///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001305/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1306/// be updated to match.
1307char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001308 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 // If we have a slash, look for an escaped newline.
1310 if (Ptr[0] == '\\') {
1311 ++Size;
1312 ++Ptr;
1313Slash:
1314 // Common case, backslash-char where the char is not whitespace.
1315 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001316
Chris Lattner22eb9722006-06-18 05:43:12 +00001317 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001318 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1319 // Found backslash<whitespace><newline>. Parse the char after it.
1320 Size += EscapedNewLineSize;
1321 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001323 // If the char that we finally got was a \n, then we must have had
1324 // something like \<newline><newline>. We don't want to consume the
1325 // second newline.
1326 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1327 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001328
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001329 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001330 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001331 }
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattner22eb9722006-06-18 05:43:12 +00001333 // Otherwise, this is not an escaped newline, just return the slash.
1334 return '\\';
1335 }
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001338 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 // If this is actually a legal trigraph (not something like "??x"), return
1340 // it.
1341 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1342 Ptr += 3;
1343 Size += 3;
1344 if (C == '\\') goto Slash;
1345 return C;
1346 }
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Chris Lattner22eb9722006-06-18 05:43:12 +00001349 // If this is neither, return a single character.
1350 ++Size;
1351 return *Ptr;
1352}
1353
Chris Lattner22eb9722006-06-18 05:43:12 +00001354//===----------------------------------------------------------------------===//
1355// Helper methods for lexing.
1356//===----------------------------------------------------------------------===//
1357
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001358/// \brief Routine that indiscriminately skips bytes in the source file.
1359void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1360 BufferPtr += Bytes;
1361 if (BufferPtr > BufferEnd)
1362 BufferPtr = BufferEnd;
1363 IsAtStartOfLine = StartOfLine;
1364}
1365
Jordan Rose58c61e02013-02-09 01:10:25 +00001366static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1367 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1368 return isCharInSet(C, C11AllowedIDChars);
1369 else if (LangOpts.CPlusPlus)
1370 return isCharInSet(C, CXX03AllowedIDChars);
1371 else
1372 return isCharInSet(C, C99AllowedIDChars);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001373}
1374
Jordan Rose58c61e02013-02-09 01:10:25 +00001375static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1376 assert(isAllowedIDChar(C, LangOpts));
1377 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1378 return !isCharInSet(C, C11DisallowedInitialIDChars);
1379 else if (LangOpts.CPlusPlus)
1380 return true;
1381 else
1382 return !isCharInSet(C, C99DisallowedInitialIDChars);
1383}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001384
Jordan Rose58c61e02013-02-09 01:10:25 +00001385static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1386 const char *End) {
1387 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1388 L.getSourceLocation(End));
1389}
1390
1391static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1392 CharSourceRange Range, bool IsFirst) {
1393 // Check C99 compatibility.
1394 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1395 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1396 enum {
1397 CannotAppearInIdentifier = 0,
1398 CannotStartIdentifier
1399 };
1400
1401 if (!isCharInSet(C, C99AllowedIDChars)) {
1402 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1403 << Range
1404 << CannotAppearInIdentifier;
1405 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1406 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1407 << Range
1408 << CannotStartIdentifier;
1409 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001410 }
1411
Jordan Rose58c61e02013-02-09 01:10:25 +00001412 // Check C++98 compatibility.
1413 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1414 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1415 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1416 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1417 << Range;
1418 }
1419 }
1420 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001421
Chris Lattner146762e2007-07-20 16:59:19 +00001422void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001423 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1424 unsigned Size;
1425 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001426 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001427 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001428
Chris Lattner22eb9722006-06-18 05:43:12 +00001429 --CurPtr; // Back up over the skipped character.
1430
1431 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1432 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001433 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001434 // TODO: Could merge these checks into an InfoTable flag to make the
1435 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001436 if (isASCII(C) && C != '\\' && C != '?' &&
1437 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001438FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001439 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001440 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1441 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Chris Lattner0f1f5052006-07-20 04:16:23 +00001443 // If we are in raw mode, return this identifier raw. There is no need to
1444 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001445 if (LexingRawMode)
1446 return;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001448 // Fill in Result.IdentifierInfo and update the token kind,
1449 // looking up the identifier in the identifier table.
1450 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001451
Chris Lattnerc5a00062006-06-18 16:41:01 +00001452 // Finally, now that we know we have an identifier, pass this off to the
1453 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001454 if (II->isHandleIdentifierCase())
Chris Lattnerad89ec02009-01-21 07:43:11 +00001455 PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001456
Chris Lattnerad89ec02009-01-21 07:43:11 +00001457 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001458 }
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner22eb9722006-06-18 05:43:12 +00001460 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chris Lattner22eb9722006-06-18 05:43:12 +00001462 C = getCharAndSize(CurPtr, Size);
1463 while (1) {
1464 if (C == '$') {
1465 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001466 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001467
Chris Lattner22eb9722006-06-18 05:43:12 +00001468 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001469 if (!isLexingRawMode())
1470 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001471 CurPtr = ConsumeChar(CurPtr, Size, Result);
1472 C = getCharAndSize(CurPtr, Size);
1473 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001474
1475 } else if (C == '\\') {
1476 const char *UCNPtr = CurPtr + Size;
1477 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Rose58c61e02013-02-09 01:10:25 +00001478 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001479 goto FinishIdentifier;
1480
Jordan Rose58c61e02013-02-09 01:10:25 +00001481 if (!isLexingRawMode()) {
1482 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1483 makeCharRange(*this, CurPtr, UCNPtr),
1484 /*IsFirst=*/false);
1485 }
1486
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001487 Result.setFlag(Token::HasUCN);
1488 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1489 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1490 CurPtr = UCNPtr;
1491 else
1492 while (CurPtr != UCNPtr)
1493 (void)getAndAdvanceChar(CurPtr, Result);
1494
1495 C = getCharAndSize(CurPtr, Size);
1496 continue;
1497 } else if (!isASCII(C)) {
1498 const char *UnicodePtr = CurPtr;
1499 UTF32 CodePoint;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00001500 ConversionResult Result =
1501 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1502 (const UTF8 *)BufferEnd,
1503 &CodePoint,
1504 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001505 if (Result != conversionOK ||
Jordan Rose58c61e02013-02-09 01:10:25 +00001506 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001507 goto FinishIdentifier;
1508
Jordan Rose58c61e02013-02-09 01:10:25 +00001509 if (!isLexingRawMode()) {
1510 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1511 makeCharRange(*this, CurPtr, UnicodePtr),
1512 /*IsFirst=*/false);
1513 }
1514
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001515 CurPtr = UnicodePtr;
1516 C = getCharAndSize(CurPtr, Size);
1517 continue;
1518 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001519 goto FinishIdentifier;
1520 }
1521
1522 // Otherwise, this character is good, consume it.
1523 CurPtr = ConsumeChar(CurPtr, Size, Result);
1524
1525 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001526 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001527 CurPtr = ConsumeChar(CurPtr, Size, Result);
1528 C = getCharAndSize(CurPtr, Size);
1529 }
1530 }
1531}
1532
Douglas Gregor759ef232010-08-30 14:50:47 +00001533/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001534/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001535bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001536 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001537 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001538 if (C1 != '0')
1539 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001540 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001541 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001542}
Chris Lattner22eb9722006-06-18 05:43:12 +00001543
Nate Begeman5eee9332008-04-14 02:26:39 +00001544/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001545/// constant. From[-1] is the first character lexed. Return the end of the
1546/// constant.
Chris Lattner146762e2007-07-20 16:59:19 +00001547void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001548 unsigned Size;
1549 char C = getCharAndSize(CurPtr, Size);
1550 char PrevCh = 0;
Jordan Rosea2100d72013-02-08 22:30:22 +00001551 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Chris Lattner22eb9722006-06-18 05:43:12 +00001552 CurPtr = ConsumeChar(CurPtr, Size, Result);
1553 PrevCh = C;
1554 C = getCharAndSize(CurPtr, Size);
1555 }
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001558 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1559 // If we are in Microsoft mode, don't continue if the constant is hex.
1560 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001561 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001562 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1563 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001564
1565 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001566 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1567 // Outside C99, we accept hexadecimal floating point numbers as a
1568 // not-quite-conforming extension. Only do so if this looks like it's
1569 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1570 bool IsHexFloat = true;
1571 if (!LangOpts.C99) {
1572 if (!isHexaLiteral(BufferPtr, LangOpts))
1573 IsHexFloat = false;
1574 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1575 IsHexFloat = false;
1576 }
1577 if (IsHexFloat)
1578 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1579 }
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattnerd01e2912006-06-18 16:22:51 +00001581 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001582 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001583 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001584 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001585}
1586
Richard Smithe18f0fa2012-03-05 04:02:15 +00001587/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001588/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001589const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1590 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001591 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001592
1593 // Maximally munch an identifier. FIXME: UCNs.
1594 unsigned Size;
1595 char C = getCharAndSize(CurPtr, Size);
1596 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001597 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001598 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001599 Diag(CurPtr,
1600 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1601 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1602 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1603 return CurPtr;
1604 }
1605
1606 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1607 // that does not start with an underscore is ill-formed. As a conforming
1608 // extension, we treat all such suffixes as if they had whitespace before
1609 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001610 bool IsUDSuffix = false;
1611 if (C == '_')
1612 IsUDSuffix = true;
1613 else if (IsStringLiteral && C == 's' && getLangOpts().CPlusPlus1y) {
1614 // In C++1y, "s" is a valid ud-suffix for a string literal.
1615 unsigned NextSize;
1616 if (!isIdentifierBody(getCharAndSizeNoWarn(CurPtr + Size, NextSize,
1617 getLangOpts())))
1618 IsUDSuffix = true;
1619 }
1620
1621 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001622 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001623 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001624 diag::ext_ms_reserved_user_defined_literal :
1625 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001626 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1627 return CurPtr;
1628 }
1629
Richard Smithd67aea22012-03-06 03:21:47 +00001630 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001631 do {
1632 CurPtr = ConsumeChar(CurPtr, Size, Result);
1633 C = getCharAndSize(CurPtr, Size);
1634 } while (isIdentifierBody(C));
1635 }
1636 return CurPtr;
1637}
1638
Chris Lattner22eb9722006-06-18 05:43:12 +00001639/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001640/// either " or L" or u8" or u" or U".
1641void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1642 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001643 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001644
Richard Smithacd4d3d2011-10-15 01:18:56 +00001645 if (!isLexingRawMode() &&
1646 (Kind == tok::utf8_string_literal ||
1647 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001648 Kind == tok::utf32_string_literal))
1649 Diag(BufferPtr, getLangOpts().CPlusPlus
1650 ? diag::warn_cxx98_compat_unicode_literal
1651 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001652
Chris Lattner22eb9722006-06-18 05:43:12 +00001653 char C = getAndAdvanceChar(CurPtr, Result);
1654 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001655 // Skip escaped characters. Escaped newlines will already be processed by
1656 // getAndAdvanceChar.
1657 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001658 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001659
Chris Lattner52d96ac2010-05-30 23:27:38 +00001660 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001661 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001662 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001663 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001664 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001665 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001666 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001667
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001668 if (C == 0) {
1669 if (isCodeCompletionPoint(CurPtr-1)) {
1670 PP->CodeCompleteNaturalLanguage();
1671 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1672 return cutOffLexing();
1673 }
1674
Chris Lattner52d96ac2010-05-30 23:27:38 +00001675 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001676 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 C = getAndAdvanceChar(CurPtr, Result);
1678 }
Mike Stump11289f42009-09-09 15:08:12 +00001679
Richard Smithe18f0fa2012-03-05 04:02:15 +00001680 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001681 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001682 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001683
Chris Lattner5a78a022006-07-20 06:02:19 +00001684 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001685 if (NulCharacter && !isLexingRawMode())
1686 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001687
Chris Lattnerd01e2912006-06-18 16:22:51 +00001688 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001689 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001690 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001691 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001692}
1693
Craig Topper54edcca2011-08-11 04:06:15 +00001694/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1695/// having lexed R", LR", u8R", uR", or UR".
1696void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1697 tok::TokenKind Kind) {
1698 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1699 // Between the initial and final double quote characters of the raw string,
1700 // any transformations performed in phases 1 and 2 (trigraphs,
1701 // universal-character-names, and line splicing) are reverted.
1702
Richard Smithacd4d3d2011-10-15 01:18:56 +00001703 if (!isLexingRawMode())
1704 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1705
Craig Topper54edcca2011-08-11 04:06:15 +00001706 unsigned PrefixLen = 0;
1707
1708 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1709 ++PrefixLen;
1710
1711 // If the last character was not a '(', then we didn't lex a valid delimiter.
1712 if (CurPtr[PrefixLen] != '(') {
1713 if (!isLexingRawMode()) {
1714 const char *PrefixEnd = &CurPtr[PrefixLen];
1715 if (PrefixLen == 16) {
1716 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1717 } else {
1718 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1719 << StringRef(PrefixEnd, 1);
1720 }
1721 }
1722
1723 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1724 // it's possible the '"' was intended to be part of the raw string, but
1725 // there's not much we can do about that.
1726 while (1) {
1727 char C = *CurPtr++;
1728
1729 if (C == '"')
1730 break;
1731 if (C == 0 && CurPtr-1 == BufferEnd) {
1732 --CurPtr;
1733 break;
1734 }
1735 }
1736
1737 FormTokenWithChars(Result, CurPtr, tok::unknown);
1738 return;
1739 }
1740
1741 // Save prefix and move CurPtr past it
1742 const char *Prefix = CurPtr;
1743 CurPtr += PrefixLen + 1; // skip over prefix and '('
1744
1745 while (1) {
1746 char C = *CurPtr++;
1747
1748 if (C == ')') {
1749 // Check for prefix match and closing quote.
1750 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1751 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1752 break;
1753 }
1754 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1755 if (!isLexingRawMode())
1756 Diag(BufferPtr, diag::err_unterminated_raw_string)
1757 << StringRef(Prefix, PrefixLen);
1758 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1759 return;
1760 }
1761 }
1762
Richard Smithe18f0fa2012-03-05 04:02:15 +00001763 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001764 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001765 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001766
Craig Topper54edcca2011-08-11 04:06:15 +00001767 // Update the location of token as well as BufferPtr.
1768 const char *TokStart = BufferPtr;
1769 FormTokenWithChars(Result, CurPtr, Kind);
1770 Result.setLiteralData(TokStart);
1771}
1772
Chris Lattner22eb9722006-06-18 05:43:12 +00001773/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1774/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattner146762e2007-07-20 16:59:19 +00001775void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001776 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001777 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001778 char C = getAndAdvanceChar(CurPtr, Result);
1779 while (C != '>') {
1780 // Skip escaped characters.
1781 if (C == '\\') {
1782 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001783 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001784 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001785 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1786 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001787 // If the filename is unterminated, then it must just be a lone <
1788 // character. Return this as such.
1789 FormTokenWithChars(Result, AfterLessPos, tok::less);
Chris Lattner5a78a022006-07-20 06:02:19 +00001790 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001791 } else if (C == 0) {
1792 NulCharacter = CurPtr-1;
1793 }
1794 C = getAndAdvanceChar(CurPtr, Result);
1795 }
Mike Stump11289f42009-09-09 15:08:12 +00001796
Chris Lattner5a78a022006-07-20 06:02:19 +00001797 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001798 if (NulCharacter && !isLexingRawMode())
1799 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Chris Lattnerd01e2912006-06-18 16:22:51 +00001801 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001802 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001803 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001804 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001805}
1806
1807
1808/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001809/// lexed either ' or L' or u' or U'.
1810void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1811 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001812 const char *NulCharacter = 0; // Does this character contain the \0 character?
1813
Richard Smithacd4d3d2011-10-15 01:18:56 +00001814 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001815 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1816 Diag(BufferPtr, getLangOpts().CPlusPlus
1817 ? diag::warn_cxx98_compat_unicode_literal
1818 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001819
Chris Lattner22eb9722006-06-18 05:43:12 +00001820 char C = getAndAdvanceChar(CurPtr, Result);
1821 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001822 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001823 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001824 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001825 return;
Chris Lattner86851b82010-07-07 23:24:27 +00001826 }
1827
1828 while (C != '\'') {
1829 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001830 if (C == '\\')
1831 C = getAndAdvanceChar(CurPtr, Result);
1832
1833 if (C == '\n' || C == '\r' || // Newline.
1834 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001835 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001836 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001837 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1838 return;
Nico Weber4e270382012-11-17 20:25:54 +00001839 }
1840
1841 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001842 if (isCodeCompletionPoint(CurPtr-1)) {
1843 PP->CodeCompleteNaturalLanguage();
1844 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1845 return cutOffLexing();
1846 }
1847
Chris Lattner86851b82010-07-07 23:24:27 +00001848 NulCharacter = CurPtr-1;
1849 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001850 C = getAndAdvanceChar(CurPtr, Result);
1851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Richard Smithe18f0fa2012-03-05 04:02:15 +00001853 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001854 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001855 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001856
Chris Lattner86851b82010-07-07 23:24:27 +00001857 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001858 if (NulCharacter && !isLexingRawMode())
1859 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001860
Chris Lattnerd01e2912006-06-18 16:22:51 +00001861 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001862 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001863 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001864 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001865}
1866
1867/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1868/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001869///
1870/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1871///
1872bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001873 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001874 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1875
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001876 unsigned char Char = *CurPtr;
1877
1878 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001879 while (1) {
1880 // Skip horizontal whitespace very aggressively.
1881 while (isHorizontalWhitespace(Char))
1882 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001883
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001884 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001885 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 break;
Mike Stump11289f42009-09-09 15:08:12 +00001887
Chris Lattner22eb9722006-06-18 05:43:12 +00001888 if (ParsingPreprocessorDirective) {
1889 // End of preprocessor directive line, let LexTokenInternal handle this.
1890 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001891 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 }
Mike Stump11289f42009-09-09 15:08:12 +00001893
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001894 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001895 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001896 Char = *++CurPtr;
1897 }
1898
Chris Lattner4d963442008-10-12 04:05:48 +00001899 // If the client wants us to return whitespace, return it now.
1900 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001901 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001902 if (SawNewline)
1903 IsAtStartOfLine = true;
1904 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001905 return true;
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001908 // If this isn't immediately after a newline, there is leading space.
1909 char PrevChar = CurPtr[-1];
1910 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1911
1912 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1913 if (SawNewline)
1914 Result.setFlag(Token::StartOfLine);
1915
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001917 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001918}
1919
Nico Weber158a31a2012-11-11 07:02:14 +00001920/// We have just read the // characters from input. Skip until we find the
1921/// newline character thats terminate the comment. Then update BufferPtr and
1922/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001923///
1924/// If we're in KeepCommentMode or any CommentHandler has inserted
1925/// some tokens, this will store the first token and return true.
Nico Weber158a31a2012-11-11 07:02:14 +00001926bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1927 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00001928 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00001929 if (!LangOpts.LineComment && !isLexingRawMode()) {
1930 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001931
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 // Mark them enabled so we only emit one warning for this translation
1933 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00001934 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 }
Mike Stump11289f42009-09-09 15:08:12 +00001936
Chris Lattner22eb9722006-06-18 05:43:12 +00001937 // Scan over the body of the comment. The common case, when scanning, is that
1938 // the comment contains normal ascii characters with nothing interesting in
1939 // them. As such, optimize for this case with the inner loop.
1940 char C;
1941 do {
1942 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 // Skip over characters in the fast loop.
1944 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00001945 C != '\n' && C != '\r') // Newline or DOS-style newline.
1946 C = *++CurPtr;
1947
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001948 const char *NextLine = CurPtr;
1949 if (C != 0) {
1950 // We found a newline, see if it's escaped.
1951 const char *EscapePtr = CurPtr-1;
1952 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1953 --EscapePtr;
1954
1955 if (*EscapePtr == '\\') // Escaped newline.
1956 CurPtr = EscapePtr;
1957 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1958 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1959 CurPtr = EscapePtr-2;
1960 else
1961 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00001965 // properly decode the character. Read it in raw mode to avoid emitting
1966 // diagnostics about things like trigraphs. If we see an escaped newline,
1967 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00001968 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00001969 bool OldRawMode = isLexingRawMode();
1970 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00001972 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00001973
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001974 // If we only read only one character, then no special handling is needed.
1975 // We're done and can skip forward to the newline.
1976 if (C != 0 && CurPtr == OldPtr+1) {
1977 CurPtr = NextLine;
1978 break;
1979 }
1980
Chris Lattner22eb9722006-06-18 05:43:12 +00001981 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00001982 // \n, then we had an escaped newline within the comment. Emit diagnostic
1983 // unless the next line is also a // comment.
1984 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001985 for (; OldPtr != CurPtr; ++OldPtr)
1986 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00001987 // Okay, we found a // comment that ends in a newline, if the next
1988 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00001989 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00001990 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00001991 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00001992 ++ForwardPtr;
1993 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1994 break;
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattner6d27a162008-11-22 02:02:22 +00001997 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00001998 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00001999 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002000 }
2001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
Douglas Gregor11583702010-08-25 17:04:25 +00002003 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002004 --CurPtr;
2005 break;
2006 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002007
2008 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2009 PP->CodeCompleteNaturalLanguage();
2010 cutOffLexing();
2011 return false;
2012 }
2013
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 } while (C != '\n' && C != '\r');
2015
Chris Lattner93ddf802010-02-03 21:06:21 +00002016 // Found but did not consume the newline. Notify comment handlers about the
2017 // comment unless we're in a #if 0 block.
2018 if (PP && !isLexingRawMode() &&
2019 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2020 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002021 BufferPtr = CurPtr;
2022 return true; // A token has to be returned.
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024
Chris Lattner457fc152006-07-29 06:30:25 +00002025 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002026 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002027 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002028
2029 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002030 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002031 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002033 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Chris Lattner22eb9722006-06-18 05:43:12 +00002036 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002037 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002038 // contribute to another token), it isn't needed for correctness. Note that
2039 // this is ok even in KeepWhitespaceMode, because we would have returned the
2040 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002041 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002042
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002044 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00002045 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002046 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002047 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002048 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002049}
Chris Lattner22eb9722006-06-18 05:43:12 +00002050
Nico Weber158a31a2012-11-11 07:02:14 +00002051/// If in save-comment mode, package up this Line comment in an appropriate
2052/// way and return it.
2053bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002054 // If we're not in a preprocessor directive, just return the // comment
2055 // directly.
2056 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002057
David Blaikied5321242012-06-06 18:52:13 +00002058 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002059 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002060
Nico Weber158a31a2012-11-11 07:02:14 +00002061 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002062 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002063 bool Invalid = false;
2064 std::string Spelling = PP->getSpelling(Result, &Invalid);
2065 if (Invalid)
2066 return true;
2067
Nico Weber158a31a2012-11-11 07:02:14 +00002068 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002069 Spelling[1] = '*'; // Change prefix to "/*".
2070 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerb11c3232008-10-12 04:51:35 +00002072 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002073 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002074 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002075 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002076}
2077
Chris Lattnercb283342006-06-18 06:48:37 +00002078/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002079/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2080/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002081static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002082 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002084
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 // Back up off the newline.
2086 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002087
Chris Lattner22eb9722006-06-18 05:43:12 +00002088 // If this is a two-character newline sequence, skip the other character.
2089 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2090 // \n\n or \r\r -> not escaped newline.
2091 if (CurPtr[0] == CurPtr[1])
2092 return false;
2093 // \n\r or \r\n -> skip the newline.
2094 --CurPtr;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattner22eb9722006-06-18 05:43:12 +00002097 // If we have horizontal whitespace, skip over it. We allow whitespace
2098 // between the slash and newline.
2099 bool HasSpace = false;
2100 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2101 --CurPtr;
2102 HasSpace = true;
2103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 // If we have a slash, we know this is an escaped newline.
2106 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002107 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002108 } else {
2109 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002110 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2111 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002112 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnercb283342006-06-18 06:48:37 +00002114 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 CurPtr -= 2;
2116
2117 // If no trigraphs are enabled, warn that we ignored this trigraph and
2118 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002119 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002120 if (!L->isLexingRawMode())
2121 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002122 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002123 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002124 if (!L->isLexingRawMode())
2125 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattner22eb9722006-06-18 05:43:12 +00002128 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002129 if (!L->isLexingRawMode())
2130 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattner22eb9722006-06-18 05:43:12 +00002132 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002133 if (HasSpace && !L->isLexingRawMode())
2134 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002135
Chris Lattnercb283342006-06-18 06:48:37 +00002136 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002137}
2138
Chris Lattneraded4a92006-10-27 04:42:31 +00002139#ifdef __SSE2__
2140#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002141#elif __ALTIVEC__
2142#include <altivec.h>
2143#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002144#endif
2145
James Dennettf442d242012-06-17 03:40:43 +00002146/// We have just read from input the / and * characters that started a comment.
2147/// Read until we find the * and / characters that terminate the comment.
2148/// Note that we don't bother decoding trigraphs or escaped newlines in block
2149/// comments, because they cannot cause the comment to end. The only thing
2150/// that can happen is the comment could end with an escaped newline between
2151/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002152///
Chris Lattner87d02082010-01-18 22:35:47 +00002153/// If we're in KeepCommentMode or any CommentHandler has inserted
2154/// some tokens, this will store the first token and return true.
Chris Lattner146762e2007-07-20 16:59:19 +00002155bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002156 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002157 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002158 // optimization helps people who like to put a lot of * characters in their
2159 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002160
2161 // The first character we get with newlines and trigraphs skipped to handle
2162 // the degenerate /*/ case below correctly if the * has an escaped newline
2163 // after it.
2164 unsigned CharSize;
2165 unsigned char C = getCharAndSize(CurPtr, CharSize);
2166 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002167 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002168 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002169 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002170 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattner99e7d232008-10-12 04:19:49 +00002172 // KeepWhitespaceMode should return this broken comment as a token. Since
2173 // it isn't a well formed comment, just return it as an 'unknown' token.
2174 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002175 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002176 return true;
2177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Chris Lattner99e7d232008-10-12 04:19:49 +00002179 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002180 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002181 }
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattnerc850ad62007-07-21 23:43:37 +00002183 // Check to see if the first character after the '/*' is another /. If so,
2184 // then this slash does not end the block comment, it is part of it.
2185 if (C == '/')
2186 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattner22eb9722006-06-18 05:43:12 +00002188 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002189 // Skip over all non-interesting characters until we find end of buffer or a
2190 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002191 if (CurPtr + 24 < BufferEnd &&
2192 // If there is a code-completion point avoid the fast scan because it
2193 // doesn't check for '\0'.
2194 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002195 // While not aligned to a 16-byte boundary.
2196 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2197 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattner6cc3e362006-10-27 04:12:35 +00002199 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002200
2201#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002202 __m128i Slashes = _mm_set1_epi8('/');
2203 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002204 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2205 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002206 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002207 // Adjust the pointer to point directly after the first slash. It's
2208 // not necessary to set C here, it will be overwritten at the end of
2209 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002210 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002211 goto FoundSlash;
2212 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002213 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002214 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002215#elif __ALTIVEC__
2216 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002217 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002218 '/', '/', '/', '/', '/', '/', '/', '/'
2219 };
2220 while (CurPtr+16 <= BufferEnd &&
2221 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2222 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002223#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002224 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002225 while (CurPtr[0] != '/' &&
2226 CurPtr[1] != '/' &&
2227 CurPtr[2] != '/' &&
2228 CurPtr[3] != '/' &&
2229 CurPtr+4 < BufferEnd) {
2230 CurPtr += 4;
2231 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002232#endif
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattneraded4a92006-10-27 04:42:31 +00002234 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002235 C = *CurPtr++;
2236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattneraded4a92006-10-27 04:42:31 +00002238 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002239 while (C != '/' && C != '\0')
2240 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002241
Chris Lattner22eb9722006-06-18 05:43:12 +00002242 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002243 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002244 if (CurPtr[-2] == '*') // We found the final */. We're done!
2245 break;
Mike Stump11289f42009-09-09 15:08:12 +00002246
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002248 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002249 // We found the final */, though it had an escaped newline between the
2250 // * and /. We're done!
2251 break;
2252 }
2253 }
2254 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2255 // If this is a /* inside of the comment, emit a warning. Don't do this
2256 // if this is a /*/, which will end the comment. This misses cases with
2257 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002258 if (!isLexingRawMode())
2259 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002260 }
2261 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002262 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002263 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002264 // Note: the user probably forgot a */. We could continue immediately
2265 // after the /*, but this would involve lexing a lot of what really is the
2266 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002267 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattner99e7d232008-10-12 04:19:49 +00002269 // KeepWhitespaceMode should return this broken comment as a token. Since
2270 // it isn't a well formed comment, just return it as an 'unknown' token.
2271 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002272 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002273 return true;
2274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattner99e7d232008-10-12 04:19:49 +00002276 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002277 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002278 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2279 PP->CodeCompleteNaturalLanguage();
2280 cutOffLexing();
2281 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002282 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002283
Chris Lattner22eb9722006-06-18 05:43:12 +00002284 C = *CurPtr++;
2285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Chris Lattner93ddf802010-02-03 21:06:21 +00002287 // Notify comment handlers about the comment unless we're in a #if 0 block.
2288 if (PP && !isLexingRawMode() &&
2289 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2290 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002291 BufferPtr = CurPtr;
2292 return true; // A token has to be returned.
2293 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002294
Chris Lattner457fc152006-07-29 06:30:25 +00002295 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002296 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002297 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002298 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002299 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002300
2301 // It is common for the tokens immediately after a /**/ comment to be
2302 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002303 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2304 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002305 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattner457fc152006-07-29 06:30:25 +00002306 SkipWhitespace(Result, CurPtr+1);
Chris Lattnere01e7582008-10-12 04:15:42 +00002307 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 }
2309
2310 // Otherwise, just return so that the next character will be lexed as a token.
2311 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002312 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002313 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002314}
2315
2316//===----------------------------------------------------------------------===//
2317// Primary Lexing Entry Points
2318//===----------------------------------------------------------------------===//
2319
Chris Lattner22eb9722006-06-18 05:43:12 +00002320/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2321/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002322void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002323 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2324 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002325 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002326
2327 // CurPtr - Cache BufferPtr in an automatic variable.
2328 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002329 while (1) {
2330 char Char = getAndAdvanceChar(CurPtr, Tmp);
2331 switch (Char) {
2332 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002333 if (Result)
2334 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002335 break;
2336 case 0: // Null.
2337 // Found end of file?
2338 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002339 if (isCodeCompletionPoint(CurPtr-1)) {
2340 PP->CodeCompleteNaturalLanguage();
2341 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002342 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002343 }
2344
Chris Lattner22eb9722006-06-18 05:43:12 +00002345 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002346 if (Result)
2347 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 break;
2349 }
2350 // FALL THROUGH.
2351 case '\r':
2352 case '\n':
2353 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2354 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2355 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002356
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002357 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002358 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002359 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002360 if (PP)
2361 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002362 Lex(Tmp);
2363 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002364 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002365
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002366 // Finally, we're done;
2367 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002368 }
2369 }
2370}
2371
2372/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2373/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002374/// This returns true if Result contains a token, false if PP.Lex should be
2375/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002376bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002377 // If we hit the end of the file while parsing a preprocessor directive,
2378 // end the preprocessor directive first. The next token returned will
2379 // then be the end of file.
2380 if (ParsingPreprocessorDirective) {
2381 // Done parsing the "line".
2382 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002383 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002384 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002385
Chris Lattner457fc152006-07-29 06:30:25 +00002386 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002387 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002388 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002389 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002390
Chris Lattner30a2fa12006-07-19 06:31:49 +00002391 // If we are in raw mode, return this event as an EOF token. Let the caller
2392 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002393 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002394 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002395 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002396 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002397 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002398 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002399
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002400 // Issue diagnostics for unterminated #if and missing newline.
2401
Chris Lattner30a2fa12006-07-19 06:31:49 +00002402 // If we are in a #if directive, emit an error.
2403 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002404 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002405 PP->Diag(ConditionalStack.back().IfLoc,
2406 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002407 ConditionalStack.pop_back();
2408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chris Lattner8f96d042008-04-12 05:54:25 +00002410 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2411 // a pedwarn.
Seth Cantrelle83c7312012-04-13 03:43:23 +00002412 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002413 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrelle83c7312012-04-13 03:43:23 +00002414 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2415 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump11289f42009-09-09 15:08:12 +00002416
Chris Lattner22eb9722006-06-18 05:43:12 +00002417 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002418
2419 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002420 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002421}
2422
Chris Lattner678c8802006-07-11 05:46:12 +00002423/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2424/// the specified lexer will return a tok::l_paren token, 0 if it is something
2425/// else and 2 if there are no more tokens in the buffer controlled by the
2426/// lexer.
2427unsigned Lexer::isNextPPTokenLParen() {
2428 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002429
Chris Lattner678c8802006-07-11 05:46:12 +00002430 // Switch to 'skipping' mode. This will ensure that we can lex a token
2431 // without emitting diagnostics, disables macro expansion, and will cause EOF
2432 // to return an EOF token instead of popping the include stack.
2433 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002434
Chris Lattner678c8802006-07-11 05:46:12 +00002435 // Save state that can be changed while lexing so that we can restore it.
2436 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002437 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattner146762e2007-07-20 16:59:19 +00002439 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +00002440 Tok.startToken();
Chris Lattner678c8802006-07-11 05:46:12 +00002441 LexTokenInternal(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattner678c8802006-07-11 05:46:12 +00002443 // Restore state that may have changed.
2444 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002445 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump11289f42009-09-09 15:08:12 +00002446
Chris Lattner678c8802006-07-11 05:46:12 +00002447 // Restore the lexer back to non-skipping mode.
2448 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002449
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002450 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002451 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002452 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002453}
2454
James Dennettf442d242012-06-17 03:40:43 +00002455/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002456static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2457 ConflictMarkerKind CMK) {
2458 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2459 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2460 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2461 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002462 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002463 // Must occur at start of line.
2464 if (RestOfBuffer[Pos-1] != '\r' &&
2465 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002466 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2467 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002468 continue;
2469 }
2470 return RestOfBuffer.data()+Pos;
2471 }
2472 return 0;
2473}
2474
2475/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2476/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2477/// and recover nicely. This returns true if it is a conflict marker and false
2478/// if not.
2479bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2480 // Only a conflict marker if it starts at the beginning of a line.
2481 if (CurPtr != BufferStart &&
2482 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2483 return false;
2484
Richard Smitha9e33d42011-10-12 00:37:51 +00002485 // Check to see if we have <<<<<<< or >>>>.
2486 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2487 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002488 return false;
2489
2490 // If we have a situation where we don't care about conflict markers, ignore
2491 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002492 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002493 return false;
2494
Richard Smitha9e33d42011-10-12 00:37:51 +00002495 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2496
2497 // Check to see if there is an ending marker somewhere in the buffer at the
2498 // start of a line to terminate this conflict marker.
2499 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002500 // We found a match. We are really in a conflict marker.
2501 // Diagnose this, and ignore to the end of line.
2502 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002503 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002504
2505 // Skip ahead to the end of line. We know this exists because the
2506 // end-of-conflict marker starts with \r or \n.
2507 while (*CurPtr != '\r' && *CurPtr != '\n') {
2508 assert(CurPtr != BufferEnd && "Didn't find end of line");
2509 ++CurPtr;
2510 }
2511 BufferPtr = CurPtr;
2512 return true;
2513 }
2514
2515 // No end of conflict marker found.
2516 return false;
2517}
2518
2519
Richard Smitha9e33d42011-10-12 00:37:51 +00002520/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2521/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2522/// is the end of a conflict marker. Handle it by ignoring up until the end of
2523/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002524bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2525 // Only a conflict marker if it starts at the beginning of a line.
2526 if (CurPtr != BufferStart &&
2527 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2528 return false;
2529
2530 // If we have a situation where we don't care about conflict markers, ignore
2531 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002532 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002533 return false;
2534
Richard Smitha9e33d42011-10-12 00:37:51 +00002535 // Check to see if we have the marker (4 characters in a row).
2536 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002537 if (CurPtr[i] != CurPtr[0])
2538 return false;
2539
2540 // If we do have it, search for the end of the conflict marker. This could
2541 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2542 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002543 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2544 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002545 CurPtr = End;
2546
2547 // Skip ahead to the end of line.
2548 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2549 ++CurPtr;
2550
2551 BufferPtr = CurPtr;
2552
2553 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002554 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002555 return true;
2556 }
2557
2558 return false;
2559}
2560
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002561bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2562 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002563 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002564 return Loc == PP->getCodeCompletionLoc();
2565 }
2566
2567 return false;
2568}
2569
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002570uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2571 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002572 unsigned CharSize;
2573 char Kind = getCharAndSize(StartPtr, CharSize);
2574
2575 unsigned NumHexDigits;
2576 if (Kind == 'u')
2577 NumHexDigits = 4;
2578 else if (Kind == 'U')
2579 NumHexDigits = 8;
2580 else
2581 return 0;
2582
Jordan Rosec0cba272013-01-27 20:12:04 +00002583 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002584 if (Result && !isLexingRawMode())
2585 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002586 return 0;
2587 }
2588
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002589 const char *CurPtr = StartPtr + CharSize;
2590 const char *KindLoc = &CurPtr[-1];
2591
2592 uint32_t CodePoint = 0;
2593 for (unsigned i = 0; i < NumHexDigits; ++i) {
2594 char C = getCharAndSize(CurPtr, CharSize);
2595
2596 unsigned Value = llvm::hexDigitValue(C);
2597 if (Value == -1U) {
2598 if (Result && !isLexingRawMode()) {
2599 if (i == 0) {
2600 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2601 << StringRef(KindLoc, 1);
2602 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002603 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002604
2605 // If the user wrote \U1234, suggest a fixit to \u.
2606 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002607 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002608 Diag(KindLoc, diag::note_ucn_four_not_eight)
2609 << FixItHint::CreateReplacement(URange, "u");
2610 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002611 }
2612 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002613
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002614 return 0;
2615 }
2616
2617 CodePoint <<= 4;
2618 CodePoint += Value;
2619
2620 CurPtr += CharSize;
2621 }
2622
2623 if (Result) {
2624 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002625 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002626 StartPtr = CurPtr;
2627 else
2628 while (StartPtr != CurPtr)
2629 (void)getAndAdvanceChar(StartPtr, *Result);
2630 } else {
2631 StartPtr = CurPtr;
2632 }
2633
2634 // C99 6.4.3p2: A universal character name shall not specify a character whose
2635 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2636 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2637 // C++11 [lex.charset]p2: If the hexadecimal value for a
2638 // universal-character-name corresponds to a surrogate code point (in the
2639 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2640 // if the hexadecimal value for a universal-character-name outside the
2641 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2642 // string literal corresponds to a control character (in either of the
2643 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2644 // basic source character set, the program is ill-formed.
2645 if (CodePoint < 0xA0) {
2646 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2647 return CodePoint;
2648
2649 // We don't use isLexingRawMode() here because we need to warn about bad
2650 // UCNs even when skipping preprocessing tokens in a #if block.
2651 if (Result && PP) {
2652 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2653 Diag(BufferPtr, diag::err_ucn_control_character);
2654 else {
2655 char C = static_cast<char>(CodePoint);
2656 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2657 }
2658 }
2659
2660 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002661
2662 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002663 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002664 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002665 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002666 if (Result && PP) {
2667 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2668 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2669 else
2670 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2671 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002672 return 0;
2673 }
2674
2675 return CodePoint;
2676}
2677
2678void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose17441582013-01-30 01:52:57 +00002679 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002680 isCharInSet(C, UnicodeWhitespaceChars)) {
Jordan Rose17441582013-01-30 01:52:57 +00002681 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002682 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002683
2684 Result.setFlag(Token::LeadingSpace);
2685 if (SkipWhitespace(Result, CurPtr))
2686 return; // KeepWhitespaceMode
2687
2688 return LexTokenInternal(Result);
2689 }
2690
Jordan Rose58c61e02013-02-09 01:10:25 +00002691 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2692 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2693 !PP->isPreprocessedOutput()) {
2694 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2695 makeCharRange(*this, BufferPtr, CurPtr),
2696 /*IsFirst=*/true);
2697 }
2698
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002699 MIOpt.ReadToken();
2700 return LexIdentifier(Result, CurPtr);
2701 }
2702
Jordan Rosecc538342013-01-31 19:48:48 +00002703 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2704 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002705 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002706 // Non-ASCII characters tend to creep into source code unintentionally.
2707 // Instead of letting the parser complain about the unknown token,
2708 // just drop the character.
2709 // Note that we can /only/ do this when the non-ASCII character is actually
2710 // spelled as Unicode, not written as a UCN. The standard requires that
2711 // we not throw away any possible preprocessor tokens, but there's a
2712 // loophole in the mapping of Unicode characters to basic character set
2713 // characters that allows us to map these particular characters to, say,
2714 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002715 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002716 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002717
2718 BufferPtr = CurPtr;
2719 return LexTokenInternal(Result);
2720 }
2721
2722 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2723 // up by accident.
2724 MIOpt.ReadToken();
2725 FormTokenWithChars(Result, CurPtr, tok::unknown);
2726}
2727
Chris Lattner22eb9722006-06-18 05:43:12 +00002728
2729/// LexTokenInternal - This implements a simple C family lexer. It is an
2730/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002731/// has a null character at the end of the file. This returns a preprocessing
2732/// token, not a normal token, as such, it is an internal interface. It assumes
2733/// that the Flags of result have been cleared before calling this.
Chris Lattner146762e2007-07-20 16:59:19 +00002734void Lexer::LexTokenInternal(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002735LexNextToken:
2736 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002737 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002738 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002739
Chris Lattner22eb9722006-06-18 05:43:12 +00002740 // CurPtr - Cache BufferPtr in an automatic variable.
2741 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002742
Chris Lattnereb54b592006-07-10 06:34:27 +00002743 // Small amounts of horizontal whitespace is very common between tokens.
2744 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2745 ++CurPtr;
2746 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2747 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002748
Chris Lattner4d963442008-10-12 04:05:48 +00002749 // If we are keeping whitespace and other tokens, just return what we just
2750 // skipped. The next lexer invocation will return the token after the
2751 // whitespace.
2752 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002753 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002754 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002755 return;
2756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Chris Lattnereb54b592006-07-10 06:34:27 +00002758 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002759 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002760 }
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattner22eb9722006-06-18 05:43:12 +00002762 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002763
Chris Lattner22eb9722006-06-18 05:43:12 +00002764 // Read a character, advancing over it.
2765 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002766 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002767
Chris Lattner22eb9722006-06-18 05:43:12 +00002768 switch (Char) {
2769 case 0: // Null.
2770 // Found end of file?
Chris Lattner2183a6e2006-07-18 06:36:12 +00002771 if (CurPtr-1 == BufferEnd) {
2772 // Read the PP instance variable into an automatic variable, because
2773 // LexEndOfFile will often delete 'this'.
Chris Lattner02b436a2007-10-17 20:41:00 +00002774 Preprocessor *PPCache = PP;
Chris Lattner2183a6e2006-07-18 06:36:12 +00002775 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2776 return; // Got a token to return.
Chris Lattner02b436a2007-10-17 20:41:00 +00002777 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2778 return PPCache->Lex(Result);
Chris Lattner2183a6e2006-07-18 06:36:12 +00002779 }
Mike Stump11289f42009-09-09 15:08:12 +00002780
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002781 // Check if we are performing code completion.
2782 if (isCodeCompletionPoint(CurPtr-1)) {
2783 // Return the code-completion token.
2784 Result.startToken();
2785 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2786 return;
2787 }
2788
Chris Lattner6d27a162008-11-22 02:02:22 +00002789 if (!isLexingRawMode())
2790 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002791 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002792 if (SkipWhitespace(Result, CurPtr))
2793 return; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002794
Chris Lattner22eb9722006-06-18 05:43:12 +00002795 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002796
2797 case 26: // DOS & CP/M EOF: "^Z".
2798 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002799 if (LangOpts.MicrosoftExt) {
Chris Lattner3dfff972009-12-17 05:29:40 +00002800 // Read the PP instance variable into an automatic variable, because
2801 // LexEndOfFile will often delete 'this'.
2802 Preprocessor *PPCache = PP;
2803 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2804 return; // Got a token to return.
2805 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2806 return PPCache->Lex(Result);
2807 }
2808 // If Microsoft extensions are disabled, this is just random garbage.
2809 Kind = tok::unknown;
2810 break;
2811
Chris Lattner22eb9722006-06-18 05:43:12 +00002812 case '\n':
2813 case '\r':
2814 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002815 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002816 if (ParsingPreprocessorDirective) {
2817 // Done parsing the "line".
2818 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002819
Chris Lattner457fc152006-07-29 06:30:25 +00002820 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002821 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002822 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002823
Chris Lattner22eb9722006-06-18 05:43:12 +00002824 // Since we consumed a newline, we are back at the start of a line.
2825 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002826
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002827 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002828 break;
2829 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002830
Chris Lattner22eb9722006-06-18 05:43:12 +00002831 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002832 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002833
Chris Lattner4d963442008-10-12 04:05:48 +00002834 if (SkipWhitespace(Result, CurPtr))
2835 return; // KeepWhitespaceMode
Chris Lattner22eb9722006-06-18 05:43:12 +00002836 goto LexNextToken; // GCC isn't tail call eliminating.
2837 case ' ':
2838 case '\t':
2839 case '\f':
2840 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002841 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002842 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002843 if (SkipWhitespace(Result, CurPtr))
2844 return; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002845
2846 SkipIgnoredUnits:
2847 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002848
Chris Lattnerb9b85972007-07-22 06:29:05 +00002849 // If the next token is obviously a // or /* */ comment, skip it efficiently
2850 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002851 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weber158a31a2012-11-11 07:02:14 +00002852 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2853 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner87d02082010-01-18 22:35:47 +00002854 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002855 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002856 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner87d02082010-01-18 22:35:47 +00002857 if (SkipBlockComment(Result, CurPtr+2))
2858 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002859 goto SkipIgnoredUnits;
2860 } else if (isHorizontalWhitespace(*CurPtr)) {
2861 goto SkipHorizontalWhitespace;
2862 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002863 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002864
Chris Lattner2b15cf72008-01-03 17:58:54 +00002865 // C99 6.4.4.1: Integer Constants.
2866 // C99 6.4.4.2: Floating Constants.
2867 case '0': case '1': case '2': case '3': case '4':
2868 case '5': case '6': case '7': case '8': case '9':
2869 // Notify MIOpt that we read a non-whitespace/non-comment token.
2870 MIOpt.ReadToken();
2871 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00002872
Richard Smith9b362092013-03-09 23:56:02 +00002873 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002874 // Notify MIOpt that we read a non-whitespace/non-comment token.
2875 MIOpt.ReadToken();
2876
Richard Smith9b362092013-03-09 23:56:02 +00002877 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002878 Char = getCharAndSize(CurPtr, SizeTmp);
2879
2880 // UTF-16 string literal
2881 if (Char == '"')
2882 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2883 tok::utf16_string_literal);
2884
2885 // UTF-16 character constant
2886 if (Char == '\'')
2887 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2888 tok::utf16_char_constant);
2889
Craig Topper54edcca2011-08-11 04:06:15 +00002890 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002891 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2892 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002893 return LexRawStringLiteral(Result,
2894 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2895 SizeTmp2, Result),
2896 tok::utf16_string_literal);
2897
2898 if (Char == '8') {
2899 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2900
2901 // UTF-8 string literal
2902 if (Char2 == '"')
2903 return LexStringLiteral(Result,
2904 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2905 SizeTmp2, Result),
2906 tok::utf8_string_literal);
2907
Richard Smith9b362092013-03-09 23:56:02 +00002908 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00002909 unsigned SizeTmp3;
2910 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2911 // UTF-8 raw string literal
2912 if (Char3 == '"') {
2913 return LexRawStringLiteral(Result,
2914 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2915 SizeTmp2, Result),
2916 SizeTmp3, Result),
2917 tok::utf8_string_literal);
2918 }
2919 }
2920 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00002921 }
2922
2923 // treat u like the start of an identifier.
2924 return LexIdentifier(Result, CurPtr);
2925
Richard Smith9b362092013-03-09 23:56:02 +00002926 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002927 // Notify MIOpt that we read a non-whitespace/non-comment token.
2928 MIOpt.ReadToken();
2929
Richard Smith9b362092013-03-09 23:56:02 +00002930 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002931 Char = getCharAndSize(CurPtr, SizeTmp);
2932
2933 // UTF-32 string literal
2934 if (Char == '"')
2935 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2936 tok::utf32_string_literal);
2937
2938 // UTF-32 character constant
2939 if (Char == '\'')
2940 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2941 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00002942
2943 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002944 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2945 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002946 return LexRawStringLiteral(Result,
2947 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2948 SizeTmp2, Result),
2949 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00002950 }
2951
2952 // treat U like the start of an identifier.
2953 return LexIdentifier(Result, CurPtr);
2954
Craig Topper54edcca2011-08-11 04:06:15 +00002955 case 'R': // Identifier or C++0x raw string literal
2956 // Notify MIOpt that we read a non-whitespace/non-comment token.
2957 MIOpt.ReadToken();
2958
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002959 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00002960 Char = getCharAndSize(CurPtr, SizeTmp);
2961
2962 if (Char == '"')
2963 return LexRawStringLiteral(Result,
2964 ConsumeChar(CurPtr, SizeTmp, Result),
2965 tok::string_literal);
2966 }
2967
2968 // treat R like the start of an identifier.
2969 return LexIdentifier(Result, CurPtr);
2970
Chris Lattner2b15cf72008-01-03 17:58:54 +00002971 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00002972 // Notify MIOpt that we read a non-whitespace/non-comment token.
2973 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00002974 Char = getCharAndSize(CurPtr, SizeTmp);
2975
2976 // Wide string literal.
2977 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00002978 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002979 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00002980
Craig Topper54edcca2011-08-11 04:06:15 +00002981 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002982 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00002983 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2984 return LexRawStringLiteral(Result,
2985 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2986 SizeTmp2, Result),
2987 tok::wide_string_literal);
2988
Chris Lattner22eb9722006-06-18 05:43:12 +00002989 // Wide character constant.
2990 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00002991 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2992 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00002993 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00002994
Chris Lattner22eb9722006-06-18 05:43:12 +00002995 // C99 6.4.2: Identifiers.
2996 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2997 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00002998 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00002999 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3000 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3001 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003002 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003003 case 'v': case 'w': case 'x': case 'y': case 'z':
3004 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003005 // Notify MIOpt that we read a non-whitespace/non-comment token.
3006 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003007 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003008
3009 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003010 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003011 if (!isLexingRawMode())
3012 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003013 // Notify MIOpt that we read a non-whitespace/non-comment token.
3014 MIOpt.ReadToken();
3015 return LexIdentifier(Result, CurPtr);
3016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattnerb11c3232008-10-12 04:51:35 +00003018 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003019 break;
Mike Stump11289f42009-09-09 15:08:12 +00003020
Chris Lattner22eb9722006-06-18 05:43:12 +00003021 // C99 6.4.4: Character Constants.
3022 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003023 // Notify MIOpt that we read a non-whitespace/non-comment token.
3024 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003025 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003026
3027 // C99 6.4.5: String Literals.
3028 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003029 // Notify MIOpt that we read a non-whitespace/non-comment token.
3030 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003031 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003032
3033 // C99 6.4.6: Punctuators.
3034 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003035 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003036 break;
3037 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003038 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003039 break;
3040 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003041 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003042 break;
3043 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003044 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003045 break;
3046 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003047 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003048 break;
3049 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003050 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003051 break;
3052 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003053 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003054 break;
3055 case '.':
3056 Char = getCharAndSize(CurPtr, SizeTmp);
3057 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003058 // Notify MIOpt that we read a non-whitespace/non-comment token.
3059 MIOpt.ReadToken();
3060
Chris Lattner22eb9722006-06-18 05:43:12 +00003061 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003062 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003063 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003064 CurPtr += SizeTmp;
3065 } else if (Char == '.' &&
3066 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003067 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003068 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3069 SizeTmp2, Result);
3070 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003071 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003072 }
3073 break;
3074 case '&':
3075 Char = getCharAndSize(CurPtr, SizeTmp);
3076 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003077 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003078 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3079 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003080 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003081 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3082 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003083 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003084 }
3085 break;
Mike Stump11289f42009-09-09 15:08:12 +00003086 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003087 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003088 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003089 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3090 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003091 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003092 }
3093 break;
3094 case '+':
3095 Char = getCharAndSize(CurPtr, SizeTmp);
3096 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003097 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003098 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003099 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003100 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003101 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003102 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003103 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003104 }
3105 break;
3106 case '-':
3107 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003108 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003109 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003110 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003111 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003112 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003113 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3114 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003115 Kind = tok::arrowstar;
3116 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003117 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003118 Kind = tok::arrow;
3119 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003120 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003121 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003122 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003123 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003124 }
3125 break;
3126 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003127 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003128 break;
3129 case '!':
3130 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003131 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003132 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3133 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003134 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003135 }
3136 break;
3137 case '/':
3138 // 6.4.9: Comments
3139 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003140 if (Char == '/') { // Line comment.
3141 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003142 // want to lex this as a comment. There is one problem with this though,
3143 // that in one particular corner case, this can change the behavior of the
3144 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003145 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003146 // "foo". Check to see if the character after the second slash is a '*'.
3147 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003148 // However, we never do this if we are just preprocessing.
3149 bool TreatAsComment = LangOpts.LineComment && !LangOpts.TraditionalCPP;
3150 if (!TreatAsComment)
3151 if (!(PP && PP->isPreprocessedOutput()))
3152 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3153
3154 if (TreatAsComment) {
Nico Weber158a31a2012-11-11 07:02:14 +00003155 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003156 return; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003157
Chris Lattner58827712009-01-16 22:39:25 +00003158 // It is common for the tokens immediately after a // comment to be
3159 // whitespace (indentation for the next line). Instead of going through
3160 // the big switch, handle it efficiently now.
3161 goto SkipIgnoredUnits;
3162 }
3163 }
Mike Stump11289f42009-09-09 15:08:12 +00003164
Chris Lattner58827712009-01-16 22:39:25 +00003165 if (Char == '*') { // /**/ comment.
Chris Lattner457fc152006-07-29 06:30:25 +00003166 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003167 return; // There is a token to return.
Chris Lattnere01e7582008-10-12 04:15:42 +00003168 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner58827712009-01-16 22:39:25 +00003169 }
Mike Stump11289f42009-09-09 15:08:12 +00003170
Chris Lattner58827712009-01-16 22:39:25 +00003171 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003172 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003173 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003174 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003175 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003176 }
3177 break;
3178 case '%':
3179 Char = getCharAndSize(CurPtr, SizeTmp);
3180 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003181 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003182 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003183 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003184 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003185 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003186 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003188 Char = getCharAndSize(CurPtr, SizeTmp);
3189 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003190 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003191 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3192 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003193 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003194 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003195 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003196 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003197 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003198 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003199 // We parsed a # character. If this occurs at the start of the line,
3200 // it's actually the start of a preprocessing directive. Callback to
3201 // the preprocessor to handle it.
3202 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003203 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3204 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003205
Chris Lattner2534324a2009-03-18 20:58:27 +00003206 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003207 }
3208 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003209 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003210 }
3211 break;
3212 case '<':
3213 Char = getCharAndSize(CurPtr, SizeTmp);
3214 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003215 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003216 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003217 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3218 if (After == '=') {
3219 Kind = tok::lesslessequal;
3220 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3221 SizeTmp2, Result);
3222 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3223 // If this is actually a '<<<<<<<' version control conflict marker,
3224 // recognize it as such and recover nicely.
3225 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003226 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3227 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3228 // ignore it.
3229 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003230 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003231 Kind = tok::lesslessless;
3232 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3233 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003234 } else {
3235 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3236 Kind = tok::lessless;
3237 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003238 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003239 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003240 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003241 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003242 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003243 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3244 // C++0x [lex.pptoken]p3:
3245 // Otherwise, if the next three characters are <:: and the subsequent
3246 // character is neither : nor >, the < is treated as a preprocessor
3247 // token by itself and not as the first character of the alternative
3248 // token <:.
3249 unsigned SizeTmp3;
3250 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3251 if (After != ':' && After != '>') {
3252 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003253 if (!isLexingRawMode())
3254 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003255 break;
3256 }
3257 }
3258
Chris Lattner22eb9722006-06-18 05:43:12 +00003259 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003260 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003261 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003262 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003263 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003264 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003265 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 }
3267 break;
3268 case '>':
3269 Char = getCharAndSize(CurPtr, SizeTmp);
3270 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003271 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003272 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003273 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003274 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3275 if (After == '=') {
3276 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3277 SizeTmp2, Result);
3278 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003279 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3280 // If this is actually a '>>>>' conflict marker, recognize it as such
3281 // and recover nicely.
3282 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003283 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3284 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3285 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003286 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003287 Kind = tok::greatergreatergreater;
3288 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3289 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003290 } else {
3291 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3292 Kind = tok::greatergreater;
3293 }
3294
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003296 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003297 }
3298 break;
3299 case '^':
3300 Char = getCharAndSize(CurPtr, SizeTmp);
3301 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003302 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003303 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003304 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003305 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003306 }
3307 break;
3308 case '|':
3309 Char = getCharAndSize(CurPtr, SizeTmp);
3310 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003311 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003312 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3313 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003314 // If this is '|||||||' and we're in a conflict marker, ignore it.
3315 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3316 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003317 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3319 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003320 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003321 }
3322 break;
3323 case ':':
3324 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003325 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003327 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003328 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003331 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003332 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003333 }
3334 break;
3335 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003336 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003337 break;
3338 case '=':
3339 Char = getCharAndSize(CurPtr, SizeTmp);
3340 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003341 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003342 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3343 goto LexNextToken;
3344
Chris Lattnerb11c3232008-10-12 04:51:35 +00003345 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003346 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003347 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003348 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003349 }
3350 break;
3351 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003352 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003353 break;
3354 case '#':
3355 Char = getCharAndSize(CurPtr, SizeTmp);
3356 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003357 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003358 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003359 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003360 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003361 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003362 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003363 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003364 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003365 // We parsed a # character. If this occurs at the start of the line,
3366 // it's actually the start of a preprocessing directive. Callback to
3367 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003368 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003369 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3370 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003371
Chris Lattner2534324a2009-03-18 20:58:27 +00003372 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003373 }
3374 break;
3375
Chris Lattner2b15cf72008-01-03 17:58:54 +00003376 case '@':
3377 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003378 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003379 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003380 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003381 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003382 break;
Mike Stump11289f42009-09-09 15:08:12 +00003383
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003384 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003385 case '\\':
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003386 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3387 return LexUnicode(Result, CodePoint, CurPtr);
3388
Chris Lattnerb11c3232008-10-12 04:51:35 +00003389 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003390 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003391
3392 default: {
3393 if (isASCII(Char)) {
3394 Kind = tok::unknown;
3395 break;
3396 }
3397
3398 UTF32 CodePoint;
3399
3400 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3401 // an escaped newline.
3402 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003403 ConversionResult Status =
3404 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3405 (const UTF8 *)BufferEnd,
3406 &CodePoint,
3407 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003408 if (Status == conversionOK)
3409 return LexUnicode(Result, CodePoint, CurPtr);
3410
Jordan Rosecc538342013-01-31 19:48:48 +00003411 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3412 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003413 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003414 Kind = tok::unknown;
3415 break;
3416 }
3417
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003418 // Non-ASCII characters tend to creep into source code unintentionally.
3419 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003420 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003421 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003422
3423 BufferPtr = CurPtr+1;
3424 goto LexNextToken;
3425 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 }
Mike Stump11289f42009-09-09 15:08:12 +00003427
Chris Lattner371ac8a2006-07-04 07:11:10 +00003428 // Notify MIOpt that we read a non-whitespace/non-comment token.
3429 MIOpt.ReadToken();
3430
Chris Lattnerd01e2912006-06-18 16:22:51 +00003431 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003432 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003433 return;
3434
3435HandleDirective:
3436 // We parsed a # character and it's the start of a preprocessing directive.
3437
3438 FormTokenWithChars(Result, CurPtr, tok::hash);
3439 PP->HandleDirective(Result);
3440
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003441 if (PP->hadModuleLoaderFatalFailure()) {
3442 // With a fatal failure in the module loader, we abort parsing.
3443 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3444 return;
3445 }
3446
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003447 // As an optimization, if the preprocessor didn't switch lexers, tail
3448 // recurse.
3449 if (PP->isCurrentLexer(this)) {
3450 // Start a new token. If this is a #include or something, the PP may
3451 // want us starting at the beginning of the line again. If so, set
3452 // the StartOfLine flag and clear LeadingSpace.
3453 if (IsAtStartOfLine) {
3454 Result.setFlag(Token::StartOfLine);
3455 Result.clearFlag(Token::LeadingSpace);
3456 IsAtStartOfLine = false;
3457 }
3458 goto LexNextToken; // GCC isn't tail call eliminating.
3459 }
3460 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003461}