blob: 66498b1a2c9d40c40480a8d44303ee2f5e65cd13 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +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:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
Jordan Rose98939022013-02-08 22:30:22 +000028#include "clang/Basic/CharInfo.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000029#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/CodeCompletionHandler.h"
31#include "clang/Lex/LexDiagnostic.h"
32#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Jordan Rosec7629d92013-01-24 20:50:46 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Support/MemoryBuffer.h"
Jordan Roseed9c59f2013-02-09 01:10:25 +000039#include "UnicodeCharSets.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000040#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Chris Lattnerdbf388b2007-10-07 08:47:24 +000043//===----------------------------------------------------------------------===//
44// Token Class Implementation
45//===----------------------------------------------------------------------===//
46
Mike Stump1eb44332009-09-09 15:08:12 +000047/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000048bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattnerdbf388b2007-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 Lattner53702cd2007-12-13 01:59:49 +000060
Chris Lattnerdbf388b2007-10-07 08:47:24 +000061//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie99ba9e32011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump1eb44332009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattner22d91ca2009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner22d91ca2009-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 Stump1eb44332009-09-09 15:08:12 +000076
Eric Christopher156119d2011-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 Lattner5f9e2722011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-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 Lattner22d91ca2009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000093
Chris Lattner22d91ca2009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Chris Lattner22d91ca2009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner22d91ca2009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner22d91ca2009-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 Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner22d91ca2009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner0770dab2009-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 Lattner6e290142009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikie4e4d0842012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner0770dab2009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Jordan Rose6aad4a32013-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 Lattner0770dab2009-01-17 07:56:59 +0000134}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000135
Chris Lattner168ae2d2007-10-17 20:41:00 +0000136/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000137/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner590f0cc2008-10-12 01:15:46 +0000138/// range will outlive it, so it doesn't take ownership of it.
David Blaikie4e4d0842012-03-11 07:00:24 +0000139Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000140 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikie4e4d0842012-03-11 07:00:24 +0000141 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000142
Chris Lattner22d91ca2009-01-17 06:55:17 +0000143 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Chris Lattner168ae2d2007-10-17 20:41:00 +0000145 // We *are* in raw mode.
146 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000147}
148
Chris Lattner025c3a62009-01-17 07:35:14 +0000149/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000150/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner025c3a62009-01-17 07:35:14 +0000151/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000152Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikie4e4d0842012-03-11 07:00:24 +0000153 const SourceManager &SM, const LangOptions &langOpts)
154 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000155
Mike Stump1eb44332009-09-09 15:08:12 +0000156 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000157 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000158
Chris Lattner025c3a62009-01-17 07:35:14 +0000159 // We *are* in raw mode.
160 LexingRawMode = true;
161}
162
Chris Lattner42e00d12009-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 Carruth433db062011-07-14 08:20:40 +0000169/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-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 Stump1eb44332009-09-09 15:08:12 +0000178Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000179 SourceLocation ExpansionLocStart,
180 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000181 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000182 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000183
184 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000185 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000186 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
187 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattner42e00d12009-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 Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner42e00d12009-01-17 08:27:52 +0000194 L->BufferPtr = StrData;
195 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000196 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-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 Carruthbf340e42011-07-26 03:03:05 +0000200 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
201 ExpansionLocStart,
202 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner42e00d12009-01-17 08:27:52 +0000204 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000205 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000206 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Chris Lattner42e00d12009-01-17 08:27:52 +0000208 // This lexer really is for _Pragma.
209 L->Is_PragmaLexer = true;
210 return L;
211}
212
Chris Lattner168ae2d2007-10-17 20:41:00 +0000213
Reid Spencer5f016e22007-07-11 17:01:13 +0000214/// Stringify - Convert the specified string into a C string, with surrounding
215/// ""'s, and with escaped \ and " characters.
216std::string Lexer::Stringify(const std::string &Str, bool Charify) {
217 std::string Result = Str;
218 char Quote = Charify ? '\'' : '"';
219 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
220 if (Result[i] == '\\' || Result[i] == Quote) {
221 Result.insert(Result.begin()+i, '\\');
222 ++i; ++e;
223 }
224 }
225 return Result;
226}
227
Chris Lattnerd8e30832007-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 Lattner5f9e2722011-07-23 10:55:15 +0000230void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-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 Lattnerb0607272010-11-17 07:26:20 +0000239//===----------------------------------------------------------------------===//
240// Token Spelling
241//===----------------------------------------------------------------------===//
242
Richard Smith30cddae2012-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 Lattnerb0607272010-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 Lattner5f9e2722011-07-23 10:55:15 +0000299StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith30cddae2012-11-28 07:29:00 +0000300 SmallVectorImpl<char> &buffer,
301 const SourceManager &SM,
302 const LangOptions &options,
303 bool *invalid) {
John McCall834e3f62011-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 Lattner5f9e2722011-07-23 10:55:15 +0000309 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000310 if (invalidTemp) {
311 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000312 return StringRef();
John McCall834e3f62011-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 Lattner5f9e2722011-07-23 10:55:15 +0000327 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000328
Richard Smith30cddae2012-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 Lattner5f9e2722011-07-23 10:55:15 +0000332 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-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 Lattnerb0607272010-11-17 07:26:20 +0000340std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000341 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000342 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith30cddae2012-11-28 07:29:00 +0000343
Chris Lattnerb0607272010-11-17 07:26:20 +0000344 bool CharDataInvalid = false;
Richard Smith30cddae2012-11-28 07:29:00 +0000345 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 &CharDataInvalid);
347 if (Invalid)
348 *Invalid = CharDataInvalid;
349 if (CharDataInvalid)
350 return std::string();
Richard Smith30cddae2012-11-28 07:29:00 +0000351
352 // If this token contains nothing interesting, return it directly.
Chris Lattnerb0607272010-11-17 07:26:20 +0000353 if (!Tok.needsCleaning())
Richard Smith30cddae2012-11-28 07:29:00 +0000354 return std::string(TokStart, TokStart + Tok.getLength());
355
Chris Lattnerb0607272010-11-17 07:26:20 +0000356 std::string Result;
Richard Smith30cddae2012-11-28 07:29:00 +0000357 Result.resize(Tok.getLength());
358 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattnerb0607272010-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 Blaikie4e4d0842012-03-11 07:00:24 +0000374 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000375 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-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 Rosec7629d92013-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 Lattnerb0607272010-11-17 07:26:20 +0000387 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000388
389 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000390 if (Tok.isLiteral())
391 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000392
Chris Lattnerb0607272010-11-17 07:26:20 +0000393 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000394 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-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 Bagnarac4bf2b92010-12-22 08:23:18 +0000404
Chris Lattnerb0607272010-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 Bagnarac4bf2b92010-12-22 08:23:18 +0000410
Chris Lattnerb0607272010-11-17 07:26:20 +0000411 // Otherwise, hard case, relex the characters into the string.
Richard Smith30cddae2012-11-28 07:29:00 +0000412 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattnerb0607272010-11-17 07:26:20 +0000413}
414
415
Chris Lattner9a611942007-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 Lattner2c78b872009-04-14 23:22:57 +0000421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
Argyrios Kyrtzidisd93335c2013-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 Lattner9a611942007-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 Stump1eb44332009-09-09 15:08:12 +0000436 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000437 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
438 // something.
Chris Lattnerde7aeef2009-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 Carruth40278532011-07-25 16:49:02 +0000442 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000443 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000444 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000445 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000446 if (Invalid)
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000447 return true;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000448
449 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000450
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000451 if (isWhitespace(StrData[0]))
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000452 return true;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000453
Chris Lattner9a611942007-10-17 21:18:47 +0000454 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000455 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
456 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000457 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000458 TheLexer.LexFromRawLexer(Result);
459 return false;
Chris Lattner9a611942007-10-17 21:18:47 +0000460}
461
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000462static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
463 const SourceManager &SM,
464 const LangOptions &LangOpts) {
465 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000466 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000467 if (LocInfo.first.isInvalid())
468 return Loc;
469
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000470 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000471 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-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 Gregor3de84242011-01-31 22:42:36 +0000478 if (LocInfo.second >= Buffer.size())
479 return Loc;
480
Douglas Gregora8e5c5b2010-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 Kyrtzidisa64ccef2011-09-19 20:40:19 +0000496 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-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 Kyrtzidis0e870622011-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 Carruthae9f85b2012-01-15 09:03:45 +0000534 std::pair<FileID, unsigned> BeginFileLocInfo
535 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000536 assert(FileLocInfo.first == BeginFileLocInfo.first &&
537 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000538 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000539}
540
Douglas Gregorf033f1d2010-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 Gregorf4f6c9d2010-07-26 21:36:20 +0000550std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000551Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000552 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-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 Kyrtzidis1cb71422012-10-25 01:51:45 +0000557 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
558 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000559 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis355dae62013-04-19 23:24:25 +0000560 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis1cb71422012-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 Gregorf033f1d2010-07-20 20:18:03 +0000565 bool InPreprocessorDirective = false;
566 Token TheTok;
567 Token IfStartTok;
568 unsigned IfCount = 0;
Argyrios Kyrtzidis355dae62013-04-19 23:24:25 +0000569 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisc8c97a02011-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 Gregordf95a132010-08-09 20:45:32 +0000586
Douglas Gregorf033f1d2010-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 Gregorf033f1d2010-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 Gregordf95a132010-08-09 20:45:32 +0000606 // Keep track of the # of lines in the preamble.
607 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000608 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-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 Kyrtzidisc8c97a02011-09-04 03:32:04 +0000612 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000613 break;
614 }
615
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000616 // Comments are okay; skip over them.
Argyrios Kyrtzidis355dae62013-04-19 23:24:25 +0000617 if (TheTok.getKind() == tok::comment) {
618 if (ActiveCommentLoc.isInvalid())
619 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000620 continue;
Argyrios Kyrtzidis355dae62013-04-19 23:24:25 +0000621 }
Douglas Gregorf033f1d2010-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 Kyrtzidis355dae62013-04-19 23:24:25 +0000627 ActiveCommentLoc = SourceLocation();
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000628
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000629 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-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 Bagnarac4bf2b92010-12-22 08:23:18 +0000633 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000634 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000635 TheTok.getLength());
Douglas Gregorf033f1d2010-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 Gregordf95a132010-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 Gregorf033f1d2010-07-20 20:18:03 +0000695 break;
696 } while (true);
697
Argyrios Kyrtzidis355dae62013-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 Gregorf4f6c9d2010-07-26 21:36:20 +0000706 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
707 IfCount? IfStartTok.isAtStartOfLine()
708 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000709}
710
Chris Lattner7ef5c272010-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 Blaikie4e4d0842012-03-11 07:00:24 +0000717 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000718 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-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 Kyrtzidisa64ccef2011-09-19 20:40:19 +0000735 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-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 Blaikie4e4d0842012-03-11 07:00:24 +0000743 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-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 Kyrtzidisa64ccef2011-09-19 20:40:19 +0000755 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-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 Blaikie4e4d0842012-03-11 07:00:24 +0000775 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000776 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000777 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000778
779 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000780 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000781 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000782 }
783
David Blaikie4e4d0842012-03-11 07:00:24 +0000784 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000785 if (Len > Offset)
786 Len = Len - Offset;
787 else
788 return Loc;
789
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000790 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000791}
792
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000793/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000794/// token of the macro expansion.
795bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000796 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000797 const LangOptions &LangOpts,
798 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000799 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
800
801 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
802 // FIXME: If the token comes from the macro token paste operator ('##')
803 // this function will always return false;
804 if (infoLoc.second > 0)
805 return false; // Does not point at the start of token.
806
Chandler Carruth433db062011-07-14 08:20:40 +0000807 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000808 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000809 if (expansionLoc.isFileID()) {
810 // No other macro expansions, this is the first.
811 if (MacroBegin)
812 *MacroBegin = expansionLoc;
813 return true;
814 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000815
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000816 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000817}
818
819/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000820/// token of the macro expansion.
821bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000822 const SourceManager &SM,
823 const LangOptions &LangOpts,
824 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000825 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
826
827 SourceLocation spellLoc = SM.getSpellingLoc(loc);
828 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
829 if (tokLen == 0)
830 return false;
831
832 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000833 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000834 if (SM.isInFileID(afterLoc, FID))
835 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000836
837 // FIXME: If the token comes from the macro token paste operator ('##')
838 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000839
Chandler Carruth433db062011-07-14 08:20:40 +0000840 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000841 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000842 if (expansionLoc.isFileID()) {
843 // No other macro expansions.
844 if (MacroEnd)
845 *MacroEnd = expansionLoc;
846 return true;
847 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000848
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000849 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000850}
851
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000852static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000853 const SourceManager &SM,
854 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000855 SourceLocation Begin = Range.getBegin();
856 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000857 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000858 if (Range.isTokenRange()) {
859 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
860 if (End.isInvalid())
861 return CharSourceRange();
862 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000863
864 // Break down the source locations.
865 FileID FID;
866 unsigned BeginOffs;
867 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
868 if (FID.isInvalid())
869 return CharSourceRange();
870
871 unsigned EndOffs;
872 if (!SM.isInFileID(End, FID, &EndOffs) ||
873 BeginOffs > EndOffs)
874 return CharSourceRange();
875
876 return CharSourceRange::getCharRange(Begin, End);
877}
878
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000879CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000880 const SourceManager &SM,
881 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000882 SourceLocation Begin = Range.getBegin();
883 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000884 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000885 return CharSourceRange();
886
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000887 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000888 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000889
890 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000891 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
892 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000893 Range.setBegin(Begin);
894 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000895 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000896
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000897 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000898 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
899 &End)) ||
900 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
901 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000902 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000903 Range.setEnd(End);
904 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000905 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000906
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000907 assert(Begin.isMacroID() && End.isMacroID());
908 SourceLocation MacroBegin, MacroEnd;
909 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000910 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
911 &MacroEnd)) ||
912 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
913 &MacroEnd)))) {
914 Range.setBegin(MacroBegin);
915 Range.setEnd(MacroEnd);
916 return makeRangeFromFileLocs(Range, SM, LangOpts);
917 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000918
919 FileID FID;
920 unsigned BeginOffs;
921 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
922 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000923 return CharSourceRange();
924
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000925 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000926 if (!SM.isInFileID(End, FID, &EndOffs) ||
927 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000928 return CharSourceRange();
929
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000930 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
931 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
932 if (Expansion.isMacroArgExpansion() &&
933 Expansion.getSpellingLoc().isFileID()) {
934 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000935 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
936 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
937 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000938 }
939
940 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000941}
942
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000943StringRef Lexer::getSourceText(CharSourceRange Range,
944 const SourceManager &SM,
945 const LangOptions &LangOpts,
946 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000947 Range = makeFileCharRange(Range, SM, LangOpts);
948 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000949 if (Invalid) *Invalid = true;
950 return StringRef();
951 }
952
953 // Break down the source location.
954 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
955 if (beginInfo.first.isInvalid()) {
956 if (Invalid) *Invalid = true;
957 return StringRef();
958 }
959
960 unsigned EndOffs;
961 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
962 beginInfo.second > EndOffs) {
963 if (Invalid) *Invalid = true;
964 return StringRef();
965 }
966
967 // Try to the load the file buffer.
968 bool invalidTemp = false;
969 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
970 if (invalidTemp) {
971 if (Invalid) *Invalid = true;
972 return StringRef();
973 }
974
975 if (Invalid) *Invalid = false;
976 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
977}
978
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000979StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
980 const SourceManager &SM,
981 const LangOptions &LangOpts) {
982 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000983
984 // Find the location of the immediate macro expansion.
985 while (1) {
986 FileID FID = SM.getFileID(Loc);
987 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
988 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
989 Loc = Expansion.getExpansionLocStart();
990 if (!Expansion.isMacroArgExpansion())
991 break;
992
993 // For macro arguments we need to check that the argument did not come
994 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
995
996 // Loc points to the argument id of the macro definition, move to the
997 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000998 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000999 SourceLocation SpellLoc = Expansion.getSpellingLoc();
1000 if (SpellLoc.isFileID())
1001 break; // No inner macro.
1002
1003 // If spelling location resides in the same FileID as macro expansion
1004 // location, it means there is no inner macro.
1005 FileID MacroFID = SM.getFileID(Loc);
1006 if (SM.isInFileID(SpellLoc, MacroFID))
1007 break;
1008
1009 // Argument came from inner macro.
1010 Loc = SpellLoc;
1011 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +00001012
1013 // Find the spelling location of the start of the non-argument expansion
1014 // range. This is where the macro name was spelled in order to begin
1015 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +00001016 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +00001017
1018 // Dig out the buffer where the macro name was spelled and the extents of the
1019 // name so that we can render it into the expansion note.
1020 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1021 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1022 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1023 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1024}
1025
Jordan Rosed880b3a2012-06-07 01:10:31 +00001026bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rose98939022013-02-08 22:30:22 +00001027 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rosed880b3a2012-06-07 01:10:31 +00001028}
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030
1031//===----------------------------------------------------------------------===//
1032// Diagnostics forwarding code.
1033//===----------------------------------------------------------------------===//
1034
Chris Lattner409a0362007-07-22 18:38:25 +00001035/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001036/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001037/// This is currently only used for _Pragma implementation, so it is the slow
1038/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001039static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1040 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001041static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1042 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001043 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001044 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner409a0362007-07-22 18:38:25 +00001046 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001047 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001048 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001049 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Chandler Carruth433db062011-07-14 08:20:40 +00001051 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001052 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001053 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001054 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Chris Lattnere7fb4842009-02-15 20:52:18 +00001056 // Figure out the expansion loc range, which is the range covered by the
1057 // original _Pragma(...) sequence.
1058 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001059 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Chandler Carruthbf340e42011-07-26 03:03:05 +00001061 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001062}
1063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064/// getSourceLocation - Return a source location identifier for the specified
1065/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001066SourceLocation Lexer::getSourceLocation(const char *Loc,
1067 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001068 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001070
1071 // In the normal case, we're just lexing from a simple file buffer, return
1072 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001073 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001074 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001075 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Chris Lattner2b2453a2009-01-17 06:22:33 +00001077 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1078 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001079 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001080 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001081}
1082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083/// Diag - Forwarding function for diagnostics. This translate a source
1084/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001085DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001086 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001087}
Reid Spencer5f016e22007-07-11 17:01:13 +00001088
1089//===----------------------------------------------------------------------===//
1090// Trigraph and Escaped Newline Handling Code.
1091//===----------------------------------------------------------------------===//
1092
1093/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1094/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1095static char GetTrigraphCharForLetter(char Letter) {
1096 switch (Letter) {
1097 default: return 0;
1098 case '=': return '#';
1099 case ')': return ']';
1100 case '(': return '[';
1101 case '!': return '|';
1102 case '\'': return '^';
1103 case '>': return '}';
1104 case '/': return '\\';
1105 case '<': return '{';
1106 case '-': return '~';
1107 }
1108}
1109
1110/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1111/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1112/// return the result character. Finally, emit a warning about trigraph use
1113/// whether trigraphs are enabled or not.
1114static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1115 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001116 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001117
David Blaikie4e4d0842012-03-11 07:00:24 +00001118 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001119 if (!L->isLexingRawMode())
1120 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001121 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner74d15df2008-11-22 02:02:22 +00001124 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001125 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 return Res;
1127}
1128
Chris Lattner24f0e482009-04-18 22:05:41 +00001129/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1130/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump1eb44332009-09-09 15:08:12 +00001131/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001132unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1133 unsigned Size = 0;
1134 while (isWhitespace(Ptr[Size])) {
1135 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner24f0e482009-04-18 22:05:41 +00001137 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1138 continue;
1139
1140 // If this is a \r\n or \n\r, skip the other half.
1141 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1142 Ptr[Size-1] != Ptr[Size])
1143 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Chris Lattner24f0e482009-04-18 22:05:41 +00001145 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001146 }
1147
Chris Lattner24f0e482009-04-18 22:05:41 +00001148 // Not an escaped newline, must be a \t or something else.
1149 return 0;
1150}
1151
Chris Lattner03374952009-04-18 22:27:02 +00001152/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1153/// them), skip over them and return the first non-escaped-newline found,
1154/// otherwise return P.
1155const char *Lexer::SkipEscapedNewLines(const char *P) {
1156 while (1) {
1157 const char *AfterEscape;
1158 if (*P == '\\') {
1159 AfterEscape = P+1;
1160 } else if (*P == '?') {
1161 // If not a trigraph for escape, bail out.
1162 if (P[1] != '?' || P[2] != '/')
1163 return P;
1164 AfterEscape = P+3;
1165 } else {
1166 return P;
1167 }
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner03374952009-04-18 22:27:02 +00001169 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1170 if (NewLineSize == 0) return P;
1171 P = AfterEscape+NewLineSize;
1172 }
1173}
1174
Anna Zaksaca25bc2011-07-27 21:43:43 +00001175/// \brief Checks that the given token is the first token that occurs after the
1176/// given location (this excludes comments and whitespace). Returns the location
1177/// immediately after the specified token. If the token is not found or the
1178/// location is inside a macro, the returned source location will be invalid.
1179SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1180 tok::TokenKind TKind,
1181 const SourceManager &SM,
1182 const LangOptions &LangOpts,
1183 bool SkipTrailingWhitespaceAndNewLine) {
1184 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001185 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001186 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001187 }
1188 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1189
1190 // Break down the source location.
1191 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1192
1193 // Try to load the file buffer.
1194 bool InvalidTemp = false;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001195 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001196 if (InvalidTemp)
1197 return SourceLocation();
1198
1199 const char *TokenBegin = File.data() + LocInfo.second;
1200
1201 // Lex from the start of the given location.
1202 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1203 TokenBegin, File.end());
1204 // Find the token.
1205 Token Tok;
1206 lexer.LexFromRawLexer(Tok);
1207 if (Tok.isNot(TKind))
1208 return SourceLocation();
1209 SourceLocation TokenLoc = Tok.getLocation();
1210
1211 // Calculate how much whitespace needs to be skipped if any.
1212 unsigned NumWhitespaceChars = 0;
1213 if (SkipTrailingWhitespaceAndNewLine) {
1214 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1215 Tok.getLength();
1216 unsigned char C = *TokenEnd;
1217 while (isHorizontalWhitespace(C)) {
1218 C = *(++TokenEnd);
1219 NumWhitespaceChars++;
1220 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001221
1222 // Skip \r, \n, \r\n, or \n\r
1223 if (C == '\n' || C == '\r') {
1224 char PrevC = C;
1225 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001226 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001227 if ((C == '\n' || C == '\r') && C != PrevC)
1228 NumWhitespaceChars++;
1229 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001230 }
1231
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001232 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001233}
Chris Lattner24f0e482009-04-18 22:05:41 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1236/// get its size, and return it. This is tricky in several cases:
1237/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1238/// then either return the trigraph (skipping 3 chars) or the '?',
1239/// depending on whether trigraphs are enabled or not.
1240/// 2. If this is an escaped newline (potentially with whitespace between
1241/// the backslash and newline), implicitly skip the newline and return
1242/// the char after it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001243///
1244/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1245/// know that we can accumulate into Size, and that we have already incremented
1246/// Ptr by Size bytes.
1247///
1248/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1249/// be updated to match.
1250///
1251char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001252 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 // If we have a slash, look for an escaped newline.
1254 if (Ptr[0] == '\\') {
1255 ++Size;
1256 ++Ptr;
1257Slash:
1258 // Common case, backslash-char where the char is not whitespace.
1259 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Chris Lattner5636a3b2009-06-23 05:15:06 +00001261 // See if we have optional whitespace characters between the slash and
1262 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001263 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1264 // Remember that this token needs to be cleaned.
1265 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266
Chris Lattner24f0e482009-04-18 22:05:41 +00001267 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001268 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001269 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner24f0e482009-04-18 22:05:41 +00001271 // Found backslash<whitespace><newline>. Parse the char after it.
1272 Size += EscapedNewLineSize;
1273 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001274
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001275 // If the char that we finally got was a \n, then we must have had
1276 // something like \<newline><newline>. We don't want to consume the
1277 // second newline.
1278 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1279 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001280
Chris Lattner24f0e482009-04-18 22:05:41 +00001281 // Use slow version to accumulate a correct size field.
1282 return getCharAndSizeSlow(Ptr, Size, Tok);
1283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // Otherwise, this is not an escaped newline, just return the slash.
1286 return '\\';
1287 }
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // If this is a trigraph, process it.
1290 if (Ptr[0] == '?' && Ptr[1] == '?') {
1291 // If this is actually a legal trigraph (not something like "??x"), emit
1292 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1293 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1294 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001295 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296
1297 Ptr += 3;
1298 Size += 3;
1299 if (C == '\\') goto Slash;
1300 return C;
1301 }
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // If this is neither, return a single character.
1305 ++Size;
1306 return *Ptr;
1307}
1308
1309
1310/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1311/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1312/// and that we have already incremented Ptr by Size bytes.
1313///
1314/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1315/// be updated to match.
1316char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001317 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // If we have a slash, look for an escaped newline.
1319 if (Ptr[0] == '\\') {
1320 ++Size;
1321 ++Ptr;
1322Slash:
1323 // Common case, backslash-char where the char is not whitespace.
1324 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001327 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1328 // Found backslash<whitespace><newline>. Parse the char after it.
1329 Size += EscapedNewLineSize;
1330 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001332 // If the char that we finally got was a \n, then we must have had
1333 // something like \<newline><newline>. We don't want to consume the
1334 // second newline.
1335 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1336 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001337
Chris Lattner24f0e482009-04-18 22:05:41 +00001338 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001339 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 // Otherwise, this is not an escaped newline, just return the slash.
1343 return '\\';
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001347 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 // If this is actually a legal trigraph (not something like "??x"), return
1349 // it.
1350 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1351 Ptr += 3;
1352 Size += 3;
1353 if (C == '\\') goto Slash;
1354 return C;
1355 }
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 // If this is neither, return a single character.
1359 ++Size;
1360 return *Ptr;
1361}
1362
1363//===----------------------------------------------------------------------===//
1364// Helper methods for lexing.
1365//===----------------------------------------------------------------------===//
1366
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001367/// \brief Routine that indiscriminately skips bytes in the source file.
1368void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1369 BufferPtr += Bytes;
1370 if (BufferPtr > BufferEnd)
1371 BufferPtr = BufferEnd;
1372 IsAtStartOfLine = StartOfLine;
1373}
1374
Jordan Roseed9c59f2013-02-09 01:10:25 +00001375static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1376 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1377 return isCharInSet(C, C11AllowedIDChars);
1378 else if (LangOpts.CPlusPlus)
1379 return isCharInSet(C, CXX03AllowedIDChars);
1380 else
1381 return isCharInSet(C, C99AllowedIDChars);
Jordan Rosec7629d92013-01-24 20:50:46 +00001382}
1383
Jordan Roseed9c59f2013-02-09 01:10:25 +00001384static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1385 assert(isAllowedIDChar(C, LangOpts));
1386 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1387 return !isCharInSet(C, C11DisallowedInitialIDChars);
1388 else if (LangOpts.CPlusPlus)
1389 return true;
1390 else
1391 return !isCharInSet(C, C99DisallowedInitialIDChars);
1392}
Jordan Rosec7629d92013-01-24 20:50:46 +00001393
Jordan Roseed9c59f2013-02-09 01:10:25 +00001394static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1395 const char *End) {
1396 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1397 L.getSourceLocation(End));
1398}
1399
1400static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1401 CharSourceRange Range, bool IsFirst) {
1402 // Check C99 compatibility.
1403 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1404 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1405 enum {
1406 CannotAppearInIdentifier = 0,
1407 CannotStartIdentifier
1408 };
1409
1410 if (!isCharInSet(C, C99AllowedIDChars)) {
1411 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1412 << Range
1413 << CannotAppearInIdentifier;
1414 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1415 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1416 << Range
1417 << CannotStartIdentifier;
1418 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001419 }
1420
Jordan Roseed9c59f2013-02-09 01:10:25 +00001421 // Check C++98 compatibility.
1422 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1423 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1424 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1425 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1426 << Range;
1427 }
1428 }
1429 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001430
Chris Lattnerd2177732007-07-20 16:59:19 +00001431void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1433 unsigned Size;
1434 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001435 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 --CurPtr; // Back up over the skipped character.
1439
1440 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1441 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattnercd991db2010-01-11 02:38:50 +00001442 //
Jordan Rose98939022013-02-08 22:30:22 +00001443 // TODO: Could merge these checks into an InfoTable flag to make the
1444 // comparison cheaper
Jordan Rosec7629d92013-01-24 20:50:46 +00001445 if (isASCII(C) && C != '\\' && C != '?' &&
1446 (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001447FinishIdentifier:
1448 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001449 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1450 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 // If we are in raw mode, return this identifier raw. There is no need to
1453 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001454 if (LexingRawMode)
1455 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001457 // Fill in Result.IdentifierInfo and update the token kind,
1458 // looking up the identifier in the identifier table.
1459 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 // Finally, now that we know we have an identifier, pass this off to the
1462 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001463 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001464 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001465
Chris Lattner6a170eb2009-01-21 07:43:11 +00001466 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 C = getCharAndSize(CurPtr, Size);
1472 while (1) {
1473 if (C == '$') {
1474 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001475 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001478 if (!isLexingRawMode())
1479 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 CurPtr = ConsumeChar(CurPtr, Size, Result);
1481 C = getCharAndSize(CurPtr, Size);
1482 continue;
Jordan Rosec7629d92013-01-24 20:50:46 +00001483
1484 } else if (C == '\\') {
1485 const char *UCNPtr = CurPtr + Size;
1486 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Roseed9c59f2013-02-09 01:10:25 +00001487 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001488 goto FinishIdentifier;
1489
Jordan Roseed9c59f2013-02-09 01:10:25 +00001490 if (!isLexingRawMode()) {
1491 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1492 makeCharRange(*this, CurPtr, UCNPtr),
1493 /*IsFirst=*/false);
1494 }
1495
Jordan Rosec7629d92013-01-24 20:50:46 +00001496 Result.setFlag(Token::HasUCN);
1497 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1498 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1499 CurPtr = UCNPtr;
1500 else
1501 while (CurPtr != UCNPtr)
1502 (void)getAndAdvanceChar(CurPtr, Result);
1503
1504 C = getCharAndSize(CurPtr, Size);
1505 continue;
1506 } else if (!isASCII(C)) {
1507 const char *UnicodePtr = CurPtr;
1508 UTF32 CodePoint;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00001509 ConversionResult Result =
1510 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1511 (const UTF8 *)BufferEnd,
1512 &CodePoint,
1513 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00001514 if (Result != conversionOK ||
Jordan Roseed9c59f2013-02-09 01:10:25 +00001515 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001516 goto FinishIdentifier;
1517
Jordan Roseed9c59f2013-02-09 01:10:25 +00001518 if (!isLexingRawMode()) {
1519 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1520 makeCharRange(*this, CurPtr, UnicodePtr),
1521 /*IsFirst=*/false);
1522 }
1523
Jordan Rosec7629d92013-01-24 20:50:46 +00001524 CurPtr = UnicodePtr;
1525 C = getCharAndSize(CurPtr, Size);
1526 continue;
1527 } else if (!isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 goto FinishIdentifier;
1529 }
1530
1531 // Otherwise, this character is good, consume it.
1532 CurPtr = ConsumeChar(CurPtr, Size, Result);
1533
1534 C = getCharAndSize(CurPtr, Size);
Jordan Rosec7629d92013-01-24 20:50:46 +00001535 while (isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 CurPtr = ConsumeChar(CurPtr, Size, Result);
1537 C = getCharAndSize(CurPtr, Size);
1538 }
1539 }
1540}
1541
Douglas Gregora75ec432010-08-30 14:50:47 +00001542/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001543/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001544bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001545 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001546 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001547 if (C1 != '0')
1548 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001549 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001550 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001551}
Reid Spencer5f016e22007-07-11 17:01:13 +00001552
Nate Begeman5253c7f2008-04-14 02:26:39 +00001553/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001554/// constant. From[-1] is the first character lexed. Return the end of the
1555/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001556void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 unsigned Size;
1558 char C = getCharAndSize(CurPtr, Size);
1559 char PrevCh = 0;
Jordan Rose98939022013-02-08 22:30:22 +00001560 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 CurPtr = ConsumeChar(CurPtr, Size, Result);
1562 PrevCh = C;
1563 C = getCharAndSize(CurPtr, Size);
1564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001567 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1568 // If we are in Microsoft mode, don't continue if the constant is hex.
1569 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001570 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001571 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001573
1574 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001575 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1576 // Outside C99, we accept hexadecimal floating point numbers as a
1577 // not-quite-conforming extension. Only do so if this looks like it's
1578 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1579 bool IsHexFloat = true;
1580 if (!LangOpts.C99) {
1581 if (!isHexaLiteral(BufferPtr, LangOpts))
1582 IsHexFloat = false;
1583 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1584 IsHexFloat = false;
1585 }
1586 if (IsHexFloat)
1587 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001591 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001592 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001593 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594}
1595
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001596/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001597/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001598const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001599 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001600
1601 // Maximally munch an identifier. FIXME: UCNs.
1602 unsigned Size;
1603 char C = getCharAndSize(CurPtr, Size);
1604 if (isIdentifierHead(C)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001605 if (!getLangOpts().CPlusPlus11) {
Richard Smithe816c712012-03-07 03:13:00 +00001606 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001607 Diag(CurPtr,
1608 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1609 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1610 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1611 return CurPtr;
1612 }
1613
1614 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1615 // that does not start with an underscore is ill-formed. As a conforming
1616 // extension, we treat all such suffixes as if they had whitespace before
1617 // them.
1618 if (C != '_') {
1619 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001620 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1621 diag::ext_ms_reserved_user_defined_literal :
1622 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001623 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1624 return CurPtr;
1625 }
1626
Richard Smith99831e42012-03-06 03:21:47 +00001627 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001628 do {
1629 CurPtr = ConsumeChar(CurPtr, Size, Result);
1630 C = getCharAndSize(CurPtr, Size);
1631 } while (isIdentifierBody(C));
1632 }
1633 return CurPtr;
1634}
1635
Reid Spencer5f016e22007-07-11 17:01:13 +00001636/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001637/// either " or L" or u8" or u" or U".
1638void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1639 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Richard Smith661a9962011-10-15 01:18:56 +00001642 if (!isLexingRawMode() &&
1643 (Kind == tok::utf8_string_literal ||
1644 Kind == tok::utf16_string_literal ||
Richard Smithd4bf7602013-03-11 18:01:42 +00001645 Kind == tok::utf32_string_literal))
1646 Diag(BufferPtr, getLangOpts().CPlusPlus
1647 ? diag::warn_cxx98_compat_unicode_literal
1648 : diag::warn_c99_compat_unicode_literal);
Richard Smith661a9962011-10-15 01:18:56 +00001649
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 char C = getAndAdvanceChar(CurPtr, Result);
1651 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001652 // Skip escaped characters. Escaped newlines will already be processed by
1653 // getAndAdvanceChar.
1654 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001656
Chris Lattner571339c2010-05-30 23:27:38 +00001657 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001658 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001659 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001660 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001661 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 }
Chris Lattner571339c2010-05-30 23:27:38 +00001664
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001665 if (C == 0) {
1666 if (isCodeCompletionPoint(CurPtr-1)) {
1667 PP->CodeCompleteNaturalLanguage();
1668 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1669 return cutOffLexing();
1670 }
1671
Chris Lattner571339c2010-05-30 23:27:38 +00001672 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001673 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 C = getAndAdvanceChar(CurPtr, Result);
1675 }
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001677 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001678 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001679 CurPtr = LexUDSuffix(Result, CurPtr);
1680
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001682 if (NulCharacter && !isLexingRawMode())
1683 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001686 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001687 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001688 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689}
1690
Craig Topper2fa4e862011-08-11 04:06:15 +00001691/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1692/// having lexed R", LR", u8R", uR", or UR".
1693void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1694 tok::TokenKind Kind) {
1695 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1696 // Between the initial and final double quote characters of the raw string,
1697 // any transformations performed in phases 1 and 2 (trigraphs,
1698 // universal-character-names, and line splicing) are reverted.
1699
Richard Smith661a9962011-10-15 01:18:56 +00001700 if (!isLexingRawMode())
1701 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1702
Craig Topper2fa4e862011-08-11 04:06:15 +00001703 unsigned PrefixLen = 0;
1704
1705 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1706 ++PrefixLen;
1707
1708 // If the last character was not a '(', then we didn't lex a valid delimiter.
1709 if (CurPtr[PrefixLen] != '(') {
1710 if (!isLexingRawMode()) {
1711 const char *PrefixEnd = &CurPtr[PrefixLen];
1712 if (PrefixLen == 16) {
1713 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1714 } else {
1715 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1716 << StringRef(PrefixEnd, 1);
1717 }
1718 }
1719
1720 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1721 // it's possible the '"' was intended to be part of the raw string, but
1722 // there's not much we can do about that.
1723 while (1) {
1724 char C = *CurPtr++;
1725
1726 if (C == '"')
1727 break;
1728 if (C == 0 && CurPtr-1 == BufferEnd) {
1729 --CurPtr;
1730 break;
1731 }
1732 }
1733
1734 FormTokenWithChars(Result, CurPtr, tok::unknown);
1735 return;
1736 }
1737
1738 // Save prefix and move CurPtr past it
1739 const char *Prefix = CurPtr;
1740 CurPtr += PrefixLen + 1; // skip over prefix and '('
1741
1742 while (1) {
1743 char C = *CurPtr++;
1744
1745 if (C == ')') {
1746 // Check for prefix match and closing quote.
1747 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1748 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1749 break;
1750 }
1751 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1752 if (!isLexingRawMode())
1753 Diag(BufferPtr, diag::err_unterminated_raw_string)
1754 << StringRef(Prefix, PrefixLen);
1755 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1756 return;
1757 }
1758 }
1759
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001760 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001761 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001762 CurPtr = LexUDSuffix(Result, CurPtr);
1763
Craig Topper2fa4e862011-08-11 04:06:15 +00001764 // Update the location of token as well as BufferPtr.
1765 const char *TokStart = BufferPtr;
1766 FormTokenWithChars(Result, CurPtr, Kind);
1767 Result.setLiteralData(TokStart);
1768}
1769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1771/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001772void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001774 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 char C = getAndAdvanceChar(CurPtr, Result);
1776 while (C != '>') {
1777 // Skip escaped characters.
1778 if (C == '\\') {
1779 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001780 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001782 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1783 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001784 // If the filename is unterminated, then it must just be a lone <
1785 // character. Return this as such.
1786 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 return;
1788 } else if (C == 0) {
1789 NulCharacter = CurPtr-1;
1790 }
1791 C = getAndAdvanceChar(CurPtr, Result);
1792 }
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001795 if (NulCharacter && !isLexingRawMode())
1796 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001799 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001800 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001801 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802}
1803
1804
1805/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001806/// lexed either ' or L' or u' or U'.
1807void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1808 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 const char *NulCharacter = 0; // Does this character contain the \0 character?
1810
Richard Smith661a9962011-10-15 01:18:56 +00001811 if (!isLexingRawMode() &&
Richard Smithd4bf7602013-03-11 18:01:42 +00001812 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1813 Diag(BufferPtr, getLangOpts().CPlusPlus
1814 ? diag::warn_cxx98_compat_unicode_literal
1815 : diag::warn_c99_compat_unicode_literal);
Richard Smith661a9962011-10-15 01:18:56 +00001816
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 char C = getAndAdvanceChar(CurPtr, Result);
1818 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001819 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001820 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001821 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001823 }
1824
1825 while (C != '\'') {
1826 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001827 if (C == '\\')
1828 C = getAndAdvanceChar(CurPtr, Result);
1829
1830 if (C == '\n' || C == '\r' || // Newline.
1831 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001832 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001833 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001834 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1835 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001836 }
1837
1838 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001839 if (isCodeCompletionPoint(CurPtr-1)) {
1840 PP->CodeCompleteNaturalLanguage();
1841 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1842 return cutOffLexing();
1843 }
1844
Chris Lattnerd80f7862010-07-07 23:24:27 +00001845 NulCharacter = CurPtr-1;
1846 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 C = getAndAdvanceChar(CurPtr, Result);
1848 }
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001850 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001851 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001852 CurPtr = LexUDSuffix(Result, CurPtr);
1853
Chris Lattnerd80f7862010-07-07 23:24:27 +00001854 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001855 if (NulCharacter && !isLexingRawMode())
1856 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001857
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001859 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001860 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001861 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001862}
1863
1864/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1865/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001866///
1867/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1868///
1869bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001871 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1872
Richard Smith8f190032013-05-10 02:36:35 +00001873 unsigned char Char = *CurPtr;
1874
1875 // Skip consecutive spaces efficiently.
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 while (1) {
1877 // Skip horizontal whitespace very aggressively.
1878 while (isHorizontalWhitespace(Char))
1879 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001881 // Otherwise if we have something other than whitespace, we're done.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001882 if (!isVerticalWhitespace(Char))
Reid Spencer5f016e22007-07-11 17:01:13 +00001883 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 if (ParsingPreprocessorDirective) {
1886 // End of preprocessor directive line, let LexTokenInternal handle this.
1887 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001888 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Richard Smith8f190032013-05-10 02:36:35 +00001891 // OK, but handle newline.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001892 SawNewline = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 Char = *++CurPtr;
1894 }
1895
Chris Lattnerd88dc482008-10-12 04:05:48 +00001896 // If the client wants us to return whitespace, return it now.
1897 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001898 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rose6aad4a32013-02-21 18:53:19 +00001899 if (SawNewline)
1900 IsAtStartOfLine = true;
1901 // FIXME: The next token will not have LeadingSpace set.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001902 return true;
1903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Jordan Rose6aad4a32013-02-21 18:53:19 +00001905 // If this isn't immediately after a newline, there is leading space.
1906 char PrevChar = CurPtr[-1];
1907 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1908
1909 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1910 if (SawNewline)
1911 Result.setFlag(Token::StartOfLine);
1912
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001914 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001915}
1916
Nico Weberbb236282012-11-11 07:02:14 +00001917/// We have just read the // characters from input. Skip until we find the
1918/// newline character thats terminate the comment. Then update BufferPtr and
1919/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001920///
1921/// If we're in KeepCommentMode or any CommentHandler has inserted
1922/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001923bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1924 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001926 if (!LangOpts.LineComment && !isLexingRawMode()) {
1927 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 // Mark them enabled so we only emit one warning for this translation
1930 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001931 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 // Scan over the body of the comment. The common case, when scanning, is that
1935 // the comment contains normal ascii characters with nothing interesting in
1936 // them. As such, optimize for this case with the inner loop.
1937 char C;
1938 do {
1939 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 // Skip over characters in the fast loop.
1941 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 C != '\n' && C != '\r') // Newline or DOS-style newline.
1943 C = *++CurPtr;
1944
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001945 const char *NextLine = CurPtr;
1946 if (C != 0) {
1947 // We found a newline, see if it's escaped.
1948 const char *EscapePtr = CurPtr-1;
1949 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1950 --EscapePtr;
1951
1952 if (*EscapePtr == '\\') // Escaped newline.
1953 CurPtr = EscapePtr;
1954 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1955 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1956 CurPtr = EscapePtr-2;
1957 else
1958 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001962 // properly decode the character. Read it in raw mode to avoid emitting
1963 // diagnostics about things like trigraphs. If we see an escaped newline,
1964 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001966 bool OldRawMode = isLexingRawMode();
1967 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001969 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001970
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001971 // If we only read only one character, then no special handling is needed.
1972 // We're done and can skip forward to the newline.
1973 if (C != 0 && CurPtr == OldPtr+1) {
1974 CurPtr = NextLine;
1975 break;
1976 }
1977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // If we read multiple characters, and one of those characters was a \r or
1979 // \n, then we had an escaped newline within the comment. Emit diagnostic
1980 // unless the next line is also a // comment.
1981 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1982 for (; OldPtr != CurPtr; ++OldPtr)
1983 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1984 // Okay, we found a // comment that ends in a newline, if the next
1985 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001986 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001988 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 ++ForwardPtr;
1990 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1991 break;
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Chris Lattner74d15df2008-11-22 02:02:22 +00001994 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00001995 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 break;
1997 }
1998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Douglas Gregor55817af2010-08-25 17:04:25 +00002000 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00002001 --CurPtr;
2002 break;
2003 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002004
2005 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2006 PP->CodeCompleteNaturalLanguage();
2007 cutOffLexing();
2008 return false;
2009 }
2010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 } while (C != '\n' && C != '\r');
2012
Chris Lattner3d0ad582010-02-03 21:06:21 +00002013 // Found but did not consume the newline. Notify comment handlers about the
2014 // comment unless we're in a #if 0 block.
2015 if (PP && !isLexingRawMode() &&
2016 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2017 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002018 BufferPtr = CurPtr;
2019 return true; // A token has to be returned.
2020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002023 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002024 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002025
2026 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002027 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2029 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002030 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 }
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002034 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002035 // contribute to another token), it isn't needed for correctness. Note that
2036 // this is ok even in KeepWhitespaceMode, because we would have returned the
2037 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002041 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002043 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002045 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002046}
2047
Nico Weberbb236282012-11-11 07:02:14 +00002048/// If in save-comment mode, package up this Line comment in an appropriate
2049/// way and return it.
2050bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002051 // If we're not in a preprocessor directive, just return the // comment
2052 // directly.
2053 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
David Blaikie8c0b3782012-06-06 18:52:13 +00002055 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002056 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Nico Weberbb236282012-11-11 07:02:14 +00002058 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002059 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002060 bool Invalid = false;
2061 std::string Spelling = PP->getSpelling(Result, &Invalid);
2062 if (Invalid)
2063 return true;
2064
Nico Weberbb236282012-11-11 07:02:14 +00002065 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002066 Spelling[1] = '*'; // Change prefix to "/*".
2067 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Chris Lattner9e6293d2008-10-12 04:51:35 +00002069 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002070 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002071 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002072 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073}
2074
2075/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002076/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2077/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002078static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 Lexer *L) {
2080 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 // Back up off the newline.
2083 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // If this is a two-character newline sequence, skip the other character.
2086 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2087 // \n\n or \r\r -> not escaped newline.
2088 if (CurPtr[0] == CurPtr[1])
2089 return false;
2090 // \n\r or \r\n -> skip the newline.
2091 --CurPtr;
2092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // If we have horizontal whitespace, skip over it. We allow whitespace
2095 // between the slash and newline.
2096 bool HasSpace = false;
2097 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2098 --CurPtr;
2099 HasSpace = true;
2100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // If we have a slash, we know this is an escaped newline.
2103 if (*CurPtr == '\\') {
2104 if (CurPtr[-1] != '*') return false;
2105 } else {
2106 // It isn't a slash, is it the ?? / trigraph?
2107 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2108 CurPtr[-3] != '*')
2109 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // This is the trigraph ending the comment. Emit a stern warning!
2112 CurPtr -= 2;
2113
2114 // If no trigraphs are enabled, warn that we ignored this trigraph and
2115 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002116 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002117 if (!L->isLexingRawMode())
2118 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 return false;
2120 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002121 if (!L->isLexingRawMode())
2122 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002126 if (!L->isLexingRawMode())
2127 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002130 if (HasSpace && !L->isLexingRawMode())
2131 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 return true;
2134}
2135
2136#ifdef __SSE2__
2137#include <emmintrin.h>
2138#elif __ALTIVEC__
2139#include <altivec.h>
2140#undef bool
2141#endif
2142
James Dennettec769932012-06-17 03:40:43 +00002143/// We have just read from input the / and * characters that started a comment.
2144/// Read until we find the * and / characters that terminate the comment.
2145/// Note that we don't bother decoding trigraphs or escaped newlines in block
2146/// comments, because they cannot cause the comment to end. The only thing
2147/// that can happen is the comment could end with an escaped newline between
2148/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002149///
Chris Lattner046c2272010-01-18 22:35:47 +00002150/// If we're in KeepCommentMode or any CommentHandler has inserted
2151/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002152bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002154 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 // optimization helps people who like to put a lot of * characters in their
2156 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002157
2158 // The first character we get with newlines and trigraphs skipped to handle
2159 // the degenerate /*/ case below correctly if the * has an escaped newline
2160 // after it.
2161 unsigned CharSize;
2162 unsigned char C = getCharAndSize(CurPtr, CharSize);
2163 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002165 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002166 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002167 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Chris Lattner31f0eca2008-10-12 04:19:49 +00002169 // KeepWhitespaceMode should return this broken comment as a token. Since
2170 // it isn't a well formed comment, just return it as an 'unknown' token.
2171 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002172 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002173 return true;
2174 }
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Chris Lattner31f0eca2008-10-12 04:19:49 +00002176 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002177 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Chris Lattner8146b682007-07-21 23:43:37 +00002180 // Check to see if the first character after the '/*' is another /. If so,
2181 // then this slash does not end the block comment, it is part of it.
2182 if (C == '/')
2183 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Reid Spencer5f016e22007-07-11 17:01:13 +00002185 while (1) {
2186 // Skip over all non-interesting characters until we find end of buffer or a
2187 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002188 if (CurPtr + 24 < BufferEnd &&
2189 // If there is a code-completion point avoid the fast scan because it
2190 // doesn't check for '\0'.
2191 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002192 // While not aligned to a 16-byte boundary.
2193 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2194 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 if (C == '/') goto FoundSlash;
2197
2198#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002199 __m128i Slashes = _mm_set1_epi8('/');
2200 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002201 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2202 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002203 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002204 // Adjust the pointer to point directly after the first slash. It's
2205 // not necessary to set C here, it will be overwritten at the end of
2206 // the outer loop.
2207 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002208 goto FoundSlash;
2209 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002211 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002212#elif __ALTIVEC__
2213 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002214 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 '/', '/', '/', '/', '/', '/', '/', '/'
2216 };
2217 while (CurPtr+16 <= BufferEnd &&
2218 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2219 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002220#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 // Scan for '/' quickly. Many block comments are very large.
2222 while (CurPtr[0] != '/' &&
2223 CurPtr[1] != '/' &&
2224 CurPtr[2] != '/' &&
2225 CurPtr[3] != '/' &&
2226 CurPtr+4 < BufferEnd) {
2227 CurPtr += 4;
2228 }
2229#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 // It has to be one of the bytes scanned, increment to it and read one.
2232 C = *CurPtr++;
2233 }
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 // Loop to scan the remainder.
2236 while (C != '/' && C != '\0')
2237 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Reid Spencer5f016e22007-07-11 17:01:13 +00002239 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002240 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 if (CurPtr[-2] == '*') // We found the final */. We're done!
2242 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2245 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2246 // We found the final */, though it had an escaped newline between the
2247 // * and /. We're done!
2248 break;
2249 }
2250 }
2251 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2252 // If this is a /* inside of the comment, emit a warning. Don't do this
2253 // if this is a /*/, which will end the comment. This misses cases with
2254 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002255 if (!isLexingRawMode())
2256 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 }
2258 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002259 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002260 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 // Note: the user probably forgot a */. We could continue immediately
2262 // after the /*, but this would involve lexing a lot of what really is the
2263 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002264 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Chris Lattner31f0eca2008-10-12 04:19:49 +00002266 // KeepWhitespaceMode should return this broken comment as a token. Since
2267 // it isn't a well formed comment, just return it as an 'unknown' token.
2268 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002269 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002270 return true;
2271 }
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattner31f0eca2008-10-12 04:19:49 +00002273 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002274 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002275 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2276 PP->CodeCompleteNaturalLanguage();
2277 cutOffLexing();
2278 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002280
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 C = *CurPtr++;
2282 }
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Chris Lattner3d0ad582010-02-03 21:06:21 +00002284 // Notify comment handlers about the comment unless we're in a #if 0 block.
2285 if (PP && !isLexingRawMode() &&
2286 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2287 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002288 BufferPtr = CurPtr;
2289 return true; // A token has to be returned.
2290 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002291
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002293 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002294 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002295 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 }
2297
2298 // It is common for the tokens immediately after a /**/ comment to be
2299 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002300 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2301 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 if (isHorizontalWhitespace(*CurPtr)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002304 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 }
2306
2307 // Otherwise, just return so that the next character will be lexed as a token.
2308 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002309 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002310 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002311}
2312
2313//===----------------------------------------------------------------------===//
2314// Primary Lexing Entry Points
2315//===----------------------------------------------------------------------===//
2316
Reid Spencer5f016e22007-07-11 17:01:13 +00002317/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2318/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002319void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2321 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002322 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002323
2324 // CurPtr - Cache BufferPtr in an automatic variable.
2325 const char *CurPtr = BufferPtr;
2326 while (1) {
2327 char Char = getAndAdvanceChar(CurPtr, Tmp);
2328 switch (Char) {
2329 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002330 if (Result)
2331 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 break;
2333 case 0: // Null.
2334 // Found end of file?
2335 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002336 if (isCodeCompletionPoint(CurPtr-1)) {
2337 PP->CodeCompleteNaturalLanguage();
2338 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002339 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002340 }
2341
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002343 if (Result)
2344 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 break;
2346 }
2347 // FALL THROUGH.
2348 case '\r':
2349 case '\n':
2350 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2351 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2352 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Peter Collingbourne84021552011-02-28 02:37:51 +00002354 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002356 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002357 if (PP)
2358 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002359 Lex(Tmp);
2360 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002361 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Benjamin Kramer3093b202012-05-18 19:32:16 +00002363 // Finally, we're done;
2364 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002365 }
2366 }
2367}
2368
2369/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2370/// condition, reporting diagnostics and handling other edge cases as required.
2371/// This returns true if Result contains a token, false if PP.Lex should be
2372/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002373bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 // If we hit the end of the file while parsing a preprocessor directive,
2375 // end the preprocessor directive first. The next token returned will
2376 // then be the end of file.
2377 if (ParsingPreprocessorDirective) {
2378 // Done parsing the "line".
2379 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002381 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rose6aad4a32013-02-21 18:53:19 +00002384 resetExtendedTokenMode();
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002386 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002387
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 // If we are in raw mode, return this event as an EOF token. Let the caller
2389 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002390 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 Result.startToken();
2392 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002393 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 return true;
2395 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002396
Douglas Gregorf44e8542010-08-24 19:08:16 +00002397 // Issue diagnostics for unterminated #if and missing newline.
2398
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 // If we are in a #if directive, emit an error.
2400 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002401 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002402 PP->Diag(ConditionalStack.back().IfLoc,
2403 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002404 ConditionalStack.pop_back();
2405 }
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002407 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2408 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002409 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith80ad52f2013-01-02 11:42:31 +00002410 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002411 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2412 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 BufferPtr = CurPtr;
2415
2416 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002417 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002418}
2419
2420/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2421/// the specified lexer will return a tok::l_paren token, 0 if it is something
2422/// else and 2 if there are no more tokens in the buffer controlled by the
2423/// lexer.
2424unsigned Lexer::isNextPPTokenLParen() {
2425 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // Switch to 'skipping' mode. This will ensure that we can lex a token
2428 // without emitting diagnostics, disables macro expansion, and will cause EOF
2429 // to return an EOF token instead of popping the include stack.
2430 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 // Save state that can be changed while lexing so that we can restore it.
2433 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002434 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Chris Lattnerd2177732007-07-20 16:59:19 +00002436 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002437 Tok.startToken();
2438 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 // Restore state that may have changed.
2441 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002442 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 // Restore the lexer back to non-skipping mode.
2445 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002447 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002449 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002450}
2451
James Dennettec769932012-06-17 03:40:43 +00002452/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002453static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2454 ConflictMarkerKind CMK) {
2455 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2456 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2457 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2458 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002459 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002460 // Must occur at start of line.
2461 if (RestOfBuffer[Pos-1] != '\r' &&
2462 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002463 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2464 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002465 continue;
2466 }
2467 return RestOfBuffer.data()+Pos;
2468 }
2469 return 0;
2470}
2471
2472/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2473/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2474/// and recover nicely. This returns true if it is a conflict marker and false
2475/// if not.
2476bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2477 // Only a conflict marker if it starts at the beginning of a line.
2478 if (CurPtr != BufferStart &&
2479 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2480 return false;
2481
Richard Smithd5e1d602011-10-12 00:37:51 +00002482 // Check to see if we have <<<<<<< or >>>>.
2483 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2484 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002485 return false;
2486
2487 // If we have a situation where we don't care about conflict markers, ignore
2488 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002489 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002490 return false;
2491
Richard Smithd5e1d602011-10-12 00:37:51 +00002492 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2493
2494 // Check to see if there is an ending marker somewhere in the buffer at the
2495 // start of a line to terminate this conflict marker.
2496 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002497 // We found a match. We are really in a conflict marker.
2498 // Diagnose this, and ignore to the end of line.
2499 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002500 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002501
2502 // Skip ahead to the end of line. We know this exists because the
2503 // end-of-conflict marker starts with \r or \n.
2504 while (*CurPtr != '\r' && *CurPtr != '\n') {
2505 assert(CurPtr != BufferEnd && "Didn't find end of line");
2506 ++CurPtr;
2507 }
2508 BufferPtr = CurPtr;
2509 return true;
2510 }
2511
2512 // No end of conflict marker found.
2513 return false;
2514}
2515
2516
Richard Smithd5e1d602011-10-12 00:37:51 +00002517/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2518/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2519/// is the end of a conflict marker. Handle it by ignoring up until the end of
2520/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002521bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2522 // Only a conflict marker if it starts at the beginning of a line.
2523 if (CurPtr != BufferStart &&
2524 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2525 return false;
2526
2527 // If we have a situation where we don't care about conflict markers, ignore
2528 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002529 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002530 return false;
2531
Richard Smithd5e1d602011-10-12 00:37:51 +00002532 // Check to see if we have the marker (4 characters in a row).
2533 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002534 if (CurPtr[i] != CurPtr[0])
2535 return false;
2536
2537 // If we do have it, search for the end of the conflict marker. This could
2538 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2539 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002540 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2541 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002542 CurPtr = End;
2543
2544 // Skip ahead to the end of line.
2545 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2546 ++CurPtr;
2547
2548 BufferPtr = CurPtr;
2549
2550 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002551 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002552 return true;
2553 }
2554
2555 return false;
2556}
2557
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002558bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2559 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002560 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002561 return Loc == PP->getCodeCompletionLoc();
2562 }
2563
2564 return false;
2565}
2566
Jordan Rosec7629d92013-01-24 20:50:46 +00002567uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2568 Token *Result) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002569 unsigned CharSize;
2570 char Kind = getCharAndSize(StartPtr, CharSize);
2571
2572 unsigned NumHexDigits;
2573 if (Kind == 'u')
2574 NumHexDigits = 4;
2575 else if (Kind == 'U')
2576 NumHexDigits = 8;
2577 else
2578 return 0;
2579
Jordan Rosebfec9162013-01-27 20:12:04 +00002580 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rose8094bac2013-01-28 17:49:02 +00002581 if (Result && !isLexingRawMode())
2582 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosebfec9162013-01-27 20:12:04 +00002583 return 0;
2584 }
2585
Jordan Rosec7629d92013-01-24 20:50:46 +00002586 const char *CurPtr = StartPtr + CharSize;
2587 const char *KindLoc = &CurPtr[-1];
2588
2589 uint32_t CodePoint = 0;
2590 for (unsigned i = 0; i < NumHexDigits; ++i) {
2591 char C = getCharAndSize(CurPtr, CharSize);
2592
2593 unsigned Value = llvm::hexDigitValue(C);
2594 if (Value == -1U) {
2595 if (Result && !isLexingRawMode()) {
2596 if (i == 0) {
2597 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2598 << StringRef(KindLoc, 1);
2599 } else {
Jordan Rosec7629d92013-01-24 20:50:46 +00002600 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Roseb87672b2013-01-24 20:50:52 +00002601
2602 // If the user wrote \U1234, suggest a fixit to \u.
2603 if (i == 4 && NumHexDigits == 8) {
Jordan Roseed9c59f2013-02-09 01:10:25 +00002604 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Roseb87672b2013-01-24 20:50:52 +00002605 Diag(KindLoc, diag::note_ucn_four_not_eight)
2606 << FixItHint::CreateReplacement(URange, "u");
2607 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002608 }
2609 }
Jordan Rosebfec9162013-01-27 20:12:04 +00002610
Jordan Rosec7629d92013-01-24 20:50:46 +00002611 return 0;
2612 }
2613
2614 CodePoint <<= 4;
2615 CodePoint += Value;
2616
2617 CurPtr += CharSize;
2618 }
2619
2620 if (Result) {
2621 Result->setFlag(Token::HasUCN);
NAKAMURA Takumib6c08a62013-01-25 14:57:21 +00002622 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rosec7629d92013-01-24 20:50:46 +00002623 StartPtr = CurPtr;
2624 else
2625 while (StartPtr != CurPtr)
2626 (void)getAndAdvanceChar(StartPtr, *Result);
2627 } else {
2628 StartPtr = CurPtr;
2629 }
2630
2631 // C99 6.4.3p2: A universal character name shall not specify a character whose
2632 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2633 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2634 // C++11 [lex.charset]p2: If the hexadecimal value for a
2635 // universal-character-name corresponds to a surrogate code point (in the
2636 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2637 // if the hexadecimal value for a universal-character-name outside the
2638 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2639 // string literal corresponds to a control character (in either of the
2640 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2641 // basic source character set, the program is ill-formed.
2642 if (CodePoint < 0xA0) {
2643 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2644 return CodePoint;
2645
2646 // We don't use isLexingRawMode() here because we need to warn about bad
2647 // UCNs even when skipping preprocessing tokens in a #if block.
2648 if (Result && PP) {
2649 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2650 Diag(BufferPtr, diag::err_ucn_control_character);
2651 else {
2652 char C = static_cast<char>(CodePoint);
2653 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2654 }
2655 }
2656
2657 return 0;
Jordan Roseed9c59f2013-02-09 01:10:25 +00002658
2659 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002660 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002661 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rosec7629d92013-01-24 20:50:46 +00002662 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002663 if (Result && PP) {
2664 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2665 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2666 else
2667 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2668 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002669 return 0;
2670 }
2671
2672 return CodePoint;
2673}
2674
2675void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose74c24982013-01-30 01:52:57 +00002676 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002677 isCharInSet(C, UnicodeWhitespaceChars)) {
Jordan Rose74c24982013-01-30 01:52:57 +00002678 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002679 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rosefc120602013-01-24 20:50:50 +00002680
2681 Result.setFlag(Token::LeadingSpace);
2682 if (SkipWhitespace(Result, CurPtr))
2683 return; // KeepWhitespaceMode
2684
2685 return LexTokenInternal(Result);
2686 }
2687
Jordan Roseed9c59f2013-02-09 01:10:25 +00002688 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2689 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2690 !PP->isPreprocessedOutput()) {
2691 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2692 makeCharRange(*this, BufferPtr, CurPtr),
2693 /*IsFirst=*/true);
2694 }
2695
Jordan Rosec7629d92013-01-24 20:50:46 +00002696 MIOpt.ReadToken();
2697 return LexIdentifier(Result, CurPtr);
2698 }
2699
Jordan Rose0ed43942013-01-31 19:48:48 +00002700 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2701 !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002702 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002703 // Non-ASCII characters tend to creep into source code unintentionally.
2704 // Instead of letting the parser complain about the unknown token,
2705 // just drop the character.
2706 // Note that we can /only/ do this when the non-ASCII character is actually
2707 // spelled as Unicode, not written as a UCN. The standard requires that
2708 // we not throw away any possible preprocessor tokens, but there's a
2709 // loophole in the mapping of Unicode characters to basic character set
2710 // characters that allows us to map these particular characters to, say,
2711 // whitespace.
Jordan Rose74c24982013-01-30 01:52:57 +00002712 Diag(BufferPtr, diag::err_non_ascii)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002713 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rosec7629d92013-01-24 20:50:46 +00002714
2715 BufferPtr = CurPtr;
2716 return LexTokenInternal(Result);
2717 }
2718
2719 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2720 // up by accident.
2721 MIOpt.ReadToken();
2722 FormTokenWithChars(Result, CurPtr, tok::unknown);
2723}
2724
Reid Spencer5f016e22007-07-11 17:01:13 +00002725
2726/// LexTokenInternal - This implements a simple C family lexer. It is an
2727/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002728/// has a null character at the end of the file. This returns a preprocessing
2729/// token, not a normal token, as such, it is an internal interface. It assumes
2730/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002731void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002732LexNextToken:
2733 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002734 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // CurPtr - Cache BufferPtr in an automatic variable.
2738 const char *CurPtr = BufferPtr;
2739
2740 // Small amounts of horizontal whitespace is very common between tokens.
2741 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2742 ++CurPtr;
2743 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2744 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Chris Lattnerd88dc482008-10-12 04:05:48 +00002746 // If we are keeping whitespace and other tokens, just return what we just
2747 // skipped. The next lexer invocation will return the token after the
2748 // whitespace.
2749 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002750 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rose6aad4a32013-02-21 18:53:19 +00002751 // FIXME: The next token will not have LeadingSpace set.
Chris Lattnerd88dc482008-10-12 04:05:48 +00002752 return;
2753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002756 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 // Read a character, advancing over it.
2762 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002763 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 switch (Char) {
2766 case 0: // Null.
2767 // Found end of file?
2768 if (CurPtr-1 == BufferEnd) {
2769 // Read the PP instance variable into an automatic variable, because
2770 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002771 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2773 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002774 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2775 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 }
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002778 // Check if we are performing code completion.
2779 if (isCodeCompletionPoint(CurPtr-1)) {
2780 // Return the code-completion token.
2781 Result.startToken();
2782 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2783 return;
2784 }
2785
Chris Lattner74d15df2008-11-22 02:02:22 +00002786 if (!isLexingRawMode())
2787 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002788 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002789 if (SkipWhitespace(Result, CurPtr))
2790 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002793
2794 case 26: // DOS & CP/M EOF: "^Z".
2795 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002796 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002797 // Read the PP instance variable into an automatic variable, because
2798 // LexEndOfFile will often delete 'this'.
2799 Preprocessor *PPCache = PP;
2800 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2801 return; // Got a token to return.
2802 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2803 return PPCache->Lex(Result);
2804 }
2805 // If Microsoft extensions are disabled, this is just random garbage.
2806 Kind = tok::unknown;
2807 break;
2808
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 case '\n':
2810 case '\r':
2811 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002812 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 if (ParsingPreprocessorDirective) {
2814 // Done parsing the "line".
2815 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002818 if (PP)
Jordan Rose6aad4a32013-02-21 18:53:19 +00002819 resetExtendedTokenMode();
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 // Since we consumed a newline, we are back at the start of a line.
2822 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Peter Collingbourne84021552011-02-28 02:37:51 +00002824 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 break;
2826 }
Jordan Rose6aad4a32013-02-21 18:53:19 +00002827
Reid Spencer5f016e22007-07-11 17:01:13 +00002828 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002829 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Chris Lattnerd88dc482008-10-12 04:05:48 +00002831 if (SkipWhitespace(Result, CurPtr))
2832 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 goto LexNextToken; // GCC isn't tail call eliminating.
2834 case ' ':
2835 case '\t':
2836 case '\f':
2837 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002838 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002839 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002840 if (SkipWhitespace(Result, CurPtr))
2841 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002842
2843 SkipIgnoredUnits:
2844 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Chris Lattner8133cfc2007-07-22 06:29:05 +00002846 // If the next token is obviously a // or /* */ comment, skip it efficiently
2847 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002848 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002849 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2850 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002851 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002852 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002853 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002854 if (SkipBlockComment(Result, CurPtr+2))
2855 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002856 goto SkipIgnoredUnits;
2857 } else if (isHorizontalWhitespace(*CurPtr)) {
2858 goto SkipHorizontalWhitespace;
2859 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002861
Chris Lattner3a570772008-01-03 17:58:54 +00002862 // C99 6.4.4.1: Integer Constants.
2863 // C99 6.4.4.2: Floating Constants.
2864 case '0': case '1': case '2': case '3': case '4':
2865 case '5': case '6': case '7': case '8': case '9':
2866 // Notify MIOpt that we read a non-whitespace/non-comment token.
2867 MIOpt.ReadToken();
2868 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Richard Smith0093e122013-03-09 23:56:02 +00002870 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregor5cee1192011-07-27 05:40:30 +00002871 // Notify MIOpt that we read a non-whitespace/non-comment token.
2872 MIOpt.ReadToken();
2873
Richard Smith0093e122013-03-09 23:56:02 +00002874 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002875 Char = getCharAndSize(CurPtr, SizeTmp);
2876
2877 // UTF-16 string literal
2878 if (Char == '"')
2879 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2880 tok::utf16_string_literal);
2881
2882 // UTF-16 character constant
2883 if (Char == '\'')
2884 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2885 tok::utf16_char_constant);
2886
Craig Topper2fa4e862011-08-11 04:06:15 +00002887 // UTF-16 raw string literal
Richard Smith0093e122013-03-09 23:56:02 +00002888 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2889 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper2fa4e862011-08-11 04:06:15 +00002890 return LexRawStringLiteral(Result,
2891 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2892 SizeTmp2, Result),
2893 tok::utf16_string_literal);
2894
2895 if (Char == '8') {
2896 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2897
2898 // UTF-8 string literal
2899 if (Char2 == '"')
2900 return LexStringLiteral(Result,
2901 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2902 SizeTmp2, Result),
2903 tok::utf8_string_literal);
2904
Richard Smith0093e122013-03-09 23:56:02 +00002905 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002906 unsigned SizeTmp3;
2907 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2908 // UTF-8 raw string literal
2909 if (Char3 == '"') {
2910 return LexRawStringLiteral(Result,
2911 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2912 SizeTmp2, Result),
2913 SizeTmp3, Result),
2914 tok::utf8_string_literal);
2915 }
2916 }
2917 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002918 }
2919
2920 // treat u like the start of an identifier.
2921 return LexIdentifier(Result, CurPtr);
2922
Richard Smith0093e122013-03-09 23:56:02 +00002923 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregor5cee1192011-07-27 05:40:30 +00002924 // Notify MIOpt that we read a non-whitespace/non-comment token.
2925 MIOpt.ReadToken();
2926
Richard Smith0093e122013-03-09 23:56:02 +00002927 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002928 Char = getCharAndSize(CurPtr, SizeTmp);
2929
2930 // UTF-32 string literal
2931 if (Char == '"')
2932 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2933 tok::utf32_string_literal);
2934
2935 // UTF-32 character constant
2936 if (Char == '\'')
2937 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2938 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002939
2940 // UTF-32 raw string literal
Richard Smith0093e122013-03-09 23:56:02 +00002941 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2942 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper2fa4e862011-08-11 04:06:15 +00002943 return LexRawStringLiteral(Result,
2944 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2945 SizeTmp2, Result),
2946 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002947 }
2948
2949 // treat U like the start of an identifier.
2950 return LexIdentifier(Result, CurPtr);
2951
Craig Topper2fa4e862011-08-11 04:06:15 +00002952 case 'R': // Identifier or C++0x raw string literal
2953 // Notify MIOpt that we read a non-whitespace/non-comment token.
2954 MIOpt.ReadToken();
2955
Richard Smith80ad52f2013-01-02 11:42:31 +00002956 if (LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002957 Char = getCharAndSize(CurPtr, SizeTmp);
2958
2959 if (Char == '"')
2960 return LexRawStringLiteral(Result,
2961 ConsumeChar(CurPtr, SizeTmp, Result),
2962 tok::string_literal);
2963 }
2964
2965 // treat R like the start of an identifier.
2966 return LexIdentifier(Result, CurPtr);
2967
Chris Lattner3a570772008-01-03 17:58:54 +00002968 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 // Notify MIOpt that we read a non-whitespace/non-comment token.
2970 MIOpt.ReadToken();
2971 Char = getCharAndSize(CurPtr, SizeTmp);
2972
2973 // Wide string literal.
2974 if (Char == '"')
2975 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002976 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002977
Craig Topper2fa4e862011-08-11 04:06:15 +00002978 // Wide raw string literal.
Richard Smith80ad52f2013-01-02 11:42:31 +00002979 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002980 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2981 return LexRawStringLiteral(Result,
2982 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2983 SizeTmp2, Result),
2984 tok::wide_string_literal);
2985
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 // Wide character constant.
2987 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002988 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2989 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Reid Spencer5f016e22007-07-11 17:01:13 +00002992 // C99 6.4.2: Identifiers.
2993 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2994 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002995 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002996 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2997 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2998 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002999 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 case 'v': case 'w': case 'x': case 'y': case 'z':
3001 case '_':
3002 // Notify MIOpt that we read a non-whitespace/non-comment token.
3003 MIOpt.ReadToken();
3004 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00003005
3006 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003007 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00003008 if (!isLexingRawMode())
3009 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00003010 // Notify MIOpt that we read a non-whitespace/non-comment token.
3011 MIOpt.ReadToken();
3012 return LexIdentifier(Result, CurPtr);
3013 }
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Chris Lattner9e6293d2008-10-12 04:51:35 +00003015 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003016 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 // C99 6.4.4: Character Constants.
3019 case '\'':
3020 // Notify MIOpt that we read a non-whitespace/non-comment token.
3021 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003022 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00003023
3024 // C99 6.4.5: String Literals.
3025 case '"':
3026 // Notify MIOpt that we read a non-whitespace/non-comment token.
3027 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003028 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003029
3030 // C99 6.4.6: Punctuators.
3031 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003032 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00003033 break;
3034 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003035 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 break;
3037 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003038 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 break;
3040 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003041 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003042 break;
3043 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003044 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 break;
3046 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003047 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 break;
3049 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003050 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 break;
3052 case '.':
3053 Char = getCharAndSize(CurPtr, SizeTmp);
3054 if (Char >= '0' && Char <= '9') {
3055 // Notify MIOpt that we read a non-whitespace/non-comment token.
3056 MIOpt.ReadToken();
3057
3058 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00003059 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003060 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00003061 CurPtr += SizeTmp;
3062 } else if (Char == '.' &&
3063 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003064 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00003065 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3066 SizeTmp2, Result);
3067 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003068 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 }
3070 break;
3071 case '&':
3072 Char = getCharAndSize(CurPtr, SizeTmp);
3073 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003074 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003075 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3076 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003077 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3079 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003080 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003081 }
3082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003083 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00003084 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003085 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003086 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3087 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003088 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 }
3090 break;
3091 case '+':
3092 Char = getCharAndSize(CurPtr, SizeTmp);
3093 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003095 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003098 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003099 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003100 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 }
3102 break;
3103 case '-':
3104 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003105 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00003106 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003107 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00003108 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00003109 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00003110 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3111 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003112 Kind = tok::arrowstar;
3113 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00003114 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003115 Kind = tok::arrow;
3116 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00003117 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003118 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003119 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003120 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003121 }
3122 break;
3123 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003124 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00003125 break;
3126 case '!':
3127 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003128 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003129 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3130 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003131 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00003132 }
3133 break;
3134 case '/':
3135 // 6.4.9: Comments
3136 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00003137 if (Char == '/') { // Line comment.
3138 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00003139 // want to lex this as a comment. There is one problem with this though,
3140 // that in one particular corner case, this can change the behavior of the
3141 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003142 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003143 // "foo". Check to see if the character after the second slash is a '*'.
3144 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose693fdfa2013-03-05 22:51:04 +00003145 // However, we never do this if we are just preprocessing.
3146 bool TreatAsComment = LangOpts.LineComment && !LangOpts.TraditionalCPP;
3147 if (!TreatAsComment)
3148 if (!(PP && PP->isPreprocessedOutput()))
3149 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3150
3151 if (TreatAsComment) {
Nico Weberbb236282012-11-11 07:02:14 +00003152 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003153 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Chris Lattner8402c732009-01-16 22:39:25 +00003155 // It is common for the tokens immediately after a // comment to be
3156 // whitespace (indentation for the next line). Instead of going through
3157 // the big switch, handle it efficiently now.
3158 goto SkipIgnoredUnits;
3159 }
3160 }
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Chris Lattner8402c732009-01-16 22:39:25 +00003162 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003163 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003164 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003165 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003166 }
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Chris Lattner8402c732009-01-16 22:39:25 +00003168 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003169 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003170 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003171 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003172 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003173 }
3174 break;
3175 case '%':
3176 Char = getCharAndSize(CurPtr, SizeTmp);
3177 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003178 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003180 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003181 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003182 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003183 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003184 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3185 Char = getCharAndSize(CurPtr, SizeTmp);
3186 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003187 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3189 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003190 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003192 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003193 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003194 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003195 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 // We parsed a # character. If this occurs at the start of the line,
3197 // it's actually the start of a preprocessing directive. Callback to
3198 // the preprocessor to handle it.
3199 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003200 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3201 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Chris Lattnere91e9322009-03-18 20:58:27 +00003203 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 }
3205 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003206 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003207 }
3208 break;
3209 case '<':
3210 Char = getCharAndSize(CurPtr, SizeTmp);
3211 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003212 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003213 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003214 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3215 if (After == '=') {
3216 Kind = tok::lesslessequal;
3217 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3218 SizeTmp2, Result);
3219 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3220 // If this is actually a '<<<<<<<' version control conflict marker,
3221 // recognize it as such and recover nicely.
3222 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003223 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3224 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3225 // ignore it.
3226 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003227 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003228 Kind = tok::lesslessless;
3229 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3230 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003231 } else {
3232 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3233 Kind = tok::lessless;
3234 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003235 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003236 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003237 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003238 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith80ad52f2013-01-02 11:42:31 +00003239 if (LangOpts.CPlusPlus11 &&
Richard Smith87a1e192011-04-14 18:36:27 +00003240 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3241 // C++0x [lex.pptoken]p3:
3242 // Otherwise, if the next three characters are <:: and the subsequent
3243 // character is neither : nor >, the < is treated as a preprocessor
3244 // token by itself and not as the first character of the alternative
3245 // token <:.
3246 unsigned SizeTmp3;
3247 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3248 if (After != ':' && After != '>') {
3249 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003250 if (!isLexingRawMode())
3251 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003252 break;
3253 }
3254 }
3255
Reid Spencer5f016e22007-07-11 17:01:13 +00003256 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003257 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003258 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003259 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003260 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003261 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003262 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003263 }
3264 break;
3265 case '>':
3266 Char = getCharAndSize(CurPtr, SizeTmp);
3267 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003268 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003269 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003270 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003271 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3272 if (After == '=') {
3273 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3274 SizeTmp2, Result);
3275 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003276 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3277 // If this is actually a '>>>>' conflict marker, recognize it as such
3278 // and recover nicely.
3279 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003280 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3281 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3282 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003283 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003284 Kind = tok::greatergreatergreater;
3285 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3286 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003287 } else {
3288 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3289 Kind = tok::greatergreater;
3290 }
3291
Reid Spencer5f016e22007-07-11 17:01:13 +00003292 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003293 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003294 }
3295 break;
3296 case '^':
3297 Char = getCharAndSize(CurPtr, SizeTmp);
3298 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003299 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003300 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003301 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003302 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 }
3304 break;
3305 case '|':
3306 Char = getCharAndSize(CurPtr, SizeTmp);
3307 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003308 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003309 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3310 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003311 // If this is '|||||||' and we're in a conflict marker, ignore it.
3312 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3313 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003314 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003315 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3316 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003317 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003318 }
3319 break;
3320 case ':':
3321 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003322 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003323 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003324 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003325 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003326 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003327 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003328 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003329 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003330 }
3331 break;
3332 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003333 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003334 break;
3335 case '=':
3336 Char = getCharAndSize(CurPtr, SizeTmp);
3337 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003338 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003339 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3340 goto LexNextToken;
3341
Chris Lattner9e6293d2008-10-12 04:51:35 +00003342 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003343 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003344 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003345 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003346 }
3347 break;
3348 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003349 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003350 break;
3351 case '#':
3352 Char = getCharAndSize(CurPtr, SizeTmp);
3353 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003354 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003355 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003356 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003357 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003358 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003359 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003360 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3361 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003362 // We parsed a # character. If this occurs at the start of the line,
3363 // it's actually the start of a preprocessing directive. Callback to
3364 // the preprocessor to handle it.
3365 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003366 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3367 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Chris Lattnere91e9322009-03-18 20:58:27 +00003369 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003370 }
3371 break;
3372
Chris Lattner3a570772008-01-03 17:58:54 +00003373 case '@':
3374 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003375 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003376 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003377 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003378 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003379 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Jordan Rosec7629d92013-01-24 20:50:46 +00003381 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 case '\\':
Jordan Rosec7629d92013-01-24 20:50:46 +00003383 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3384 return LexUnicode(Result, CodePoint, CurPtr);
3385
Chris Lattner9e6293d2008-10-12 04:51:35 +00003386 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003387 break;
Jordan Rosec7629d92013-01-24 20:50:46 +00003388
3389 default: {
3390 if (isASCII(Char)) {
3391 Kind = tok::unknown;
3392 break;
3393 }
3394
3395 UTF32 CodePoint;
3396
3397 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3398 // an escaped newline.
3399 --CurPtr;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00003400 ConversionResult Status =
3401 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3402 (const UTF8 *)BufferEnd,
3403 &CodePoint,
3404 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00003405 if (Status == conversionOK)
3406 return LexUnicode(Result, CodePoint, CurPtr);
3407
Jordan Rose0ed43942013-01-31 19:48:48 +00003408 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3409 PP->isPreprocessedOutput()) {
Jordan Rose20afc292013-01-30 19:21:12 +00003410 ++CurPtr;
Jordan Rose74c24982013-01-30 01:52:57 +00003411 Kind = tok::unknown;
3412 break;
3413 }
3414
Jordan Rosec7629d92013-01-24 20:50:46 +00003415 // Non-ASCII characters tend to creep into source code unintentionally.
3416 // Instead of letting the parser complain about the unknown token,
Jordan Roseae82c2b2013-01-25 00:20:28 +00003417 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose74c24982013-01-30 01:52:57 +00003418 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rosec7629d92013-01-24 20:50:46 +00003419
3420 BufferPtr = CurPtr+1;
3421 goto LexNextToken;
3422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 }
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Reid Spencer5f016e22007-07-11 17:01:13 +00003425 // Notify MIOpt that we read a non-whitespace/non-comment token.
3426 MIOpt.ReadToken();
3427
3428 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003429 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003430 return;
3431
3432HandleDirective:
3433 // We parsed a # character and it's the start of a preprocessing directive.
3434
3435 FormTokenWithChars(Result, CurPtr, tok::hash);
3436 PP->HandleDirective(Result);
3437
3438 // As an optimization, if the preprocessor didn't switch lexers, tail
3439 // recurse.
3440 if (PP->isCurrentLexer(this)) {
3441 // Start a new token. If this is a #include or something, the PP may
3442 // want us starting at the beginning of the line again. If so, set
3443 // the StartOfLine flag and clear LeadingSpace.
3444 if (IsAtStartOfLine) {
3445 Result.setFlag(Token::StartOfLine);
3446 Result.clearFlag(Token::LeadingSpace);
3447 IsAtStartOfLine = false;
3448 }
3449 goto LexNextToken; // GCC isn't tail call eliminating.
3450 }
3451 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003452}