blob: 65ea5e3996442ee754354c24f060dd70ec587779 [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 Kyrtzidis1cb71422012-10-25 01:51:45 +0000560
561 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
562 SourceLocation StartLoc = TheLexer.getSourceLocation();
563
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000564 bool InPreprocessorDirective = false;
565 Token TheTok;
566 Token IfStartTok;
567 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000568
569 unsigned MaxLineOffset = 0;
570 if (MaxLines) {
571 const char *CurPtr = Buffer->getBufferStart();
572 unsigned CurLine = 0;
573 while (CurPtr != Buffer->getBufferEnd()) {
574 char ch = *CurPtr++;
575 if (ch == '\n') {
576 ++CurLine;
577 if (CurLine == MaxLines)
578 break;
579 }
580 }
581 if (CurPtr != Buffer->getBufferEnd())
582 MaxLineOffset = CurPtr - Buffer->getBufferStart();
583 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000584
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000585 do {
586 TheLexer.LexFromRawLexer(TheTok);
587
588 if (InPreprocessorDirective) {
589 // If we've hit the end of the file, we're done.
590 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000591 break;
592 }
593
594 // If we haven't hit the end of the preprocessor directive, skip this
595 // token.
596 if (!TheTok.isAtStartOfLine())
597 continue;
598
599 // We've passed the end of the preprocessor directive, and will look
600 // at this token again below.
601 InPreprocessorDirective = false;
602 }
603
Douglas Gregordf95a132010-08-09 20:45:32 +0000604 // Keep track of the # of lines in the preamble.
605 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000606 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000607
608 // If we were asked to limit the number of lines in the preamble,
609 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000610 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000611 break;
612 }
613
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000614 // Comments are okay; skip over them.
615 if (TheTok.getKind() == tok::comment)
616 continue;
617
618 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
619 // This is the start of a preprocessor directive.
620 Token HashTok = TheTok;
621 InPreprocessorDirective = true;
622
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000623 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000624 // we don't have an identifier table available. Instead, just look at
625 // the raw identifier to recognize and categorize preprocessor directives.
626 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000627 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000628 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000629 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000630 PreambleDirectiveKind PDK
631 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
632 .Case("include", PDK_Skipped)
633 .Case("__include_macros", PDK_Skipped)
634 .Case("define", PDK_Skipped)
635 .Case("undef", PDK_Skipped)
636 .Case("line", PDK_Skipped)
637 .Case("error", PDK_Skipped)
638 .Case("pragma", PDK_Skipped)
639 .Case("import", PDK_Skipped)
640 .Case("include_next", PDK_Skipped)
641 .Case("warning", PDK_Skipped)
642 .Case("ident", PDK_Skipped)
643 .Case("sccs", PDK_Skipped)
644 .Case("assert", PDK_Skipped)
645 .Case("unassert", PDK_Skipped)
646 .Case("if", PDK_StartIf)
647 .Case("ifdef", PDK_StartIf)
648 .Case("ifndef", PDK_StartIf)
649 .Case("elif", PDK_Skipped)
650 .Case("else", PDK_Skipped)
651 .Case("endif", PDK_EndIf)
652 .Default(PDK_Unknown);
653
654 switch (PDK) {
655 case PDK_Skipped:
656 continue;
657
658 case PDK_StartIf:
659 if (IfCount == 0)
660 IfStartTok = HashTok;
661
662 ++IfCount;
663 continue;
664
665 case PDK_EndIf:
666 // Mismatched #endif. The preamble ends here.
667 if (IfCount == 0)
668 break;
669
670 --IfCount;
671 continue;
672
673 case PDK_Unknown:
674 // We don't know what this directive is; stop at the '#'.
675 break;
676 }
677 }
678
679 // We only end up here if we didn't recognize the preprocessor
680 // directive or it was one that can't occur in the preamble at this
681 // point. Roll back the current token to the location of the '#'.
682 InPreprocessorDirective = false;
683 TheTok = HashTok;
684 }
685
Douglas Gregordf95a132010-08-09 20:45:32 +0000686 // We hit a token that we don't recognize as being in the
687 // "preprocessing only" part of the file, so we're no longer in
688 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000689 break;
690 } while (true);
691
692 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000693 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
694 IfCount? IfStartTok.isAtStartOfLine()
695 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000696}
697
Chris Lattner7ef5c272010-11-17 07:05:50 +0000698
699/// AdvanceToTokenCharacter - Given a location that specifies the start of a
700/// token, return a new location that specifies a character within the token.
701SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
702 unsigned CharNo,
703 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000704 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000705 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000706 // character is. This needs to take into consideration newlines and
707 // trigraphs.
708 bool Invalid = false;
709 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
710
711 // If they request the first char of the token, we're trivially done.
712 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
713 return TokStart;
714
715 unsigned PhysOffset = 0;
716
717 // The usual case is that tokens don't contain anything interesting. Skip
718 // over the uninteresting characters. If a token only consists of simple
719 // chars, this method is extremely fast.
720 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
721 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000722 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000723 ++TokPtr, --CharNo, ++PhysOffset;
724 }
725
726 // If we have a character that may be a trigraph or escaped newline, use a
727 // lexer to parse it correctly.
728 for (; CharNo; --CharNo) {
729 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000730 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000731 TokPtr += Size;
732 PhysOffset += Size;
733 }
734
735 // Final detail: if we end up on an escaped newline, we want to return the
736 // location of the actual byte of the token. For example foo\<newline>bar
737 // advanced by 3 should return the location of b, not of \\. One compounding
738 // detail of this is that the escape may be made by a trigraph.
739 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
740 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
741
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000742 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000743}
744
745/// \brief Computes the source location just past the end of the
746/// token at this source location.
747///
748/// This routine can be used to produce a source location that
749/// points just past the end of the token referenced by \p Loc, and
750/// is generally used when a diagnostic needs to point just after a
751/// token where it expected something different that it received. If
752/// the returned source location would not be meaningful (e.g., if
753/// it points into a macro), this routine returns an invalid
754/// source location.
755///
756/// \param Offset an offset from the end of the token, where the source
757/// location should refer to. The default offset (0) produces a source
758/// location pointing just past the end of the token; an offset of 1 produces
759/// a source location pointing to the last character in the token, etc.
760SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
761 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000762 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000763 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000764 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000765
766 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000767 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000768 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000769 }
770
David Blaikie4e4d0842012-03-11 07:00:24 +0000771 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000772 if (Len > Offset)
773 Len = Len - Offset;
774 else
775 return Loc;
776
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000777 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000778}
779
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000780/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000781/// token of the macro expansion.
782bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000783 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000784 const LangOptions &LangOpts,
785 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000786 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
787
788 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
789 // FIXME: If the token comes from the macro token paste operator ('##')
790 // this function will always return false;
791 if (infoLoc.second > 0)
792 return false; // Does not point at the start of token.
793
Chandler Carruth433db062011-07-14 08:20:40 +0000794 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000795 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000796 if (expansionLoc.isFileID()) {
797 // No other macro expansions, this is the first.
798 if (MacroBegin)
799 *MacroBegin = expansionLoc;
800 return true;
801 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000802
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000803 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000804}
805
806/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000807/// token of the macro expansion.
808bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000809 const SourceManager &SM,
810 const LangOptions &LangOpts,
811 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000812 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
813
814 SourceLocation spellLoc = SM.getSpellingLoc(loc);
815 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
816 if (tokLen == 0)
817 return false;
818
819 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000820 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000821 if (SM.isInFileID(afterLoc, FID))
822 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000823
824 // FIXME: If the token comes from the macro token paste operator ('##')
825 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000826
Chandler Carruth433db062011-07-14 08:20:40 +0000827 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000828 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000829 if (expansionLoc.isFileID()) {
830 // No other macro expansions.
831 if (MacroEnd)
832 *MacroEnd = expansionLoc;
833 return true;
834 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000835
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000836 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000837}
838
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000839static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000840 const SourceManager &SM,
841 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000842 SourceLocation Begin = Range.getBegin();
843 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000844 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000845 if (Range.isTokenRange()) {
846 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
847 if (End.isInvalid())
848 return CharSourceRange();
849 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000850
851 // Break down the source locations.
852 FileID FID;
853 unsigned BeginOffs;
854 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
855 if (FID.isInvalid())
856 return CharSourceRange();
857
858 unsigned EndOffs;
859 if (!SM.isInFileID(End, FID, &EndOffs) ||
860 BeginOffs > EndOffs)
861 return CharSourceRange();
862
863 return CharSourceRange::getCharRange(Begin, End);
864}
865
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000866CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000867 const SourceManager &SM,
868 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000869 SourceLocation Begin = Range.getBegin();
870 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000871 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000872 return CharSourceRange();
873
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000874 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000875 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000876
877 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000878 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
879 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000880 Range.setBegin(Begin);
881 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000882 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000883
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000884 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000885 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
886 &End)) ||
887 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
888 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000889 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000890 Range.setEnd(End);
891 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000892 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000893
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000894 assert(Begin.isMacroID() && End.isMacroID());
895 SourceLocation MacroBegin, MacroEnd;
896 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000897 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
898 &MacroEnd)) ||
899 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
900 &MacroEnd)))) {
901 Range.setBegin(MacroBegin);
902 Range.setEnd(MacroEnd);
903 return makeRangeFromFileLocs(Range, SM, LangOpts);
904 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000905
906 FileID FID;
907 unsigned BeginOffs;
908 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
909 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000910 return CharSourceRange();
911
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000912 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000913 if (!SM.isInFileID(End, FID, &EndOffs) ||
914 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000915 return CharSourceRange();
916
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000917 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
918 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
919 if (Expansion.isMacroArgExpansion() &&
920 Expansion.getSpellingLoc().isFileID()) {
921 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000922 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
923 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
924 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000925 }
926
927 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000928}
929
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000930StringRef Lexer::getSourceText(CharSourceRange Range,
931 const SourceManager &SM,
932 const LangOptions &LangOpts,
933 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000934 Range = makeFileCharRange(Range, SM, LangOpts);
935 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000936 if (Invalid) *Invalid = true;
937 return StringRef();
938 }
939
940 // Break down the source location.
941 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
942 if (beginInfo.first.isInvalid()) {
943 if (Invalid) *Invalid = true;
944 return StringRef();
945 }
946
947 unsigned EndOffs;
948 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
949 beginInfo.second > EndOffs) {
950 if (Invalid) *Invalid = true;
951 return StringRef();
952 }
953
954 // Try to the load the file buffer.
955 bool invalidTemp = false;
956 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
957 if (invalidTemp) {
958 if (Invalid) *Invalid = true;
959 return StringRef();
960 }
961
962 if (Invalid) *Invalid = false;
963 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
964}
965
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000966StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
967 const SourceManager &SM,
968 const LangOptions &LangOpts) {
969 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000970
971 // Find the location of the immediate macro expansion.
972 while (1) {
973 FileID FID = SM.getFileID(Loc);
974 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
975 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
976 Loc = Expansion.getExpansionLocStart();
977 if (!Expansion.isMacroArgExpansion())
978 break;
979
980 // For macro arguments we need to check that the argument did not come
981 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
982
983 // Loc points to the argument id of the macro definition, move to the
984 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000985 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000986 SourceLocation SpellLoc = Expansion.getSpellingLoc();
987 if (SpellLoc.isFileID())
988 break; // No inner macro.
989
990 // If spelling location resides in the same FileID as macro expansion
991 // location, it means there is no inner macro.
992 FileID MacroFID = SM.getFileID(Loc);
993 if (SM.isInFileID(SpellLoc, MacroFID))
994 break;
995
996 // Argument came from inner macro.
997 Loc = SpellLoc;
998 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000999
1000 // Find the spelling location of the start of the non-argument expansion
1001 // range. This is where the macro name was spelled in order to begin
1002 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +00001003 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +00001004
1005 // Dig out the buffer where the macro name was spelled and the extents of the
1006 // name so that we can render it into the expansion note.
1007 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1008 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1009 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1010 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1011}
1012
Jordan Rosed880b3a2012-06-07 01:10:31 +00001013bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rose98939022013-02-08 22:30:22 +00001014 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rosed880b3a2012-06-07 01:10:31 +00001015}
1016
Reid Spencer5f016e22007-07-11 17:01:13 +00001017
1018//===----------------------------------------------------------------------===//
1019// Diagnostics forwarding code.
1020//===----------------------------------------------------------------------===//
1021
Chris Lattner409a0362007-07-22 18:38:25 +00001022/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001023/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001024/// This is currently only used for _Pragma implementation, so it is the slow
1025/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001026static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1027 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001028static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1029 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001030 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001031 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner409a0362007-07-22 18:38:25 +00001033 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001034 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001035 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001036 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chandler Carruth433db062011-07-14 08:20:40 +00001038 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001039 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001040 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001041 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattnere7fb4842009-02-15 20:52:18 +00001043 // Figure out the expansion loc range, which is the range covered by the
1044 // original _Pragma(...) sequence.
1045 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001046 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chandler Carruthbf340e42011-07-26 03:03:05 +00001048 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001049}
1050
Reid Spencer5f016e22007-07-11 17:01:13 +00001051/// getSourceLocation - Return a source location identifier for the specified
1052/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001053SourceLocation Lexer::getSourceLocation(const char *Loc,
1054 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001055 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001057
1058 // In the normal case, we're just lexing from a simple file buffer, return
1059 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001060 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001061 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001062 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattner2b2453a2009-01-17 06:22:33 +00001064 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1065 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001066 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001067 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001068}
1069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070/// Diag - Forwarding function for diagnostics. This translate a source
1071/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001072DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001073 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001074}
Reid Spencer5f016e22007-07-11 17:01:13 +00001075
1076//===----------------------------------------------------------------------===//
1077// Trigraph and Escaped Newline Handling Code.
1078//===----------------------------------------------------------------------===//
1079
1080/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1081/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1082static char GetTrigraphCharForLetter(char Letter) {
1083 switch (Letter) {
1084 default: return 0;
1085 case '=': return '#';
1086 case ')': return ']';
1087 case '(': return '[';
1088 case '!': return '|';
1089 case '\'': return '^';
1090 case '>': return '}';
1091 case '/': return '\\';
1092 case '<': return '{';
1093 case '-': return '~';
1094 }
1095}
1096
1097/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1098/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1099/// return the result character. Finally, emit a warning about trigraph use
1100/// whether trigraphs are enabled or not.
1101static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1102 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001103 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
David Blaikie4e4d0842012-03-11 07:00:24 +00001105 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001106 if (!L->isLexingRawMode())
1107 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001108 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner74d15df2008-11-22 02:02:22 +00001111 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001112 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 return Res;
1114}
1115
Chris Lattner24f0e482009-04-18 22:05:41 +00001116/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1117/// 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 +00001118/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001119unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1120 unsigned Size = 0;
1121 while (isWhitespace(Ptr[Size])) {
1122 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner24f0e482009-04-18 22:05:41 +00001124 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1125 continue;
1126
1127 // If this is a \r\n or \n\r, skip the other half.
1128 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1129 Ptr[Size-1] != Ptr[Size])
1130 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Chris Lattner24f0e482009-04-18 22:05:41 +00001132 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001133 }
1134
Chris Lattner24f0e482009-04-18 22:05:41 +00001135 // Not an escaped newline, must be a \t or something else.
1136 return 0;
1137}
1138
Chris Lattner03374952009-04-18 22:27:02 +00001139/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1140/// them), skip over them and return the first non-escaped-newline found,
1141/// otherwise return P.
1142const char *Lexer::SkipEscapedNewLines(const char *P) {
1143 while (1) {
1144 const char *AfterEscape;
1145 if (*P == '\\') {
1146 AfterEscape = P+1;
1147 } else if (*P == '?') {
1148 // If not a trigraph for escape, bail out.
1149 if (P[1] != '?' || P[2] != '/')
1150 return P;
1151 AfterEscape = P+3;
1152 } else {
1153 return P;
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Chris Lattner03374952009-04-18 22:27:02 +00001156 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1157 if (NewLineSize == 0) return P;
1158 P = AfterEscape+NewLineSize;
1159 }
1160}
1161
Anna Zaksaca25bc2011-07-27 21:43:43 +00001162/// \brief Checks that the given token is the first token that occurs after the
1163/// given location (this excludes comments and whitespace). Returns the location
1164/// immediately after the specified token. If the token is not found or the
1165/// location is inside a macro, the returned source location will be invalid.
1166SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1167 tok::TokenKind TKind,
1168 const SourceManager &SM,
1169 const LangOptions &LangOpts,
1170 bool SkipTrailingWhitespaceAndNewLine) {
1171 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001172 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001173 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001174 }
1175 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1176
1177 // Break down the source location.
1178 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1179
1180 // Try to load the file buffer.
1181 bool InvalidTemp = false;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001182 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001183 if (InvalidTemp)
1184 return SourceLocation();
1185
1186 const char *TokenBegin = File.data() + LocInfo.second;
1187
1188 // Lex from the start of the given location.
1189 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1190 TokenBegin, File.end());
1191 // Find the token.
1192 Token Tok;
1193 lexer.LexFromRawLexer(Tok);
1194 if (Tok.isNot(TKind))
1195 return SourceLocation();
1196 SourceLocation TokenLoc = Tok.getLocation();
1197
1198 // Calculate how much whitespace needs to be skipped if any.
1199 unsigned NumWhitespaceChars = 0;
1200 if (SkipTrailingWhitespaceAndNewLine) {
1201 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1202 Tok.getLength();
1203 unsigned char C = *TokenEnd;
1204 while (isHorizontalWhitespace(C)) {
1205 C = *(++TokenEnd);
1206 NumWhitespaceChars++;
1207 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001208
1209 // Skip \r, \n, \r\n, or \n\r
1210 if (C == '\n' || C == '\r') {
1211 char PrevC = C;
1212 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001213 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001214 if ((C == '\n' || C == '\r') && C != PrevC)
1215 NumWhitespaceChars++;
1216 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001217 }
1218
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001219 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001220}
Chris Lattner24f0e482009-04-18 22:05:41 +00001221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1223/// get its size, and return it. This is tricky in several cases:
1224/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1225/// then either return the trigraph (skipping 3 chars) or the '?',
1226/// depending on whether trigraphs are enabled or not.
1227/// 2. If this is an escaped newline (potentially with whitespace between
1228/// the backslash and newline), implicitly skip the newline and return
1229/// the char after it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001230///
1231/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1232/// know that we can accumulate into Size, and that we have already incremented
1233/// Ptr by Size bytes.
1234///
1235/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1236/// be updated to match.
1237///
1238char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001239 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // If we have a slash, look for an escaped newline.
1241 if (Ptr[0] == '\\') {
1242 ++Size;
1243 ++Ptr;
1244Slash:
1245 // Common case, backslash-char where the char is not whitespace.
1246 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Chris Lattner5636a3b2009-06-23 05:15:06 +00001248 // See if we have optional whitespace characters between the slash and
1249 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001250 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1251 // Remember that this token needs to be cleaned.
1252 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001253
Chris Lattner24f0e482009-04-18 22:05:41 +00001254 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001255 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001256 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattner24f0e482009-04-18 22:05:41 +00001258 // Found backslash<whitespace><newline>. Parse the char after it.
1259 Size += EscapedNewLineSize;
1260 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001261
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001262 // If the char that we finally got was a \n, then we must have had
1263 // something like \<newline><newline>. We don't want to consume the
1264 // second newline.
1265 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1266 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001267
Chris Lattner24f0e482009-04-18 22:05:41 +00001268 // Use slow version to accumulate a correct size field.
1269 return getCharAndSizeSlow(Ptr, Size, Tok);
1270 }
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 // Otherwise, this is not an escaped newline, just return the slash.
1273 return '\\';
1274 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // If this is a trigraph, process it.
1277 if (Ptr[0] == '?' && Ptr[1] == '?') {
1278 // If this is actually a legal trigraph (not something like "??x"), emit
1279 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1280 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1281 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001282 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001283
1284 Ptr += 3;
1285 Size += 3;
1286 if (C == '\\') goto Slash;
1287 return C;
1288 }
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // If this is neither, return a single character.
1292 ++Size;
1293 return *Ptr;
1294}
1295
1296
1297/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1298/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1299/// and that we have already incremented Ptr by Size bytes.
1300///
1301/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1302/// be updated to match.
1303char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001304 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 // If we have a slash, look for an escaped newline.
1306 if (Ptr[0] == '\\') {
1307 ++Size;
1308 ++Ptr;
1309Slash:
1310 // Common case, backslash-char where the char is not whitespace.
1311 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001314 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1315 // Found backslash<whitespace><newline>. Parse the char after it.
1316 Size += EscapedNewLineSize;
1317 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001319 // If the char that we finally got was a \n, then we must have had
1320 // something like \<newline><newline>. We don't want to consume the
1321 // second newline.
1322 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1323 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001324
Chris Lattner24f0e482009-04-18 22:05:41 +00001325 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001327 }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // Otherwise, this is not an escaped newline, just return the slash.
1330 return '\\';
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001334 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 // If this is actually a legal trigraph (not something like "??x"), return
1336 // it.
1337 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1338 Ptr += 3;
1339 Size += 3;
1340 if (C == '\\') goto Slash;
1341 return C;
1342 }
1343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // If this is neither, return a single character.
1346 ++Size;
1347 return *Ptr;
1348}
1349
1350//===----------------------------------------------------------------------===//
1351// Helper methods for lexing.
1352//===----------------------------------------------------------------------===//
1353
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001354/// \brief Routine that indiscriminately skips bytes in the source file.
1355void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1356 BufferPtr += Bytes;
1357 if (BufferPtr > BufferEnd)
1358 BufferPtr = BufferEnd;
1359 IsAtStartOfLine = StartOfLine;
1360}
1361
Jordan Roseed9c59f2013-02-09 01:10:25 +00001362static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1363 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1364 return isCharInSet(C, C11AllowedIDChars);
1365 else if (LangOpts.CPlusPlus)
1366 return isCharInSet(C, CXX03AllowedIDChars);
1367 else
1368 return isCharInSet(C, C99AllowedIDChars);
Jordan Rosec7629d92013-01-24 20:50:46 +00001369}
1370
Jordan Roseed9c59f2013-02-09 01:10:25 +00001371static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1372 assert(isAllowedIDChar(C, LangOpts));
1373 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1374 return !isCharInSet(C, C11DisallowedInitialIDChars);
1375 else if (LangOpts.CPlusPlus)
1376 return true;
1377 else
1378 return !isCharInSet(C, C99DisallowedInitialIDChars);
1379}
Jordan Rosec7629d92013-01-24 20:50:46 +00001380
Jordan Roseed9c59f2013-02-09 01:10:25 +00001381static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1382 const char *End) {
1383 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1384 L.getSourceLocation(End));
1385}
1386
1387static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1388 CharSourceRange Range, bool IsFirst) {
1389 // Check C99 compatibility.
1390 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1391 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1392 enum {
1393 CannotAppearInIdentifier = 0,
1394 CannotStartIdentifier
1395 };
1396
1397 if (!isCharInSet(C, C99AllowedIDChars)) {
1398 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1399 << Range
1400 << CannotAppearInIdentifier;
1401 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1402 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1403 << Range
1404 << CannotStartIdentifier;
1405 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001406 }
1407
Jordan Roseed9c59f2013-02-09 01:10:25 +00001408 // Check C++98 compatibility.
1409 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1410 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1411 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1412 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1413 << Range;
1414 }
1415 }
1416 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001417
Chris Lattnerd2177732007-07-20 16:59:19 +00001418void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1420 unsigned Size;
1421 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001422 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001424
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 --CurPtr; // Back up over the skipped character.
1426
1427 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1428 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattnercd991db2010-01-11 02:38:50 +00001429 //
Jordan Rose98939022013-02-08 22:30:22 +00001430 // TODO: Could merge these checks into an InfoTable flag to make the
1431 // comparison cheaper
Jordan Rosec7629d92013-01-24 20:50:46 +00001432 if (isASCII(C) && C != '\\' && C != '?' &&
1433 (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001434FinishIdentifier:
1435 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001436 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1437 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 // If we are in raw mode, return this identifier raw. There is no need to
1440 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001441 if (LexingRawMode)
1442 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001444 // Fill in Result.IdentifierInfo and update the token kind,
1445 // looking up the identifier in the identifier table.
1446 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 // Finally, now that we know we have an identifier, pass this off to the
1449 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001450 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001451 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001452
Chris Lattner6a170eb2009-01-21 07:43:11 +00001453 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 }
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 C = getCharAndSize(CurPtr, Size);
1459 while (1) {
1460 if (C == '$') {
1461 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001462 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001465 if (!isLexingRawMode())
1466 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 CurPtr = ConsumeChar(CurPtr, Size, Result);
1468 C = getCharAndSize(CurPtr, Size);
1469 continue;
Jordan Rosec7629d92013-01-24 20:50:46 +00001470
1471 } else if (C == '\\') {
1472 const char *UCNPtr = CurPtr + Size;
1473 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Roseed9c59f2013-02-09 01:10:25 +00001474 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001475 goto FinishIdentifier;
1476
Jordan Roseed9c59f2013-02-09 01:10:25 +00001477 if (!isLexingRawMode()) {
1478 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1479 makeCharRange(*this, CurPtr, UCNPtr),
1480 /*IsFirst=*/false);
1481 }
1482
Jordan Rosec7629d92013-01-24 20:50:46 +00001483 Result.setFlag(Token::HasUCN);
1484 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1485 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1486 CurPtr = UCNPtr;
1487 else
1488 while (CurPtr != UCNPtr)
1489 (void)getAndAdvanceChar(CurPtr, Result);
1490
1491 C = getCharAndSize(CurPtr, Size);
1492 continue;
1493 } else if (!isASCII(C)) {
1494 const char *UnicodePtr = CurPtr;
1495 UTF32 CodePoint;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00001496 ConversionResult Result =
1497 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1498 (const UTF8 *)BufferEnd,
1499 &CodePoint,
1500 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00001501 if (Result != conversionOK ||
Jordan Roseed9c59f2013-02-09 01:10:25 +00001502 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001503 goto FinishIdentifier;
1504
Jordan Roseed9c59f2013-02-09 01:10:25 +00001505 if (!isLexingRawMode()) {
1506 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1507 makeCharRange(*this, CurPtr, UnicodePtr),
1508 /*IsFirst=*/false);
1509 }
1510
Jordan Rosec7629d92013-01-24 20:50:46 +00001511 CurPtr = UnicodePtr;
1512 C = getCharAndSize(CurPtr, Size);
1513 continue;
1514 } else if (!isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 goto FinishIdentifier;
1516 }
1517
1518 // Otherwise, this character is good, consume it.
1519 CurPtr = ConsumeChar(CurPtr, Size, Result);
1520
1521 C = getCharAndSize(CurPtr, Size);
Jordan Rosec7629d92013-01-24 20:50:46 +00001522 while (isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 CurPtr = ConsumeChar(CurPtr, Size, Result);
1524 C = getCharAndSize(CurPtr, Size);
1525 }
1526 }
1527}
1528
Douglas Gregora75ec432010-08-30 14:50:47 +00001529/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001530/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001531bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001532 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001533 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001534 if (C1 != '0')
1535 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001536 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001537 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001538}
Reid Spencer5f016e22007-07-11 17:01:13 +00001539
Nate Begeman5253c7f2008-04-14 02:26:39 +00001540/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001541/// constant. From[-1] is the first character lexed. Return the end of the
1542/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001543void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 unsigned Size;
1545 char C = getCharAndSize(CurPtr, Size);
1546 char PrevCh = 0;
Jordan Rose98939022013-02-08 22:30:22 +00001547 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 CurPtr = ConsumeChar(CurPtr, Size, Result);
1549 PrevCh = C;
1550 C = getCharAndSize(CurPtr, Size);
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001554 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1555 // If we are in Microsoft mode, don't continue if the constant is hex.
1556 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001557 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001558 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1559 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001560
1561 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001562 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1563 // Outside C99, we accept hexadecimal floating point numbers as a
1564 // not-quite-conforming extension. Only do so if this looks like it's
1565 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1566 bool IsHexFloat = true;
1567 if (!LangOpts.C99) {
1568 if (!isHexaLiteral(BufferPtr, LangOpts))
1569 IsHexFloat = false;
1570 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1571 IsHexFloat = false;
1572 }
1573 if (IsHexFloat)
1574 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001578 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001579 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001580 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001581}
1582
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001583/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001584/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001585const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001586 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001587
1588 // Maximally munch an identifier. FIXME: UCNs.
1589 unsigned Size;
1590 char C = getCharAndSize(CurPtr, Size);
1591 if (isIdentifierHead(C)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001592 if (!getLangOpts().CPlusPlus11) {
Richard Smithe816c712012-03-07 03:13:00 +00001593 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001594 Diag(CurPtr,
1595 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1596 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1597 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1598 return CurPtr;
1599 }
1600
1601 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1602 // that does not start with an underscore is ill-formed. As a conforming
1603 // extension, we treat all such suffixes as if they had whitespace before
1604 // them.
1605 if (C != '_') {
1606 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001607 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1608 diag::ext_ms_reserved_user_defined_literal :
1609 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001610 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1611 return CurPtr;
1612 }
1613
Richard Smith99831e42012-03-06 03:21:47 +00001614 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001615 do {
1616 CurPtr = ConsumeChar(CurPtr, Size, Result);
1617 C = getCharAndSize(CurPtr, Size);
1618 } while (isIdentifierBody(C));
1619 }
1620 return CurPtr;
1621}
1622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001624/// either " or L" or u8" or u" or U".
1625void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1626 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Richard Smith661a9962011-10-15 01:18:56 +00001629 if (!isLexingRawMode() &&
1630 (Kind == tok::utf8_string_literal ||
1631 Kind == tok::utf16_string_literal ||
1632 Kind == tok::utf32_string_literal))
1633 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 char C = getAndAdvanceChar(CurPtr, Result);
1636 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001637 // Skip escaped characters. Escaped newlines will already be processed by
1638 // getAndAdvanceChar.
1639 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001641
Chris Lattner571339c2010-05-30 23:27:38 +00001642 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001643 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001644 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001645 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001646 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 }
Chris Lattner571339c2010-05-30 23:27:38 +00001649
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001650 if (C == 0) {
1651 if (isCodeCompletionPoint(CurPtr-1)) {
1652 PP->CodeCompleteNaturalLanguage();
1653 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1654 return cutOffLexing();
1655 }
1656
Chris Lattner571339c2010-05-30 23:27:38 +00001657 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001658 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 C = getAndAdvanceChar(CurPtr, Result);
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001662 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001663 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001664 CurPtr = LexUDSuffix(Result, CurPtr);
1665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001667 if (NulCharacter && !isLexingRawMode())
1668 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001669
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001671 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001672 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001673 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001674}
1675
Craig Topper2fa4e862011-08-11 04:06:15 +00001676/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1677/// having lexed R", LR", u8R", uR", or UR".
1678void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1679 tok::TokenKind Kind) {
1680 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1681 // Between the initial and final double quote characters of the raw string,
1682 // any transformations performed in phases 1 and 2 (trigraphs,
1683 // universal-character-names, and line splicing) are reverted.
1684
Richard Smith661a9962011-10-15 01:18:56 +00001685 if (!isLexingRawMode())
1686 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1687
Craig Topper2fa4e862011-08-11 04:06:15 +00001688 unsigned PrefixLen = 0;
1689
1690 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1691 ++PrefixLen;
1692
1693 // If the last character was not a '(', then we didn't lex a valid delimiter.
1694 if (CurPtr[PrefixLen] != '(') {
1695 if (!isLexingRawMode()) {
1696 const char *PrefixEnd = &CurPtr[PrefixLen];
1697 if (PrefixLen == 16) {
1698 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1699 } else {
1700 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1701 << StringRef(PrefixEnd, 1);
1702 }
1703 }
1704
1705 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1706 // it's possible the '"' was intended to be part of the raw string, but
1707 // there's not much we can do about that.
1708 while (1) {
1709 char C = *CurPtr++;
1710
1711 if (C == '"')
1712 break;
1713 if (C == 0 && CurPtr-1 == BufferEnd) {
1714 --CurPtr;
1715 break;
1716 }
1717 }
1718
1719 FormTokenWithChars(Result, CurPtr, tok::unknown);
1720 return;
1721 }
1722
1723 // Save prefix and move CurPtr past it
1724 const char *Prefix = CurPtr;
1725 CurPtr += PrefixLen + 1; // skip over prefix and '('
1726
1727 while (1) {
1728 char C = *CurPtr++;
1729
1730 if (C == ')') {
1731 // Check for prefix match and closing quote.
1732 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1733 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1734 break;
1735 }
1736 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1737 if (!isLexingRawMode())
1738 Diag(BufferPtr, diag::err_unterminated_raw_string)
1739 << StringRef(Prefix, PrefixLen);
1740 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1741 return;
1742 }
1743 }
1744
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001745 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001746 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001747 CurPtr = LexUDSuffix(Result, CurPtr);
1748
Craig Topper2fa4e862011-08-11 04:06:15 +00001749 // Update the location of token as well as BufferPtr.
1750 const char *TokStart = BufferPtr;
1751 FormTokenWithChars(Result, CurPtr, Kind);
1752 Result.setLiteralData(TokStart);
1753}
1754
Reid Spencer5f016e22007-07-11 17:01:13 +00001755/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1756/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001757void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001759 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 char C = getAndAdvanceChar(CurPtr, Result);
1761 while (C != '>') {
1762 // Skip escaped characters.
1763 if (C == '\\') {
1764 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001765 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001767 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1768 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001769 // If the filename is unterminated, then it must just be a lone <
1770 // character. Return this as such.
1771 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 return;
1773 } else if (C == 0) {
1774 NulCharacter = CurPtr-1;
1775 }
1776 C = getAndAdvanceChar(CurPtr, Result);
1777 }
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001780 if (NulCharacter && !isLexingRawMode())
1781 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001784 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001785 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001786 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787}
1788
1789
1790/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001791/// lexed either ' or L' or u' or U'.
1792void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1793 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 const char *NulCharacter = 0; // Does this character contain the \0 character?
1795
Richard Smith661a9962011-10-15 01:18:56 +00001796 if (!isLexingRawMode() &&
1797 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1798 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1799
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 char C = getAndAdvanceChar(CurPtr, Result);
1801 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001802 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001803 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001804 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001806 }
1807
1808 while (C != '\'') {
1809 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001810 if (C == '\\')
1811 C = getAndAdvanceChar(CurPtr, Result);
1812
1813 if (C == '\n' || C == '\r' || // Newline.
1814 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001815 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001816 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001817 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1818 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001819 }
1820
1821 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001822 if (isCodeCompletionPoint(CurPtr-1)) {
1823 PP->CodeCompleteNaturalLanguage();
1824 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1825 return cutOffLexing();
1826 }
1827
Chris Lattnerd80f7862010-07-07 23:24:27 +00001828 NulCharacter = CurPtr-1;
1829 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 C = getAndAdvanceChar(CurPtr, Result);
1831 }
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001833 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001834 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001835 CurPtr = LexUDSuffix(Result, CurPtr);
1836
Chris Lattnerd80f7862010-07-07 23:24:27 +00001837 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001838 if (NulCharacter && !isLexingRawMode())
1839 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001842 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001843 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001844 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001845}
1846
1847/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1848/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001849///
1850/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1851///
1852bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001854 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1855
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1857 while (1) {
1858 // Skip horizontal whitespace very aggressively.
1859 while (isHorizontalWhitespace(Char))
1860 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001862 // Otherwise if we have something other than whitespace, we're done.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001863 if (!isVerticalWhitespace(Char))
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 if (ParsingPreprocessorDirective) {
1867 // End of preprocessor directive line, let LexTokenInternal handle this.
1868 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001869 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 }
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 // ok, but handle newline.
Jordan Rose6aad4a32013-02-21 18:53:19 +00001873 SawNewline = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 Char = *++CurPtr;
1875 }
1876
Chris Lattnerd88dc482008-10-12 04:05:48 +00001877 // If the client wants us to return whitespace, return it now.
1878 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001879 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rose6aad4a32013-02-21 18:53:19 +00001880 if (SawNewline)
1881 IsAtStartOfLine = true;
1882 // FIXME: The next token will not have LeadingSpace set.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001883 return true;
1884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Jordan Rose6aad4a32013-02-21 18:53:19 +00001886 // If this isn't immediately after a newline, there is leading space.
1887 char PrevChar = CurPtr[-1];
1888 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1889
1890 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1891 if (SawNewline)
1892 Result.setFlag(Token::StartOfLine);
1893
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001895 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001896}
1897
Nico Weberbb236282012-11-11 07:02:14 +00001898/// We have just read the // characters from input. Skip until we find the
1899/// newline character thats terminate the comment. Then update BufferPtr and
1900/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001901///
1902/// If we're in KeepCommentMode or any CommentHandler has inserted
1903/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001904bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1905 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001907 if (!LangOpts.LineComment && !isLexingRawMode()) {
1908 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // Mark them enabled so we only emit one warning for this translation
1911 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001912 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 }
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // Scan over the body of the comment. The common case, when scanning, is that
1916 // the comment contains normal ascii characters with nothing interesting in
1917 // them. As such, optimize for this case with the inner loop.
1918 char C;
1919 do {
1920 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // Skip over characters in the fast loop.
1922 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 C != '\n' && C != '\r') // Newline or DOS-style newline.
1924 C = *++CurPtr;
1925
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001926 const char *NextLine = CurPtr;
1927 if (C != 0) {
1928 // We found a newline, see if it's escaped.
1929 const char *EscapePtr = CurPtr-1;
1930 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1931 --EscapePtr;
1932
1933 if (*EscapePtr == '\\') // Escaped newline.
1934 CurPtr = EscapePtr;
1935 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1936 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1937 CurPtr = EscapePtr-2;
1938 else
1939 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001943 // properly decode the character. Read it in raw mode to avoid emitting
1944 // diagnostics about things like trigraphs. If we see an escaped newline,
1945 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001947 bool OldRawMode = isLexingRawMode();
1948 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001950 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001951
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001952 // If we only read only one character, then no special handling is needed.
1953 // We're done and can skip forward to the newline.
1954 if (C != 0 && CurPtr == OldPtr+1) {
1955 CurPtr = NextLine;
1956 break;
1957 }
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // If we read multiple characters, and one of those characters was a \r or
1960 // \n, then we had an escaped newline within the comment. Emit diagnostic
1961 // unless the next line is also a // comment.
1962 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1963 for (; OldPtr != CurPtr; ++OldPtr)
1964 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1965 // Okay, we found a // comment that ends in a newline, if the next
1966 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001967 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001969 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 ++ForwardPtr;
1971 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1972 break;
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Chris Lattner74d15df2008-11-22 02:02:22 +00001975 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00001976 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 break;
1978 }
1979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor55817af2010-08-25 17:04:25 +00001981 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001982 --CurPtr;
1983 break;
1984 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001985
1986 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1987 PP->CodeCompleteNaturalLanguage();
1988 cutOffLexing();
1989 return false;
1990 }
1991
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 } while (C != '\n' && C != '\r');
1993
Chris Lattner3d0ad582010-02-03 21:06:21 +00001994 // Found but did not consume the newline. Notify comment handlers about the
1995 // comment unless we're in a #if 0 block.
1996 if (PP && !isLexingRawMode() &&
1997 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1998 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001999 BufferPtr = CurPtr;
2000 return true; // A token has to be returned.
2001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002004 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002005 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002006
2007 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002008 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2010 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002011 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002015 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002016 // contribute to another token), it isn't needed for correctness. Note that
2017 // this is ok even in KeepWhitespaceMode, because we would have returned the
2018 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002022 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002024 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002026 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002027}
2028
Nico Weberbb236282012-11-11 07:02:14 +00002029/// If in save-comment mode, package up this Line comment in an appropriate
2030/// way and return it.
2031bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002032 // If we're not in a preprocessor directive, just return the // comment
2033 // directly.
2034 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
David Blaikie8c0b3782012-06-06 18:52:13 +00002036 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002037 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Nico Weberbb236282012-11-11 07:02:14 +00002039 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002040 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002041 bool Invalid = false;
2042 std::string Spelling = PP->getSpelling(Result, &Invalid);
2043 if (Invalid)
2044 return true;
2045
Nico Weberbb236282012-11-11 07:02:14 +00002046 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002047 Spelling[1] = '*'; // Change prefix to "/*".
2048 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattner9e6293d2008-10-12 04:51:35 +00002050 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002051 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002052 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002053 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002054}
2055
2056/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002057/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2058/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002059static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 Lexer *L) {
2061 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 // Back up off the newline.
2064 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // If this is a two-character newline sequence, skip the other character.
2067 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2068 // \n\n or \r\r -> not escaped newline.
2069 if (CurPtr[0] == CurPtr[1])
2070 return false;
2071 // \n\r or \r\n -> skip the newline.
2072 --CurPtr;
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 // If we have horizontal whitespace, skip over it. We allow whitespace
2076 // between the slash and newline.
2077 bool HasSpace = false;
2078 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2079 --CurPtr;
2080 HasSpace = true;
2081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 // If we have a slash, we know this is an escaped newline.
2084 if (*CurPtr == '\\') {
2085 if (CurPtr[-1] != '*') return false;
2086 } else {
2087 // It isn't a slash, is it the ?? / trigraph?
2088 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2089 CurPtr[-3] != '*')
2090 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // This is the trigraph ending the comment. Emit a stern warning!
2093 CurPtr -= 2;
2094
2095 // If no trigraphs are enabled, warn that we ignored this trigraph and
2096 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002097 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002098 if (!L->isLexingRawMode())
2099 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 return false;
2101 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002102 if (!L->isLexingRawMode())
2103 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002107 if (!L->isLexingRawMode())
2108 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002111 if (HasSpace && !L->isLexingRawMode())
2112 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 return true;
2115}
2116
2117#ifdef __SSE2__
2118#include <emmintrin.h>
2119#elif __ALTIVEC__
2120#include <altivec.h>
2121#undef bool
2122#endif
2123
James Dennettec769932012-06-17 03:40:43 +00002124/// We have just read from input the / and * characters that started a comment.
2125/// Read until we find the * and / characters that terminate the comment.
2126/// Note that we don't bother decoding trigraphs or escaped newlines in block
2127/// comments, because they cannot cause the comment to end. The only thing
2128/// that can happen is the comment could end with an escaped newline between
2129/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002130///
Chris Lattner046c2272010-01-18 22:35:47 +00002131/// If we're in KeepCommentMode or any CommentHandler has inserted
2132/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002133bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002135 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 // optimization helps people who like to put a lot of * characters in their
2137 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002138
2139 // The first character we get with newlines and trigraphs skipped to handle
2140 // the degenerate /*/ case below correctly if the * has an escaped newline
2141 // after it.
2142 unsigned CharSize;
2143 unsigned char C = getCharAndSize(CurPtr, CharSize);
2144 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002146 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002147 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002148 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Chris Lattner31f0eca2008-10-12 04:19:49 +00002150 // KeepWhitespaceMode should return this broken comment as a token. Since
2151 // it isn't a well formed comment, just return it as an 'unknown' token.
2152 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002153 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002154 return true;
2155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Chris Lattner31f0eca2008-10-12 04:19:49 +00002157 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002158 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Chris Lattner8146b682007-07-21 23:43:37 +00002161 // Check to see if the first character after the '/*' is another /. If so,
2162 // then this slash does not end the block comment, it is part of it.
2163 if (C == '/')
2164 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 while (1) {
2167 // Skip over all non-interesting characters until we find end of buffer or a
2168 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002169 if (CurPtr + 24 < BufferEnd &&
2170 // If there is a code-completion point avoid the fast scan because it
2171 // doesn't check for '\0'.
2172 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 // While not aligned to a 16-byte boundary.
2174 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2175 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 if (C == '/') goto FoundSlash;
2178
2179#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002180 __m128i Slashes = _mm_set1_epi8('/');
2181 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002182 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2183 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002184 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002185 // Adjust the pointer to point directly after the first slash. It's
2186 // not necessary to set C here, it will be overwritten at the end of
2187 // the outer loop.
2188 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002189 goto FoundSlash;
2190 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002192 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002193#elif __ALTIVEC__
2194 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002195 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 '/', '/', '/', '/', '/', '/', '/', '/'
2197 };
2198 while (CurPtr+16 <= BufferEnd &&
2199 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2200 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002201#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 // Scan for '/' quickly. Many block comments are very large.
2203 while (CurPtr[0] != '/' &&
2204 CurPtr[1] != '/' &&
2205 CurPtr[2] != '/' &&
2206 CurPtr[3] != '/' &&
2207 CurPtr+4 < BufferEnd) {
2208 CurPtr += 4;
2209 }
2210#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 // It has to be one of the bytes scanned, increment to it and read one.
2213 C = *CurPtr++;
2214 }
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 // Loop to scan the remainder.
2217 while (C != '/' && C != '\0')
2218 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002221 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 if (CurPtr[-2] == '*') // We found the final */. We're done!
2223 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2226 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2227 // We found the final */, though it had an escaped newline between the
2228 // * and /. We're done!
2229 break;
2230 }
2231 }
2232 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2233 // If this is a /* inside of the comment, emit a warning. Don't do this
2234 // if this is a /*/, which will end the comment. This misses cases with
2235 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002236 if (!isLexingRawMode())
2237 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 }
2239 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002240 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002241 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 // Note: the user probably forgot a */. We could continue immediately
2243 // after the /*, but this would involve lexing a lot of what really is the
2244 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002245 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Chris Lattner31f0eca2008-10-12 04:19:49 +00002247 // KeepWhitespaceMode should return this broken comment as a token. Since
2248 // it isn't a well formed comment, just return it as an 'unknown' token.
2249 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002250 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002251 return true;
2252 }
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Chris Lattner31f0eca2008-10-12 04:19:49 +00002254 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002255 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002256 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2257 PP->CodeCompleteNaturalLanguage();
2258 cutOffLexing();
2259 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002261
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 C = *CurPtr++;
2263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chris Lattner3d0ad582010-02-03 21:06:21 +00002265 // Notify comment handlers about the comment unless we're in a #if 0 block.
2266 if (PP && !isLexingRawMode() &&
2267 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2268 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002269 BufferPtr = CurPtr;
2270 return true; // A token has to be returned.
2271 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002272
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002274 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002275 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002276 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 }
2278
2279 // It is common for the tokens immediately after a /**/ comment to be
2280 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002281 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2282 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 if (isHorizontalWhitespace(*CurPtr)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002285 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 }
2287
2288 // Otherwise, just return so that the next character will be lexed as a token.
2289 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002290 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002291 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292}
2293
2294//===----------------------------------------------------------------------===//
2295// Primary Lexing Entry Points
2296//===----------------------------------------------------------------------===//
2297
Reid Spencer5f016e22007-07-11 17:01:13 +00002298/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2299/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002300void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2302 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002303 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002304
2305 // CurPtr - Cache BufferPtr in an automatic variable.
2306 const char *CurPtr = BufferPtr;
2307 while (1) {
2308 char Char = getAndAdvanceChar(CurPtr, Tmp);
2309 switch (Char) {
2310 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002311 if (Result)
2312 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 break;
2314 case 0: // Null.
2315 // Found end of file?
2316 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002317 if (isCodeCompletionPoint(CurPtr-1)) {
2318 PP->CodeCompleteNaturalLanguage();
2319 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002320 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002321 }
2322
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002324 if (Result)
2325 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 break;
2327 }
2328 // FALL THROUGH.
2329 case '\r':
2330 case '\n':
2331 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2332 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2333 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Peter Collingbourne84021552011-02-28 02:37:51 +00002335 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002337 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002338 if (PP)
2339 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002340 Lex(Tmp);
2341 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002342 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Benjamin Kramer3093b202012-05-18 19:32:16 +00002344 // Finally, we're done;
2345 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
2347 }
2348}
2349
2350/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2351/// condition, reporting diagnostics and handling other edge cases as required.
2352/// This returns true if Result contains a token, false if PP.Lex should be
2353/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002354bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 // If we hit the end of the file while parsing a preprocessor directive,
2356 // end the preprocessor directive first. The next token returned will
2357 // then be the end of file.
2358 if (ParsingPreprocessorDirective) {
2359 // Done parsing the "line".
2360 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002362 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rose6aad4a32013-02-21 18:53:19 +00002365 resetExtendedTokenMode();
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002367 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 // If we are in raw mode, return this event as an EOF token. Let the caller
2370 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002371 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 Result.startToken();
2373 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002374 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 return true;
2376 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002377
Douglas Gregorf44e8542010-08-24 19:08:16 +00002378 // Issue diagnostics for unterminated #if and missing newline.
2379
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 // If we are in a #if directive, emit an error.
2381 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002382 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002383 PP->Diag(ConditionalStack.back().IfLoc,
2384 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 ConditionalStack.pop_back();
2386 }
Mike Stump1eb44332009-09-09 15:08:12 +00002387
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002388 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2389 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002390 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith80ad52f2013-01-02 11:42:31 +00002391 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002392 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2393 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 BufferPtr = CurPtr;
2396
2397 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002398 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002399}
2400
2401/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2402/// the specified lexer will return a tok::l_paren token, 0 if it is something
2403/// else and 2 if there are no more tokens in the buffer controlled by the
2404/// lexer.
2405unsigned Lexer::isNextPPTokenLParen() {
2406 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 // Switch to 'skipping' mode. This will ensure that we can lex a token
2409 // without emitting diagnostics, disables macro expansion, and will cause EOF
2410 // to return an EOF token instead of popping the include stack.
2411 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 // Save state that can be changed while lexing so that we can restore it.
2414 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002415 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Chris Lattnerd2177732007-07-20 16:59:19 +00002417 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002418 Tok.startToken();
2419 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Reid Spencer5f016e22007-07-11 17:01:13 +00002421 // Restore state that may have changed.
2422 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002423 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 // Restore the lexer back to non-skipping mode.
2426 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002428 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002429 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002430 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002431}
2432
James Dennettec769932012-06-17 03:40:43 +00002433/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002434static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2435 ConflictMarkerKind CMK) {
2436 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2437 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2438 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2439 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002441 // Must occur at start of line.
2442 if (RestOfBuffer[Pos-1] != '\r' &&
2443 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002444 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2445 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002446 continue;
2447 }
2448 return RestOfBuffer.data()+Pos;
2449 }
2450 return 0;
2451}
2452
2453/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2454/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2455/// and recover nicely. This returns true if it is a conflict marker and false
2456/// if not.
2457bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2458 // Only a conflict marker if it starts at the beginning of a line.
2459 if (CurPtr != BufferStart &&
2460 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2461 return false;
2462
Richard Smithd5e1d602011-10-12 00:37:51 +00002463 // Check to see if we have <<<<<<< or >>>>.
2464 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2465 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002466 return false;
2467
2468 // If we have a situation where we don't care about conflict markers, ignore
2469 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002470 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002471 return false;
2472
Richard Smithd5e1d602011-10-12 00:37:51 +00002473 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2474
2475 // Check to see if there is an ending marker somewhere in the buffer at the
2476 // start of a line to terminate this conflict marker.
2477 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002478 // We found a match. We are really in a conflict marker.
2479 // Diagnose this, and ignore to the end of line.
2480 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002481 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002482
2483 // Skip ahead to the end of line. We know this exists because the
2484 // end-of-conflict marker starts with \r or \n.
2485 while (*CurPtr != '\r' && *CurPtr != '\n') {
2486 assert(CurPtr != BufferEnd && "Didn't find end of line");
2487 ++CurPtr;
2488 }
2489 BufferPtr = CurPtr;
2490 return true;
2491 }
2492
2493 // No end of conflict marker found.
2494 return false;
2495}
2496
2497
Richard Smithd5e1d602011-10-12 00:37:51 +00002498/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2499/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2500/// is the end of a conflict marker. Handle it by ignoring up until the end of
2501/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002502bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2503 // Only a conflict marker if it starts at the beginning of a line.
2504 if (CurPtr != BufferStart &&
2505 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2506 return false;
2507
2508 // If we have a situation where we don't care about conflict markers, ignore
2509 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002510 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002511 return false;
2512
Richard Smithd5e1d602011-10-12 00:37:51 +00002513 // Check to see if we have the marker (4 characters in a row).
2514 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002515 if (CurPtr[i] != CurPtr[0])
2516 return false;
2517
2518 // If we do have it, search for the end of the conflict marker. This could
2519 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2520 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002521 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2522 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002523 CurPtr = End;
2524
2525 // Skip ahead to the end of line.
2526 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2527 ++CurPtr;
2528
2529 BufferPtr = CurPtr;
2530
2531 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002532 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002533 return true;
2534 }
2535
2536 return false;
2537}
2538
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002539bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2540 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002541 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002542 return Loc == PP->getCodeCompletionLoc();
2543 }
2544
2545 return false;
2546}
2547
Jordan Rosec7629d92013-01-24 20:50:46 +00002548uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2549 Token *Result) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002550 unsigned CharSize;
2551 char Kind = getCharAndSize(StartPtr, CharSize);
2552
2553 unsigned NumHexDigits;
2554 if (Kind == 'u')
2555 NumHexDigits = 4;
2556 else if (Kind == 'U')
2557 NumHexDigits = 8;
2558 else
2559 return 0;
2560
Jordan Rosebfec9162013-01-27 20:12:04 +00002561 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rose8094bac2013-01-28 17:49:02 +00002562 if (Result && !isLexingRawMode())
2563 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosebfec9162013-01-27 20:12:04 +00002564 return 0;
2565 }
2566
Jordan Rosec7629d92013-01-24 20:50:46 +00002567 const char *CurPtr = StartPtr + CharSize;
2568 const char *KindLoc = &CurPtr[-1];
2569
2570 uint32_t CodePoint = 0;
2571 for (unsigned i = 0; i < NumHexDigits; ++i) {
2572 char C = getCharAndSize(CurPtr, CharSize);
2573
2574 unsigned Value = llvm::hexDigitValue(C);
2575 if (Value == -1U) {
2576 if (Result && !isLexingRawMode()) {
2577 if (i == 0) {
2578 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2579 << StringRef(KindLoc, 1);
2580 } else {
Jordan Rosec7629d92013-01-24 20:50:46 +00002581 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Roseb87672b2013-01-24 20:50:52 +00002582
2583 // If the user wrote \U1234, suggest a fixit to \u.
2584 if (i == 4 && NumHexDigits == 8) {
Jordan Roseed9c59f2013-02-09 01:10:25 +00002585 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Roseb87672b2013-01-24 20:50:52 +00002586 Diag(KindLoc, diag::note_ucn_four_not_eight)
2587 << FixItHint::CreateReplacement(URange, "u");
2588 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002589 }
2590 }
Jordan Rosebfec9162013-01-27 20:12:04 +00002591
Jordan Rosec7629d92013-01-24 20:50:46 +00002592 return 0;
2593 }
2594
2595 CodePoint <<= 4;
2596 CodePoint += Value;
2597
2598 CurPtr += CharSize;
2599 }
2600
2601 if (Result) {
2602 Result->setFlag(Token::HasUCN);
NAKAMURA Takumib6c08a62013-01-25 14:57:21 +00002603 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rosec7629d92013-01-24 20:50:46 +00002604 StartPtr = CurPtr;
2605 else
2606 while (StartPtr != CurPtr)
2607 (void)getAndAdvanceChar(StartPtr, *Result);
2608 } else {
2609 StartPtr = CurPtr;
2610 }
2611
2612 // C99 6.4.3p2: A universal character name shall not specify a character whose
2613 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2614 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2615 // C++11 [lex.charset]p2: If the hexadecimal value for a
2616 // universal-character-name corresponds to a surrogate code point (in the
2617 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2618 // if the hexadecimal value for a universal-character-name outside the
2619 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2620 // string literal corresponds to a control character (in either of the
2621 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2622 // basic source character set, the program is ill-formed.
2623 if (CodePoint < 0xA0) {
2624 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2625 return CodePoint;
2626
2627 // We don't use isLexingRawMode() here because we need to warn about bad
2628 // UCNs even when skipping preprocessing tokens in a #if block.
2629 if (Result && PP) {
2630 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2631 Diag(BufferPtr, diag::err_ucn_control_character);
2632 else {
2633 char C = static_cast<char>(CodePoint);
2634 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2635 }
2636 }
2637
2638 return 0;
Jordan Roseed9c59f2013-02-09 01:10:25 +00002639
2640 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002641 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002642 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rosec7629d92013-01-24 20:50:46 +00002643 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002644 if (Result && PP) {
2645 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2646 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2647 else
2648 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2649 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002650 return 0;
2651 }
2652
2653 return CodePoint;
2654}
2655
2656void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose74c24982013-01-30 01:52:57 +00002657 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002658 isCharInSet(C, UnicodeWhitespaceChars)) {
Jordan Rose74c24982013-01-30 01:52:57 +00002659 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002660 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rosefc120602013-01-24 20:50:50 +00002661
2662 Result.setFlag(Token::LeadingSpace);
2663 if (SkipWhitespace(Result, CurPtr))
2664 return; // KeepWhitespaceMode
2665
2666 return LexTokenInternal(Result);
2667 }
2668
Jordan Roseed9c59f2013-02-09 01:10:25 +00002669 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2670 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2671 !PP->isPreprocessedOutput()) {
2672 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2673 makeCharRange(*this, BufferPtr, CurPtr),
2674 /*IsFirst=*/true);
2675 }
2676
Jordan Rosec7629d92013-01-24 20:50:46 +00002677 MIOpt.ReadToken();
2678 return LexIdentifier(Result, CurPtr);
2679 }
2680
Jordan Rose0ed43942013-01-31 19:48:48 +00002681 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2682 !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002683 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002684 // Non-ASCII characters tend to creep into source code unintentionally.
2685 // Instead of letting the parser complain about the unknown token,
2686 // just drop the character.
2687 // Note that we can /only/ do this when the non-ASCII character is actually
2688 // spelled as Unicode, not written as a UCN. The standard requires that
2689 // we not throw away any possible preprocessor tokens, but there's a
2690 // loophole in the mapping of Unicode characters to basic character set
2691 // characters that allows us to map these particular characters to, say,
2692 // whitespace.
Jordan Rose74c24982013-01-30 01:52:57 +00002693 Diag(BufferPtr, diag::err_non_ascii)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002694 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rosec7629d92013-01-24 20:50:46 +00002695
2696 BufferPtr = CurPtr;
2697 return LexTokenInternal(Result);
2698 }
2699
2700 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2701 // up by accident.
2702 MIOpt.ReadToken();
2703 FormTokenWithChars(Result, CurPtr, tok::unknown);
2704}
2705
Reid Spencer5f016e22007-07-11 17:01:13 +00002706
2707/// LexTokenInternal - This implements a simple C family lexer. It is an
2708/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002709/// has a null character at the end of the file. This returns a preprocessing
2710/// token, not a normal token, as such, it is an internal interface. It assumes
2711/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002712void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002713LexNextToken:
2714 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002715 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 // CurPtr - Cache BufferPtr in an automatic variable.
2719 const char *CurPtr = BufferPtr;
2720
2721 // Small amounts of horizontal whitespace is very common between tokens.
2722 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2723 ++CurPtr;
2724 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2725 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattnerd88dc482008-10-12 04:05:48 +00002727 // If we are keeping whitespace and other tokens, just return what we just
2728 // skipped. The next lexer invocation will return the token after the
2729 // whitespace.
2730 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002731 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rose6aad4a32013-02-21 18:53:19 +00002732 // FIXME: The next token will not have LeadingSpace set.
Chris Lattnerd88dc482008-10-12 04:05:48 +00002733 return;
2734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002737 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 }
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 // Read a character, advancing over it.
2743 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002744 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 switch (Char) {
2747 case 0: // Null.
2748 // Found end of file?
2749 if (CurPtr-1 == BufferEnd) {
2750 // Read the PP instance variable into an automatic variable, because
2751 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002752 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2754 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002755 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2756 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002759 // Check if we are performing code completion.
2760 if (isCodeCompletionPoint(CurPtr-1)) {
2761 // Return the code-completion token.
2762 Result.startToken();
2763 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2764 return;
2765 }
2766
Chris Lattner74d15df2008-11-22 02:02:22 +00002767 if (!isLexingRawMode())
2768 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002769 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002770 if (SkipWhitespace(Result, CurPtr))
2771 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002774
2775 case 26: // DOS & CP/M EOF: "^Z".
2776 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002777 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002778 // Read the PP instance variable into an automatic variable, because
2779 // LexEndOfFile will often delete 'this'.
2780 Preprocessor *PPCache = PP;
2781 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2782 return; // Got a token to return.
2783 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2784 return PPCache->Lex(Result);
2785 }
2786 // If Microsoft extensions are disabled, this is just random garbage.
2787 Kind = tok::unknown;
2788 break;
2789
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 case '\n':
2791 case '\r':
2792 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002793 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 if (ParsingPreprocessorDirective) {
2795 // Done parsing the "line".
2796 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002799 if (PP)
Jordan Rose6aad4a32013-02-21 18:53:19 +00002800 resetExtendedTokenMode();
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 // Since we consumed a newline, we are back at the start of a line.
2803 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Peter Collingbourne84021552011-02-28 02:37:51 +00002805 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 break;
2807 }
Jordan Rose6aad4a32013-02-21 18:53:19 +00002808
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002810 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chris Lattnerd88dc482008-10-12 04:05:48 +00002812 if (SkipWhitespace(Result, CurPtr))
2813 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 goto LexNextToken; // GCC isn't tail call eliminating.
2815 case ' ':
2816 case '\t':
2817 case '\f':
2818 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002819 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002820 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002821 if (SkipWhitespace(Result, CurPtr))
2822 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002823
2824 SkipIgnoredUnits:
2825 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Chris Lattner8133cfc2007-07-22 06:29:05 +00002827 // If the next token is obviously a // or /* */ comment, skip it efficiently
2828 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002829 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002830 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2831 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002832 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002833 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002834 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002835 if (SkipBlockComment(Result, CurPtr+2))
2836 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002837 goto SkipIgnoredUnits;
2838 } else if (isHorizontalWhitespace(*CurPtr)) {
2839 goto SkipHorizontalWhitespace;
2840 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002842
Chris Lattner3a570772008-01-03 17:58:54 +00002843 // C99 6.4.4.1: Integer Constants.
2844 // C99 6.4.4.2: Floating Constants.
2845 case '0': case '1': case '2': case '3': case '4':
2846 case '5': case '6': case '7': case '8': case '9':
2847 // Notify MIOpt that we read a non-whitespace/non-comment token.
2848 MIOpt.ReadToken();
2849 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Douglas Gregor5cee1192011-07-27 05:40:30 +00002851 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2852 // Notify MIOpt that we read a non-whitespace/non-comment token.
2853 MIOpt.ReadToken();
2854
Richard Smith80ad52f2013-01-02 11:42:31 +00002855 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002856 Char = getCharAndSize(CurPtr, SizeTmp);
2857
2858 // UTF-16 string literal
2859 if (Char == '"')
2860 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2861 tok::utf16_string_literal);
2862
2863 // UTF-16 character constant
2864 if (Char == '\'')
2865 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2866 tok::utf16_char_constant);
2867
Craig Topper2fa4e862011-08-11 04:06:15 +00002868 // UTF-16 raw string literal
2869 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2870 return LexRawStringLiteral(Result,
2871 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2872 SizeTmp2, Result),
2873 tok::utf16_string_literal);
2874
2875 if (Char == '8') {
2876 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2877
2878 // UTF-8 string literal
2879 if (Char2 == '"')
2880 return LexStringLiteral(Result,
2881 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2882 SizeTmp2, Result),
2883 tok::utf8_string_literal);
2884
2885 if (Char2 == 'R') {
2886 unsigned SizeTmp3;
2887 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2888 // UTF-8 raw string literal
2889 if (Char3 == '"') {
2890 return LexRawStringLiteral(Result,
2891 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2892 SizeTmp2, Result),
2893 SizeTmp3, Result),
2894 tok::utf8_string_literal);
2895 }
2896 }
2897 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002898 }
2899
2900 // treat u like the start of an identifier.
2901 return LexIdentifier(Result, CurPtr);
2902
2903 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2904 // Notify MIOpt that we read a non-whitespace/non-comment token.
2905 MIOpt.ReadToken();
2906
Richard Smith80ad52f2013-01-02 11:42:31 +00002907 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002908 Char = getCharAndSize(CurPtr, SizeTmp);
2909
2910 // UTF-32 string literal
2911 if (Char == '"')
2912 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2913 tok::utf32_string_literal);
2914
2915 // UTF-32 character constant
2916 if (Char == '\'')
2917 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2918 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002919
2920 // UTF-32 raw string literal
2921 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2922 return LexRawStringLiteral(Result,
2923 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2924 SizeTmp2, Result),
2925 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002926 }
2927
2928 // treat U like the start of an identifier.
2929 return LexIdentifier(Result, CurPtr);
2930
Craig Topper2fa4e862011-08-11 04:06:15 +00002931 case 'R': // Identifier or C++0x raw string literal
2932 // Notify MIOpt that we read a non-whitespace/non-comment token.
2933 MIOpt.ReadToken();
2934
Richard Smith80ad52f2013-01-02 11:42:31 +00002935 if (LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002936 Char = getCharAndSize(CurPtr, SizeTmp);
2937
2938 if (Char == '"')
2939 return LexRawStringLiteral(Result,
2940 ConsumeChar(CurPtr, SizeTmp, Result),
2941 tok::string_literal);
2942 }
2943
2944 // treat R like the start of an identifier.
2945 return LexIdentifier(Result, CurPtr);
2946
Chris Lattner3a570772008-01-03 17:58:54 +00002947 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 // Notify MIOpt that we read a non-whitespace/non-comment token.
2949 MIOpt.ReadToken();
2950 Char = getCharAndSize(CurPtr, SizeTmp);
2951
2952 // Wide string literal.
2953 if (Char == '"')
2954 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002955 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002956
Craig Topper2fa4e862011-08-11 04:06:15 +00002957 // Wide raw string literal.
Richard Smith80ad52f2013-01-02 11:42:31 +00002958 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002959 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2960 return LexRawStringLiteral(Result,
2961 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2962 SizeTmp2, Result),
2963 tok::wide_string_literal);
2964
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 // Wide character constant.
2966 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002967 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2968 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 // C99 6.4.2: Identifiers.
2972 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2973 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002974 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2976 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2977 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002978 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 case 'v': case 'w': case 'x': case 'y': case 'z':
2980 case '_':
2981 // Notify MIOpt that we read a non-whitespace/non-comment token.
2982 MIOpt.ReadToken();
2983 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002984
2985 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002986 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002987 if (!isLexingRawMode())
2988 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002989 // Notify MIOpt that we read a non-whitespace/non-comment token.
2990 MIOpt.ReadToken();
2991 return LexIdentifier(Result, CurPtr);
2992 }
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Chris Lattner9e6293d2008-10-12 04:51:35 +00002994 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002995 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 // C99 6.4.4: Character Constants.
2998 case '\'':
2999 // Notify MIOpt that we read a non-whitespace/non-comment token.
3000 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003001 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00003002
3003 // C99 6.4.5: String Literals.
3004 case '"':
3005 // Notify MIOpt that we read a non-whitespace/non-comment token.
3006 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003007 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003008
3009 // C99 6.4.6: Punctuators.
3010 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003011 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 break;
3013 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003014 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 break;
3016 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003017 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 break;
3019 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003020 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 break;
3022 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003023 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 break;
3025 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003026 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 break;
3028 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003029 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003030 break;
3031 case '.':
3032 Char = getCharAndSize(CurPtr, SizeTmp);
3033 if (Char >= '0' && Char <= '9') {
3034 // Notify MIOpt that we read a non-whitespace/non-comment token.
3035 MIOpt.ReadToken();
3036
3037 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00003038 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003039 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00003040 CurPtr += SizeTmp;
3041 } else if (Char == '.' &&
3042 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003043 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3045 SizeTmp2, Result);
3046 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003047 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 }
3049 break;
3050 case '&':
3051 Char = getCharAndSize(CurPtr, SizeTmp);
3052 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003053 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3055 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003056 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3058 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003059 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 }
3061 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003062 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003064 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003065 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3066 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003067 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 }
3069 break;
3070 case '+':
3071 Char = getCharAndSize(CurPtr, SizeTmp);
3072 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003073 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003074 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003075 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003076 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003077 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003079 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003080 }
3081 break;
3082 case '-':
3083 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003084 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00003085 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003086 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00003087 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00003088 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3090 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003091 Kind = tok::arrowstar;
3092 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00003093 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003094 Kind = tok::arrow;
3095 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003097 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003099 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 }
3101 break;
3102 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003103 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00003104 break;
3105 case '!':
3106 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003107 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003108 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3109 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003110 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00003111 }
3112 break;
3113 case '/':
3114 // 6.4.9: Comments
3115 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00003116 if (Char == '/') { // Line comment.
3117 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00003118 // want to lex this as a comment. There is one problem with this though,
3119 // that in one particular corner case, this can change the behavior of the
3120 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003121 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003122 // "foo". Check to see if the character after the second slash is a '*'.
3123 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003124 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00003125 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003126 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003127 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00003128 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003129 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Chris Lattner8402c732009-01-16 22:39:25 +00003131 // It is common for the tokens immediately after a // comment to be
3132 // whitespace (indentation for the next line). Instead of going through
3133 // the big switch, handle it efficiently now.
3134 goto SkipIgnoredUnits;
3135 }
3136 }
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Chris Lattner8402c732009-01-16 22:39:25 +00003138 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003139 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003140 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003141 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003142 }
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Chris Lattner8402c732009-01-16 22:39:25 +00003144 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003146 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003148 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 }
3150 break;
3151 case '%':
3152 Char = getCharAndSize(CurPtr, SizeTmp);
3153 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003154 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003155 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003156 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003157 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003159 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003160 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3161 Char = getCharAndSize(CurPtr, SizeTmp);
3162 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003163 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003164 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3165 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003166 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003167 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003168 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003169 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003170 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003171 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 // We parsed a # character. If this occurs at the start of the line,
3173 // it's actually the start of a preprocessing directive. Callback to
3174 // the preprocessor to handle it.
3175 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003176 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3177 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Chris Lattnere91e9322009-03-18 20:58:27 +00003179 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003180 }
3181 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003182 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003183 }
3184 break;
3185 case '<':
3186 Char = getCharAndSize(CurPtr, SizeTmp);
3187 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003188 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003190 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3191 if (After == '=') {
3192 Kind = tok::lesslessequal;
3193 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3194 SizeTmp2, Result);
3195 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3196 // If this is actually a '<<<<<<<' version control conflict marker,
3197 // recognize it as such and recover nicely.
3198 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003199 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3200 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3201 // ignore it.
3202 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003203 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003204 Kind = tok::lesslessless;
3205 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3206 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003207 } else {
3208 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3209 Kind = tok::lessless;
3210 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003211 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003213 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003214 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith80ad52f2013-01-02 11:42:31 +00003215 if (LangOpts.CPlusPlus11 &&
Richard Smith87a1e192011-04-14 18:36:27 +00003216 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3217 // C++0x [lex.pptoken]p3:
3218 // Otherwise, if the next three characters are <:: and the subsequent
3219 // character is neither : nor >, the < is treated as a preprocessor
3220 // token by itself and not as the first character of the alternative
3221 // token <:.
3222 unsigned SizeTmp3;
3223 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3224 if (After != ':' && After != '>') {
3225 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003226 if (!isLexingRawMode())
3227 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003228 break;
3229 }
3230 }
3231
Reid Spencer5f016e22007-07-11 17:01:13 +00003232 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003233 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003234 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003235 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003236 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003237 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003238 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003239 }
3240 break;
3241 case '>':
3242 Char = getCharAndSize(CurPtr, SizeTmp);
3243 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003244 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003245 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003246 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003247 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3248 if (After == '=') {
3249 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3250 SizeTmp2, Result);
3251 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003252 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3253 // If this is actually a '>>>>' conflict marker, recognize it as such
3254 // and recover nicely.
3255 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003256 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3257 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3258 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003259 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003260 Kind = tok::greatergreatergreater;
3261 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3262 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003263 } else {
3264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3265 Kind = tok::greatergreater;
3266 }
3267
Reid Spencer5f016e22007-07-11 17:01:13 +00003268 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003269 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003270 }
3271 break;
3272 case '^':
3273 Char = getCharAndSize(CurPtr, SizeTmp);
3274 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003275 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003276 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003277 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003278 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003279 }
3280 break;
3281 case '|':
3282 Char = getCharAndSize(CurPtr, SizeTmp);
3283 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003284 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003285 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3286 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003287 // If this is '|||||||' and we're in a conflict marker, ignore it.
3288 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3289 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003290 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003291 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3292 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003293 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003294 }
3295 break;
3296 case ':':
3297 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003298 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003299 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003300 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003301 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003302 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003304 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003305 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003306 }
3307 break;
3308 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003309 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003310 break;
3311 case '=':
3312 Char = getCharAndSize(CurPtr, SizeTmp);
3313 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003314 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003315 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3316 goto LexNextToken;
3317
Chris Lattner9e6293d2008-10-12 04:51:35 +00003318 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003319 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003320 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003321 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003322 }
3323 break;
3324 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003325 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003326 break;
3327 case '#':
3328 Char = getCharAndSize(CurPtr, SizeTmp);
3329 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003330 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003331 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003332 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003333 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003334 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003335 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003336 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3337 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003338 // We parsed a # character. If this occurs at the start of the line,
3339 // it's actually the start of a preprocessing directive. Callback to
3340 // the preprocessor to handle it.
3341 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003342 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3343 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Chris Lattnere91e9322009-03-18 20:58:27 +00003345 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003346 }
3347 break;
3348
Chris Lattner3a570772008-01-03 17:58:54 +00003349 case '@':
3350 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003351 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003352 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003353 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003354 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003355 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Jordan Rosec7629d92013-01-24 20:50:46 +00003357 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 case '\\':
Jordan Rosec7629d92013-01-24 20:50:46 +00003359 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3360 return LexUnicode(Result, CodePoint, CurPtr);
3361
Chris Lattner9e6293d2008-10-12 04:51:35 +00003362 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003363 break;
Jordan Rosec7629d92013-01-24 20:50:46 +00003364
3365 default: {
3366 if (isASCII(Char)) {
3367 Kind = tok::unknown;
3368 break;
3369 }
3370
3371 UTF32 CodePoint;
3372
3373 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3374 // an escaped newline.
3375 --CurPtr;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00003376 ConversionResult Status =
3377 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3378 (const UTF8 *)BufferEnd,
3379 &CodePoint,
3380 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00003381 if (Status == conversionOK)
3382 return LexUnicode(Result, CodePoint, CurPtr);
3383
Jordan Rose0ed43942013-01-31 19:48:48 +00003384 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3385 PP->isPreprocessedOutput()) {
Jordan Rose20afc292013-01-30 19:21:12 +00003386 ++CurPtr;
Jordan Rose74c24982013-01-30 01:52:57 +00003387 Kind = tok::unknown;
3388 break;
3389 }
3390
Jordan Rosec7629d92013-01-24 20:50:46 +00003391 // Non-ASCII characters tend to creep into source code unintentionally.
3392 // Instead of letting the parser complain about the unknown token,
Jordan Roseae82c2b2013-01-25 00:20:28 +00003393 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose74c24982013-01-30 01:52:57 +00003394 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rosec7629d92013-01-24 20:50:46 +00003395
3396 BufferPtr = CurPtr+1;
3397 goto LexNextToken;
3398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003399 }
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Reid Spencer5f016e22007-07-11 17:01:13 +00003401 // Notify MIOpt that we read a non-whitespace/non-comment token.
3402 MIOpt.ReadToken();
3403
3404 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003405 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003406 return;
3407
3408HandleDirective:
3409 // We parsed a # character and it's the start of a preprocessing directive.
3410
3411 FormTokenWithChars(Result, CurPtr, tok::hash);
3412 PP->HandleDirective(Result);
3413
3414 // As an optimization, if the preprocessor didn't switch lexers, tail
3415 // recurse.
3416 if (PP->isCurrentLexer(this)) {
3417 // Start a new token. If this is a #include or something, the PP may
3418 // want us starting at the beginning of the line again. If so, set
3419 // the StartOfLine flag and clear LeadingSpace.
3420 if (IsAtStartOfLine) {
3421 Result.setFlag(Token::StartOfLine);
3422 Result.clearFlag(Token::LeadingSpace);
3423 IsAtStartOfLine = false;
3424 }
3425 goto LexNextToken; // GCC isn't tail call eliminating.
3426 }
3427 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003428}