blob: 15b1061d0571692b4c04e8b219cdeda93732dae3 [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"
Chris Lattner9dc1f532007-07-20 16:37:10 +000028#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "clang/Lex/CodeCompletionHandler.h"
30#include "clang/Lex/LexDiagnostic.h"
31#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +000032#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000034#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "llvm/Support/MemoryBuffer.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000036#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Chris Lattnera2bf1052009-12-17 05:29:40 +000039static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000040
Chris Lattnerdbf388b2007-10-07 08:47:24 +000041//===----------------------------------------------------------------------===//
42// Token Class Implementation
43//===----------------------------------------------------------------------===//
44
Mike Stump1eb44332009-09-09 15:08:12 +000045/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000046bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000047 if (IdentifierInfo *II = getIdentifierInfo())
48 return II->getObjCKeywordID() == objcKey;
49 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000050}
51
52/// getObjCKeywordID - Return the ObjC keyword kind.
53tok::ObjCKeywordKind Token::getObjCKeywordID() const {
54 IdentifierInfo *specId = getIdentifierInfo();
55 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
56}
57
Chris Lattner53702cd2007-12-13 01:59:49 +000058
Chris Lattnerdbf388b2007-10-07 08:47:24 +000059//===----------------------------------------------------------------------===//
60// Lexer Class Implementation
61//===----------------------------------------------------------------------===//
62
David Blaikie99ba9e32011-12-20 02:48:34 +000063void Lexer::anchor() { }
64
Mike Stump1eb44332009-09-09 15:08:12 +000065void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000066 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000067 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000068
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
Chris Lattner0770dab2009-01-17 07:56:59 +0000125 // Default to keeping comments if the preprocessor wants them.
126 SetCommentRetentionState(PP.getCommentRetentionState());
127}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000128
Chris Lattner168ae2d2007-10-17 20:41:00 +0000129/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000130/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner590f0cc2008-10-12 01:15:46 +0000131/// range will outlive it, so it doesn't take ownership of it.
David Blaikie4e4d0842012-03-11 07:00:24 +0000132Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000133 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikie4e4d0842012-03-11 07:00:24 +0000134 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000135
Chris Lattner22d91ca2009-01-17 06:55:17 +0000136 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner168ae2d2007-10-17 20:41:00 +0000138 // We *are* in raw mode.
139 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000140}
141
Chris Lattner025c3a62009-01-17 07:35:14 +0000142/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000143/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner025c3a62009-01-17 07:35:14 +0000144/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000145Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikie4e4d0842012-03-11 07:00:24 +0000146 const SourceManager &SM, const LangOptions &langOpts)
147 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000148
Mike Stump1eb44332009-09-09 15:08:12 +0000149 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner025c3a62009-01-17 07:35:14 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
154}
155
Chris Lattner42e00d12009-01-17 08:27:52 +0000156/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
157/// _Pragma expansion. This has a variety of magic semantics that this method
158/// sets up. It returns a new'd Lexer that must be delete'd when done.
159///
160/// On entrance to this routine, TokStartLoc is a macro location which has a
161/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000162/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000163/// "expanded from".
164///
165/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
166/// normal lexer that remaps tokens as they fly by. This would require making
167/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
168/// interface that could handle this stuff. This would pull GetMappedTokenLoc
169/// out of the critical path of the lexer!
170///
Mike Stump1eb44332009-09-09 15:08:12 +0000171Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000172 SourceLocation ExpansionLocStart,
173 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000174 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000175 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000176
177 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000178 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000179 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
180 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner42e00d12009-01-17 08:27:52 +0000182 // Now that the lexer is created, change the start/end locations so that we
183 // just lex the subsection of the file that we want. This is lexing from a
184 // scratch buffer.
185 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner42e00d12009-01-17 08:27:52 +0000187 L->BufferPtr = StrData;
188 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000189 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000190
191 // Set the SourceLocation with the remapping information. This ensures that
192 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000193 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
194 ExpansionLocStart,
195 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000198 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner42e00d12009-01-17 08:27:52 +0000201 // This lexer really is for _Pragma.
202 L->Is_PragmaLexer = true;
203 return L;
204}
205
Chris Lattner168ae2d2007-10-17 20:41:00 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207/// Stringify - Convert the specified string into a C string, with surrounding
208/// ""'s, and with escaped \ and " characters.
209std::string Lexer::Stringify(const std::string &Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
215 ++i; ++e;
216 }
217 }
218 return Result;
219}
220
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221/// Stringify - Convert the specified string into a C string by escaping '\'
222/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000223void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
230}
231
Chris Lattnerb0607272010-11-17 07:26:20 +0000232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
Richard Smith30cddae2012-11-28 07:29:00 +0000236/// \brief Slow case of getSpelling. Extract the characters comprising the
237/// spelling of this token from the provided input buffer.
238static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
241
242 size_t Length = 0;
243 const char *BufEnd = BufPtr + Tok.getLength();
244
245 if (Tok.is(tok::string_literal)) {
246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
248 unsigned Size;
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
250 BufPtr += Size;
251
252 if (Spelling[Length - 1] == '"')
253 break;
254 }
255
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
258 // r-char-sequence.
259 if (Length >= 2 &&
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
262 // quote.
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
266
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
269 Length += RawLength;
270 BufPtr += RawLength;
271
272 // The rest of the token is lexed normally.
273 }
274 }
275
276 while (BufPtr < BufEnd) {
277 unsigned Size;
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
279 BufPtr += Size;
280 }
281
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
284 return Length;
285}
286
Chris Lattnerb0607272010-11-17 07:26:20 +0000287/// getSpelling() - Return the 'spelling' of this token. The spelling of a
288/// token are the characters used to represent the token in the source file
289/// after trigraph expansion and escaped-newline folding. In particular, this
290/// wants to get the true, uncanonicalized, spelling of things like digraphs
291/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith30cddae2012-11-28 07:29:00 +0000293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
296 bool *invalid) {
John McCall834e3f62011-03-08 07:59:04 +0000297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000303 if (invalidTemp) {
304 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000305 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000306 }
307
308 const char *tokenBegin = file.data() + locInfo.second;
309
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
313 Token token;
314 lexer.LexFromRawLexer(token);
315
316 unsigned length = token.getLength();
317
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000320 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000321
Richard Smith30cddae2012-11-28 07:29:00 +0000322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner5f9e2722011-07-23 10:55:15 +0000325 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000326}
327
328/// getSpelling() - Return the 'spelling' of this token. The spelling of a
329/// token are the characters used to represent the token in the source file
330/// after trigraph expansion and escaped-newline folding. In particular, this
331/// wants to get the true, uncanonicalized, spelling of things like digraphs
332/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000333std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith30cddae2012-11-28 07:29:00 +0000336
Chris Lattnerb0607272010-11-17 07:26:20 +0000337 bool CharDataInvalid = false;
Richard Smith30cddae2012-11-28 07:29:00 +0000338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 &CharDataInvalid);
340 if (Invalid)
341 *Invalid = CharDataInvalid;
342 if (CharDataInvalid)
343 return std::string();
Richard Smith30cddae2012-11-28 07:29:00 +0000344
345 // If this token contains nothing interesting, return it directly.
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (!Tok.needsCleaning())
Richard Smith30cddae2012-11-28 07:29:00 +0000347 return std::string(TokStart, TokStart + Tok.getLength());
348
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 std::string Result;
Richard Smith30cddae2012-11-28 07:29:00 +0000350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattnerb0607272010-11-17 07:26:20 +0000352 return Result;
353}
354
355/// getSpelling - This method is used to get the spelling of a token into a
356/// preallocated buffer, instead of as an std::string. The caller is required
357/// to allocate enough space for the token, which is guaranteed to be at least
358/// Tok.getLength() bytes long. The actual length of the token is returned.
359///
360/// Note that this method may do two possible things: it may either fill in
361/// the buffer specified with characters, or it may *change the input pointer*
362/// to point to a constant buffer with the data already in it (avoiding a
363/// copy). The caller is not allowed to modify the returned buffer pointer
364/// if an internal buffer is returned.
365unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000367 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000369
370 const char *TokStart = 0;
371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
373 TokStart = Tok.getRawIdentifierData();
374 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
375 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000376 Buffer = II->getNameStart();
377 return II->getLength();
378 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000379
380 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000381 if (Tok.isLiteral())
382 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000383
Chris Lattnerb0607272010-11-17 07:26:20 +0000384 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000385 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000386 bool CharDataInvalid = false;
387 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
388 if (Invalid)
389 *Invalid = CharDataInvalid;
390 if (CharDataInvalid) {
391 Buffer = "";
392 return 0;
393 }
394 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000395
Chris Lattnerb0607272010-11-17 07:26:20 +0000396 // If this token contains nothing interesting, return it directly.
397 if (!Tok.needsCleaning()) {
398 Buffer = TokStart;
399 return Tok.getLength();
400 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000401
Chris Lattnerb0607272010-11-17 07:26:20 +0000402 // Otherwise, hard case, relex the characters into the string.
Richard Smith30cddae2012-11-28 07:29:00 +0000403 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattnerb0607272010-11-17 07:26:20 +0000404}
405
406
407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000409
Chris Lattner9a611942007-10-17 21:18:47 +0000410/// MeasureTokenLength - Relex the token at the specified location and return
411/// its length in bytes in the input file. If the token needs cleaning (e.g.
412/// includes a trigraph or an escaped newline) then this count includes bytes
413/// that are part of that.
414unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000415 const SourceManager &SM,
416 const LangOptions &LangOpts) {
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000417 Token TheTok;
418 if (getRawToken(Loc, TheTok, SM, LangOpts))
419 return 0;
420 return TheTok.getLength();
421}
422
423/// \brief Relex the token at the specified location.
424/// \returns true if there was a failure, false on success.
425bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
426 const SourceManager &SM,
427 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000428 // TODO: this could be special cased for common tokens like identifiers, ')',
429 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000430 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000431 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
432 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000433
434 // If this comes from a macro expansion, we really do want the macro name, not
435 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000436 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000437 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000438 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000440 if (Invalid)
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000441 return true;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000442
443 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000444
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000445 if (isWhitespace(StrData[0]))
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000446 return true;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000447
Chris Lattner9a611942007-10-17 21:18:47 +0000448 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000449 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
450 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000451 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000452 TheLexer.LexFromRawLexer(Result);
453 return false;
Chris Lattner9a611942007-10-17 21:18:47 +0000454}
455
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000456static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
457 const SourceManager &SM,
458 const LangOptions &LangOpts) {
459 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000460 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000461 if (LocInfo.first.isInvalid())
462 return Loc;
463
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000464 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000465 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000466 if (Invalid)
467 return Loc;
468
469 // Back up from the current location until we hit the beginning of a line
470 // (or the buffer). We'll relex from that point.
471 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000472 if (LocInfo.second >= Buffer.size())
473 return Loc;
474
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000475 const char *StrData = BufStart+LocInfo.second;
476 if (StrData[0] == '\n' || StrData[0] == '\r')
477 return Loc;
478
479 const char *LexStart = StrData;
480 while (LexStart != BufStart) {
481 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
482 ++LexStart;
483 break;
484 }
485
486 --LexStart;
487 }
488
489 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000490 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000491 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
492 TheLexer.SetCommentRetentionState(true);
493
494 // Lex tokens until we find the token that contains the source location.
495 Token TheTok;
496 do {
497 TheLexer.LexFromRawLexer(TheTok);
498
499 if (TheLexer.getBufferLocation() > StrData) {
500 // Lexing this token has taken the lexer past the source location we're
501 // looking for. If the current token encompasses our source location,
502 // return the beginning of that token.
503 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
504 return TheTok.getLocation();
505
506 // We ended up skipping over the source location entirely, which means
507 // that it points into whitespace. We're done here.
508 break;
509 }
510 } while (TheTok.getKind() != tok::eof);
511
512 // We've passed our source location; just return the original source location.
513 return Loc;
514}
515
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000516SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
517 const SourceManager &SM,
518 const LangOptions &LangOpts) {
519 if (Loc.isFileID())
520 return getBeginningOfFileToken(Loc, SM, LangOpts);
521
522 if (!SM.isMacroArgExpansion(Loc))
523 return Loc;
524
525 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
526 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
527 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000528 std::pair<FileID, unsigned> BeginFileLocInfo
529 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000530 assert(FileLocInfo.first == BeginFileLocInfo.first &&
531 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000532 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000533}
534
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000535namespace {
536 enum PreambleDirectiveKind {
537 PDK_Skipped,
538 PDK_StartIf,
539 PDK_EndIf,
540 PDK_Unknown
541 };
542}
543
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000544std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000545Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000546 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000547 // Create a lexer starting at the beginning of the file. Note that we use a
548 // "fake" file source location at offset 1 so that the lexer will track our
549 // position within the file.
550 const unsigned StartOffset = 1;
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000551 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
552 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000553 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000554
555 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
556 SourceLocation StartLoc = TheLexer.getSourceLocation();
557
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000558 bool InPreprocessorDirective = false;
559 Token TheTok;
560 Token IfStartTok;
561 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000562
563 unsigned MaxLineOffset = 0;
564 if (MaxLines) {
565 const char *CurPtr = Buffer->getBufferStart();
566 unsigned CurLine = 0;
567 while (CurPtr != Buffer->getBufferEnd()) {
568 char ch = *CurPtr++;
569 if (ch == '\n') {
570 ++CurLine;
571 if (CurLine == MaxLines)
572 break;
573 }
574 }
575 if (CurPtr != Buffer->getBufferEnd())
576 MaxLineOffset = CurPtr - Buffer->getBufferStart();
577 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000578
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000579 do {
580 TheLexer.LexFromRawLexer(TheTok);
581
582 if (InPreprocessorDirective) {
583 // If we've hit the end of the file, we're done.
584 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000585 break;
586 }
587
588 // If we haven't hit the end of the preprocessor directive, skip this
589 // token.
590 if (!TheTok.isAtStartOfLine())
591 continue;
592
593 // We've passed the end of the preprocessor directive, and will look
594 // at this token again below.
595 InPreprocessorDirective = false;
596 }
597
Douglas Gregordf95a132010-08-09 20:45:32 +0000598 // Keep track of the # of lines in the preamble.
599 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000600 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000601
602 // If we were asked to limit the number of lines in the preamble,
603 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000604 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000605 break;
606 }
607
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000608 // Comments are okay; skip over them.
609 if (TheTok.getKind() == tok::comment)
610 continue;
611
612 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
613 // This is the start of a preprocessor directive.
614 Token HashTok = TheTok;
615 InPreprocessorDirective = true;
616
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000617 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000618 // we don't have an identifier table available. Instead, just look at
619 // the raw identifier to recognize and categorize preprocessor directives.
620 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000621 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000622 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000623 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000624 PreambleDirectiveKind PDK
625 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
626 .Case("include", PDK_Skipped)
627 .Case("__include_macros", PDK_Skipped)
628 .Case("define", PDK_Skipped)
629 .Case("undef", PDK_Skipped)
630 .Case("line", PDK_Skipped)
631 .Case("error", PDK_Skipped)
632 .Case("pragma", PDK_Skipped)
633 .Case("import", PDK_Skipped)
634 .Case("include_next", PDK_Skipped)
635 .Case("warning", PDK_Skipped)
636 .Case("ident", PDK_Skipped)
637 .Case("sccs", PDK_Skipped)
638 .Case("assert", PDK_Skipped)
639 .Case("unassert", PDK_Skipped)
640 .Case("if", PDK_StartIf)
641 .Case("ifdef", PDK_StartIf)
642 .Case("ifndef", PDK_StartIf)
643 .Case("elif", PDK_Skipped)
644 .Case("else", PDK_Skipped)
645 .Case("endif", PDK_EndIf)
646 .Default(PDK_Unknown);
647
648 switch (PDK) {
649 case PDK_Skipped:
650 continue;
651
652 case PDK_StartIf:
653 if (IfCount == 0)
654 IfStartTok = HashTok;
655
656 ++IfCount;
657 continue;
658
659 case PDK_EndIf:
660 // Mismatched #endif. The preamble ends here.
661 if (IfCount == 0)
662 break;
663
664 --IfCount;
665 continue;
666
667 case PDK_Unknown:
668 // We don't know what this directive is; stop at the '#'.
669 break;
670 }
671 }
672
673 // We only end up here if we didn't recognize the preprocessor
674 // directive or it was one that can't occur in the preamble at this
675 // point. Roll back the current token to the location of the '#'.
676 InPreprocessorDirective = false;
677 TheTok = HashTok;
678 }
679
Douglas Gregordf95a132010-08-09 20:45:32 +0000680 // We hit a token that we don't recognize as being in the
681 // "preprocessing only" part of the file, so we're no longer in
682 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000683 break;
684 } while (true);
685
686 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000687 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
688 IfCount? IfStartTok.isAtStartOfLine()
689 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000690}
691
Chris Lattner7ef5c272010-11-17 07:05:50 +0000692
693/// AdvanceToTokenCharacter - Given a location that specifies the start of a
694/// token, return a new location that specifies a character within the token.
695SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
696 unsigned CharNo,
697 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000698 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000699 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000700 // character is. This needs to take into consideration newlines and
701 // trigraphs.
702 bool Invalid = false;
703 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
704
705 // If they request the first char of the token, we're trivially done.
706 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
707 return TokStart;
708
709 unsigned PhysOffset = 0;
710
711 // The usual case is that tokens don't contain anything interesting. Skip
712 // over the uninteresting characters. If a token only consists of simple
713 // chars, this method is extremely fast.
714 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
715 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000716 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000717 ++TokPtr, --CharNo, ++PhysOffset;
718 }
719
720 // If we have a character that may be a trigraph or escaped newline, use a
721 // lexer to parse it correctly.
722 for (; CharNo; --CharNo) {
723 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000724 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000725 TokPtr += Size;
726 PhysOffset += Size;
727 }
728
729 // Final detail: if we end up on an escaped newline, we want to return the
730 // location of the actual byte of the token. For example foo\<newline>bar
731 // advanced by 3 should return the location of b, not of \\. One compounding
732 // detail of this is that the escape may be made by a trigraph.
733 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
734 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
735
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000736 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000737}
738
739/// \brief Computes the source location just past the end of the
740/// token at this source location.
741///
742/// This routine can be used to produce a source location that
743/// points just past the end of the token referenced by \p Loc, and
744/// is generally used when a diagnostic needs to point just after a
745/// token where it expected something different that it received. If
746/// the returned source location would not be meaningful (e.g., if
747/// it points into a macro), this routine returns an invalid
748/// source location.
749///
750/// \param Offset an offset from the end of the token, where the source
751/// location should refer to. The default offset (0) produces a source
752/// location pointing just past the end of the token; an offset of 1 produces
753/// a source location pointing to the last character in the token, etc.
754SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
755 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000756 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000757 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000758 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000759
760 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000761 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000762 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000763 }
764
David Blaikie4e4d0842012-03-11 07:00:24 +0000765 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000766 if (Len > Offset)
767 Len = Len - Offset;
768 else
769 return Loc;
770
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000771 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000772}
773
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000774/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000775/// token of the macro expansion.
776bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000777 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000778 const LangOptions &LangOpts,
779 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000780 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
781
782 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
783 // FIXME: If the token comes from the macro token paste operator ('##')
784 // this function will always return false;
785 if (infoLoc.second > 0)
786 return false; // Does not point at the start of token.
787
Chandler Carruth433db062011-07-14 08:20:40 +0000788 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000789 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000790 if (expansionLoc.isFileID()) {
791 // No other macro expansions, this is the first.
792 if (MacroBegin)
793 *MacroBegin = expansionLoc;
794 return true;
795 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000796
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000797 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000798}
799
800/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000801/// token of the macro expansion.
802bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000803 const SourceManager &SM,
804 const LangOptions &LangOpts,
805 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000806 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
807
808 SourceLocation spellLoc = SM.getSpellingLoc(loc);
809 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
810 if (tokLen == 0)
811 return false;
812
813 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000814 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000815 if (SM.isInFileID(afterLoc, FID))
816 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000817
818 // FIXME: If the token comes from the macro token paste operator ('##')
819 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000820
Chandler Carruth433db062011-07-14 08:20:40 +0000821 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000822 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000823 if (expansionLoc.isFileID()) {
824 // No other macro expansions.
825 if (MacroEnd)
826 *MacroEnd = expansionLoc;
827 return true;
828 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000829
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000830 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000831}
832
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000833static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000834 const SourceManager &SM,
835 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000836 SourceLocation Begin = Range.getBegin();
837 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000838 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000839 if (Range.isTokenRange()) {
840 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
841 if (End.isInvalid())
842 return CharSourceRange();
843 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000844
845 // Break down the source locations.
846 FileID FID;
847 unsigned BeginOffs;
848 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
849 if (FID.isInvalid())
850 return CharSourceRange();
851
852 unsigned EndOffs;
853 if (!SM.isInFileID(End, FID, &EndOffs) ||
854 BeginOffs > EndOffs)
855 return CharSourceRange();
856
857 return CharSourceRange::getCharRange(Begin, End);
858}
859
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000860CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000861 const SourceManager &SM,
862 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000863 SourceLocation Begin = Range.getBegin();
864 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000865 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000866 return CharSourceRange();
867
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000868 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000869 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000870
871 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000872 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
873 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000874 Range.setBegin(Begin);
875 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000876 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000877
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000878 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000879 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
880 &End)) ||
881 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
882 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000883 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000884 Range.setEnd(End);
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000886 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000887
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000888 assert(Begin.isMacroID() && End.isMacroID());
889 SourceLocation MacroBegin, MacroEnd;
890 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000891 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
892 &MacroEnd)) ||
893 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
894 &MacroEnd)))) {
895 Range.setBegin(MacroBegin);
896 Range.setEnd(MacroEnd);
897 return makeRangeFromFileLocs(Range, SM, LangOpts);
898 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000899
900 FileID FID;
901 unsigned BeginOffs;
902 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
903 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000904 return CharSourceRange();
905
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000906 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000907 if (!SM.isInFileID(End, FID, &EndOffs) ||
908 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000909 return CharSourceRange();
910
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000911 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
912 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
913 if (Expansion.isMacroArgExpansion() &&
914 Expansion.getSpellingLoc().isFileID()) {
915 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000916 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
917 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
918 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000919 }
920
921 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000922}
923
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000924StringRef Lexer::getSourceText(CharSourceRange Range,
925 const SourceManager &SM,
926 const LangOptions &LangOpts,
927 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000928 Range = makeFileCharRange(Range, SM, LangOpts);
929 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000930 if (Invalid) *Invalid = true;
931 return StringRef();
932 }
933
934 // Break down the source location.
935 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
936 if (beginInfo.first.isInvalid()) {
937 if (Invalid) *Invalid = true;
938 return StringRef();
939 }
940
941 unsigned EndOffs;
942 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
943 beginInfo.second > EndOffs) {
944 if (Invalid) *Invalid = true;
945 return StringRef();
946 }
947
948 // Try to the load the file buffer.
949 bool invalidTemp = false;
950 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
951 if (invalidTemp) {
952 if (Invalid) *Invalid = true;
953 return StringRef();
954 }
955
956 if (Invalid) *Invalid = false;
957 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
958}
959
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000960StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
961 const SourceManager &SM,
962 const LangOptions &LangOpts) {
963 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000964
965 // Find the location of the immediate macro expansion.
966 while (1) {
967 FileID FID = SM.getFileID(Loc);
968 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
969 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
970 Loc = Expansion.getExpansionLocStart();
971 if (!Expansion.isMacroArgExpansion())
972 break;
973
974 // For macro arguments we need to check that the argument did not come
975 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
976
977 // Loc points to the argument id of the macro definition, move to the
978 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000979 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000980 SourceLocation SpellLoc = Expansion.getSpellingLoc();
981 if (SpellLoc.isFileID())
982 break; // No inner macro.
983
984 // If spelling location resides in the same FileID as macro expansion
985 // location, it means there is no inner macro.
986 FileID MacroFID = SM.getFileID(Loc);
987 if (SM.isInFileID(SpellLoc, MacroFID))
988 break;
989
990 // Argument came from inner macro.
991 Loc = SpellLoc;
992 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000993
994 // Find the spelling location of the start of the non-argument expansion
995 // range. This is where the macro name was spelled in order to begin
996 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000997 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000998
999 // Dig out the buffer where the macro name was spelled and the extents of the
1000 // name so that we can render it into the expansion note.
1001 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1002 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1003 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1004 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1005}
1006
Reid Spencer5f016e22007-07-11 17:01:13 +00001007//===----------------------------------------------------------------------===//
1008// Character information.
1009//===----------------------------------------------------------------------===//
1010
Reid Spencer5f016e22007-07-11 17:01:13 +00001011enum {
1012 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
1013 CHAR_VERT_WS = 0x02, // '\r', '\n'
1014 CHAR_LETTER = 0x04, // a-z,A-Z
1015 CHAR_NUMBER = 0x08, // 0-9
1016 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +00001017 CHAR_PERIOD = 0x20, // .
1018 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +00001019};
1020
Chris Lattner03b98662009-07-07 17:09:54 +00001021// Statically initialize CharInfo table based on ASCII character set
1022// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +00001023static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +00001024{
1025// 0 NUL 1 SOH 2 STX 3 ETX
1026// 4 EOT 5 ENQ 6 ACK 7 BEL
1027 0 , 0 , 0 , 0 ,
1028 0 , 0 , 0 , 0 ,
1029// 8 BS 9 HT 10 NL 11 VT
1030//12 NP 13 CR 14 SO 15 SI
1031 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
1032 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
1033//16 DLE 17 DC1 18 DC2 19 DC3
1034//20 DC4 21 NAK 22 SYN 23 ETB
1035 0 , 0 , 0 , 0 ,
1036 0 , 0 , 0 , 0 ,
1037//24 CAN 25 EM 26 SUB 27 ESC
1038//28 FS 29 GS 30 RS 31 US
1039 0 , 0 , 0 , 0 ,
1040 0 , 0 , 0 , 0 ,
1041//32 SP 33 ! 34 " 35 #
1042//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001043 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1044 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001045//40 ( 41 ) 42 * 43 +
1046//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001047 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1048 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001049//48 0 49 1 50 2 51 3
1050//52 4 53 5 54 6 55 7
1051 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1052 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1053//56 8 57 9 58 : 59 ;
1054//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001055 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1056 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001057//64 @ 65 A 66 B 67 C
1058//68 D 69 E 70 F 71 G
1059 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1060 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1061//72 H 73 I 74 J 75 K
1062//76 L 77 M 78 N 79 O
1063 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1064 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1065//80 P 81 Q 82 R 83 S
1066//84 T 85 U 86 V 87 W
1067 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1068 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1069//88 X 89 Y 90 Z 91 [
1070//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001071 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1072 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001073//96 ` 97 a 98 b 99 c
1074//100 d 101 e 102 f 103 g
1075 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1076 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1077//104 h 105 i 106 j 107 k
1078//108 l 109 m 110 n 111 o
1079 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1080 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1081//112 p 113 q 114 r 115 s
1082//116 t 117 u 118 v 119 w
1083 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1084 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1085//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001086//124 | 125 } 126 ~ 127 DEL
1087 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1088 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001089};
1090
Chris Lattnera2bf1052009-12-17 05:29:40 +00001091static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 static bool isInited = false;
1093 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001094 // check the statically-initialized CharInfo table
1095 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1096 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1097 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1098 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1099 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1100 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1101 assert(CHAR_UNDER == CharInfo[(int)'_']);
1102 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1103 for (unsigned i = 'a'; i <= 'z'; ++i) {
1104 assert(CHAR_LETTER == CharInfo[i]);
1105 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1106 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001108 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001109
Chris Lattner03b98662009-07-07 17:09:54 +00001110 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001111}
1112
Chris Lattner03b98662009-07-07 17:09:54 +00001113
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001114/// isIdentifierHead - Return true if this is the first character of an
1115/// identifier, which is [a-zA-Z_].
1116static inline bool isIdentifierHead(unsigned char c) {
1117 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1118}
1119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120/// isIdentifierBody - Return true if this is the body character of an
1121/// identifier, which is [a-zA-Z0-9_].
1122static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001123 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001124}
1125
1126/// isHorizontalWhitespace - Return true if this character is horizontal
James Dennetta05369f2012-06-15 21:36:54 +00001127/// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1128/// '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001129static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001130 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001131}
1132
Anna Zaksaca25bc2011-07-27 21:43:43 +00001133/// isVerticalWhitespace - Return true if this character is vertical
James Dennetta05369f2012-06-15 21:36:54 +00001134/// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
Anna Zaksaca25bc2011-07-27 21:43:43 +00001135static inline bool isVerticalWhitespace(unsigned char c) {
1136 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1137}
1138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139/// isWhitespace - Return true if this character is horizontal or vertical
James Dennetta05369f2012-06-15 21:36:54 +00001140/// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1141/// false for '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001142static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001143 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001144}
1145
1146/// isNumberBody - Return true if this is the body character of an
1147/// preprocessing number, which is [a-zA-Z0-9_.].
1148static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001150 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001151}
1152
Craig Topper2fa4e862011-08-11 04:06:15 +00001153/// isRawStringDelimBody - Return true if this is the body character of a
1154/// raw string delimiter.
1155static inline bool isRawStringDelimBody(unsigned char c) {
1156 return (CharInfo[c] &
1157 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1158 true : false;
1159}
1160
Jordan Rosed880b3a2012-06-07 01:10:31 +00001161// Allow external clients to make use of CharInfo.
1162bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1163 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1164}
1165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166
1167//===----------------------------------------------------------------------===//
1168// Diagnostics forwarding code.
1169//===----------------------------------------------------------------------===//
1170
Chris Lattner409a0362007-07-22 18:38:25 +00001171/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001172/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001173/// This is currently only used for _Pragma implementation, so it is the slow
1174/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001175static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1176 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001177static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1178 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001179 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001180 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattner409a0362007-07-22 18:38:25 +00001182 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001183 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001184 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001185 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chandler Carruth433db062011-07-14 08:20:40 +00001187 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001188 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001189 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001190 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattnere7fb4842009-02-15 20:52:18 +00001192 // Figure out the expansion loc range, which is the range covered by the
1193 // original _Pragma(...) sequence.
1194 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001195 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chandler Carruthbf340e42011-07-26 03:03:05 +00001197 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001198}
1199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200/// getSourceLocation - Return a source location identifier for the specified
1201/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001202SourceLocation Lexer::getSourceLocation(const char *Loc,
1203 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001204 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001206
1207 // In the normal case, we're just lexing from a simple file buffer, return
1208 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001209 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001210 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001211 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Chris Lattner2b2453a2009-01-17 06:22:33 +00001213 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1214 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001215 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001216 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217}
1218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219/// Diag - Forwarding function for diagnostics. This translate a source
1220/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001221DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001222 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223}
Reid Spencer5f016e22007-07-11 17:01:13 +00001224
1225//===----------------------------------------------------------------------===//
1226// Trigraph and Escaped Newline Handling Code.
1227//===----------------------------------------------------------------------===//
1228
1229/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1230/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1231static char GetTrigraphCharForLetter(char Letter) {
1232 switch (Letter) {
1233 default: return 0;
1234 case '=': return '#';
1235 case ')': return ']';
1236 case '(': return '[';
1237 case '!': return '|';
1238 case '\'': return '^';
1239 case '>': return '}';
1240 case '/': return '\\';
1241 case '<': return '{';
1242 case '-': return '~';
1243 }
1244}
1245
1246/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1247/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1248/// return the result character. Finally, emit a warning about trigraph use
1249/// whether trigraphs are enabled or not.
1250static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1251 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001252 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001253
David Blaikie4e4d0842012-03-11 07:00:24 +00001254 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001255 if (!L->isLexingRawMode())
1256 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001257 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Chris Lattner74d15df2008-11-22 02:02:22 +00001260 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001261 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 return Res;
1263}
1264
Chris Lattner24f0e482009-04-18 22:05:41 +00001265/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1266/// 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 +00001267/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001268unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1269 unsigned Size = 0;
1270 while (isWhitespace(Ptr[Size])) {
1271 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Chris Lattner24f0e482009-04-18 22:05:41 +00001273 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1274 continue;
1275
1276 // If this is a \r\n or \n\r, skip the other half.
1277 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1278 Ptr[Size-1] != Ptr[Size])
1279 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Chris Lattner24f0e482009-04-18 22:05:41 +00001281 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001282 }
1283
Chris Lattner24f0e482009-04-18 22:05:41 +00001284 // Not an escaped newline, must be a \t or something else.
1285 return 0;
1286}
1287
Chris Lattner03374952009-04-18 22:27:02 +00001288/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1289/// them), skip over them and return the first non-escaped-newline found,
1290/// otherwise return P.
1291const char *Lexer::SkipEscapedNewLines(const char *P) {
1292 while (1) {
1293 const char *AfterEscape;
1294 if (*P == '\\') {
1295 AfterEscape = P+1;
1296 } else if (*P == '?') {
1297 // If not a trigraph for escape, bail out.
1298 if (P[1] != '?' || P[2] != '/')
1299 return P;
1300 AfterEscape = P+3;
1301 } else {
1302 return P;
1303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Chris Lattner03374952009-04-18 22:27:02 +00001305 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1306 if (NewLineSize == 0) return P;
1307 P = AfterEscape+NewLineSize;
1308 }
1309}
1310
Anna Zaksaca25bc2011-07-27 21:43:43 +00001311/// \brief Checks that the given token is the first token that occurs after the
1312/// given location (this excludes comments and whitespace). Returns the location
1313/// immediately after the specified token. If the token is not found or the
1314/// location is inside a macro, the returned source location will be invalid.
1315SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1316 tok::TokenKind TKind,
1317 const SourceManager &SM,
1318 const LangOptions &LangOpts,
1319 bool SkipTrailingWhitespaceAndNewLine) {
1320 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001321 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001322 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001323 }
1324 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1325
1326 // Break down the source location.
1327 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1328
1329 // Try to load the file buffer.
1330 bool InvalidTemp = false;
1331 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1332 if (InvalidTemp)
1333 return SourceLocation();
1334
1335 const char *TokenBegin = File.data() + LocInfo.second;
1336
1337 // Lex from the start of the given location.
1338 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1339 TokenBegin, File.end());
1340 // Find the token.
1341 Token Tok;
1342 lexer.LexFromRawLexer(Tok);
1343 if (Tok.isNot(TKind))
1344 return SourceLocation();
1345 SourceLocation TokenLoc = Tok.getLocation();
1346
1347 // Calculate how much whitespace needs to be skipped if any.
1348 unsigned NumWhitespaceChars = 0;
1349 if (SkipTrailingWhitespaceAndNewLine) {
1350 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1351 Tok.getLength();
1352 unsigned char C = *TokenEnd;
1353 while (isHorizontalWhitespace(C)) {
1354 C = *(++TokenEnd);
1355 NumWhitespaceChars++;
1356 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001357
1358 // Skip \r, \n, \r\n, or \n\r
1359 if (C == '\n' || C == '\r') {
1360 char PrevC = C;
1361 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001362 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001363 if ((C == '\n' || C == '\r') && C != PrevC)
1364 NumWhitespaceChars++;
1365 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001366 }
1367
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001368 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001369}
Chris Lattner24f0e482009-04-18 22:05:41 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1372/// get its size, and return it. This is tricky in several cases:
1373/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1374/// then either return the trigraph (skipping 3 chars) or the '?',
1375/// depending on whether trigraphs are enabled or not.
1376/// 2. If this is an escaped newline (potentially with whitespace between
1377/// the backslash and newline), implicitly skip the newline and return
1378/// the char after it.
1379/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1380///
1381/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1382/// know that we can accumulate into Size, and that we have already incremented
1383/// Ptr by Size bytes.
1384///
1385/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1386/// be updated to match.
1387///
1388char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001389 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 // If we have a slash, look for an escaped newline.
1391 if (Ptr[0] == '\\') {
1392 ++Size;
1393 ++Ptr;
1394Slash:
1395 // Common case, backslash-char where the char is not whitespace.
1396 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Chris Lattner5636a3b2009-06-23 05:15:06 +00001398 // See if we have optional whitespace characters between the slash and
1399 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001400 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1401 // Remember that this token needs to be cleaned.
1402 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403
Chris Lattner24f0e482009-04-18 22:05:41 +00001404 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001405 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001406 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattner24f0e482009-04-18 22:05:41 +00001408 // Found backslash<whitespace><newline>. Parse the char after it.
1409 Size += EscapedNewLineSize;
1410 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001411
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001412 // If the char that we finally got was a \n, then we must have had
1413 // something like \<newline><newline>. We don't want to consume the
1414 // second newline.
1415 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1416 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001417
Chris Lattner24f0e482009-04-18 22:05:41 +00001418 // Use slow version to accumulate a correct size field.
1419 return getCharAndSizeSlow(Ptr, Size, Tok);
1420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // Otherwise, this is not an escaped newline, just return the slash.
1423 return '\\';
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 // If this is a trigraph, process it.
1427 if (Ptr[0] == '?' && Ptr[1] == '?') {
1428 // If this is actually a legal trigraph (not something like "??x"), emit
1429 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1430 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1431 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001432 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001433
1434 Ptr += 3;
1435 Size += 3;
1436 if (C == '\\') goto Slash;
1437 return C;
1438 }
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 // If this is neither, return a single character.
1442 ++Size;
1443 return *Ptr;
1444}
1445
1446
1447/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1448/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1449/// and that we have already incremented Ptr by Size bytes.
1450///
1451/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1452/// be updated to match.
1453char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001454 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 // If we have a slash, look for an escaped newline.
1456 if (Ptr[0] == '\\') {
1457 ++Size;
1458 ++Ptr;
1459Slash:
1460 // Common case, backslash-char where the char is not whitespace.
1461 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001464 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1465 // Found backslash<whitespace><newline>. Parse the char after it.
1466 Size += EscapedNewLineSize;
1467 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001469 // If the char that we finally got was a \n, then we must have had
1470 // something like \<newline><newline>. We don't want to consume the
1471 // second newline.
1472 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1473 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001474
Chris Lattner24f0e482009-04-18 22:05:41 +00001475 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001476 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001477 }
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 // Otherwise, this is not an escaped newline, just return the slash.
1480 return '\\';
1481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001484 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 // If this is actually a legal trigraph (not something like "??x"), return
1486 // it.
1487 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1488 Ptr += 3;
1489 Size += 3;
1490 if (C == '\\') goto Slash;
1491 return C;
1492 }
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // If this is neither, return a single character.
1496 ++Size;
1497 return *Ptr;
1498}
1499
1500//===----------------------------------------------------------------------===//
1501// Helper methods for lexing.
1502//===----------------------------------------------------------------------===//
1503
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001504/// \brief Routine that indiscriminately skips bytes in the source file.
1505void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1506 BufferPtr += Bytes;
1507 if (BufferPtr > BufferEnd)
1508 BufferPtr = BufferEnd;
1509 IsAtStartOfLine = StartOfLine;
1510}
1511
Chris Lattnerd2177732007-07-20 16:59:19 +00001512void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1514 unsigned Size;
1515 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001516 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 --CurPtr; // Back up over the skipped character.
1520
1521 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1522 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1523 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001524 //
1525 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1526 // cheaper
David Blaikie4e4d0842012-03-11 07:00:24 +00001527 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528FinishIdentifier:
1529 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001530 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1531 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 // If we are in raw mode, return this identifier raw. There is no need to
1534 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001535 if (LexingRawMode)
1536 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001538 // Fill in Result.IdentifierInfo and update the token kind,
1539 // looking up the identifier in the identifier table.
1540 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 // Finally, now that we know we have an identifier, pass this off to the
1543 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001544 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001545 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001546
Chris Lattner6a170eb2009-01-21 07:43:11 +00001547 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 }
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 C = getCharAndSize(CurPtr, Size);
1553 while (1) {
1554 if (C == '$') {
1555 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001556 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001559 if (!isLexingRawMode())
1560 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 CurPtr = ConsumeChar(CurPtr, Size, Result);
1562 C = getCharAndSize(CurPtr, Size);
1563 continue;
1564 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1565 // Found end of identifier.
1566 goto FinishIdentifier;
1567 }
1568
1569 // Otherwise, this character is good, consume it.
1570 CurPtr = ConsumeChar(CurPtr, Size, Result);
1571
1572 C = getCharAndSize(CurPtr, Size);
1573 while (isIdentifierBody(C)) { // FIXME: UCNs.
1574 CurPtr = ConsumeChar(CurPtr, Size, Result);
1575 C = getCharAndSize(CurPtr, Size);
1576 }
1577 }
1578}
1579
Douglas Gregora75ec432010-08-30 14:50:47 +00001580/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001581/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001582bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001583 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001584 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001585 if (C1 != '0')
1586 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001587 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001588 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001589}
Reid Spencer5f016e22007-07-11 17:01:13 +00001590
Nate Begeman5253c7f2008-04-14 02:26:39 +00001591/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001592/// constant. From[-1] is the first character lexed. Return the end of the
1593/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001594void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 unsigned Size;
1596 char C = getCharAndSize(CurPtr, Size);
1597 char PrevCh = 0;
Nico Weberdd817312012-11-13 06:25:15 +00001598 while (isNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 CurPtr = ConsumeChar(CurPtr, Size, Result);
1600 PrevCh = C;
1601 C = getCharAndSize(CurPtr, Size);
1602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001605 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1606 // If we are in Microsoft mode, don't continue if the constant is hex.
1607 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001608 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001609 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001611
1612 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001613 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1614 // Outside C99, we accept hexadecimal floating point numbers as a
1615 // not-quite-conforming extension. Only do so if this looks like it's
1616 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1617 bool IsHexFloat = true;
1618 if (!LangOpts.C99) {
1619 if (!isHexaLiteral(BufferPtr, LangOpts))
1620 IsHexFloat = false;
1621 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1622 IsHexFloat = false;
1623 }
1624 if (IsHexFloat)
1625 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001629 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001630 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001631 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001632}
1633
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001634/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001635/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001636const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001637 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001638
1639 // Maximally munch an identifier. FIXME: UCNs.
1640 unsigned Size;
1641 char C = getCharAndSize(CurPtr, Size);
1642 if (isIdentifierHead(C)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001643 if (!getLangOpts().CPlusPlus11) {
Richard Smithe816c712012-03-07 03:13:00 +00001644 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001645 Diag(CurPtr,
1646 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1647 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1648 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1649 return CurPtr;
1650 }
1651
1652 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1653 // that does not start with an underscore is ill-formed. As a conforming
1654 // extension, we treat all such suffixes as if they had whitespace before
1655 // them.
1656 if (C != '_') {
1657 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001658 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1659 diag::ext_ms_reserved_user_defined_literal :
1660 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001661 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1662 return CurPtr;
1663 }
1664
Richard Smith99831e42012-03-06 03:21:47 +00001665 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001666 do {
1667 CurPtr = ConsumeChar(CurPtr, Size, Result);
1668 C = getCharAndSize(CurPtr, Size);
1669 } while (isIdentifierBody(C));
1670 }
1671 return CurPtr;
1672}
1673
Reid Spencer5f016e22007-07-11 17:01:13 +00001674/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001675/// either " or L" or u8" or u" or U".
1676void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1677 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Richard Smith661a9962011-10-15 01:18:56 +00001680 if (!isLexingRawMode() &&
1681 (Kind == tok::utf8_string_literal ||
1682 Kind == tok::utf16_string_literal ||
1683 Kind == tok::utf32_string_literal))
1684 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 char C = getAndAdvanceChar(CurPtr, Result);
1687 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001688 // Skip escaped characters. Escaped newlines will already be processed by
1689 // getAndAdvanceChar.
1690 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001692
Chris Lattner571339c2010-05-30 23:27:38 +00001693 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001694 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001695 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001696 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001697 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 }
Chris Lattner571339c2010-05-30 23:27:38 +00001700
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001701 if (C == 0) {
1702 if (isCodeCompletionPoint(CurPtr-1)) {
1703 PP->CodeCompleteNaturalLanguage();
1704 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1705 return cutOffLexing();
1706 }
1707
Chris Lattner571339c2010-05-30 23:27:38 +00001708 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001709 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 C = getAndAdvanceChar(CurPtr, Result);
1711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001713 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001714 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001715 CurPtr = LexUDSuffix(Result, CurPtr);
1716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001718 if (NulCharacter && !isLexingRawMode())
1719 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001720
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001722 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001723 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001724 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725}
1726
Craig Topper2fa4e862011-08-11 04:06:15 +00001727/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1728/// having lexed R", LR", u8R", uR", or UR".
1729void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1730 tok::TokenKind Kind) {
1731 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1732 // Between the initial and final double quote characters of the raw string,
1733 // any transformations performed in phases 1 and 2 (trigraphs,
1734 // universal-character-names, and line splicing) are reverted.
1735
Richard Smith661a9962011-10-15 01:18:56 +00001736 if (!isLexingRawMode())
1737 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1738
Craig Topper2fa4e862011-08-11 04:06:15 +00001739 unsigned PrefixLen = 0;
1740
1741 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1742 ++PrefixLen;
1743
1744 // If the last character was not a '(', then we didn't lex a valid delimiter.
1745 if (CurPtr[PrefixLen] != '(') {
1746 if (!isLexingRawMode()) {
1747 const char *PrefixEnd = &CurPtr[PrefixLen];
1748 if (PrefixLen == 16) {
1749 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1750 } else {
1751 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1752 << StringRef(PrefixEnd, 1);
1753 }
1754 }
1755
1756 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1757 // it's possible the '"' was intended to be part of the raw string, but
1758 // there's not much we can do about that.
1759 while (1) {
1760 char C = *CurPtr++;
1761
1762 if (C == '"')
1763 break;
1764 if (C == 0 && CurPtr-1 == BufferEnd) {
1765 --CurPtr;
1766 break;
1767 }
1768 }
1769
1770 FormTokenWithChars(Result, CurPtr, tok::unknown);
1771 return;
1772 }
1773
1774 // Save prefix and move CurPtr past it
1775 const char *Prefix = CurPtr;
1776 CurPtr += PrefixLen + 1; // skip over prefix and '('
1777
1778 while (1) {
1779 char C = *CurPtr++;
1780
1781 if (C == ')') {
1782 // Check for prefix match and closing quote.
1783 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1784 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1785 break;
1786 }
1787 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1788 if (!isLexingRawMode())
1789 Diag(BufferPtr, diag::err_unterminated_raw_string)
1790 << StringRef(Prefix, PrefixLen);
1791 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1792 return;
1793 }
1794 }
1795
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001796 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001797 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001798 CurPtr = LexUDSuffix(Result, CurPtr);
1799
Craig Topper2fa4e862011-08-11 04:06:15 +00001800 // Update the location of token as well as BufferPtr.
1801 const char *TokStart = BufferPtr;
1802 FormTokenWithChars(Result, CurPtr, Kind);
1803 Result.setLiteralData(TokStart);
1804}
1805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1807/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001808void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001810 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 char C = getAndAdvanceChar(CurPtr, Result);
1812 while (C != '>') {
1813 // Skip escaped characters.
1814 if (C == '\\') {
1815 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001816 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001818 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1819 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001820 // If the filename is unterminated, then it must just be a lone <
1821 // character. Return this as such.
1822 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 return;
1824 } else if (C == 0) {
1825 NulCharacter = CurPtr-1;
1826 }
1827 C = getAndAdvanceChar(CurPtr, Result);
1828 }
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001831 if (NulCharacter && !isLexingRawMode())
1832 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001835 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001836 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001837 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001838}
1839
1840
1841/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001842/// lexed either ' or L' or u' or U'.
1843void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1844 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 const char *NulCharacter = 0; // Does this character contain the \0 character?
1846
Richard Smith661a9962011-10-15 01:18:56 +00001847 if (!isLexingRawMode() &&
1848 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1849 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1850
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 char C = getAndAdvanceChar(CurPtr, Result);
1852 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001853 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001854 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001855 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001857 }
1858
1859 while (C != '\'') {
1860 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001861 if (C == '\\')
1862 C = getAndAdvanceChar(CurPtr, Result);
1863
1864 if (C == '\n' || C == '\r' || // Newline.
1865 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001866 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001867 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001868 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1869 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001870 }
1871
1872 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001873 if (isCodeCompletionPoint(CurPtr-1)) {
1874 PP->CodeCompleteNaturalLanguage();
1875 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1876 return cutOffLexing();
1877 }
1878
Chris Lattnerd80f7862010-07-07 23:24:27 +00001879 NulCharacter = CurPtr-1;
1880 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 C = getAndAdvanceChar(CurPtr, Result);
1882 }
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001884 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001885 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001886 CurPtr = LexUDSuffix(Result, CurPtr);
1887
Chris Lattnerd80f7862010-07-07 23:24:27 +00001888 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001889 if (NulCharacter && !isLexingRawMode())
1890 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001891
Reid Spencer5f016e22007-07-11 17:01:13 +00001892 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001893 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001894 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001895 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896}
1897
1898/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1899/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001900///
1901/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1902///
1903bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 // Whitespace - Skip it, then return the token after the whitespace.
1905 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1906 while (1) {
1907 // Skip horizontal whitespace very aggressively.
1908 while (isHorizontalWhitespace(Char))
1909 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001911 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 if (Char != '\n' && Char != '\r')
1913 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 if (ParsingPreprocessorDirective) {
1916 // End of preprocessor directive line, let LexTokenInternal handle this.
1917 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001918 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // ok, but handle newline.
1922 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001923 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001925 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 Char = *++CurPtr;
1927 }
1928
1929 // If this isn't immediately after a newline, there is leading space.
1930 char PrevChar = CurPtr[-1];
1931 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001932 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001933
Chris Lattnerd88dc482008-10-12 04:05:48 +00001934 // If the client wants us to return whitespace, return it now.
1935 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001936 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001937 return true;
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001941 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001942}
1943
Nico Weberbb236282012-11-11 07:02:14 +00001944/// We have just read the // characters from input. Skip until we find the
1945/// newline character thats terminate the comment. Then update BufferPtr and
1946/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001947///
1948/// If we're in KeepCommentMode or any CommentHandler has inserted
1949/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001950bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1951 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001953 if (!LangOpts.LineComment && !isLexingRawMode()) {
1954 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 // Mark them enabled so we only emit one warning for this translation
1957 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001958 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 // Scan over the body of the comment. The common case, when scanning, is that
1962 // the comment contains normal ascii characters with nothing interesting in
1963 // them. As such, optimize for this case with the inner loop.
1964 char C;
1965 do {
1966 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // Skip over characters in the fast loop.
1968 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 C != '\n' && C != '\r') // Newline or DOS-style newline.
1970 C = *++CurPtr;
1971
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001972 const char *NextLine = CurPtr;
1973 if (C != 0) {
1974 // We found a newline, see if it's escaped.
1975 const char *EscapePtr = CurPtr-1;
1976 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1977 --EscapePtr;
1978
1979 if (*EscapePtr == '\\') // Escaped newline.
1980 CurPtr = EscapePtr;
1981 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1982 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1983 CurPtr = EscapePtr-2;
1984 else
1985 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001989 // properly decode the character. Read it in raw mode to avoid emitting
1990 // diagnostics about things like trigraphs. If we see an escaped newline,
1991 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001993 bool OldRawMode = isLexingRawMode();
1994 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001996 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001997
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001998 // If we only read only one character, then no special handling is needed.
1999 // We're done and can skip forward to the newline.
2000 if (C != 0 && CurPtr == OldPtr+1) {
2001 CurPtr = NextLine;
2002 break;
2003 }
2004
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // If we read multiple characters, and one of those characters was a \r or
2006 // \n, then we had an escaped newline within the comment. Emit diagnostic
2007 // unless the next line is also a // comment.
2008 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2009 for (; OldPtr != CurPtr; ++OldPtr)
2010 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2011 // Okay, we found a // comment that ends in a newline, if the next
2012 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002013 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002015 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 ++ForwardPtr;
2017 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2018 break;
2019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner74d15df2008-11-22 02:02:22 +00002021 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00002022 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 break;
2024 }
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor55817af2010-08-25 17:04:25 +00002027 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00002028 --CurPtr;
2029 break;
2030 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002031
2032 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2033 PP->CodeCompleteNaturalLanguage();
2034 cutOffLexing();
2035 return false;
2036 }
2037
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 } while (C != '\n' && C != '\r');
2039
Chris Lattner3d0ad582010-02-03 21:06:21 +00002040 // Found but did not consume the newline. Notify comment handlers about the
2041 // comment unless we're in a #if 0 block.
2042 if (PP && !isLexingRawMode() &&
2043 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2044 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002045 BufferPtr = CurPtr;
2046 return true; // A token has to be returned.
2047 }
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002050 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002051 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002052
2053 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002054 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2056 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002057 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002061 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002062 // contribute to another token), it isn't needed for correctness. Note that
2063 // this is ok even in KeepWhitespaceMode, because we would have returned the
2064 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002068 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002070 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002072 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002073}
2074
Nico Weberbb236282012-11-11 07:02:14 +00002075/// If in save-comment mode, package up this Line comment in an appropriate
2076/// way and return it.
2077bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002078 // If we're not in a preprocessor directive, just return the // comment
2079 // directly.
2080 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
David Blaikie8c0b3782012-06-06 18:52:13 +00002082 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002083 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Nico Weberbb236282012-11-11 07:02:14 +00002085 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002086 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002087 bool Invalid = false;
2088 std::string Spelling = PP->getSpelling(Result, &Invalid);
2089 if (Invalid)
2090 return true;
2091
Nico Weberbb236282012-11-11 07:02:14 +00002092 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002093 Spelling[1] = '*'; // Change prefix to "/*".
2094 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Chris Lattner9e6293d2008-10-12 04:51:35 +00002096 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002097 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002098 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002099 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002100}
2101
2102/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002103/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2104/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002105static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 Lexer *L) {
2107 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 // Back up off the newline.
2110 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // If this is a two-character newline sequence, skip the other character.
2113 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2114 // \n\n or \r\r -> not escaped newline.
2115 if (CurPtr[0] == CurPtr[1])
2116 return false;
2117 // \n\r or \r\n -> skip the newline.
2118 --CurPtr;
2119 }
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // If we have horizontal whitespace, skip over it. We allow whitespace
2122 // between the slash and newline.
2123 bool HasSpace = false;
2124 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2125 --CurPtr;
2126 HasSpace = true;
2127 }
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // If we have a slash, we know this is an escaped newline.
2130 if (*CurPtr == '\\') {
2131 if (CurPtr[-1] != '*') return false;
2132 } else {
2133 // It isn't a slash, is it the ?? / trigraph?
2134 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2135 CurPtr[-3] != '*')
2136 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // This is the trigraph ending the comment. Emit a stern warning!
2139 CurPtr -= 2;
2140
2141 // If no trigraphs are enabled, warn that we ignored this trigraph and
2142 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002143 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002144 if (!L->isLexingRawMode())
2145 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 return false;
2147 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002148 if (!L->isLexingRawMode())
2149 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002153 if (!L->isLexingRawMode())
2154 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002157 if (HasSpace && !L->isLexingRawMode())
2158 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 return true;
2161}
2162
2163#ifdef __SSE2__
2164#include <emmintrin.h>
2165#elif __ALTIVEC__
2166#include <altivec.h>
2167#undef bool
2168#endif
2169
James Dennettec769932012-06-17 03:40:43 +00002170/// We have just read from input the / and * characters that started a comment.
2171/// Read until we find the * and / characters that terminate the comment.
2172/// Note that we don't bother decoding trigraphs or escaped newlines in block
2173/// comments, because they cannot cause the comment to end. The only thing
2174/// that can happen is the comment could end with an escaped newline between
2175/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002176///
Chris Lattner046c2272010-01-18 22:35:47 +00002177/// If we're in KeepCommentMode or any CommentHandler has inserted
2178/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002179bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002181 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 // optimization helps people who like to put a lot of * characters in their
2183 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002184
2185 // The first character we get with newlines and trigraphs skipped to handle
2186 // the degenerate /*/ case below correctly if the * has an escaped newline
2187 // after it.
2188 unsigned CharSize;
2189 unsigned char C = getCharAndSize(CurPtr, CharSize);
2190 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002192 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002193 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002194 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Chris Lattner31f0eca2008-10-12 04:19:49 +00002196 // KeepWhitespaceMode should return this broken comment as a token. Since
2197 // it isn't a well formed comment, just return it as an 'unknown' token.
2198 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002199 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002200 return true;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Chris Lattner31f0eca2008-10-12 04:19:49 +00002203 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002204 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 }
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Chris Lattner8146b682007-07-21 23:43:37 +00002207 // Check to see if the first character after the '/*' is another /. If so,
2208 // then this slash does not end the block comment, it is part of it.
2209 if (C == '/')
2210 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 while (1) {
2213 // Skip over all non-interesting characters until we find end of buffer or a
2214 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002215 if (CurPtr + 24 < BufferEnd &&
2216 // If there is a code-completion point avoid the fast scan because it
2217 // doesn't check for '\0'.
2218 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 // While not aligned to a 16-byte boundary.
2220 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2221 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 if (C == '/') goto FoundSlash;
2224
2225#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002226 __m128i Slashes = _mm_set1_epi8('/');
2227 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002228 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2229 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002230 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002231 // Adjust the pointer to point directly after the first slash. It's
2232 // not necessary to set C here, it will be overwritten at the end of
2233 // the outer loop.
2234 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002235 goto FoundSlash;
2236 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002238 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002239#elif __ALTIVEC__
2240 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002241 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 '/', '/', '/', '/', '/', '/', '/', '/'
2243 };
2244 while (CurPtr+16 <= BufferEnd &&
2245 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2246 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002247#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // Scan for '/' quickly. Many block comments are very large.
2249 while (CurPtr[0] != '/' &&
2250 CurPtr[1] != '/' &&
2251 CurPtr[2] != '/' &&
2252 CurPtr[3] != '/' &&
2253 CurPtr+4 < BufferEnd) {
2254 CurPtr += 4;
2255 }
2256#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 // It has to be one of the bytes scanned, increment to it and read one.
2259 C = *CurPtr++;
2260 }
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 // Loop to scan the remainder.
2263 while (C != '/' && C != '\0')
2264 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002267 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002268 if (CurPtr[-2] == '*') // We found the final */. We're done!
2269 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2272 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2273 // We found the final */, though it had an escaped newline between the
2274 // * and /. We're done!
2275 break;
2276 }
2277 }
2278 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2279 // If this is a /* inside of the comment, emit a warning. Don't do this
2280 // if this is a /*/, which will end the comment. This misses cases with
2281 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002282 if (!isLexingRawMode())
2283 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 }
2285 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002286 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002287 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 // Note: the user probably forgot a */. We could continue immediately
2289 // after the /*, but this would involve lexing a lot of what really is the
2290 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002291 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Chris Lattner31f0eca2008-10-12 04:19:49 +00002293 // KeepWhitespaceMode should return this broken comment as a token. Since
2294 // it isn't a well formed comment, just return it as an 'unknown' token.
2295 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002296 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002297 return true;
2298 }
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattner31f0eca2008-10-12 04:19:49 +00002300 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002301 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002302 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2303 PP->CodeCompleteNaturalLanguage();
2304 cutOffLexing();
2305 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002307
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 C = *CurPtr++;
2309 }
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattner3d0ad582010-02-03 21:06:21 +00002311 // Notify comment handlers about the comment unless we're in a #if 0 block.
2312 if (PP && !isLexingRawMode() &&
2313 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2314 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002315 BufferPtr = CurPtr;
2316 return true; // A token has to be returned.
2317 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002318
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002320 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002321 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002322 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 }
2324
2325 // It is common for the tokens immediately after a /**/ comment to be
2326 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002327 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2328 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002330 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002332 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 }
2334
2335 // Otherwise, just return so that the next character will be lexed as a token.
2336 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002337 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002338 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002339}
2340
2341//===----------------------------------------------------------------------===//
2342// Primary Lexing Entry Points
2343//===----------------------------------------------------------------------===//
2344
Reid Spencer5f016e22007-07-11 17:01:13 +00002345/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2346/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002347void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2349 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002350 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002351
2352 // CurPtr - Cache BufferPtr in an automatic variable.
2353 const char *CurPtr = BufferPtr;
2354 while (1) {
2355 char Char = getAndAdvanceChar(CurPtr, Tmp);
2356 switch (Char) {
2357 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002358 if (Result)
2359 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 break;
2361 case 0: // Null.
2362 // Found end of file?
2363 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002364 if (isCodeCompletionPoint(CurPtr-1)) {
2365 PP->CodeCompleteNaturalLanguage();
2366 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002367 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002368 }
2369
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002371 if (Result)
2372 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 break;
2374 }
2375 // FALL THROUGH.
2376 case '\r':
2377 case '\n':
2378 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2379 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2380 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Peter Collingbourne84021552011-02-28 02:37:51 +00002382 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002384 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002385 if (PP)
2386 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002387 Lex(Tmp);
2388 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002389 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Benjamin Kramer3093b202012-05-18 19:32:16 +00002391 // Finally, we're done;
2392 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002393 }
2394 }
2395}
2396
2397/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2398/// condition, reporting diagnostics and handling other edge cases as required.
2399/// This returns true if Result contains a token, false if PP.Lex should be
2400/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002401bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 // If we hit the end of the file while parsing a preprocessor directive,
2403 // end the preprocessor directive first. The next token returned will
2404 // then be the end of file.
2405 if (ParsingPreprocessorDirective) {
2406 // Done parsing the "line".
2407 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002409 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002412 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002414 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002415
Reid Spencer5f016e22007-07-11 17:01:13 +00002416 // If we are in raw mode, return this event as an EOF token. Let the caller
2417 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002418 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002419 Result.startToken();
2420 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002421 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 return true;
2423 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002424
Douglas Gregorf44e8542010-08-24 19:08:16 +00002425 // Issue diagnostics for unterminated #if and missing newline.
2426
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // If we are in a #if directive, emit an error.
2428 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002429 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002430 PP->Diag(ConditionalStack.back().IfLoc,
2431 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 ConditionalStack.pop_back();
2433 }
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002435 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2436 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002437 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith80ad52f2013-01-02 11:42:31 +00002438 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002439 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2440 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Reid Spencer5f016e22007-07-11 17:01:13 +00002442 BufferPtr = CurPtr;
2443
2444 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002445 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002446}
2447
2448/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2449/// the specified lexer will return a tok::l_paren token, 0 if it is something
2450/// else and 2 if there are no more tokens in the buffer controlled by the
2451/// lexer.
2452unsigned Lexer::isNextPPTokenLParen() {
2453 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Reid Spencer5f016e22007-07-11 17:01:13 +00002455 // Switch to 'skipping' mode. This will ensure that we can lex a token
2456 // without emitting diagnostics, disables macro expansion, and will cause EOF
2457 // to return an EOF token instead of popping the include stack.
2458 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Reid Spencer5f016e22007-07-11 17:01:13 +00002460 // Save state that can be changed while lexing so that we can restore it.
2461 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002462 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Chris Lattnerd2177732007-07-20 16:59:19 +00002464 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002465 Tok.startToken();
2466 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 // Restore state that may have changed.
2469 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002470 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 // Restore the lexer back to non-skipping mode.
2473 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002475 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002477 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002478}
2479
James Dennettec769932012-06-17 03:40:43 +00002480/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002481static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2482 ConflictMarkerKind CMK) {
2483 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2484 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2485 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2486 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002487 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002488 // Must occur at start of line.
2489 if (RestOfBuffer[Pos-1] != '\r' &&
2490 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002491 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2492 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002493 continue;
2494 }
2495 return RestOfBuffer.data()+Pos;
2496 }
2497 return 0;
2498}
2499
2500/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2501/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2502/// and recover nicely. This returns true if it is a conflict marker and false
2503/// if not.
2504bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2505 // Only a conflict marker if it starts at the beginning of a line.
2506 if (CurPtr != BufferStart &&
2507 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2508 return false;
2509
Richard Smithd5e1d602011-10-12 00:37:51 +00002510 // Check to see if we have <<<<<<< or >>>>.
2511 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2512 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002513 return false;
2514
2515 // If we have a situation where we don't care about conflict markers, ignore
2516 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002517 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002518 return false;
2519
Richard Smithd5e1d602011-10-12 00:37:51 +00002520 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2521
2522 // Check to see if there is an ending marker somewhere in the buffer at the
2523 // start of a line to terminate this conflict marker.
2524 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002525 // We found a match. We are really in a conflict marker.
2526 // Diagnose this, and ignore to the end of line.
2527 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002528 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002529
2530 // Skip ahead to the end of line. We know this exists because the
2531 // end-of-conflict marker starts with \r or \n.
2532 while (*CurPtr != '\r' && *CurPtr != '\n') {
2533 assert(CurPtr != BufferEnd && "Didn't find end of line");
2534 ++CurPtr;
2535 }
2536 BufferPtr = CurPtr;
2537 return true;
2538 }
2539
2540 // No end of conflict marker found.
2541 return false;
2542}
2543
2544
Richard Smithd5e1d602011-10-12 00:37:51 +00002545/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2546/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2547/// is the end of a conflict marker. Handle it by ignoring up until the end of
2548/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002549bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2550 // Only a conflict marker if it starts at the beginning of a line.
2551 if (CurPtr != BufferStart &&
2552 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2553 return false;
2554
2555 // If we have a situation where we don't care about conflict markers, ignore
2556 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002557 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002558 return false;
2559
Richard Smithd5e1d602011-10-12 00:37:51 +00002560 // Check to see if we have the marker (4 characters in a row).
2561 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002562 if (CurPtr[i] != CurPtr[0])
2563 return false;
2564
2565 // If we do have it, search for the end of the conflict marker. This could
2566 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2567 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002568 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2569 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002570 CurPtr = End;
2571
2572 // Skip ahead to the end of line.
2573 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2574 ++CurPtr;
2575
2576 BufferPtr = CurPtr;
2577
2578 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002579 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002580 return true;
2581 }
2582
2583 return false;
2584}
2585
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002586bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2587 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002588 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002589 return Loc == PP->getCodeCompletionLoc();
2590 }
2591
2592 return false;
2593}
2594
Reid Spencer5f016e22007-07-11 17:01:13 +00002595
2596/// LexTokenInternal - This implements a simple C family lexer. It is an
2597/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002598/// has a null character at the end of the file. This returns a preprocessing
2599/// token, not a normal token, as such, it is an internal interface. It assumes
2600/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002601void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002602LexNextToken:
2603 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002604 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 // CurPtr - Cache BufferPtr in an automatic variable.
2608 const char *CurPtr = BufferPtr;
2609
2610 // Small amounts of horizontal whitespace is very common between tokens.
2611 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2612 ++CurPtr;
2613 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2614 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Chris Lattnerd88dc482008-10-12 04:05:48 +00002616 // If we are keeping whitespace and other tokens, just return what we just
2617 // skipped. The next lexer invocation will return the token after the
2618 // whitespace.
2619 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002620 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002621 return;
2622 }
Mike Stump1eb44332009-09-09 15:08:12 +00002623
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002625 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 }
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 // Read a character, advancing over it.
2631 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002632 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 switch (Char) {
2635 case 0: // Null.
2636 // Found end of file?
2637 if (CurPtr-1 == BufferEnd) {
2638 // Read the PP instance variable into an automatic variable, because
2639 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002640 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2642 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002643 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2644 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 }
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002647 // Check if we are performing code completion.
2648 if (isCodeCompletionPoint(CurPtr-1)) {
2649 // Return the code-completion token.
2650 Result.startToken();
2651 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2652 return;
2653 }
2654
Chris Lattner74d15df2008-11-22 02:02:22 +00002655 if (!isLexingRawMode())
2656 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002657 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002658 if (SkipWhitespace(Result, CurPtr))
2659 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002662
2663 case 26: // DOS & CP/M EOF: "^Z".
2664 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002665 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002666 // Read the PP instance variable into an automatic variable, because
2667 // LexEndOfFile will often delete 'this'.
2668 Preprocessor *PPCache = PP;
2669 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2670 return; // Got a token to return.
2671 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2672 return PPCache->Lex(Result);
2673 }
2674 // If Microsoft extensions are disabled, this is just random garbage.
2675 Kind = tok::unknown;
2676 break;
2677
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 case '\n':
2679 case '\r':
2680 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002681 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 if (ParsingPreprocessorDirective) {
2683 // Done parsing the "line".
2684 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002687 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002688 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Reid Spencer5f016e22007-07-11 17:01:13 +00002690 // Since we consumed a newline, we are back at the start of a line.
2691 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Peter Collingbourne84021552011-02-28 02:37:51 +00002693 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 break;
2695 }
2696 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002697 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002699 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Chris Lattnerd88dc482008-10-12 04:05:48 +00002701 if (SkipWhitespace(Result, CurPtr))
2702 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 goto LexNextToken; // GCC isn't tail call eliminating.
2704 case ' ':
2705 case '\t':
2706 case '\f':
2707 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002708 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002709 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002710 if (SkipWhitespace(Result, CurPtr))
2711 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002712
2713 SkipIgnoredUnits:
2714 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattner8133cfc2007-07-22 06:29:05 +00002716 // If the next token is obviously a // or /* */ comment, skip it efficiently
2717 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002718 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002719 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2720 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002721 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002722 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002723 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002724 if (SkipBlockComment(Result, CurPtr+2))
2725 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002726 goto SkipIgnoredUnits;
2727 } else if (isHorizontalWhitespace(*CurPtr)) {
2728 goto SkipHorizontalWhitespace;
2729 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002731
Chris Lattner3a570772008-01-03 17:58:54 +00002732 // C99 6.4.4.1: Integer Constants.
2733 // C99 6.4.4.2: Floating Constants.
2734 case '0': case '1': case '2': case '3': case '4':
2735 case '5': case '6': case '7': case '8': case '9':
2736 // Notify MIOpt that we read a non-whitespace/non-comment token.
2737 MIOpt.ReadToken();
2738 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Douglas Gregor5cee1192011-07-27 05:40:30 +00002740 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2741 // Notify MIOpt that we read a non-whitespace/non-comment token.
2742 MIOpt.ReadToken();
2743
Richard Smith80ad52f2013-01-02 11:42:31 +00002744 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002745 Char = getCharAndSize(CurPtr, SizeTmp);
2746
2747 // UTF-16 string literal
2748 if (Char == '"')
2749 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2750 tok::utf16_string_literal);
2751
2752 // UTF-16 character constant
2753 if (Char == '\'')
2754 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2755 tok::utf16_char_constant);
2756
Craig Topper2fa4e862011-08-11 04:06:15 +00002757 // UTF-16 raw string literal
2758 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2759 return LexRawStringLiteral(Result,
2760 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2761 SizeTmp2, Result),
2762 tok::utf16_string_literal);
2763
2764 if (Char == '8') {
2765 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2766
2767 // UTF-8 string literal
2768 if (Char2 == '"')
2769 return LexStringLiteral(Result,
2770 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2771 SizeTmp2, Result),
2772 tok::utf8_string_literal);
2773
2774 if (Char2 == 'R') {
2775 unsigned SizeTmp3;
2776 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2777 // UTF-8 raw string literal
2778 if (Char3 == '"') {
2779 return LexRawStringLiteral(Result,
2780 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2781 SizeTmp2, Result),
2782 SizeTmp3, Result),
2783 tok::utf8_string_literal);
2784 }
2785 }
2786 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002787 }
2788
2789 // treat u like the start of an identifier.
2790 return LexIdentifier(Result, CurPtr);
2791
2792 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2793 // Notify MIOpt that we read a non-whitespace/non-comment token.
2794 MIOpt.ReadToken();
2795
Richard Smith80ad52f2013-01-02 11:42:31 +00002796 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002797 Char = getCharAndSize(CurPtr, SizeTmp);
2798
2799 // UTF-32 string literal
2800 if (Char == '"')
2801 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2802 tok::utf32_string_literal);
2803
2804 // UTF-32 character constant
2805 if (Char == '\'')
2806 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2807 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002808
2809 // UTF-32 raw string literal
2810 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2811 return LexRawStringLiteral(Result,
2812 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2813 SizeTmp2, Result),
2814 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002815 }
2816
2817 // treat U like the start of an identifier.
2818 return LexIdentifier(Result, CurPtr);
2819
Craig Topper2fa4e862011-08-11 04:06:15 +00002820 case 'R': // Identifier or C++0x raw string literal
2821 // Notify MIOpt that we read a non-whitespace/non-comment token.
2822 MIOpt.ReadToken();
2823
Richard Smith80ad52f2013-01-02 11:42:31 +00002824 if (LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002825 Char = getCharAndSize(CurPtr, SizeTmp);
2826
2827 if (Char == '"')
2828 return LexRawStringLiteral(Result,
2829 ConsumeChar(CurPtr, SizeTmp, Result),
2830 tok::string_literal);
2831 }
2832
2833 // treat R like the start of an identifier.
2834 return LexIdentifier(Result, CurPtr);
2835
Chris Lattner3a570772008-01-03 17:58:54 +00002836 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 // Notify MIOpt that we read a non-whitespace/non-comment token.
2838 MIOpt.ReadToken();
2839 Char = getCharAndSize(CurPtr, SizeTmp);
2840
2841 // Wide string literal.
2842 if (Char == '"')
2843 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002844 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002845
Craig Topper2fa4e862011-08-11 04:06:15 +00002846 // Wide raw string literal.
Richard Smith80ad52f2013-01-02 11:42:31 +00002847 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002848 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2849 return LexRawStringLiteral(Result,
2850 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2851 SizeTmp2, Result),
2852 tok::wide_string_literal);
2853
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 // Wide character constant.
2855 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002856 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2857 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 // C99 6.4.2: Identifiers.
2861 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2862 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002863 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2865 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2866 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002867 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 case 'v': case 'w': case 'x': case 'y': case 'z':
2869 case '_':
2870 // Notify MIOpt that we read a non-whitespace/non-comment token.
2871 MIOpt.ReadToken();
2872 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002873
2874 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002875 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002876 if (!isLexingRawMode())
2877 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002878 // Notify MIOpt that we read a non-whitespace/non-comment token.
2879 MIOpt.ReadToken();
2880 return LexIdentifier(Result, CurPtr);
2881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Chris Lattner9e6293d2008-10-12 04:51:35 +00002883 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002884 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 // C99 6.4.4: Character Constants.
2887 case '\'':
2888 // Notify MIOpt that we read a non-whitespace/non-comment token.
2889 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002890 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002891
2892 // C99 6.4.5: String Literals.
2893 case '"':
2894 // Notify MIOpt that we read a non-whitespace/non-comment token.
2895 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002896 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002897
2898 // C99 6.4.6: Punctuators.
2899 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002900 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002901 break;
2902 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002903 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002904 break;
2905 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002906 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002907 break;
2908 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002909 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 break;
2911 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002912 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 break;
2914 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002915 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 break;
2917 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002918 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 break;
2920 case '.':
2921 Char = getCharAndSize(CurPtr, SizeTmp);
2922 if (Char >= '0' && Char <= '9') {
2923 // Notify MIOpt that we read a non-whitespace/non-comment token.
2924 MIOpt.ReadToken();
2925
2926 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00002927 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002928 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 CurPtr += SizeTmp;
2930 } else if (Char == '.' &&
2931 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002932 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2934 SizeTmp2, Result);
2935 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002936 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 }
2938 break;
2939 case '&':
2940 Char = getCharAndSize(CurPtr, SizeTmp);
2941 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002942 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002943 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2944 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002945 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2947 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002948 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002949 }
2950 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002951 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002953 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2955 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002956 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 }
2958 break;
2959 case '+':
2960 Char = getCharAndSize(CurPtr, SizeTmp);
2961 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002963 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002966 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002967 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002968 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 }
2970 break;
2971 case '-':
2972 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002973 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002974 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002975 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00002976 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002977 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002978 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2979 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002980 Kind = tok::arrowstar;
2981 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002983 Kind = tok::arrow;
2984 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002986 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002988 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 }
2990 break;
2991 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002992 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 break;
2994 case '!':
2995 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002996 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2998 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002999 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 }
3001 break;
3002 case '/':
3003 // 6.4.9: Comments
3004 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00003005 if (Char == '/') { // Line comment.
3006 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00003007 // want to lex this as a comment. There is one problem with this though,
3008 // that in one particular corner case, this can change the behavior of the
3009 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003010 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003011 // "foo". Check to see if the character after the second slash is a '*'.
3012 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003013 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00003014 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003015 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003016 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00003017 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003018 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Chris Lattner8402c732009-01-16 22:39:25 +00003020 // It is common for the tokens immediately after a // comment to be
3021 // whitespace (indentation for the next line). Instead of going through
3022 // the big switch, handle it efficiently now.
3023 goto SkipIgnoredUnits;
3024 }
3025 }
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Chris Lattner8402c732009-01-16 22:39:25 +00003027 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003029 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003030 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003031 }
Mike Stump1eb44332009-09-09 15:08:12 +00003032
Chris Lattner8402c732009-01-16 22:39:25 +00003033 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003035 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003037 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 }
3039 break;
3040 case '%':
3041 Char = getCharAndSize(CurPtr, SizeTmp);
3042 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003043 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003045 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003046 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003047 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003048 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003049 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3050 Char = getCharAndSize(CurPtr, SizeTmp);
3051 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003052 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003053 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3054 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003055 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003057 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003058 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003059 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003060 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003061 // We parsed a # character. If this occurs at the start of the line,
3062 // it's actually the start of a preprocessing directive. Callback to
3063 // the preprocessor to handle it.
3064 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003065 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3066 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Chris Lattnere91e9322009-03-18 20:58:27 +00003068 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 }
3070 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003071 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 }
3073 break;
3074 case '<':
3075 Char = getCharAndSize(CurPtr, SizeTmp);
3076 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003077 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003079 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3080 if (After == '=') {
3081 Kind = tok::lesslessequal;
3082 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3083 SizeTmp2, Result);
3084 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3085 // If this is actually a '<<<<<<<' version control conflict marker,
3086 // recognize it as such and recover nicely.
3087 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003088 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3089 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3090 // ignore it.
3091 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003092 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003093 Kind = tok::lesslessless;
3094 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3095 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003096 } else {
3097 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3098 Kind = tok::lessless;
3099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003102 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003103 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith80ad52f2013-01-02 11:42:31 +00003104 if (LangOpts.CPlusPlus11 &&
Richard Smith87a1e192011-04-14 18:36:27 +00003105 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3106 // C++0x [lex.pptoken]p3:
3107 // Otherwise, if the next three characters are <:: and the subsequent
3108 // character is neither : nor >, the < is treated as a preprocessor
3109 // token by itself and not as the first character of the alternative
3110 // token <:.
3111 unsigned SizeTmp3;
3112 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3113 if (After != ':' && After != '>') {
3114 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003115 if (!isLexingRawMode())
3116 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003117 break;
3118 }
3119 }
3120
Reid Spencer5f016e22007-07-11 17:01:13 +00003121 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003122 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003123 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003124 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003125 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003126 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003127 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003128 }
3129 break;
3130 case '>':
3131 Char = getCharAndSize(CurPtr, SizeTmp);
3132 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003134 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003135 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003136 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3137 if (After == '=') {
3138 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3139 SizeTmp2, Result);
3140 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003141 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3142 // If this is actually a '>>>>' conflict marker, recognize it as such
3143 // and recover nicely.
3144 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003145 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3146 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3147 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003148 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003149 Kind = tok::greatergreatergreater;
3150 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3151 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003152 } else {
3153 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3154 Kind = tok::greatergreater;
3155 }
3156
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003158 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003159 }
3160 break;
3161 case '^':
3162 Char = getCharAndSize(CurPtr, SizeTmp);
3163 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003164 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003165 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003167 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003168 }
3169 break;
3170 case '|':
3171 Char = getCharAndSize(CurPtr, SizeTmp);
3172 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003173 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003174 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3175 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003176 // If this is '|||||||' and we're in a conflict marker, ignore it.
3177 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3178 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003179 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003180 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3181 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003182 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003183 }
3184 break;
3185 case ':':
3186 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003187 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003188 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003190 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003191 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003192 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003193 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003194 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003195 }
3196 break;
3197 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003198 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003199 break;
3200 case '=':
3201 Char = getCharAndSize(CurPtr, SizeTmp);
3202 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003203 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003204 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3205 goto LexNextToken;
3206
Chris Lattner9e6293d2008-10-12 04:51:35 +00003207 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003208 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003209 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003210 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003211 }
3212 break;
3213 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003214 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 break;
3216 case '#':
3217 Char = getCharAndSize(CurPtr, SizeTmp);
3218 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003219 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003221 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003222 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003223 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003224 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003225 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3226 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003227 // We parsed a # character. If this occurs at the start of the line,
3228 // it's actually the start of a preprocessing directive. Callback to
3229 // the preprocessor to handle it.
3230 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003231 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3232 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Chris Lattnere91e9322009-03-18 20:58:27 +00003234 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003235 }
3236 break;
3237
Chris Lattner3a570772008-01-03 17:58:54 +00003238 case '@':
3239 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003240 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003241 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003242 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003243 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003244 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Reid Spencer5f016e22007-07-11 17:01:13 +00003246 case '\\':
3247 // FIXME: UCN's.
3248 // FALL THROUGH.
3249 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003250 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 break;
3252 }
Mike Stump1eb44332009-09-09 15:08:12 +00003253
Reid Spencer5f016e22007-07-11 17:01:13 +00003254 // Notify MIOpt that we read a non-whitespace/non-comment token.
3255 MIOpt.ReadToken();
3256
3257 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003258 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003259 return;
3260
3261HandleDirective:
3262 // We parsed a # character and it's the start of a preprocessing directive.
3263
3264 FormTokenWithChars(Result, CurPtr, tok::hash);
3265 PP->HandleDirective(Result);
3266
3267 // As an optimization, if the preprocessor didn't switch lexers, tail
3268 // recurse.
3269 if (PP->isCurrentLexer(this)) {
3270 // Start a new token. If this is a #include or something, the PP may
3271 // want us starting at the beginning of the line again. If so, set
3272 // the StartOfLine flag and clear LeadingSpace.
3273 if (IsAtStartOfLine) {
3274 Result.setFlag(Token::StartOfLine);
3275 Result.clearFlag(Token::LeadingSpace);
3276 IsAtStartOfLine = false;
3277 }
3278 goto LexNextToken; // GCC isn't tail call eliminating.
3279 }
3280 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003281}