blob: 12cb76722bf7e4fc0618d72b32eb9372b211a3f6 [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"
28#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor55817af2010-08-25 17:04:25 +000030#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000032#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/Support/MemoryBuffer.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000035#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Chris Lattnera2bf1052009-12-17 05:29:40 +000038static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000039
Chris Lattnerdbf388b2007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump1eb44332009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000046 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
48 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000049}
50
51/// getObjCKeywordID - Return the ObjC keyword kind.
52tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55}
56
Chris Lattner53702cd2007-12-13 01:59:49 +000057
Chris Lattnerdbf388b2007-10-07 08:47:24 +000058//===----------------------------------------------------------------------===//
59// Lexer Class Implementation
60//===----------------------------------------------------------------------===//
61
David Blaikie99ba9e32011-12-20 02:48:34 +000062void Lexer::anchor() { }
63
Mike Stump1eb44332009-09-09 15:08:12 +000064void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000065 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000066 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner22d91ca2009-01-17 06:55:17 +000068 BufferStart = BufStart;
69 BufferPtr = BufPtr;
70 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner22d91ca2009-01-17 06:55:17 +000072 assert(BufEnd[0] == 0 &&
73 "We assume that the input buffer has a null character at the end"
74 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000075
Eric Christopher156119d2011-04-09 00:01:04 +000076 // Check whether we have a BOM in the beginning of the buffer. If yes - act
77 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
78 // skip the UTF-8 BOM if it's present.
79 if (BufferStart == BufferPtr) {
80 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000081 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000082 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000083 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
84 .Default(0);
85
86 // Skip the BOM.
87 BufferPtr += BOMLength;
88 }
89
Chris Lattner22d91ca2009-01-17 06:55:17 +000090 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000091 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000092
Chris Lattner22d91ca2009-01-17 06:55:17 +000093 // Start of the file is a start of line.
94 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner22d91ca2009-01-17 06:55:17 +000096 // We are not after parsing a #.
97 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner22d91ca2009-01-17 06:55:17 +000099 // We are not after parsing #include.
100 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner22d91ca2009-01-17 06:55:17 +0000102 // We are not in raw mode. Raw mode disables diagnostics and interpretation
103 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
104 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
105 // or otherwise skipping over tokens.
106 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattner22d91ca2009-01-17 06:55:17 +0000108 // Default to not keeping comments.
109 ExtendedTokenMode = 0;
110}
111
Chris Lattner0770dab2009-01-17 07:56:59 +0000112/// Lexer constructor - Create a new lexer object for the specified buffer
113/// with the specified preprocessor managing the lexing process. This lexer
114/// assumes that the associated file buffer and Preprocessor objects will
115/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000116Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000117 : PreprocessorLexer(&PP, FID),
118 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
119 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner0770dab2009-01-17 07:56:59 +0000121 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
122 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Chris Lattner0770dab2009-01-17 07:56:59 +0000124 // Default to keeping comments if the preprocessor wants them.
125 SetCommentRetentionState(PP.getCommentRetentionState());
126}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000127
Chris Lattner168ae2d2007-10-17 20:41:00 +0000128/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000129/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
130/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000131Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000132 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000133 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000134
Chris Lattner22d91ca2009-01-17 06:55:17 +0000135 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner168ae2d2007-10-17 20:41:00 +0000137 // We *are* in raw mode.
138 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000139}
140
Chris Lattner025c3a62009-01-17 07:35:14 +0000141/// Lexer constructor - Create a new raw lexer object. This object is only
142/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
143/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000144Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
145 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000146 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000147
Mike Stump1eb44332009-09-09 15:08:12 +0000148 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000149 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattner025c3a62009-01-17 07:35:14 +0000151 // We *are* in raw mode.
152 LexingRawMode = true;
153}
154
Chris Lattner42e00d12009-01-17 08:27:52 +0000155/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
156/// _Pragma expansion. This has a variety of magic semantics that this method
157/// sets up. It returns a new'd Lexer that must be delete'd when done.
158///
159/// On entrance to this routine, TokStartLoc is a macro location which has a
160/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000161/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000162/// "expanded from".
163///
164/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
165/// normal lexer that remaps tokens as they fly by. This would require making
166/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
167/// interface that could handle this stuff. This would pull GetMappedTokenLoc
168/// out of the critical path of the lexer!
169///
Mike Stump1eb44332009-09-09 15:08:12 +0000170Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000171 SourceLocation ExpansionLocStart,
172 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000173 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000174 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000175
176 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000177 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000178 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
179 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner42e00d12009-01-17 08:27:52 +0000181 // Now that the lexer is created, change the start/end locations so that we
182 // just lex the subsection of the file that we want. This is lexing from a
183 // scratch buffer.
184 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner42e00d12009-01-17 08:27:52 +0000186 L->BufferPtr = StrData;
187 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000188 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000189
190 // Set the SourceLocation with the remapping information. This ensures that
191 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000192 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
193 ExpansionLocStart,
194 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner42e00d12009-01-17 08:27:52 +0000196 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000197 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000198 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattner42e00d12009-01-17 08:27:52 +0000200 // This lexer really is for _Pragma.
201 L->Is_PragmaLexer = true;
202 return L;
203}
204
Chris Lattner168ae2d2007-10-17 20:41:00 +0000205
Reid Spencer5f016e22007-07-11 17:01:13 +0000206/// Stringify - Convert the specified string into a C string, with surrounding
207/// ""'s, and with escaped \ and " characters.
208std::string Lexer::Stringify(const std::string &Str, bool Charify) {
209 std::string Result = Str;
210 char Quote = Charify ? '\'' : '"';
211 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
212 if (Result[i] == '\\' || Result[i] == Quote) {
213 Result.insert(Result.begin()+i, '\\');
214 ++i; ++e;
215 }
216 }
217 return Result;
218}
219
Chris Lattnerd8e30832007-07-24 06:57:14 +0000220/// Stringify - Convert the specified string into a C string by escaping '\'
221/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000222void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000223 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
224 if (Str[i] == '\\' || Str[i] == '"') {
225 Str.insert(Str.begin()+i, '\\');
226 ++i; ++e;
227 }
228 }
229}
230
Chris Lattnerb0607272010-11-17 07:26:20 +0000231//===----------------------------------------------------------------------===//
232// Token Spelling
233//===----------------------------------------------------------------------===//
234
235/// getSpelling() - Return the 'spelling' of this token. The spelling of a
236/// token are the characters used to represent the token in the source file
237/// after trigraph expansion and escaped-newline folding. In particular, this
238/// wants to get the true, uncanonicalized, spelling of things like digraphs
239/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000240StringRef Lexer::getSpelling(SourceLocation loc,
241 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000242 const SourceManager &SM,
243 const LangOptions &options,
244 bool *invalid) {
245 // Break down the source location.
246 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
247
248 // Try to the load the file buffer.
249 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000250 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000251 if (invalidTemp) {
252 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000253 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000254 }
255
256 const char *tokenBegin = file.data() + locInfo.second;
257
258 // Lex from the start of the given location.
259 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
260 file.begin(), tokenBegin, file.end());
261 Token token;
262 lexer.LexFromRawLexer(token);
263
264 unsigned length = token.getLength();
265
266 // Common case: no need for cleaning.
267 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000268 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000269
270 // Hard case, we need to relex the characters into the string.
271 buffer.clear();
272 buffer.reserve(length);
273
274 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
275 unsigned charSize;
276 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
277 ti += charSize;
278 }
279
Chris Lattner5f9e2722011-07-23 10:55:15 +0000280 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000281}
282
283/// getSpelling() - Return the 'spelling' of this token. The spelling of a
284/// token are the characters used to represent the token in the source file
285/// after trigraph expansion and escaped-newline folding. In particular, this
286/// wants to get the true, uncanonicalized, spelling of things like digraphs
287/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000288std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
289 const LangOptions &Features, bool *Invalid) {
290 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
291
292 // If this token contains nothing interesting, return it directly.
293 bool CharDataInvalid = false;
294 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
295 &CharDataInvalid);
296 if (Invalid)
297 *Invalid = CharDataInvalid;
298 if (CharDataInvalid)
299 return std::string();
300
301 if (!Tok.needsCleaning())
302 return std::string(TokStart, TokStart+Tok.getLength());
303
304 std::string Result;
305 Result.reserve(Tok.getLength());
306
307 // Otherwise, hard case, relex the characters into the string.
308 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
309 Ptr != End; ) {
310 unsigned CharSize;
311 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
312 Ptr += CharSize;
313 }
314 assert(Result.size() != unsigned(Tok.getLength()) &&
315 "NeedsCleaning flag set on something that didn't need cleaning!");
316 return Result;
317}
318
319/// getSpelling - This method is used to get the spelling of a token into a
320/// preallocated buffer, instead of as an std::string. The caller is required
321/// to allocate enough space for the token, which is guaranteed to be at least
322/// Tok.getLength() bytes long. The actual length of the token is returned.
323///
324/// Note that this method may do two possible things: it may either fill in
325/// the buffer specified with characters, or it may *change the input pointer*
326/// to point to a constant buffer with the data already in it (avoiding a
327/// copy). The caller is not allowed to modify the returned buffer pointer
328/// if an internal buffer is returned.
329unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
330 const SourceManager &SourceMgr,
331 const LangOptions &Features, bool *Invalid) {
332 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000333
334 const char *TokStart = 0;
335 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
336 if (Tok.is(tok::raw_identifier))
337 TokStart = Tok.getRawIdentifierData();
338 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
339 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000340 Buffer = II->getNameStart();
341 return II->getLength();
342 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000343
344 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000345 if (Tok.isLiteral())
346 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000347
Chris Lattnerb0607272010-11-17 07:26:20 +0000348 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000349 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000350 bool CharDataInvalid = false;
351 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
352 if (Invalid)
353 *Invalid = CharDataInvalid;
354 if (CharDataInvalid) {
355 Buffer = "";
356 return 0;
357 }
358 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000359
Chris Lattnerb0607272010-11-17 07:26:20 +0000360 // If this token contains nothing interesting, return it directly.
361 if (!Tok.needsCleaning()) {
362 Buffer = TokStart;
363 return Tok.getLength();
364 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000365
Chris Lattnerb0607272010-11-17 07:26:20 +0000366 // Otherwise, hard case, relex the characters into the string.
367 char *OutBuf = const_cast<char*>(Buffer);
368 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
369 Ptr != End; ) {
370 unsigned CharSize;
371 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
372 Ptr += CharSize;
373 }
374 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
375 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000376
Chris Lattnerb0607272010-11-17 07:26:20 +0000377 return OutBuf-Buffer;
378}
379
380
381
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000382static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Chris Lattner9a611942007-10-17 21:18:47 +0000384/// MeasureTokenLength - Relex the token at the specified location and return
385/// its length in bytes in the input file. If the token needs cleaning (e.g.
386/// includes a trigraph or an escaped newline) then this count includes bytes
387/// that are part of that.
388unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000389 const SourceManager &SM,
390 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000391 // TODO: this could be special cased for common tokens like identifiers, ')',
392 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000393 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000394 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
395 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000396
397 // If this comes from a macro expansion, we really do want the macro name, not
398 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000399 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000400 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000401 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000402 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000403 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000404 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000405
406 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408 if (isWhitespace(StrData[0]))
409 return 0;
410
Chris Lattner9a611942007-10-17 21:18:47 +0000411 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000412 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
413 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000414 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000415 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000416 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000417 return TheTok.getLength();
418}
419
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000420static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
423 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000424 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000425 if (LocInfo.first.isInvalid())
426 return Loc;
427
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000428 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000430 if (Invalid)
431 return Loc;
432
433 // Back up from the current location until we hit the beginning of a line
434 // (or the buffer). We'll relex from that point.
435 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000436 if (LocInfo.second >= Buffer.size())
437 return Loc;
438
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000439 const char *StrData = BufStart+LocInfo.second;
440 if (StrData[0] == '\n' || StrData[0] == '\r')
441 return Loc;
442
443 const char *LexStart = StrData;
444 while (LexStart != BufStart) {
445 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
446 ++LexStart;
447 break;
448 }
449
450 --LexStart;
451 }
452
453 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000454 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000455 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
456 TheLexer.SetCommentRetentionState(true);
457
458 // Lex tokens until we find the token that contains the source location.
459 Token TheTok;
460 do {
461 TheLexer.LexFromRawLexer(TheTok);
462
463 if (TheLexer.getBufferLocation() > StrData) {
464 // Lexing this token has taken the lexer past the source location we're
465 // looking for. If the current token encompasses our source location,
466 // return the beginning of that token.
467 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
468 return TheTok.getLocation();
469
470 // We ended up skipping over the source location entirely, which means
471 // that it points into whitespace. We're done here.
472 break;
473 }
474 } while (TheTok.getKind() != tok::eof);
475
476 // We've passed our source location; just return the original source location.
477 return Loc;
478}
479
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000480SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
481 const SourceManager &SM,
482 const LangOptions &LangOpts) {
483 if (Loc.isFileID())
484 return getBeginningOfFileToken(Loc, SM, LangOpts);
485
486 if (!SM.isMacroArgExpansion(Loc))
487 return Loc;
488
489 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
490 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
491 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000492 std::pair<FileID, unsigned> BeginFileLocInfo
493 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000494 assert(FileLocInfo.first == BeginFileLocInfo.first &&
495 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000496 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000497}
498
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000499namespace {
500 enum PreambleDirectiveKind {
501 PDK_Skipped,
502 PDK_StartIf,
503 PDK_EndIf,
504 PDK_Unknown
505 };
506}
507
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000508std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000509Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
510 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000511 // Create a lexer starting at the beginning of the file. Note that we use a
512 // "fake" file source location at offset 1 so that the lexer will track our
513 // position within the file.
514 const unsigned StartOffset = 1;
515 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000516 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000517 Buffer->getBufferStart(), Buffer->getBufferEnd());
518
519 bool InPreprocessorDirective = false;
520 Token TheTok;
521 Token IfStartTok;
522 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000523
524 unsigned MaxLineOffset = 0;
525 if (MaxLines) {
526 const char *CurPtr = Buffer->getBufferStart();
527 unsigned CurLine = 0;
528 while (CurPtr != Buffer->getBufferEnd()) {
529 char ch = *CurPtr++;
530 if (ch == '\n') {
531 ++CurLine;
532 if (CurLine == MaxLines)
533 break;
534 }
535 }
536 if (CurPtr != Buffer->getBufferEnd())
537 MaxLineOffset = CurPtr - Buffer->getBufferStart();
538 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000539
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000540 do {
541 TheLexer.LexFromRawLexer(TheTok);
542
543 if (InPreprocessorDirective) {
544 // If we've hit the end of the file, we're done.
545 if (TheTok.getKind() == tok::eof) {
546 InPreprocessorDirective = false;
547 break;
548 }
549
550 // If we haven't hit the end of the preprocessor directive, skip this
551 // token.
552 if (!TheTok.isAtStartOfLine())
553 continue;
554
555 // We've passed the end of the preprocessor directive, and will look
556 // at this token again below.
557 InPreprocessorDirective = false;
558 }
559
Douglas Gregordf95a132010-08-09 20:45:32 +0000560 // Keep track of the # of lines in the preamble.
561 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000562 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000563
564 // If we were asked to limit the number of lines in the preamble,
565 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000566 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000567 break;
568 }
569
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000570 // Comments are okay; skip over them.
571 if (TheTok.getKind() == tok::comment)
572 continue;
573
574 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
575 // This is the start of a preprocessor directive.
576 Token HashTok = TheTok;
577 InPreprocessorDirective = true;
578
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000579 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000580 // we don't have an identifier table available. Instead, just look at
581 // the raw identifier to recognize and categorize preprocessor directives.
582 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000583 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000585 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000586 PreambleDirectiveKind PDK
587 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
588 .Case("include", PDK_Skipped)
589 .Case("__include_macros", PDK_Skipped)
590 .Case("define", PDK_Skipped)
591 .Case("undef", PDK_Skipped)
592 .Case("line", PDK_Skipped)
593 .Case("error", PDK_Skipped)
594 .Case("pragma", PDK_Skipped)
595 .Case("import", PDK_Skipped)
596 .Case("include_next", PDK_Skipped)
597 .Case("warning", PDK_Skipped)
598 .Case("ident", PDK_Skipped)
599 .Case("sccs", PDK_Skipped)
600 .Case("assert", PDK_Skipped)
601 .Case("unassert", PDK_Skipped)
602 .Case("if", PDK_StartIf)
603 .Case("ifdef", PDK_StartIf)
604 .Case("ifndef", PDK_StartIf)
605 .Case("elif", PDK_Skipped)
606 .Case("else", PDK_Skipped)
607 .Case("endif", PDK_EndIf)
608 .Default(PDK_Unknown);
609
610 switch (PDK) {
611 case PDK_Skipped:
612 continue;
613
614 case PDK_StartIf:
615 if (IfCount == 0)
616 IfStartTok = HashTok;
617
618 ++IfCount;
619 continue;
620
621 case PDK_EndIf:
622 // Mismatched #endif. The preamble ends here.
623 if (IfCount == 0)
624 break;
625
626 --IfCount;
627 continue;
628
629 case PDK_Unknown:
630 // We don't know what this directive is; stop at the '#'.
631 break;
632 }
633 }
634
635 // We only end up here if we didn't recognize the preprocessor
636 // directive or it was one that can't occur in the preamble at this
637 // point. Roll back the current token to the location of the '#'.
638 InPreprocessorDirective = false;
639 TheTok = HashTok;
640 }
641
Douglas Gregordf95a132010-08-09 20:45:32 +0000642 // We hit a token that we don't recognize as being in the
643 // "preprocessing only" part of the file, so we're no longer in
644 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000645 break;
646 } while (true);
647
648 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000649 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
650 IfCount? IfStartTok.isAtStartOfLine()
651 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000652}
653
Chris Lattner7ef5c272010-11-17 07:05:50 +0000654
655/// AdvanceToTokenCharacter - Given a location that specifies the start of a
656/// token, return a new location that specifies a character within the token.
657SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
658 unsigned CharNo,
659 const SourceManager &SM,
660 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000661 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000662 // character is. This needs to take into consideration newlines and
663 // trigraphs.
664 bool Invalid = false;
665 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
666
667 // If they request the first char of the token, we're trivially done.
668 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
669 return TokStart;
670
671 unsigned PhysOffset = 0;
672
673 // The usual case is that tokens don't contain anything interesting. Skip
674 // over the uninteresting characters. If a token only consists of simple
675 // chars, this method is extremely fast.
676 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
677 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000678 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000679 ++TokPtr, --CharNo, ++PhysOffset;
680 }
681
682 // If we have a character that may be a trigraph or escaped newline, use a
683 // lexer to parse it correctly.
684 for (; CharNo; --CharNo) {
685 unsigned Size;
686 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
687 TokPtr += Size;
688 PhysOffset += Size;
689 }
690
691 // Final detail: if we end up on an escaped newline, we want to return the
692 // location of the actual byte of the token. For example foo\<newline>bar
693 // advanced by 3 should return the location of b, not of \\. One compounding
694 // detail of this is that the escape may be made by a trigraph.
695 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
696 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
697
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000698 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000699}
700
701/// \brief Computes the source location just past the end of the
702/// token at this source location.
703///
704/// This routine can be used to produce a source location that
705/// points just past the end of the token referenced by \p Loc, and
706/// is generally used when a diagnostic needs to point just after a
707/// token where it expected something different that it received. If
708/// the returned source location would not be meaningful (e.g., if
709/// it points into a macro), this routine returns an invalid
710/// source location.
711///
712/// \param Offset an offset from the end of the token, where the source
713/// location should refer to. The default offset (0) produces a source
714/// location pointing just past the end of the token; an offset of 1 produces
715/// a source location pointing to the last character in the token, etc.
716SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
717 const SourceManager &SM,
718 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000719 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000720 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000721
722 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000723 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000724 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000725 }
726
Chris Lattner7ef5c272010-11-17 07:05:50 +0000727 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
728 if (Len > Offset)
729 Len = Len - Offset;
730 else
731 return Loc;
732
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000733 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000734}
735
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000736/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000737/// token of the macro expansion.
738bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000739 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000740 const LangOptions &LangOpts,
741 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000742 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
743
744 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
745 // FIXME: If the token comes from the macro token paste operator ('##')
746 // this function will always return false;
747 if (infoLoc.second > 0)
748 return false; // Does not point at the start of token.
749
Chandler Carruth433db062011-07-14 08:20:40 +0000750 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000751 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000752 if (expansionLoc.isFileID()) {
753 // No other macro expansions, this is the first.
754 if (MacroBegin)
755 *MacroBegin = expansionLoc;
756 return true;
757 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000758
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000759 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000760}
761
762/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000763/// token of the macro expansion.
764bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000765 const SourceManager &SM,
766 const LangOptions &LangOpts,
767 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000768 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
769
770 SourceLocation spellLoc = SM.getSpellingLoc(loc);
771 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
772 if (tokLen == 0)
773 return false;
774
775 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000776 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000777 if (SM.isInFileID(afterLoc, FID))
778 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000779
780 // FIXME: If the token comes from the macro token paste operator ('##')
781 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000782
Chandler Carruth433db062011-07-14 08:20:40 +0000783 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000784 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000785 if (expansionLoc.isFileID()) {
786 // No other macro expansions.
787 if (MacroEnd)
788 *MacroEnd = expansionLoc;
789 return true;
790 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000791
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000792 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000793}
794
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000795/// \brief Accepts a token source range and returns a character range with
796/// file locations.
797/// Returns a null range if a part of the range resides inside a macro
798/// expansion or the range does not reside on the same FileID.
799CharSourceRange Lexer::makeFileCharRange(SourceRange TokenRange,
800 const SourceManager &SM,
801 const LangOptions &LangOpts) {
802 SourceLocation Begin = TokenRange.getBegin();
803 if (Begin.isInvalid())
804 return CharSourceRange();
805
806 if (Begin.isMacroID())
807 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
808 return CharSourceRange();
809
810 SourceLocation End = getLocForEndOfToken(TokenRange.getEnd(), 0, SM,LangOpts);
811 if (End.isInvalid())
812 return CharSourceRange();
813
814 // Break down the source locations.
815 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000816 if (beginInfo.first.isInvalid())
817 return CharSourceRange();
818
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000819 unsigned EndOffs;
820 if (!SM.isInFileID(End, beginInfo.first, &EndOffs) ||
821 beginInfo.second > EndOffs)
822 return CharSourceRange();
823
824 return CharSourceRange::getCharRange(Begin, End);
825}
826
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000827StringRef Lexer::getSourceText(CharSourceRange Range,
828 const SourceManager &SM,
829 const LangOptions &LangOpts,
830 bool *Invalid) {
831 if (Range.isTokenRange())
832 Range = makeFileCharRange(Range.getAsRange(), SM, LangOpts);
833
834 if (Range.isInvalid() ||
835 Range.getBegin().isMacroID() || Range.getEnd().isMacroID()) {
836 if (Invalid) *Invalid = true;
837 return StringRef();
838 }
839
840 // Break down the source location.
841 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
842 if (beginInfo.first.isInvalid()) {
843 if (Invalid) *Invalid = true;
844 return StringRef();
845 }
846
847 unsigned EndOffs;
848 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
849 beginInfo.second > EndOffs) {
850 if (Invalid) *Invalid = true;
851 return StringRef();
852 }
853
854 // Try to the load the file buffer.
855 bool invalidTemp = false;
856 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
857 if (invalidTemp) {
858 if (Invalid) *Invalid = true;
859 return StringRef();
860 }
861
862 if (Invalid) *Invalid = false;
863 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
864}
865
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000866StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
867 const SourceManager &SM,
868 const LangOptions &LangOpts) {
869 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
870 // Walk past macro argument expanions.
871 while (SM.isMacroArgExpansion(Loc))
872 Loc = SM.getImmediateExpansionRange(Loc).first;
873
874 // Find the spelling location of the start of the non-argument expansion
875 // range. This is where the macro name was spelled in order to begin
876 // expanding this macro.
877 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
878
879 // Dig out the buffer where the macro name was spelled and the extents of the
880 // name so that we can render it into the expansion note.
881 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
882 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
883 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
884 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
885}
886
Reid Spencer5f016e22007-07-11 17:01:13 +0000887//===----------------------------------------------------------------------===//
888// Character information.
889//===----------------------------------------------------------------------===//
890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891enum {
892 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
893 CHAR_VERT_WS = 0x02, // '\r', '\n'
894 CHAR_LETTER = 0x04, // a-z,A-Z
895 CHAR_NUMBER = 0x08, // 0-9
896 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000897 CHAR_PERIOD = 0x20, // .
898 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000899};
900
Chris Lattner03b98662009-07-07 17:09:54 +0000901// Statically initialize CharInfo table based on ASCII character set
902// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000903static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000904{
905// 0 NUL 1 SOH 2 STX 3 ETX
906// 4 EOT 5 ENQ 6 ACK 7 BEL
907 0 , 0 , 0 , 0 ,
908 0 , 0 , 0 , 0 ,
909// 8 BS 9 HT 10 NL 11 VT
910//12 NP 13 CR 14 SO 15 SI
911 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
912 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
913//16 DLE 17 DC1 18 DC2 19 DC3
914//20 DC4 21 NAK 22 SYN 23 ETB
915 0 , 0 , 0 , 0 ,
916 0 , 0 , 0 , 0 ,
917//24 CAN 25 EM 26 SUB 27 ESC
918//28 FS 29 GS 30 RS 31 US
919 0 , 0 , 0 , 0 ,
920 0 , 0 , 0 , 0 ,
921//32 SP 33 ! 34 " 35 #
922//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000923 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
924 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000925//40 ( 41 ) 42 * 43 +
926//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000927 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
928 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000929//48 0 49 1 50 2 51 3
930//52 4 53 5 54 6 55 7
931 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
932 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
933//56 8 57 9 58 : 59 ;
934//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000935 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
936 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000937//64 @ 65 A 66 B 67 C
938//68 D 69 E 70 F 71 G
939 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
940 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
941//72 H 73 I 74 J 75 K
942//76 L 77 M 78 N 79 O
943 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
944 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
945//80 P 81 Q 82 R 83 S
946//84 T 85 U 86 V 87 W
947 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
948 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
949//88 X 89 Y 90 Z 91 [
950//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000951 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
952 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000953//96 ` 97 a 98 b 99 c
954//100 d 101 e 102 f 103 g
955 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
956 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
957//104 h 105 i 106 j 107 k
958//108 l 109 m 110 n 111 o
959 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
960 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
961//112 p 113 q 114 r 115 s
962//116 t 117 u 118 v 119 w
963 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
964 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
965//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000966//124 | 125 } 126 ~ 127 DEL
967 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
968 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000969};
970
Chris Lattnera2bf1052009-12-17 05:29:40 +0000971static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 static bool isInited = false;
973 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000974 // check the statically-initialized CharInfo table
975 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
976 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
977 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
978 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
979 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
980 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
981 assert(CHAR_UNDER == CharInfo[(int)'_']);
982 assert(CHAR_PERIOD == CharInfo[(int)'.']);
983 for (unsigned i = 'a'; i <= 'z'; ++i) {
984 assert(CHAR_LETTER == CharInfo[i]);
985 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
986 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000988 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000989
Chris Lattner03b98662009-07-07 17:09:54 +0000990 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000991}
992
Chris Lattner03b98662009-07-07 17:09:54 +0000993
Reid Spencer5f016e22007-07-11 17:01:13 +0000994/// isIdentifierBody - Return true if this is the body character of an
995/// identifier, which is [a-zA-Z0-9_].
996static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000997 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998}
999
1000/// isHorizontalWhitespace - Return true if this character is horizontal
1001/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
1002static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001003 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001004}
1005
Anna Zaksaca25bc2011-07-27 21:43:43 +00001006/// isVerticalWhitespace - Return true if this character is vertical
1007/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
1008static inline bool isVerticalWhitespace(unsigned char c) {
1009 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1010}
1011
Reid Spencer5f016e22007-07-11 17:01:13 +00001012/// isWhitespace - Return true if this character is horizontal or vertical
1013/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
1014/// for '\0'.
1015static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001016 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001017}
1018
1019/// isNumberBody - Return true if this is the body character of an
1020/// preprocessing number, which is [a-zA-Z0-9_.].
1021static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001022 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001023 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001024}
1025
Craig Topper2fa4e862011-08-11 04:06:15 +00001026/// isRawStringDelimBody - Return true if this is the body character of a
1027/// raw string delimiter.
1028static inline bool isRawStringDelimBody(unsigned char c) {
1029 return (CharInfo[c] &
1030 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1031 true : false;
1032}
1033
Reid Spencer5f016e22007-07-11 17:01:13 +00001034
1035//===----------------------------------------------------------------------===//
1036// Diagnostics forwarding code.
1037//===----------------------------------------------------------------------===//
1038
Chris Lattner409a0362007-07-22 18:38:25 +00001039/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001040/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001041/// This is currently only used for _Pragma implementation, so it is the slow
1042/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001043static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1044 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001045static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1046 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001047 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001048 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattner409a0362007-07-22 18:38:25 +00001050 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001051 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001052 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001053 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Chandler Carruth433db062011-07-14 08:20:40 +00001055 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001056 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001057 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001058 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Chris Lattnere7fb4842009-02-15 20:52:18 +00001060 // Figure out the expansion loc range, which is the range covered by the
1061 // original _Pragma(...) sequence.
1062 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001063 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Chandler Carruthbf340e42011-07-26 03:03:05 +00001065 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001066}
1067
Reid Spencer5f016e22007-07-11 17:01:13 +00001068/// getSourceLocation - Return a source location identifier for the specified
1069/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001070SourceLocation Lexer::getSourceLocation(const char *Loc,
1071 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001072 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001074
1075 // In the normal case, we're just lexing from a simple file buffer, return
1076 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001077 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001078 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001079 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Chris Lattner2b2453a2009-01-17 06:22:33 +00001081 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1082 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001083 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001084 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085}
1086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087/// Diag - Forwarding function for diagnostics. This translate a source
1088/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001089DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001090 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001091}
Reid Spencer5f016e22007-07-11 17:01:13 +00001092
1093//===----------------------------------------------------------------------===//
1094// Trigraph and Escaped Newline Handling Code.
1095//===----------------------------------------------------------------------===//
1096
1097/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1098/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1099static char GetTrigraphCharForLetter(char Letter) {
1100 switch (Letter) {
1101 default: return 0;
1102 case '=': return '#';
1103 case ')': return ']';
1104 case '(': return '[';
1105 case '!': return '|';
1106 case '\'': return '^';
1107 case '>': return '}';
1108 case '/': return '\\';
1109 case '<': return '{';
1110 case '-': return '~';
1111 }
1112}
1113
1114/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1115/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1116/// return the result character. Finally, emit a warning about trigraph use
1117/// whether trigraphs are enabled or not.
1118static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1119 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001120 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Chris Lattner3692b092008-11-18 07:59:24 +00001122 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001123 if (!L->isLexingRawMode())
1124 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001125 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Chris Lattner74d15df2008-11-22 02:02:22 +00001128 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001129 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 return Res;
1131}
1132
Chris Lattner24f0e482009-04-18 22:05:41 +00001133/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1134/// 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 +00001135/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001136unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1137 unsigned Size = 0;
1138 while (isWhitespace(Ptr[Size])) {
1139 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Chris Lattner24f0e482009-04-18 22:05:41 +00001141 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1142 continue;
1143
1144 // If this is a \r\n or \n\r, skip the other half.
1145 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1146 Ptr[Size-1] != Ptr[Size])
1147 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner24f0e482009-04-18 22:05:41 +00001149 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001150 }
1151
Chris Lattner24f0e482009-04-18 22:05:41 +00001152 // Not an escaped newline, must be a \t or something else.
1153 return 0;
1154}
1155
Chris Lattner03374952009-04-18 22:27:02 +00001156/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1157/// them), skip over them and return the first non-escaped-newline found,
1158/// otherwise return P.
1159const char *Lexer::SkipEscapedNewLines(const char *P) {
1160 while (1) {
1161 const char *AfterEscape;
1162 if (*P == '\\') {
1163 AfterEscape = P+1;
1164 } else if (*P == '?') {
1165 // If not a trigraph for escape, bail out.
1166 if (P[1] != '?' || P[2] != '/')
1167 return P;
1168 AfterEscape = P+3;
1169 } else {
1170 return P;
1171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Chris Lattner03374952009-04-18 22:27:02 +00001173 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1174 if (NewLineSize == 0) return P;
1175 P = AfterEscape+NewLineSize;
1176 }
1177}
1178
Anna Zaksaca25bc2011-07-27 21:43:43 +00001179/// \brief Checks that the given token is the first token that occurs after the
1180/// given location (this excludes comments and whitespace). Returns the location
1181/// immediately after the specified token. If the token is not found or the
1182/// location is inside a macro, the returned source location will be invalid.
1183SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1184 tok::TokenKind TKind,
1185 const SourceManager &SM,
1186 const LangOptions &LangOpts,
1187 bool SkipTrailingWhitespaceAndNewLine) {
1188 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001189 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001190 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001191 }
1192 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1193
1194 // Break down the source location.
1195 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1196
1197 // Try to load the file buffer.
1198 bool InvalidTemp = false;
1199 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1200 if (InvalidTemp)
1201 return SourceLocation();
1202
1203 const char *TokenBegin = File.data() + LocInfo.second;
1204
1205 // Lex from the start of the given location.
1206 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1207 TokenBegin, File.end());
1208 // Find the token.
1209 Token Tok;
1210 lexer.LexFromRawLexer(Tok);
1211 if (Tok.isNot(TKind))
1212 return SourceLocation();
1213 SourceLocation TokenLoc = Tok.getLocation();
1214
1215 // Calculate how much whitespace needs to be skipped if any.
1216 unsigned NumWhitespaceChars = 0;
1217 if (SkipTrailingWhitespaceAndNewLine) {
1218 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1219 Tok.getLength();
1220 unsigned char C = *TokenEnd;
1221 while (isHorizontalWhitespace(C)) {
1222 C = *(++TokenEnd);
1223 NumWhitespaceChars++;
1224 }
1225 if (isVerticalWhitespace(C))
1226 NumWhitespaceChars++;
1227 }
1228
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001229 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001230}
Chris Lattner24f0e482009-04-18 22:05:41 +00001231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1233/// get its size, and return it. This is tricky in several cases:
1234/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1235/// then either return the trigraph (skipping 3 chars) or the '?',
1236/// depending on whether trigraphs are enabled or not.
1237/// 2. If this is an escaped newline (potentially with whitespace between
1238/// the backslash and newline), implicitly skip the newline and return
1239/// the char after it.
1240/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1241///
1242/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1243/// know that we can accumulate into Size, and that we have already incremented
1244/// Ptr by Size bytes.
1245///
1246/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1247/// be updated to match.
1248///
1249char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001250 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 // If we have a slash, look for an escaped newline.
1252 if (Ptr[0] == '\\') {
1253 ++Size;
1254 ++Ptr;
1255Slash:
1256 // Common case, backslash-char where the char is not whitespace.
1257 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner5636a3b2009-06-23 05:15:06 +00001259 // See if we have optional whitespace characters between the slash and
1260 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001261 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1262 // Remember that this token needs to be cleaned.
1263 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001264
Chris Lattner24f0e482009-04-18 22:05:41 +00001265 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001266 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001267 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattner24f0e482009-04-18 22:05:41 +00001269 // Found backslash<whitespace><newline>. Parse the char after it.
1270 Size += EscapedNewLineSize;
1271 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001272
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001273 // If the char that we finally got was a \n, then we must have had
1274 // something like \<newline><newline>. We don't want to consume the
1275 // second newline.
1276 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1277 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001278
Chris Lattner24f0e482009-04-18 22:05:41 +00001279 // Use slow version to accumulate a correct size field.
1280 return getCharAndSizeSlow(Ptr, Size, Tok);
1281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // Otherwise, this is not an escaped newline, just return the slash.
1284 return '\\';
1285 }
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 // If this is a trigraph, process it.
1288 if (Ptr[0] == '?' && Ptr[1] == '?') {
1289 // If this is actually a legal trigraph (not something like "??x"), emit
1290 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1291 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1292 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001293 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001294
1295 Ptr += 3;
1296 Size += 3;
1297 if (C == '\\') goto Slash;
1298 return C;
1299 }
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 // If this is neither, return a single character.
1303 ++Size;
1304 return *Ptr;
1305}
1306
1307
1308/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1309/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1310/// and that we have already incremented Ptr by Size bytes.
1311///
1312/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1313/// be updated to match.
1314char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1315 const LangOptions &Features) {
1316 // If we have a slash, look for an escaped newline.
1317 if (Ptr[0] == '\\') {
1318 ++Size;
1319 ++Ptr;
1320Slash:
1321 // Common case, backslash-char where the char is not whitespace.
1322 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001325 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1326 // Found backslash<whitespace><newline>. Parse the char after it.
1327 Size += EscapedNewLineSize;
1328 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001330 // If the char that we finally got was a \n, then we must have had
1331 // something like \<newline><newline>. We don't want to consume the
1332 // second newline.
1333 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1334 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001335
Chris Lattner24f0e482009-04-18 22:05:41 +00001336 // Use slow version to accumulate a correct size field.
1337 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // Otherwise, this is not an escaped newline, just return the slash.
1341 return '\\';
1342 }
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 // If this is a trigraph, process it.
1345 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1346 // If this is actually a legal trigraph (not something like "??x"), return
1347 // it.
1348 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1349 Ptr += 3;
1350 Size += 3;
1351 if (C == '\\') goto Slash;
1352 return C;
1353 }
1354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // If this is neither, return a single character.
1357 ++Size;
1358 return *Ptr;
1359}
1360
1361//===----------------------------------------------------------------------===//
1362// Helper methods for lexing.
1363//===----------------------------------------------------------------------===//
1364
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001365/// \brief Routine that indiscriminately skips bytes in the source file.
1366void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1367 BufferPtr += Bytes;
1368 if (BufferPtr > BufferEnd)
1369 BufferPtr = BufferEnd;
1370 IsAtStartOfLine = StartOfLine;
1371}
1372
Chris Lattnerd2177732007-07-20 16:59:19 +00001373void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1375 unsigned Size;
1376 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001377 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001379
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 --CurPtr; // Back up over the skipped character.
1381
1382 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1383 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1384 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001385 //
1386 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1387 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1389FinishIdentifier:
1390 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001391 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1392 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // If we are in raw mode, return this identifier raw. There is no need to
1395 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001396 if (LexingRawMode)
1397 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001399 // Fill in Result.IdentifierInfo and update the token kind,
1400 // looking up the identifier in the identifier table.
1401 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 // Finally, now that we know we have an identifier, pass this off to the
1404 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001405 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001406 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001407
Chris Lattner6a170eb2009-01-21 07:43:11 +00001408 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 C = getCharAndSize(CurPtr, Size);
1414 while (1) {
1415 if (C == '$') {
1416 // If we hit a $ and they are not supported in identifiers, we are done.
1417 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001420 if (!isLexingRawMode())
1421 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 CurPtr = ConsumeChar(CurPtr, Size, Result);
1423 C = getCharAndSize(CurPtr, Size);
1424 continue;
1425 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1426 // Found end of identifier.
1427 goto FinishIdentifier;
1428 }
1429
1430 // Otherwise, this character is good, consume it.
1431 CurPtr = ConsumeChar(CurPtr, Size, Result);
1432
1433 C = getCharAndSize(CurPtr, Size);
1434 while (isIdentifierBody(C)) { // FIXME: UCNs.
1435 CurPtr = ConsumeChar(CurPtr, Size, Result);
1436 C = getCharAndSize(CurPtr, Size);
1437 }
1438 }
1439}
1440
Douglas Gregora75ec432010-08-30 14:50:47 +00001441/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001442/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001443static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1444 unsigned Size;
1445 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1446 if (C1 != '0')
1447 return false;
1448 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1449 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001450}
Reid Spencer5f016e22007-07-11 17:01:13 +00001451
Nate Begeman5253c7f2008-04-14 02:26:39 +00001452/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001453/// constant. From[-1] is the first character lexed. Return the end of the
1454/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001455void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 unsigned Size;
1457 char C = getCharAndSize(CurPtr, Size);
1458 char PrevCh = 0;
1459 while (isNumberBody(C)) { // FIXME: UCNs?
1460 CurPtr = ConsumeChar(CurPtr, Size, Result);
1461 PrevCh = C;
1462 C = getCharAndSize(CurPtr, Size);
1463 }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001466 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1467 // If we are in Microsoft mode, don't continue if the constant is hex.
1468 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Francois Pichet62ec1f22011-09-17 17:15:52 +00001469 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001470 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001472
1473 // If we have a hex FP constant, continue.
Douglas Gregor46717302011-10-12 18:51:02 +00001474 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001478 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001479 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001480 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001481}
1482
1483/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001484/// either " or L" or u8" or u" or U".
1485void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1486 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Richard Smith661a9962011-10-15 01:18:56 +00001489 if (!isLexingRawMode() &&
1490 (Kind == tok::utf8_string_literal ||
1491 Kind == tok::utf16_string_literal ||
1492 Kind == tok::utf32_string_literal))
1493 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 char C = getAndAdvanceChar(CurPtr, Result);
1496 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001497 // Skip escaped characters. Escaped newlines will already be processed by
1498 // getAndAdvanceChar.
1499 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001501
Chris Lattner571339c2010-05-30 23:27:38 +00001502 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001503 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001504 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001505 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001506 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 }
Chris Lattner571339c2010-05-30 23:27:38 +00001509
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001510 if (C == 0) {
1511 if (isCodeCompletionPoint(CurPtr-1)) {
1512 PP->CodeCompleteNaturalLanguage();
1513 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1514 return cutOffLexing();
1515 }
1516
Chris Lattner571339c2010-05-30 23:27:38 +00001517 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001518 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 C = getAndAdvanceChar(CurPtr, Result);
1520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001523 if (NulCharacter && !isLexingRawMode())
1524 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001527 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001528 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001529 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530}
1531
Craig Topper2fa4e862011-08-11 04:06:15 +00001532/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1533/// having lexed R", LR", u8R", uR", or UR".
1534void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1535 tok::TokenKind Kind) {
1536 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1537 // Between the initial and final double quote characters of the raw string,
1538 // any transformations performed in phases 1 and 2 (trigraphs,
1539 // universal-character-names, and line splicing) are reverted.
1540
Richard Smith661a9962011-10-15 01:18:56 +00001541 if (!isLexingRawMode())
1542 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1543
Craig Topper2fa4e862011-08-11 04:06:15 +00001544 unsigned PrefixLen = 0;
1545
1546 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1547 ++PrefixLen;
1548
1549 // If the last character was not a '(', then we didn't lex a valid delimiter.
1550 if (CurPtr[PrefixLen] != '(') {
1551 if (!isLexingRawMode()) {
1552 const char *PrefixEnd = &CurPtr[PrefixLen];
1553 if (PrefixLen == 16) {
1554 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1555 } else {
1556 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1557 << StringRef(PrefixEnd, 1);
1558 }
1559 }
1560
1561 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1562 // it's possible the '"' was intended to be part of the raw string, but
1563 // there's not much we can do about that.
1564 while (1) {
1565 char C = *CurPtr++;
1566
1567 if (C == '"')
1568 break;
1569 if (C == 0 && CurPtr-1 == BufferEnd) {
1570 --CurPtr;
1571 break;
1572 }
1573 }
1574
1575 FormTokenWithChars(Result, CurPtr, tok::unknown);
1576 return;
1577 }
1578
1579 // Save prefix and move CurPtr past it
1580 const char *Prefix = CurPtr;
1581 CurPtr += PrefixLen + 1; // skip over prefix and '('
1582
1583 while (1) {
1584 char C = *CurPtr++;
1585
1586 if (C == ')') {
1587 // Check for prefix match and closing quote.
1588 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1589 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1590 break;
1591 }
1592 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1593 if (!isLexingRawMode())
1594 Diag(BufferPtr, diag::err_unterminated_raw_string)
1595 << StringRef(Prefix, PrefixLen);
1596 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1597 return;
1598 }
1599 }
1600
1601 // Update the location of token as well as BufferPtr.
1602 const char *TokStart = BufferPtr;
1603 FormTokenWithChars(Result, CurPtr, Kind);
1604 Result.setLiteralData(TokStart);
1605}
1606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1608/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001609void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001611 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 char C = getAndAdvanceChar(CurPtr, Result);
1613 while (C != '>') {
1614 // Skip escaped characters.
1615 if (C == '\\') {
1616 // Skip the escaped character.
1617 C = getAndAdvanceChar(CurPtr, Result);
1618 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001619 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1620 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001621 // If the filename is unterminated, then it must just be a lone <
1622 // character. Return this as such.
1623 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 return;
1625 } else if (C == 0) {
1626 NulCharacter = CurPtr-1;
1627 }
1628 C = getAndAdvanceChar(CurPtr, Result);
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001632 if (NulCharacter && !isLexingRawMode())
1633 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001636 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001637 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001638 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001639}
1640
1641
1642/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001643/// lexed either ' or L' or u' or U'.
1644void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1645 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 const char *NulCharacter = 0; // Does this character contain the \0 character?
1647
Richard Smith661a9962011-10-15 01:18:56 +00001648 if (!isLexingRawMode() &&
1649 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1650 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1651
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 char C = getAndAdvanceChar(CurPtr, Result);
1653 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001654 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001655 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001656 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001658 }
1659
1660 while (C != '\'') {
1661 // Skip escaped characters.
1662 if (C == '\\') {
1663 // Skip the escaped character.
1664 // FIXME: UCN's
1665 C = getAndAdvanceChar(CurPtr, Result);
1666 } else if (C == '\n' || C == '\r' || // Newline.
1667 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001668 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001669 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001670 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1671 return;
1672 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001673 if (isCodeCompletionPoint(CurPtr-1)) {
1674 PP->CodeCompleteNaturalLanguage();
1675 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1676 return cutOffLexing();
1677 }
1678
Chris Lattnerd80f7862010-07-07 23:24:27 +00001679 NulCharacter = CurPtr-1;
1680 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 C = getAndAdvanceChar(CurPtr, Result);
1682 }
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Chris Lattnerd80f7862010-07-07 23:24:27 +00001684 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001685 if (NulCharacter && !isLexingRawMode())
1686 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001689 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001690 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001691 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001692}
1693
1694/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1695/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001696///
1697/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1698///
1699bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 // Whitespace - Skip it, then return the token after the whitespace.
1701 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1702 while (1) {
1703 // Skip horizontal whitespace very aggressively.
1704 while (isHorizontalWhitespace(Char))
1705 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001707 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 if (Char != '\n' && Char != '\r')
1709 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 if (ParsingPreprocessorDirective) {
1712 // End of preprocessor directive line, let LexTokenInternal handle this.
1713 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001714 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // ok, but handle newline.
1718 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001719 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001721 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 Char = *++CurPtr;
1723 }
1724
1725 // If this isn't immediately after a newline, there is leading space.
1726 char PrevChar = CurPtr[-1];
1727 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001728 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729
Chris Lattnerd88dc482008-10-12 04:05:48 +00001730 // If the client wants us to return whitespace, return it now.
1731 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001732 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001733 return true;
1734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001737 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001738}
1739
1740// SkipBCPLComment - We have just read the // characters from input. Skip until
1741// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001742/// BufferPtr and return.
1743///
1744/// If we're in KeepCommentMode or any CommentHandler has inserted
1745/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001746bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // If BCPL comments aren't explicitly enabled for this language, emit an
1748 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001749 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // Mark them enabled so we only emit one warning for this translation
1753 // unit.
1754 Features.BCPLComment = true;
1755 }
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 // Scan over the body of the comment. The common case, when scanning, is that
1758 // the comment contains normal ascii characters with nothing interesting in
1759 // them. As such, optimize for this case with the inner loop.
1760 char C;
1761 do {
1762 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 // Skip over characters in the fast loop.
1764 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 C != '\n' && C != '\r') // Newline or DOS-style newline.
1766 C = *++CurPtr;
1767
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001768 const char *NextLine = CurPtr;
1769 if (C != 0) {
1770 // We found a newline, see if it's escaped.
1771 const char *EscapePtr = CurPtr-1;
1772 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1773 --EscapePtr;
1774
1775 if (*EscapePtr == '\\') // Escaped newline.
1776 CurPtr = EscapePtr;
1777 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1778 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1779 CurPtr = EscapePtr-2;
1780 else
1781 break; // This is a newline, we're done.
1782
1783 C = *CurPtr;
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001787 // properly decode the character. Read it in raw mode to avoid emitting
1788 // diagnostics about things like trigraphs. If we see an escaped newline,
1789 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001791 bool OldRawMode = isLexingRawMode();
1792 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001794 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001795
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001796 // If we only read only one character, then no special handling is needed.
1797 // We're done and can skip forward to the newline.
1798 if (C != 0 && CurPtr == OldPtr+1) {
1799 CurPtr = NextLine;
1800 break;
1801 }
1802
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 // If we read multiple characters, and one of those characters was a \r or
1804 // \n, then we had an escaped newline within the comment. Emit diagnostic
1805 // unless the next line is also a // comment.
1806 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1807 for (; OldPtr != CurPtr; ++OldPtr)
1808 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1809 // Okay, we found a // comment that ends in a newline, if the next
1810 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001811 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001813 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 ++ForwardPtr;
1815 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1816 break;
1817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Chris Lattner74d15df2008-11-22 02:02:22 +00001819 if (!isLexingRawMode())
1820 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 break;
1822 }
1823 }
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Douglas Gregor55817af2010-08-25 17:04:25 +00001825 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001826 --CurPtr;
1827 break;
1828 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001829
1830 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1831 PP->CodeCompleteNaturalLanguage();
1832 cutOffLexing();
1833 return false;
1834 }
1835
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 } while (C != '\n' && C != '\r');
1837
Chris Lattner3d0ad582010-02-03 21:06:21 +00001838 // Found but did not consume the newline. Notify comment handlers about the
1839 // comment unless we're in a #if 0 block.
1840 if (PP && !isLexingRawMode() &&
1841 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1842 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001843 BufferPtr = CurPtr;
1844 return true; // A token has to be returned.
1845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001848 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 return SaveBCPLComment(Result, CurPtr);
1850
1851 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001852 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1854 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001855 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001859 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001860 // contribute to another token), it isn't needed for correctness. Note that
1861 // this is ok even in KeepWhitespaceMode, because we would have returned the
1862 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001866 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001868 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001870 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001871}
1872
1873/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1874/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001875bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001876 // If we're not in a preprocessor directive, just return the // comment
1877 // directly.
1878 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Chris Lattner9e6293d2008-10-12 04:51:35 +00001880 if (!ParsingPreprocessorDirective)
1881 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Chris Lattner9e6293d2008-10-12 04:51:35 +00001883 // If this BCPL-style comment is in a macro definition, transmogrify it into
1884 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001885 bool Invalid = false;
1886 std::string Spelling = PP->getSpelling(Result, &Invalid);
1887 if (Invalid)
1888 return true;
1889
Chris Lattner9e6293d2008-10-12 04:51:35 +00001890 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1891 Spelling[1] = '*'; // Change prefix to "/*".
1892 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Chris Lattner9e6293d2008-10-12 04:51:35 +00001894 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001895 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001896 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001897 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001898}
1899
1900/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1901/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001902/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001903static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 Lexer *L) {
1905 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 // Back up off the newline.
1908 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // If this is a two-character newline sequence, skip the other character.
1911 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1912 // \n\n or \r\r -> not escaped newline.
1913 if (CurPtr[0] == CurPtr[1])
1914 return false;
1915 // \n\r or \r\n -> skip the newline.
1916 --CurPtr;
1917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 // If we have horizontal whitespace, skip over it. We allow whitespace
1920 // between the slash and newline.
1921 bool HasSpace = false;
1922 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1923 --CurPtr;
1924 HasSpace = true;
1925 }
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 // If we have a slash, we know this is an escaped newline.
1928 if (*CurPtr == '\\') {
1929 if (CurPtr[-1] != '*') return false;
1930 } else {
1931 // It isn't a slash, is it the ?? / trigraph?
1932 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1933 CurPtr[-3] != '*')
1934 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 // This is the trigraph ending the comment. Emit a stern warning!
1937 CurPtr -= 2;
1938
1939 // If no trigraphs are enabled, warn that we ignored this trigraph and
1940 // ignore this * character.
1941 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001942 if (!L->isLexingRawMode())
1943 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 return false;
1945 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001946 if (!L->isLexingRawMode())
1947 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001951 if (!L->isLexingRawMode())
1952 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001955 if (HasSpace && !L->isLexingRawMode())
1956 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 return true;
1959}
1960
1961#ifdef __SSE2__
1962#include <emmintrin.h>
1963#elif __ALTIVEC__
1964#include <altivec.h>
1965#undef bool
1966#endif
1967
1968/// SkipBlockComment - We have just read the /* characters from input. Read
1969/// until we find the */ characters that terminate the comment. Note that we
1970/// don't bother decoding trigraphs or escaped newlines in block comments,
1971/// because they cannot cause the comment to end. The only thing that can
1972/// happen is the comment could end with an escaped newline between the */ end
1973/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001974///
Chris Lattner046c2272010-01-18 22:35:47 +00001975/// If we're in KeepCommentMode or any CommentHandler has inserted
1976/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001977bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001979 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 // optimization helps people who like to put a lot of * characters in their
1981 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001982
1983 // The first character we get with newlines and trigraphs skipped to handle
1984 // the degenerate /*/ case below correctly if the * has an escaped newline
1985 // after it.
1986 unsigned CharSize;
1987 unsigned char C = getCharAndSize(CurPtr, CharSize);
1988 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001990 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001991 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001992 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Chris Lattner31f0eca2008-10-12 04:19:49 +00001994 // KeepWhitespaceMode should return this broken comment as a token. Since
1995 // it isn't a well formed comment, just return it as an 'unknown' token.
1996 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001997 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001998 return true;
1999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Chris Lattner31f0eca2008-10-12 04:19:49 +00002001 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002002 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Chris Lattner8146b682007-07-21 23:43:37 +00002005 // Check to see if the first character after the '/*' is another /. If so,
2006 // then this slash does not end the block comment, it is part of it.
2007 if (C == '/')
2008 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 while (1) {
2011 // Skip over all non-interesting characters until we find end of buffer or a
2012 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002013 if (CurPtr + 24 < BufferEnd &&
2014 // If there is a code-completion point avoid the fast scan because it
2015 // doesn't check for '\0'.
2016 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 // While not aligned to a 16-byte boundary.
2018 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2019 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 if (C == '/') goto FoundSlash;
2022
2023#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002024 __m128i Slashes = _mm_set1_epi8('/');
2025 while (CurPtr+16 <= BufferEnd) {
2026 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
2027 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002028 // Adjust the pointer to point directly after the first slash. It's
2029 // not necessary to set C here, it will be overwritten at the end of
2030 // the outer loop.
2031 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002032 goto FoundSlash;
2033 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002035 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002036#elif __ALTIVEC__
2037 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002038 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 '/', '/', '/', '/', '/', '/', '/', '/'
2040 };
2041 while (CurPtr+16 <= BufferEnd &&
2042 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2043 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002044#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 // Scan for '/' quickly. Many block comments are very large.
2046 while (CurPtr[0] != '/' &&
2047 CurPtr[1] != '/' &&
2048 CurPtr[2] != '/' &&
2049 CurPtr[3] != '/' &&
2050 CurPtr+4 < BufferEnd) {
2051 CurPtr += 4;
2052 }
2053#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 // It has to be one of the bytes scanned, increment to it and read one.
2056 C = *CurPtr++;
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 // Loop to scan the remainder.
2060 while (C != '/' && C != '\0')
2061 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002064 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 if (CurPtr[-2] == '*') // We found the final */. We're done!
2066 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2069 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2070 // We found the final */, though it had an escaped newline between the
2071 // * and /. We're done!
2072 break;
2073 }
2074 }
2075 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2076 // If this is a /* inside of the comment, emit a warning. Don't do this
2077 // if this is a /*/, which will end the comment. This misses cases with
2078 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002079 if (!isLexingRawMode())
2080 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 }
2082 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002083 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002084 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // Note: the user probably forgot a */. We could continue immediately
2086 // after the /*, but this would involve lexing a lot of what really is the
2087 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002088 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Chris Lattner31f0eca2008-10-12 04:19:49 +00002090 // KeepWhitespaceMode should return this broken comment as a token. Since
2091 // it isn't a well formed comment, just return it as an 'unknown' token.
2092 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002093 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002094 return true;
2095 }
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Chris Lattner31f0eca2008-10-12 04:19:49 +00002097 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002098 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002099 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2100 PP->CodeCompleteNaturalLanguage();
2101 cutOffLexing();
2102 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 C = *CurPtr++;
2106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Chris Lattner3d0ad582010-02-03 21:06:21 +00002108 // Notify comment handlers about the comment unless we're in a #if 0 block.
2109 if (PP && !isLexingRawMode() &&
2110 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2111 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002112 BufferPtr = CurPtr;
2113 return true; // A token has to be returned.
2114 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002117 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002118 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002119 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
2121
2122 // It is common for the tokens immediately after a /**/ comment to be
2123 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002124 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2125 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002127 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002129 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 }
2131
2132 // Otherwise, just return so that the next character will be lexed as a token.
2133 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002134 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002135 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002136}
2137
2138//===----------------------------------------------------------------------===//
2139// Primary Lexing Entry Points
2140//===----------------------------------------------------------------------===//
2141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2143/// uninterpreted string. This switches the lexer out of directive mode.
2144std::string Lexer::ReadToEndOfLine() {
2145 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2146 "Must be in a preprocessing directive!");
2147 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002148 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002149
2150 // CurPtr - Cache BufferPtr in an automatic variable.
2151 const char *CurPtr = BufferPtr;
2152 while (1) {
2153 char Char = getAndAdvanceChar(CurPtr, Tmp);
2154 switch (Char) {
2155 default:
2156 Result += Char;
2157 break;
2158 case 0: // Null.
2159 // Found end of file?
2160 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002161 if (isCodeCompletionPoint(CurPtr-1)) {
2162 PP->CodeCompleteNaturalLanguage();
2163 cutOffLexing();
2164 return Result;
2165 }
2166
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 // Nope, normal character, continue.
2168 Result += Char;
2169 break;
2170 }
2171 // FALL THROUGH.
2172 case '\r':
2173 case '\n':
2174 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2175 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2176 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Peter Collingbourne84021552011-02-28 02:37:51 +00002178 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002180 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002181 if (PP)
2182 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002183 Lex(Tmp);
2184 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002185 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 // Finally, we're done, return the string we found.
2188 return Result;
2189 }
2190 }
2191}
2192
2193/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2194/// condition, reporting diagnostics and handling other edge cases as required.
2195/// This returns true if Result contains a token, false if PP.Lex should be
2196/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002197bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // If we hit the end of the file while parsing a preprocessor directive,
2199 // end the preprocessor directive first. The next token returned will
2200 // then be the end of file.
2201 if (ParsingPreprocessorDirective) {
2202 // Done parsing the "line".
2203 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002205 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002208 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002210 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002211
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 // If we are in raw mode, return this event as an EOF token. Let the caller
2213 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002214 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 Result.startToken();
2216 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002217 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 return true;
2219 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002220
Douglas Gregorf44e8542010-08-24 19:08:16 +00002221 // Issue diagnostics for unterminated #if and missing newline.
2222
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 // If we are in a #if directive, emit an error.
2224 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002225 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002226 PP->Diag(ConditionalStack.back().IfLoc,
2227 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 ConditionalStack.pop_back();
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002231 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2232 // a pedwarn.
2233 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002234 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002235 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 BufferPtr = CurPtr;
2238
2239 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002240 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002241}
2242
2243/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2244/// the specified lexer will return a tok::l_paren token, 0 if it is something
2245/// else and 2 if there are no more tokens in the buffer controlled by the
2246/// lexer.
2247unsigned Lexer::isNextPPTokenLParen() {
2248 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 // Switch to 'skipping' mode. This will ensure that we can lex a token
2251 // without emitting diagnostics, disables macro expansion, and will cause EOF
2252 // to return an EOF token instead of popping the include stack.
2253 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 // Save state that can be changed while lexing so that we can restore it.
2256 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002257 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Chris Lattnerd2177732007-07-20 16:59:19 +00002259 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 Tok.startToken();
2261 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 // Restore state that may have changed.
2264 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002265 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 // Restore the lexer back to non-skipping mode.
2268 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002270 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002272 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002273}
2274
Chris Lattner34f349d2009-12-14 06:16:57 +00002275/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002276static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2277 ConflictMarkerKind CMK) {
2278 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2279 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2280 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2281 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002282 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002283 // Must occur at start of line.
2284 if (RestOfBuffer[Pos-1] != '\r' &&
2285 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002286 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2287 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002288 continue;
2289 }
2290 return RestOfBuffer.data()+Pos;
2291 }
2292 return 0;
2293}
2294
2295/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2296/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2297/// and recover nicely. This returns true if it is a conflict marker and false
2298/// if not.
2299bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2300 // Only a conflict marker if it starts at the beginning of a line.
2301 if (CurPtr != BufferStart &&
2302 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2303 return false;
2304
Richard Smithd5e1d602011-10-12 00:37:51 +00002305 // Check to see if we have <<<<<<< or >>>>.
2306 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2307 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002308 return false;
2309
2310 // If we have a situation where we don't care about conflict markers, ignore
2311 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002312 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002313 return false;
2314
Richard Smithd5e1d602011-10-12 00:37:51 +00002315 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2316
2317 // Check to see if there is an ending marker somewhere in the buffer at the
2318 // start of a line to terminate this conflict marker.
2319 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002320 // We found a match. We are really in a conflict marker.
2321 // Diagnose this, and ignore to the end of line.
2322 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002323 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002324
2325 // Skip ahead to the end of line. We know this exists because the
2326 // end-of-conflict marker starts with \r or \n.
2327 while (*CurPtr != '\r' && *CurPtr != '\n') {
2328 assert(CurPtr != BufferEnd && "Didn't find end of line");
2329 ++CurPtr;
2330 }
2331 BufferPtr = CurPtr;
2332 return true;
2333 }
2334
2335 // No end of conflict marker found.
2336 return false;
2337}
2338
2339
Richard Smithd5e1d602011-10-12 00:37:51 +00002340/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2341/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2342/// is the end of a conflict marker. Handle it by ignoring up until the end of
2343/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002344bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2345 // Only a conflict marker if it starts at the beginning of a line.
2346 if (CurPtr != BufferStart &&
2347 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2348 return false;
2349
2350 // If we have a situation where we don't care about conflict markers, ignore
2351 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002352 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002353 return false;
2354
Richard Smithd5e1d602011-10-12 00:37:51 +00002355 // Check to see if we have the marker (4 characters in a row).
2356 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002357 if (CurPtr[i] != CurPtr[0])
2358 return false;
2359
2360 // If we do have it, search for the end of the conflict marker. This could
2361 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2362 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002363 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2364 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002365 CurPtr = End;
2366
2367 // Skip ahead to the end of line.
2368 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2369 ++CurPtr;
2370
2371 BufferPtr = CurPtr;
2372
2373 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002374 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002375 return true;
2376 }
2377
2378 return false;
2379}
2380
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002381bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2382 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002383 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002384 return Loc == PP->getCodeCompletionLoc();
2385 }
2386
2387 return false;
2388}
2389
Reid Spencer5f016e22007-07-11 17:01:13 +00002390
2391/// LexTokenInternal - This implements a simple C family lexer. It is an
2392/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002393/// has a null character at the end of the file. This returns a preprocessing
2394/// token, not a normal token, as such, it is an internal interface. It assumes
2395/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002396void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002397LexNextToken:
2398 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002399 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 // CurPtr - Cache BufferPtr in an automatic variable.
2403 const char *CurPtr = BufferPtr;
2404
2405 // Small amounts of horizontal whitespace is very common between tokens.
2406 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2407 ++CurPtr;
2408 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2409 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Chris Lattnerd88dc482008-10-12 04:05:48 +00002411 // If we are keeping whitespace and other tokens, just return what we just
2412 // skipped. The next lexer invocation will return the token after the
2413 // whitespace.
2414 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002415 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002416 return;
2417 }
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Reid Spencer5f016e22007-07-11 17:01:13 +00002419 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002420 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002421 }
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 // Read a character, advancing over it.
2426 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002427 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Reid Spencer5f016e22007-07-11 17:01:13 +00002429 switch (Char) {
2430 case 0: // Null.
2431 // Found end of file?
2432 if (CurPtr-1 == BufferEnd) {
2433 // Read the PP instance variable into an automatic variable, because
2434 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002435 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2437 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002438 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2439 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 }
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002442 // Check if we are performing code completion.
2443 if (isCodeCompletionPoint(CurPtr-1)) {
2444 // Return the code-completion token.
2445 Result.startToken();
2446 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2447 return;
2448 }
2449
Chris Lattner74d15df2008-11-22 02:02:22 +00002450 if (!isLexingRawMode())
2451 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002452 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002453 if (SkipWhitespace(Result, CurPtr))
2454 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002457
2458 case 26: // DOS & CP/M EOF: "^Z".
2459 // If we're in Microsoft extensions mode, treat this as end of file.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002460 if (Features.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002461 // Read the PP instance variable into an automatic variable, because
2462 // LexEndOfFile will often delete 'this'.
2463 Preprocessor *PPCache = PP;
2464 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2465 return; // Got a token to return.
2466 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2467 return PPCache->Lex(Result);
2468 }
2469 // If Microsoft extensions are disabled, this is just random garbage.
2470 Kind = tok::unknown;
2471 break;
2472
Reid Spencer5f016e22007-07-11 17:01:13 +00002473 case '\n':
2474 case '\r':
2475 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002476 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 if (ParsingPreprocessorDirective) {
2478 // Done parsing the "line".
2479 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002482 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 // Since we consumed a newline, we are back at the start of a line.
2485 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Peter Collingbourne84021552011-02-28 02:37:51 +00002487 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 break;
2489 }
2490 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002491 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002493 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Chris Lattnerd88dc482008-10-12 04:05:48 +00002495 if (SkipWhitespace(Result, CurPtr))
2496 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 goto LexNextToken; // GCC isn't tail call eliminating.
2498 case ' ':
2499 case '\t':
2500 case '\f':
2501 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002502 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002503 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002504 if (SkipWhitespace(Result, CurPtr))
2505 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002506
2507 SkipIgnoredUnits:
2508 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Chris Lattner8133cfc2007-07-22 06:29:05 +00002510 // If the next token is obviously a // or /* */ comment, skip it efficiently
2511 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002512 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002513 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002514 if (SkipBCPLComment(Result, CurPtr+2))
2515 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002516 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002517 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002518 if (SkipBlockComment(Result, CurPtr+2))
2519 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002520 goto SkipIgnoredUnits;
2521 } else if (isHorizontalWhitespace(*CurPtr)) {
2522 goto SkipHorizontalWhitespace;
2523 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002525
Chris Lattner3a570772008-01-03 17:58:54 +00002526 // C99 6.4.4.1: Integer Constants.
2527 // C99 6.4.4.2: Floating Constants.
2528 case '0': case '1': case '2': case '3': case '4':
2529 case '5': case '6': case '7': case '8': case '9':
2530 // Notify MIOpt that we read a non-whitespace/non-comment token.
2531 MIOpt.ReadToken();
2532 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Douglas Gregor5cee1192011-07-27 05:40:30 +00002534 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2535 // Notify MIOpt that we read a non-whitespace/non-comment token.
2536 MIOpt.ReadToken();
2537
2538 if (Features.CPlusPlus0x) {
2539 Char = getCharAndSize(CurPtr, SizeTmp);
2540
2541 // UTF-16 string literal
2542 if (Char == '"')
2543 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2544 tok::utf16_string_literal);
2545
2546 // UTF-16 character constant
2547 if (Char == '\'')
2548 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2549 tok::utf16_char_constant);
2550
Craig Topper2fa4e862011-08-11 04:06:15 +00002551 // UTF-16 raw string literal
2552 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2553 return LexRawStringLiteral(Result,
2554 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2555 SizeTmp2, Result),
2556 tok::utf16_string_literal);
2557
2558 if (Char == '8') {
2559 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2560
2561 // UTF-8 string literal
2562 if (Char2 == '"')
2563 return LexStringLiteral(Result,
2564 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2565 SizeTmp2, Result),
2566 tok::utf8_string_literal);
2567
2568 if (Char2 == 'R') {
2569 unsigned SizeTmp3;
2570 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2571 // UTF-8 raw string literal
2572 if (Char3 == '"') {
2573 return LexRawStringLiteral(Result,
2574 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2575 SizeTmp2, Result),
2576 SizeTmp3, Result),
2577 tok::utf8_string_literal);
2578 }
2579 }
2580 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002581 }
2582
2583 // treat u like the start of an identifier.
2584 return LexIdentifier(Result, CurPtr);
2585
2586 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2587 // Notify MIOpt that we read a non-whitespace/non-comment token.
2588 MIOpt.ReadToken();
2589
2590 if (Features.CPlusPlus0x) {
2591 Char = getCharAndSize(CurPtr, SizeTmp);
2592
2593 // UTF-32 string literal
2594 if (Char == '"')
2595 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2596 tok::utf32_string_literal);
2597
2598 // UTF-32 character constant
2599 if (Char == '\'')
2600 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2601 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002602
2603 // UTF-32 raw string literal
2604 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2605 return LexRawStringLiteral(Result,
2606 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2607 SizeTmp2, Result),
2608 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002609 }
2610
2611 // treat U like the start of an identifier.
2612 return LexIdentifier(Result, CurPtr);
2613
Craig Topper2fa4e862011-08-11 04:06:15 +00002614 case 'R': // Identifier or C++0x raw string literal
2615 // Notify MIOpt that we read a non-whitespace/non-comment token.
2616 MIOpt.ReadToken();
2617
2618 if (Features.CPlusPlus0x) {
2619 Char = getCharAndSize(CurPtr, SizeTmp);
2620
2621 if (Char == '"')
2622 return LexRawStringLiteral(Result,
2623 ConsumeChar(CurPtr, SizeTmp, Result),
2624 tok::string_literal);
2625 }
2626
2627 // treat R like the start of an identifier.
2628 return LexIdentifier(Result, CurPtr);
2629
Chris Lattner3a570772008-01-03 17:58:54 +00002630 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 // Notify MIOpt that we read a non-whitespace/non-comment token.
2632 MIOpt.ReadToken();
2633 Char = getCharAndSize(CurPtr, SizeTmp);
2634
2635 // Wide string literal.
2636 if (Char == '"')
2637 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002638 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002639
Craig Topper2fa4e862011-08-11 04:06:15 +00002640 // Wide raw string literal.
2641 if (Features.CPlusPlus0x && Char == 'R' &&
2642 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2643 return LexRawStringLiteral(Result,
2644 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2645 SizeTmp2, Result),
2646 tok::wide_string_literal);
2647
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 // Wide character constant.
2649 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002650 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2651 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 // C99 6.4.2: Identifiers.
2655 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2656 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002657 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2659 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2660 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002661 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 case 'v': case 'w': case 'x': case 'y': case 'z':
2663 case '_':
2664 // Notify MIOpt that we read a non-whitespace/non-comment token.
2665 MIOpt.ReadToken();
2666 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002667
2668 case '$': // $ in identifiers.
2669 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002670 if (!isLexingRawMode())
2671 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002672 // Notify MIOpt that we read a non-whitespace/non-comment token.
2673 MIOpt.ReadToken();
2674 return LexIdentifier(Result, CurPtr);
2675 }
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Chris Lattner9e6293d2008-10-12 04:51:35 +00002677 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002678 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 // C99 6.4.4: Character Constants.
2681 case '\'':
2682 // Notify MIOpt that we read a non-whitespace/non-comment token.
2683 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002684 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002685
2686 // C99 6.4.5: String Literals.
2687 case '"':
2688 // Notify MIOpt that we read a non-whitespace/non-comment token.
2689 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002690 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002691
2692 // C99 6.4.6: Punctuators.
2693 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002694 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 break;
2696 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002697 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 break;
2699 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002700 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 break;
2702 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002703 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 break;
2705 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002706 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 break;
2708 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002709 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 break;
2711 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002712 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 break;
2714 case '.':
2715 Char = getCharAndSize(CurPtr, SizeTmp);
2716 if (Char >= '0' && Char <= '9') {
2717 // Notify MIOpt that we read a non-whitespace/non-comment token.
2718 MIOpt.ReadToken();
2719
2720 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2721 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002722 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 CurPtr += SizeTmp;
2724 } else if (Char == '.' &&
2725 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002726 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2728 SizeTmp2, Result);
2729 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002730 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 }
2732 break;
2733 case '&':
2734 Char = getCharAndSize(CurPtr, SizeTmp);
2735 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002736 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2738 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002739 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2741 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002742 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 }
2744 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002745 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002747 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2749 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002750 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 }
2752 break;
2753 case '+':
2754 Char = getCharAndSize(CurPtr, SizeTmp);
2755 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002757 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002760 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002762 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 }
2764 break;
2765 case '-':
2766 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002767 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002769 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002771 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2773 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002774 Kind = tok::arrowstar;
2775 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002777 Kind = tok::arrow;
2778 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002780 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002782 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 }
2784 break;
2785 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002786 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 break;
2788 case '!':
2789 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002790 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2792 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002793 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 }
2795 break;
2796 case '/':
2797 // 6.4.9: Comments
2798 Char = getCharAndSize(CurPtr, SizeTmp);
2799 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002800 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2801 // want to lex this as a comment. There is one problem with this though,
2802 // that in one particular corner case, this can change the behavior of the
2803 // resultant program. For example, In "foo //**/ bar", C89 would lex
2804 // this as "foo / bar" and langauges with BCPL comments would lex it as
2805 // "foo". Check to see if the character after the second slash is a '*'.
2806 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002807 // However, we never do this in -traditional-cpp mode.
2808 if ((Features.BCPLComment ||
2809 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2810 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002811 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002812 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Chris Lattner8402c732009-01-16 22:39:25 +00002814 // It is common for the tokens immediately after a // comment to be
2815 // whitespace (indentation for the next line). Instead of going through
2816 // the big switch, handle it efficiently now.
2817 goto SkipIgnoredUnits;
2818 }
2819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Chris Lattner8402c732009-01-16 22:39:25 +00002821 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002823 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002824 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Chris Lattner8402c732009-01-16 22:39:25 +00002827 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002828 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002829 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002831 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 }
2833 break;
2834 case '%':
2835 Char = getCharAndSize(CurPtr, SizeTmp);
2836 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002837 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2839 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002840 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2842 } else if (Features.Digraphs && Char == ':') {
2843 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2844 Char = getCharAndSize(CurPtr, SizeTmp);
2845 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002846 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2848 SizeTmp2, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002849 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002851 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002852 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002853 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002854 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 // We parsed a # character. If this occurs at the start of the line,
2856 // it's actually the start of a preprocessing directive. Callback to
2857 // the preprocessor to handle it.
2858 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002859 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002860 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002861 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 // As an optimization, if the preprocessor didn't switch lexers, tail
2864 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002865 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 // Start a new token. If this is a #include or something, the PP may
2867 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002868 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002870 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002871 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002872 IsAtStartOfLine = false;
2873 }
2874 goto LexNextToken; // GCC isn't tail call eliminating.
2875 }
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Chris Lattner168ae2d2007-10-17 20:41:00 +00002877 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 }
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Chris Lattnere91e9322009-03-18 20:58:27 +00002880 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 }
2882 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002883 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 }
2885 break;
2886 case '<':
2887 Char = getCharAndSize(CurPtr, SizeTmp);
2888 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002889 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002891 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2892 if (After == '=') {
2893 Kind = tok::lesslessequal;
2894 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2895 SizeTmp2, Result);
2896 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2897 // If this is actually a '<<<<<<<' version control conflict marker,
2898 // recognize it as such and recover nicely.
2899 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00002900 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
2901 // If this is '<<<<' and we're in a Perforce-style conflict marker,
2902 // ignore it.
2903 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002904 } else if (Features.CUDA && After == '<') {
2905 Kind = tok::lesslessless;
2906 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2907 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002908 } else {
2909 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2910 Kind = tok::lessless;
2911 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002914 Kind = tok::lessequal;
2915 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002916 if (Features.CPlusPlus0x &&
2917 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2918 // C++0x [lex.pptoken]p3:
2919 // Otherwise, if the next three characters are <:: and the subsequent
2920 // character is neither : nor >, the < is treated as a preprocessor
2921 // token by itself and not as the first character of the alternative
2922 // token <:.
2923 unsigned SizeTmp3;
2924 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2925 if (After != ':' && After != '>') {
2926 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00002927 if (!isLexingRawMode())
2928 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00002929 break;
2930 }
2931 }
2932
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002934 Kind = tok::l_square;
2935 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002936 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002937 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002938 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002939 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 }
2941 break;
2942 case '>':
2943 Char = getCharAndSize(CurPtr, SizeTmp);
2944 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002946 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002947 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002948 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2949 if (After == '=') {
2950 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2951 SizeTmp2, Result);
2952 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00002953 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
2954 // If this is actually a '>>>>' conflict marker, recognize it as such
2955 // and recover nicely.
2956 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00002957 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2958 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2959 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002960 } else if (Features.CUDA && After == '>') {
2961 Kind = tok::greatergreatergreater;
2962 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2963 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002964 } else {
2965 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2966 Kind = tok::greatergreater;
2967 }
2968
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002970 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 }
2972 break;
2973 case '^':
2974 Char = getCharAndSize(CurPtr, SizeTmp);
2975 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002976 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002977 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002978 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002979 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002980 }
2981 break;
2982 case '|':
2983 Char = getCharAndSize(CurPtr, SizeTmp);
2984 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002985 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2987 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002988 // If this is '|||||||' and we're in a conflict marker, ignore it.
2989 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2990 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002991 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002992 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2993 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002994 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 }
2996 break;
2997 case ':':
2998 Char = getCharAndSize(CurPtr, SizeTmp);
2999 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003000 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3002 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003003 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003005 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003006 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 }
3008 break;
3009 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003010 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 break;
3012 case '=':
3013 Char = getCharAndSize(CurPtr, SizeTmp);
3014 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003015 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003016 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3017 goto LexNextToken;
3018
Chris Lattner9e6293d2008-10-12 04:51:35 +00003019 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003020 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003021 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003022 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 }
3024 break;
3025 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003026 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 break;
3028 case '#':
3029 Char = getCharAndSize(CurPtr, SizeTmp);
3030 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003031 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00003033 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003034 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003035 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003036 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3038 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 // We parsed a # character. If this occurs at the start of the line,
3040 // it's actually the start of a preprocessing directive. Callback to
3041 // the preprocessor to handle it.
3042 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003043 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003044 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003045 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Reid Spencer5f016e22007-07-11 17:01:13 +00003047 // As an optimization, if the preprocessor didn't switch lexers, tail
3048 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003049 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003050 // Start a new token. If this is a #include or something, the PP may
3051 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003052 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003053 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003054 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003055 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 IsAtStartOfLine = false;
3057 }
3058 goto LexNextToken; // GCC isn't tail call eliminating.
3059 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00003060 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003061 }
Mike Stump1eb44332009-09-09 15:08:12 +00003062
Chris Lattnere91e9322009-03-18 20:58:27 +00003063 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003064 }
3065 break;
3066
Chris Lattner3a570772008-01-03 17:58:54 +00003067 case '@':
3068 // Objective C support.
3069 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003070 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003071 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003072 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Reid Spencer5f016e22007-07-11 17:01:13 +00003075 case '\\':
3076 // FIXME: UCN's.
3077 // FALL THROUGH.
3078 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003079 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003080 break;
3081 }
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Reid Spencer5f016e22007-07-11 17:01:13 +00003083 // Notify MIOpt that we read a non-whitespace/non-comment token.
3084 MIOpt.ReadToken();
3085
3086 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003087 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003088}