blob: 1a469bef488e0ad8e6dd7845061aa95e5571c97c [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);
816 unsigned EndOffs;
817 if (!SM.isInFileID(End, beginInfo.first, &EndOffs) ||
818 beginInfo.second > EndOffs)
819 return CharSourceRange();
820
821 return CharSourceRange::getCharRange(Begin, End);
822}
823
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000824StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
825 const SourceManager &SM,
826 const LangOptions &LangOpts) {
827 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
828 // Walk past macro argument expanions.
829 while (SM.isMacroArgExpansion(Loc))
830 Loc = SM.getImmediateExpansionRange(Loc).first;
831
832 // Find the spelling location of the start of the non-argument expansion
833 // range. This is where the macro name was spelled in order to begin
834 // expanding this macro.
835 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
836
837 // Dig out the buffer where the macro name was spelled and the extents of the
838 // name so that we can render it into the expansion note.
839 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
840 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
841 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
842 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
843}
844
Reid Spencer5f016e22007-07-11 17:01:13 +0000845//===----------------------------------------------------------------------===//
846// Character information.
847//===----------------------------------------------------------------------===//
848
Reid Spencer5f016e22007-07-11 17:01:13 +0000849enum {
850 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
851 CHAR_VERT_WS = 0x02, // '\r', '\n'
852 CHAR_LETTER = 0x04, // a-z,A-Z
853 CHAR_NUMBER = 0x08, // 0-9
854 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000855 CHAR_PERIOD = 0x20, // .
856 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000857};
858
Chris Lattner03b98662009-07-07 17:09:54 +0000859// Statically initialize CharInfo table based on ASCII character set
860// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000861static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000862{
863// 0 NUL 1 SOH 2 STX 3 ETX
864// 4 EOT 5 ENQ 6 ACK 7 BEL
865 0 , 0 , 0 , 0 ,
866 0 , 0 , 0 , 0 ,
867// 8 BS 9 HT 10 NL 11 VT
868//12 NP 13 CR 14 SO 15 SI
869 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
870 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
871//16 DLE 17 DC1 18 DC2 19 DC3
872//20 DC4 21 NAK 22 SYN 23 ETB
873 0 , 0 , 0 , 0 ,
874 0 , 0 , 0 , 0 ,
875//24 CAN 25 EM 26 SUB 27 ESC
876//28 FS 29 GS 30 RS 31 US
877 0 , 0 , 0 , 0 ,
878 0 , 0 , 0 , 0 ,
879//32 SP 33 ! 34 " 35 #
880//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000881 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
882 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000883//40 ( 41 ) 42 * 43 +
884//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000885 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
886 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000887//48 0 49 1 50 2 51 3
888//52 4 53 5 54 6 55 7
889 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
890 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
891//56 8 57 9 58 : 59 ;
892//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000893 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
894 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000895//64 @ 65 A 66 B 67 C
896//68 D 69 E 70 F 71 G
897 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
898 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
899//72 H 73 I 74 J 75 K
900//76 L 77 M 78 N 79 O
901 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
902 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
903//80 P 81 Q 82 R 83 S
904//84 T 85 U 86 V 87 W
905 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
906 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
907//88 X 89 Y 90 Z 91 [
908//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000909 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
910 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000911//96 ` 97 a 98 b 99 c
912//100 d 101 e 102 f 103 g
913 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
914 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
915//104 h 105 i 106 j 107 k
916//108 l 109 m 110 n 111 o
917 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
918 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
919//112 p 113 q 114 r 115 s
920//116 t 117 u 118 v 119 w
921 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
922 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
923//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000924//124 | 125 } 126 ~ 127 DEL
925 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
926 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000927};
928
Chris Lattnera2bf1052009-12-17 05:29:40 +0000929static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 static bool isInited = false;
931 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000932 // check the statically-initialized CharInfo table
933 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
934 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
935 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
936 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
937 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
938 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
939 assert(CHAR_UNDER == CharInfo[(int)'_']);
940 assert(CHAR_PERIOD == CharInfo[(int)'.']);
941 for (unsigned i = 'a'; i <= 'z'; ++i) {
942 assert(CHAR_LETTER == CharInfo[i]);
943 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
944 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000946 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000947
Chris Lattner03b98662009-07-07 17:09:54 +0000948 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000949}
950
Chris Lattner03b98662009-07-07 17:09:54 +0000951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952/// isIdentifierBody - Return true if this is the body character of an
953/// identifier, which is [a-zA-Z0-9_].
954static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000955 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956}
957
958/// isHorizontalWhitespace - Return true if this character is horizontal
959/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
960static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000961 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000962}
963
Anna Zaksaca25bc2011-07-27 21:43:43 +0000964/// isVerticalWhitespace - Return true if this character is vertical
965/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
966static inline bool isVerticalWhitespace(unsigned char c) {
967 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
968}
969
Reid Spencer5f016e22007-07-11 17:01:13 +0000970/// isWhitespace - Return true if this character is horizontal or vertical
971/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
972/// for '\0'.
973static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000974 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975}
976
977/// isNumberBody - Return true if this is the body character of an
978/// preprocessing number, which is [a-zA-Z0-9_.].
979static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000980 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000981 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000982}
983
Craig Topper2fa4e862011-08-11 04:06:15 +0000984/// isRawStringDelimBody - Return true if this is the body character of a
985/// raw string delimiter.
986static inline bool isRawStringDelimBody(unsigned char c) {
987 return (CharInfo[c] &
988 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
989 true : false;
990}
991
Reid Spencer5f016e22007-07-11 17:01:13 +0000992
993//===----------------------------------------------------------------------===//
994// Diagnostics forwarding code.
995//===----------------------------------------------------------------------===//
996
Chris Lattner409a0362007-07-22 18:38:25 +0000997/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000998/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000999/// This is currently only used for _Pragma implementation, so it is the slow
1000/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001001static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1002 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001003static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1004 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001005 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001006 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner409a0362007-07-22 18:38:25 +00001008 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001009 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001010 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001011 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chandler Carruth433db062011-07-14 08:20:40 +00001013 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001014 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001015 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001016 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chris Lattnere7fb4842009-02-15 20:52:18 +00001018 // Figure out the expansion loc range, which is the range covered by the
1019 // original _Pragma(...) sequence.
1020 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001021 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chandler Carruthbf340e42011-07-26 03:03:05 +00001023 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001024}
1025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026/// getSourceLocation - Return a source location identifier for the specified
1027/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001028SourceLocation Lexer::getSourceLocation(const char *Loc,
1029 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001030 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001032
1033 // In the normal case, we're just lexing from a simple file buffer, return
1034 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001035 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001036 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001037 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Chris Lattner2b2453a2009-01-17 06:22:33 +00001039 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1040 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001041 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001042 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001043}
1044
Reid Spencer5f016e22007-07-11 17:01:13 +00001045/// Diag - Forwarding function for diagnostics. This translate a source
1046/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001047DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001048 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001049}
Reid Spencer5f016e22007-07-11 17:01:13 +00001050
1051//===----------------------------------------------------------------------===//
1052// Trigraph and Escaped Newline Handling Code.
1053//===----------------------------------------------------------------------===//
1054
1055/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1056/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1057static char GetTrigraphCharForLetter(char Letter) {
1058 switch (Letter) {
1059 default: return 0;
1060 case '=': return '#';
1061 case ')': return ']';
1062 case '(': return '[';
1063 case '!': return '|';
1064 case '\'': return '^';
1065 case '>': return '}';
1066 case '/': return '\\';
1067 case '<': return '{';
1068 case '-': return '~';
1069 }
1070}
1071
1072/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1073/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1074/// return the result character. Finally, emit a warning about trigraph use
1075/// whether trigraphs are enabled or not.
1076static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1077 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001078 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner3692b092008-11-18 07:59:24 +00001080 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001081 if (!L->isLexingRawMode())
1082 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001083 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattner74d15df2008-11-22 02:02:22 +00001086 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001087 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 return Res;
1089}
1090
Chris Lattner24f0e482009-04-18 22:05:41 +00001091/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1092/// 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 +00001093/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001094unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1095 unsigned Size = 0;
1096 while (isWhitespace(Ptr[Size])) {
1097 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Chris Lattner24f0e482009-04-18 22:05:41 +00001099 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1100 continue;
1101
1102 // If this is a \r\n or \n\r, skip the other half.
1103 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1104 Ptr[Size-1] != Ptr[Size])
1105 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Chris Lattner24f0e482009-04-18 22:05:41 +00001107 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001108 }
1109
Chris Lattner24f0e482009-04-18 22:05:41 +00001110 // Not an escaped newline, must be a \t or something else.
1111 return 0;
1112}
1113
Chris Lattner03374952009-04-18 22:27:02 +00001114/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1115/// them), skip over them and return the first non-escaped-newline found,
1116/// otherwise return P.
1117const char *Lexer::SkipEscapedNewLines(const char *P) {
1118 while (1) {
1119 const char *AfterEscape;
1120 if (*P == '\\') {
1121 AfterEscape = P+1;
1122 } else if (*P == '?') {
1123 // If not a trigraph for escape, bail out.
1124 if (P[1] != '?' || P[2] != '/')
1125 return P;
1126 AfterEscape = P+3;
1127 } else {
1128 return P;
1129 }
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattner03374952009-04-18 22:27:02 +00001131 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1132 if (NewLineSize == 0) return P;
1133 P = AfterEscape+NewLineSize;
1134 }
1135}
1136
Anna Zaksaca25bc2011-07-27 21:43:43 +00001137/// \brief Checks that the given token is the first token that occurs after the
1138/// given location (this excludes comments and whitespace). Returns the location
1139/// immediately after the specified token. If the token is not found or the
1140/// location is inside a macro, the returned source location will be invalid.
1141SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1142 tok::TokenKind TKind,
1143 const SourceManager &SM,
1144 const LangOptions &LangOpts,
1145 bool SkipTrailingWhitespaceAndNewLine) {
1146 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001147 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001148 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001149 }
1150 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1151
1152 // Break down the source location.
1153 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1154
1155 // Try to load the file buffer.
1156 bool InvalidTemp = false;
1157 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1158 if (InvalidTemp)
1159 return SourceLocation();
1160
1161 const char *TokenBegin = File.data() + LocInfo.second;
1162
1163 // Lex from the start of the given location.
1164 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1165 TokenBegin, File.end());
1166 // Find the token.
1167 Token Tok;
1168 lexer.LexFromRawLexer(Tok);
1169 if (Tok.isNot(TKind))
1170 return SourceLocation();
1171 SourceLocation TokenLoc = Tok.getLocation();
1172
1173 // Calculate how much whitespace needs to be skipped if any.
1174 unsigned NumWhitespaceChars = 0;
1175 if (SkipTrailingWhitespaceAndNewLine) {
1176 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1177 Tok.getLength();
1178 unsigned char C = *TokenEnd;
1179 while (isHorizontalWhitespace(C)) {
1180 C = *(++TokenEnd);
1181 NumWhitespaceChars++;
1182 }
1183 if (isVerticalWhitespace(C))
1184 NumWhitespaceChars++;
1185 }
1186
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001187 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001188}
Chris Lattner24f0e482009-04-18 22:05:41 +00001189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1191/// get its size, and return it. This is tricky in several cases:
1192/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1193/// then either return the trigraph (skipping 3 chars) or the '?',
1194/// depending on whether trigraphs are enabled or not.
1195/// 2. If this is an escaped newline (potentially with whitespace between
1196/// the backslash and newline), implicitly skip the newline and return
1197/// the char after it.
1198/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1199///
1200/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1201/// know that we can accumulate into Size, and that we have already incremented
1202/// Ptr by Size bytes.
1203///
1204/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1205/// be updated to match.
1206///
1207char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001208 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 // If we have a slash, look for an escaped newline.
1210 if (Ptr[0] == '\\') {
1211 ++Size;
1212 ++Ptr;
1213Slash:
1214 // Common case, backslash-char where the char is not whitespace.
1215 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner5636a3b2009-06-23 05:15:06 +00001217 // See if we have optional whitespace characters between the slash and
1218 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001219 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1220 // Remember that this token needs to be cleaned.
1221 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001222
Chris Lattner24f0e482009-04-18 22:05:41 +00001223 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001224 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001225 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Chris Lattner24f0e482009-04-18 22:05:41 +00001227 // Found backslash<whitespace><newline>. Parse the char after it.
1228 Size += EscapedNewLineSize;
1229 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001230
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001231 // If the char that we finally got was a \n, then we must have had
1232 // something like \<newline><newline>. We don't want to consume the
1233 // second newline.
1234 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1235 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001236
Chris Lattner24f0e482009-04-18 22:05:41 +00001237 // Use slow version to accumulate a correct size field.
1238 return getCharAndSizeSlow(Ptr, Size, Tok);
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 // Otherwise, this is not an escaped newline, just return the slash.
1242 return '\\';
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // If this is a trigraph, process it.
1246 if (Ptr[0] == '?' && Ptr[1] == '?') {
1247 // If this is actually a legal trigraph (not something like "??x"), emit
1248 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1249 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1250 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001251 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252
1253 Ptr += 3;
1254 Size += 3;
1255 if (C == '\\') goto Slash;
1256 return C;
1257 }
1258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 // If this is neither, return a single character.
1261 ++Size;
1262 return *Ptr;
1263}
1264
1265
1266/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1267/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1268/// and that we have already incremented Ptr by Size bytes.
1269///
1270/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1271/// be updated to match.
1272char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1273 const LangOptions &Features) {
1274 // If we have a slash, look for an escaped newline.
1275 if (Ptr[0] == '\\') {
1276 ++Size;
1277 ++Ptr;
1278Slash:
1279 // Common case, backslash-char where the char is not whitespace.
1280 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001283 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1284 // Found backslash<whitespace><newline>. Parse the char after it.
1285 Size += EscapedNewLineSize;
1286 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001288 // If the char that we finally got was a \n, then we must have had
1289 // something like \<newline><newline>. We don't want to consume the
1290 // second newline.
1291 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1292 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001293
Chris Lattner24f0e482009-04-18 22:05:41 +00001294 // Use slow version to accumulate a correct size field.
1295 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // Otherwise, this is not an escaped newline, just return the slash.
1299 return '\\';
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 // If this is a trigraph, process it.
1303 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1304 // If this is actually a legal trigraph (not something like "??x"), return
1305 // it.
1306 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1307 Ptr += 3;
1308 Size += 3;
1309 if (C == '\\') goto Slash;
1310 return C;
1311 }
1312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // If this is neither, return a single character.
1315 ++Size;
1316 return *Ptr;
1317}
1318
1319//===----------------------------------------------------------------------===//
1320// Helper methods for lexing.
1321//===----------------------------------------------------------------------===//
1322
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001323/// \brief Routine that indiscriminately skips bytes in the source file.
1324void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1325 BufferPtr += Bytes;
1326 if (BufferPtr > BufferEnd)
1327 BufferPtr = BufferEnd;
1328 IsAtStartOfLine = StartOfLine;
1329}
1330
Chris Lattnerd2177732007-07-20 16:59:19 +00001331void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1333 unsigned Size;
1334 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001335 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 --CurPtr; // Back up over the skipped character.
1339
1340 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1341 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1342 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001343 //
1344 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1345 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1347FinishIdentifier:
1348 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001349 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1350 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // If we are in raw mode, return this identifier raw. There is no need to
1353 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001354 if (LexingRawMode)
1355 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001357 // Fill in Result.IdentifierInfo and update the token kind,
1358 // looking up the identifier in the identifier table.
1359 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Finally, now that we know we have an identifier, pass this off to the
1362 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001363 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001364 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001365
Chris Lattner6a170eb2009-01-21 07:43:11 +00001366 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 C = getCharAndSize(CurPtr, Size);
1372 while (1) {
1373 if (C == '$') {
1374 // If we hit a $ and they are not supported in identifiers, we are done.
1375 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001378 if (!isLexingRawMode())
1379 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 CurPtr = ConsumeChar(CurPtr, Size, Result);
1381 C = getCharAndSize(CurPtr, Size);
1382 continue;
1383 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1384 // Found end of identifier.
1385 goto FinishIdentifier;
1386 }
1387
1388 // Otherwise, this character is good, consume it.
1389 CurPtr = ConsumeChar(CurPtr, Size, Result);
1390
1391 C = getCharAndSize(CurPtr, Size);
1392 while (isIdentifierBody(C)) { // FIXME: UCNs.
1393 CurPtr = ConsumeChar(CurPtr, Size, Result);
1394 C = getCharAndSize(CurPtr, Size);
1395 }
1396 }
1397}
1398
Douglas Gregora75ec432010-08-30 14:50:47 +00001399/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001400/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001401static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1402 unsigned Size;
1403 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1404 if (C1 != '0')
1405 return false;
1406 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1407 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001408}
Reid Spencer5f016e22007-07-11 17:01:13 +00001409
Nate Begeman5253c7f2008-04-14 02:26:39 +00001410/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001411/// constant. From[-1] is the first character lexed. Return the end of the
1412/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001413void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 unsigned Size;
1415 char C = getCharAndSize(CurPtr, Size);
1416 char PrevCh = 0;
1417 while (isNumberBody(C)) { // FIXME: UCNs?
1418 CurPtr = ConsumeChar(CurPtr, Size, Result);
1419 PrevCh = C;
1420 C = getCharAndSize(CurPtr, Size);
1421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001424 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1425 // If we are in Microsoft mode, don't continue if the constant is hex.
1426 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Francois Pichet62ec1f22011-09-17 17:15:52 +00001427 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001428 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1429 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001430
1431 // If we have a hex FP constant, continue.
Douglas Gregor46717302011-10-12 18:51:02 +00001432 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001436 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001437 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001438 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001439}
1440
1441/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001442/// either " or L" or u8" or u" or U".
1443void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1444 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Richard Smith661a9962011-10-15 01:18:56 +00001447 if (!isLexingRawMode() &&
1448 (Kind == tok::utf8_string_literal ||
1449 Kind == tok::utf16_string_literal ||
1450 Kind == tok::utf32_string_literal))
1451 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1452
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 char C = getAndAdvanceChar(CurPtr, Result);
1454 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001455 // Skip escaped characters. Escaped newlines will already be processed by
1456 // getAndAdvanceChar.
1457 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001459
Chris Lattner571339c2010-05-30 23:27:38 +00001460 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001461 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001462 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001463 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001464 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 }
Chris Lattner571339c2010-05-30 23:27:38 +00001467
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001468 if (C == 0) {
1469 if (isCodeCompletionPoint(CurPtr-1)) {
1470 PP->CodeCompleteNaturalLanguage();
1471 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1472 return cutOffLexing();
1473 }
1474
Chris Lattner571339c2010-05-30 23:27:38 +00001475 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001476 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 C = getAndAdvanceChar(CurPtr, Result);
1478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001481 if (NulCharacter && !isLexingRawMode())
1482 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001485 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001486 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001487 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001488}
1489
Craig Topper2fa4e862011-08-11 04:06:15 +00001490/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1491/// having lexed R", LR", u8R", uR", or UR".
1492void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1493 tok::TokenKind Kind) {
1494 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1495 // Between the initial and final double quote characters of the raw string,
1496 // any transformations performed in phases 1 and 2 (trigraphs,
1497 // universal-character-names, and line splicing) are reverted.
1498
Richard Smith661a9962011-10-15 01:18:56 +00001499 if (!isLexingRawMode())
1500 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1501
Craig Topper2fa4e862011-08-11 04:06:15 +00001502 unsigned PrefixLen = 0;
1503
1504 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1505 ++PrefixLen;
1506
1507 // If the last character was not a '(', then we didn't lex a valid delimiter.
1508 if (CurPtr[PrefixLen] != '(') {
1509 if (!isLexingRawMode()) {
1510 const char *PrefixEnd = &CurPtr[PrefixLen];
1511 if (PrefixLen == 16) {
1512 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1513 } else {
1514 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1515 << StringRef(PrefixEnd, 1);
1516 }
1517 }
1518
1519 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1520 // it's possible the '"' was intended to be part of the raw string, but
1521 // there's not much we can do about that.
1522 while (1) {
1523 char C = *CurPtr++;
1524
1525 if (C == '"')
1526 break;
1527 if (C == 0 && CurPtr-1 == BufferEnd) {
1528 --CurPtr;
1529 break;
1530 }
1531 }
1532
1533 FormTokenWithChars(Result, CurPtr, tok::unknown);
1534 return;
1535 }
1536
1537 // Save prefix and move CurPtr past it
1538 const char *Prefix = CurPtr;
1539 CurPtr += PrefixLen + 1; // skip over prefix and '('
1540
1541 while (1) {
1542 char C = *CurPtr++;
1543
1544 if (C == ')') {
1545 // Check for prefix match and closing quote.
1546 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1547 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1548 break;
1549 }
1550 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1551 if (!isLexingRawMode())
1552 Diag(BufferPtr, diag::err_unterminated_raw_string)
1553 << StringRef(Prefix, PrefixLen);
1554 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1555 return;
1556 }
1557 }
1558
1559 // Update the location of token as well as BufferPtr.
1560 const char *TokStart = BufferPtr;
1561 FormTokenWithChars(Result, CurPtr, Kind);
1562 Result.setLiteralData(TokStart);
1563}
1564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1566/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001567void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001569 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 char C = getAndAdvanceChar(CurPtr, Result);
1571 while (C != '>') {
1572 // Skip escaped characters.
1573 if (C == '\\') {
1574 // Skip the escaped character.
1575 C = getAndAdvanceChar(CurPtr, Result);
1576 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001577 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1578 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001579 // If the filename is unterminated, then it must just be a lone <
1580 // character. Return this as such.
1581 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 return;
1583 } else if (C == 0) {
1584 NulCharacter = CurPtr-1;
1585 }
1586 C = getAndAdvanceChar(CurPtr, Result);
1587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001590 if (NulCharacter && !isLexingRawMode())
1591 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001594 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001595 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001596 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597}
1598
1599
1600/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001601/// lexed either ' or L' or u' or U'.
1602void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1603 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 const char *NulCharacter = 0; // Does this character contain the \0 character?
1605
Richard Smith661a9962011-10-15 01:18:56 +00001606 if (!isLexingRawMode() &&
1607 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1608 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 char C = getAndAdvanceChar(CurPtr, Result);
1611 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001612 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001613 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001614 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001616 }
1617
1618 while (C != '\'') {
1619 // Skip escaped characters.
1620 if (C == '\\') {
1621 // Skip the escaped character.
1622 // FIXME: UCN's
1623 C = getAndAdvanceChar(CurPtr, Result);
1624 } else if (C == '\n' || C == '\r' || // Newline.
1625 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001626 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001627 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001628 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1629 return;
1630 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001631 if (isCodeCompletionPoint(CurPtr-1)) {
1632 PP->CodeCompleteNaturalLanguage();
1633 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1634 return cutOffLexing();
1635 }
1636
Chris Lattnerd80f7862010-07-07 23:24:27 +00001637 NulCharacter = CurPtr-1;
1638 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 C = getAndAdvanceChar(CurPtr, Result);
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattnerd80f7862010-07-07 23:24:27 +00001642 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001643 if (NulCharacter && !isLexingRawMode())
1644 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001647 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001648 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001649 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001650}
1651
1652/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1653/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001654///
1655/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1656///
1657bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // Whitespace - Skip it, then return the token after the whitespace.
1659 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1660 while (1) {
1661 // Skip horizontal whitespace very aggressively.
1662 while (isHorizontalWhitespace(Char))
1663 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001665 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 if (Char != '\n' && Char != '\r')
1667 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 if (ParsingPreprocessorDirective) {
1670 // End of preprocessor directive line, let LexTokenInternal handle this.
1671 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001672 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 // ok, but handle newline.
1676 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001677 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001679 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 Char = *++CurPtr;
1681 }
1682
1683 // If this isn't immediately after a newline, there is leading space.
1684 char PrevChar = CurPtr[-1];
1685 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001686 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687
Chris Lattnerd88dc482008-10-12 04:05:48 +00001688 // If the client wants us to return whitespace, return it now.
1689 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001690 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001691 return true;
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001695 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696}
1697
1698// SkipBCPLComment - We have just read the // characters from input. Skip until
1699// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001700/// BufferPtr and return.
1701///
1702/// If we're in KeepCommentMode or any CommentHandler has inserted
1703/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001704bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 // If BCPL comments aren't explicitly enabled for this language, emit an
1706 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001707 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 // Mark them enabled so we only emit one warning for this translation
1711 // unit.
1712 Features.BCPLComment = true;
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 // Scan over the body of the comment. The common case, when scanning, is that
1716 // the comment contains normal ascii characters with nothing interesting in
1717 // them. As such, optimize for this case with the inner loop.
1718 char C;
1719 do {
1720 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001721 // Skip over characters in the fast loop.
1722 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 C != '\n' && C != '\r') // Newline or DOS-style newline.
1724 C = *++CurPtr;
1725
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001726 const char *NextLine = CurPtr;
1727 if (C != 0) {
1728 // We found a newline, see if it's escaped.
1729 const char *EscapePtr = CurPtr-1;
1730 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1731 --EscapePtr;
1732
1733 if (*EscapePtr == '\\') // Escaped newline.
1734 CurPtr = EscapePtr;
1735 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1736 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1737 CurPtr = EscapePtr-2;
1738 else
1739 break; // This is a newline, we're done.
1740
1741 C = *CurPtr;
1742 }
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001745 // properly decode the character. Read it in raw mode to avoid emitting
1746 // diagnostics about things like trigraphs. If we see an escaped newline,
1747 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001749 bool OldRawMode = isLexingRawMode();
1750 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001752 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001753
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001754 // If we only read only one character, then no special handling is needed.
1755 // We're done and can skip forward to the newline.
1756 if (C != 0 && CurPtr == OldPtr+1) {
1757 CurPtr = NextLine;
1758 break;
1759 }
1760
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 // If we read multiple characters, and one of those characters was a \r or
1762 // \n, then we had an escaped newline within the comment. Emit diagnostic
1763 // unless the next line is also a // comment.
1764 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1765 for (; OldPtr != CurPtr; ++OldPtr)
1766 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1767 // Okay, we found a // comment that ends in a newline, if the next
1768 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001769 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001771 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 ++ForwardPtr;
1773 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1774 break;
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Chris Lattner74d15df2008-11-22 02:02:22 +00001777 if (!isLexingRawMode())
1778 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 break;
1780 }
1781 }
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor55817af2010-08-25 17:04:25 +00001783 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001784 --CurPtr;
1785 break;
1786 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001787
1788 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1789 PP->CodeCompleteNaturalLanguage();
1790 cutOffLexing();
1791 return false;
1792 }
1793
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 } while (C != '\n' && C != '\r');
1795
Chris Lattner3d0ad582010-02-03 21:06:21 +00001796 // Found but did not consume the newline. Notify comment handlers about the
1797 // comment unless we're in a #if 0 block.
1798 if (PP && !isLexingRawMode() &&
1799 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1800 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001801 BufferPtr = CurPtr;
1802 return true; // A token has to be returned.
1803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001806 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 return SaveBCPLComment(Result, CurPtr);
1808
1809 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001810 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1812 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001813 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 }
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001817 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001818 // contribute to another token), it isn't needed for correctness. Note that
1819 // this is ok even in KeepWhitespaceMode, because we would have returned the
1820 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001824 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001826 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001828 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001829}
1830
1831/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1832/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001833bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001834 // If we're not in a preprocessor directive, just return the // comment
1835 // directly.
1836 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Chris Lattner9e6293d2008-10-12 04:51:35 +00001838 if (!ParsingPreprocessorDirective)
1839 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Chris Lattner9e6293d2008-10-12 04:51:35 +00001841 // If this BCPL-style comment is in a macro definition, transmogrify it into
1842 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001843 bool Invalid = false;
1844 std::string Spelling = PP->getSpelling(Result, &Invalid);
1845 if (Invalid)
1846 return true;
1847
Chris Lattner9e6293d2008-10-12 04:51:35 +00001848 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1849 Spelling[1] = '*'; // Change prefix to "/*".
1850 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Chris Lattner9e6293d2008-10-12 04:51:35 +00001852 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001853 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001854 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001855 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001856}
1857
1858/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1859/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001860/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001861static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 Lexer *L) {
1863 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 // Back up off the newline.
1866 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 // If this is a two-character newline sequence, skip the other character.
1869 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1870 // \n\n or \r\r -> not escaped newline.
1871 if (CurPtr[0] == CurPtr[1])
1872 return false;
1873 // \n\r or \r\n -> skip the newline.
1874 --CurPtr;
1875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // If we have horizontal whitespace, skip over it. We allow whitespace
1878 // between the slash and newline.
1879 bool HasSpace = false;
1880 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1881 --CurPtr;
1882 HasSpace = true;
1883 }
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // If we have a slash, we know this is an escaped newline.
1886 if (*CurPtr == '\\') {
1887 if (CurPtr[-1] != '*') return false;
1888 } else {
1889 // It isn't a slash, is it the ?? / trigraph?
1890 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1891 CurPtr[-3] != '*')
1892 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // This is the trigraph ending the comment. Emit a stern warning!
1895 CurPtr -= 2;
1896
1897 // If no trigraphs are enabled, warn that we ignored this trigraph and
1898 // ignore this * character.
1899 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001900 if (!L->isLexingRawMode())
1901 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 return false;
1903 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001904 if (!L->isLexingRawMode())
1905 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001909 if (!L->isLexingRawMode())
1910 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001913 if (HasSpace && !L->isLexingRawMode())
1914 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 return true;
1917}
1918
1919#ifdef __SSE2__
1920#include <emmintrin.h>
1921#elif __ALTIVEC__
1922#include <altivec.h>
1923#undef bool
1924#endif
1925
1926/// SkipBlockComment - We have just read the /* characters from input. Read
1927/// until we find the */ characters that terminate the comment. Note that we
1928/// don't bother decoding trigraphs or escaped newlines in block comments,
1929/// because they cannot cause the comment to end. The only thing that can
1930/// happen is the comment could end with an escaped newline between the */ end
1931/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001932///
Chris Lattner046c2272010-01-18 22:35:47 +00001933/// If we're in KeepCommentMode or any CommentHandler has inserted
1934/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001935bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001937 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 // optimization helps people who like to put a lot of * characters in their
1939 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001940
1941 // The first character we get with newlines and trigraphs skipped to handle
1942 // the degenerate /*/ case below correctly if the * has an escaped newline
1943 // after it.
1944 unsigned CharSize;
1945 unsigned char C = getCharAndSize(CurPtr, CharSize);
1946 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001948 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001949 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001950 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattner31f0eca2008-10-12 04:19:49 +00001952 // KeepWhitespaceMode should return this broken comment as a token. Since
1953 // it isn't a well formed comment, just return it as an 'unknown' token.
1954 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001955 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001956 return true;
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Chris Lattner31f0eca2008-10-12 04:19:49 +00001959 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001960 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Chris Lattner8146b682007-07-21 23:43:37 +00001963 // Check to see if the first character after the '/*' is another /. If so,
1964 // then this slash does not end the block comment, it is part of it.
1965 if (C == '/')
1966 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 while (1) {
1969 // Skip over all non-interesting characters until we find end of buffer or a
1970 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001971 if (CurPtr + 24 < BufferEnd &&
1972 // If there is a code-completion point avoid the fast scan because it
1973 // doesn't check for '\0'.
1974 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 // While not aligned to a 16-byte boundary.
1976 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1977 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 if (C == '/') goto FoundSlash;
1980
1981#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001982 __m128i Slashes = _mm_set1_epi8('/');
1983 while (CurPtr+16 <= BufferEnd) {
1984 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
1985 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00001986 // Adjust the pointer to point directly after the first slash. It's
1987 // not necessary to set C here, it will be overwritten at the end of
1988 // the outer loop.
1989 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001990 goto FoundSlash;
1991 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001994#elif __ALTIVEC__
1995 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001996 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 '/', '/', '/', '/', '/', '/', '/', '/'
1998 };
1999 while (CurPtr+16 <= BufferEnd &&
2000 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2001 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002002#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // Scan for '/' quickly. Many block comments are very large.
2004 while (CurPtr[0] != '/' &&
2005 CurPtr[1] != '/' &&
2006 CurPtr[2] != '/' &&
2007 CurPtr[3] != '/' &&
2008 CurPtr+4 < BufferEnd) {
2009 CurPtr += 4;
2010 }
2011#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 // It has to be one of the bytes scanned, increment to it and read one.
2014 C = *CurPtr++;
2015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 // Loop to scan the remainder.
2018 while (C != '/' && C != '\0')
2019 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002022 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 if (CurPtr[-2] == '*') // We found the final */. We're done!
2024 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2027 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2028 // We found the final */, though it had an escaped newline between the
2029 // * and /. We're done!
2030 break;
2031 }
2032 }
2033 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2034 // If this is a /* inside of the comment, emit a warning. Don't do this
2035 // if this is a /*/, which will end the comment. This misses cases with
2036 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002037 if (!isLexingRawMode())
2038 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 }
2040 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002041 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002042 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 // Note: the user probably forgot a */. We could continue immediately
2044 // after the /*, but this would involve lexing a lot of what really is the
2045 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002046 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattner31f0eca2008-10-12 04:19:49 +00002048 // KeepWhitespaceMode should return this broken comment as a token. Since
2049 // it isn't a well formed comment, just return it as an 'unknown' token.
2050 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002051 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002052 return true;
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Chris Lattner31f0eca2008-10-12 04:19:49 +00002055 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002056 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002057 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2058 PP->CodeCompleteNaturalLanguage();
2059 cutOffLexing();
2060 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 C = *CurPtr++;
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Chris Lattner3d0ad582010-02-03 21:06:21 +00002066 // Notify comment handlers about the comment unless we're in a #if 0 block.
2067 if (PP && !isLexingRawMode() &&
2068 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2069 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002070 BufferPtr = CurPtr;
2071 return true; // A token has to be returned.
2072 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002073
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002075 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002076 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002077 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 }
2079
2080 // It is common for the tokens immediately after a /**/ comment to be
2081 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002082 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2083 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002085 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002087 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 }
2089
2090 // Otherwise, just return so that the next character will be lexed as a token.
2091 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002092 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002093 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002094}
2095
2096//===----------------------------------------------------------------------===//
2097// Primary Lexing Entry Points
2098//===----------------------------------------------------------------------===//
2099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2101/// uninterpreted string. This switches the lexer out of directive mode.
2102std::string Lexer::ReadToEndOfLine() {
2103 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2104 "Must be in a preprocessing directive!");
2105 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002106 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002107
2108 // CurPtr - Cache BufferPtr in an automatic variable.
2109 const char *CurPtr = BufferPtr;
2110 while (1) {
2111 char Char = getAndAdvanceChar(CurPtr, Tmp);
2112 switch (Char) {
2113 default:
2114 Result += Char;
2115 break;
2116 case 0: // Null.
2117 // Found end of file?
2118 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002119 if (isCodeCompletionPoint(CurPtr-1)) {
2120 PP->CodeCompleteNaturalLanguage();
2121 cutOffLexing();
2122 return Result;
2123 }
2124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // Nope, normal character, continue.
2126 Result += Char;
2127 break;
2128 }
2129 // FALL THROUGH.
2130 case '\r':
2131 case '\n':
2132 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2133 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2134 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Peter Collingbourne84021552011-02-28 02:37:51 +00002136 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002138 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002139 if (PP)
2140 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002141 Lex(Tmp);
2142 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002143 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 // Finally, we're done, return the string we found.
2146 return Result;
2147 }
2148 }
2149}
2150
2151/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2152/// condition, reporting diagnostics and handling other edge cases as required.
2153/// This returns true if Result contains a token, false if PP.Lex should be
2154/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002155bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 // If we hit the end of the file while parsing a preprocessor directive,
2157 // end the preprocessor directive first. The next token returned will
2158 // then be the end of file.
2159 if (ParsingPreprocessorDirective) {
2160 // Done parsing the "line".
2161 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002163 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002166 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002168 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 // If we are in raw mode, return this event as an EOF token. Let the caller
2171 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002172 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 Result.startToken();
2174 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002175 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 return true;
2177 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002178
Douglas Gregorf44e8542010-08-24 19:08:16 +00002179 // Issue diagnostics for unterminated #if and missing newline.
2180
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 // If we are in a #if directive, emit an error.
2182 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002183 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002184 PP->Diag(ConditionalStack.back().IfLoc,
2185 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 ConditionalStack.pop_back();
2187 }
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002189 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2190 // a pedwarn.
2191 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002192 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002193 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 BufferPtr = CurPtr;
2196
2197 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002198 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002199}
2200
2201/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2202/// the specified lexer will return a tok::l_paren token, 0 if it is something
2203/// else and 2 if there are no more tokens in the buffer controlled by the
2204/// lexer.
2205unsigned Lexer::isNextPPTokenLParen() {
2206 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 // Switch to 'skipping' mode. This will ensure that we can lex a token
2209 // without emitting diagnostics, disables macro expansion, and will cause EOF
2210 // to return an EOF token instead of popping the include stack.
2211 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 // Save state that can be changed while lexing so that we can restore it.
2214 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002215 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Chris Lattnerd2177732007-07-20 16:59:19 +00002217 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 Tok.startToken();
2219 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 // Restore state that may have changed.
2222 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002223 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // Restore the lexer back to non-skipping mode.
2226 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002228 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002230 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002231}
2232
Chris Lattner34f349d2009-12-14 06:16:57 +00002233/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002234static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2235 ConflictMarkerKind CMK) {
2236 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2237 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2238 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2239 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002240 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002241 // Must occur at start of line.
2242 if (RestOfBuffer[Pos-1] != '\r' &&
2243 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002244 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2245 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002246 continue;
2247 }
2248 return RestOfBuffer.data()+Pos;
2249 }
2250 return 0;
2251}
2252
2253/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2254/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2255/// and recover nicely. This returns true if it is a conflict marker and false
2256/// if not.
2257bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2258 // Only a conflict marker if it starts at the beginning of a line.
2259 if (CurPtr != BufferStart &&
2260 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2261 return false;
2262
Richard Smithd5e1d602011-10-12 00:37:51 +00002263 // Check to see if we have <<<<<<< or >>>>.
2264 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2265 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002266 return false;
2267
2268 // If we have a situation where we don't care about conflict markers, ignore
2269 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002270 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002271 return false;
2272
Richard Smithd5e1d602011-10-12 00:37:51 +00002273 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2274
2275 // Check to see if there is an ending marker somewhere in the buffer at the
2276 // start of a line to terminate this conflict marker.
2277 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002278 // We found a match. We are really in a conflict marker.
2279 // Diagnose this, and ignore to the end of line.
2280 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002281 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002282
2283 // Skip ahead to the end of line. We know this exists because the
2284 // end-of-conflict marker starts with \r or \n.
2285 while (*CurPtr != '\r' && *CurPtr != '\n') {
2286 assert(CurPtr != BufferEnd && "Didn't find end of line");
2287 ++CurPtr;
2288 }
2289 BufferPtr = CurPtr;
2290 return true;
2291 }
2292
2293 // No end of conflict marker found.
2294 return false;
2295}
2296
2297
Richard Smithd5e1d602011-10-12 00:37:51 +00002298/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2299/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2300/// is the end of a conflict marker. Handle it by ignoring up until the end of
2301/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002302bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2303 // Only a conflict marker if it starts at the beginning of a line.
2304 if (CurPtr != BufferStart &&
2305 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2306 return false;
2307
2308 // If we have a situation where we don't care about conflict markers, ignore
2309 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002310 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002311 return false;
2312
Richard Smithd5e1d602011-10-12 00:37:51 +00002313 // Check to see if we have the marker (4 characters in a row).
2314 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002315 if (CurPtr[i] != CurPtr[0])
2316 return false;
2317
2318 // If we do have it, search for the end of the conflict marker. This could
2319 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2320 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002321 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2322 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002323 CurPtr = End;
2324
2325 // Skip ahead to the end of line.
2326 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2327 ++CurPtr;
2328
2329 BufferPtr = CurPtr;
2330
2331 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002332 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002333 return true;
2334 }
2335
2336 return false;
2337}
2338
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002339bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2340 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002341 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002342 return Loc == PP->getCodeCompletionLoc();
2343 }
2344
2345 return false;
2346}
2347
Reid Spencer5f016e22007-07-11 17:01:13 +00002348
2349/// LexTokenInternal - This implements a simple C family lexer. It is an
2350/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002351/// has a null character at the end of the file. This returns a preprocessing
2352/// token, not a normal token, as such, it is an internal interface. It assumes
2353/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002354void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002355LexNextToken:
2356 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002357 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 // CurPtr - Cache BufferPtr in an automatic variable.
2361 const char *CurPtr = BufferPtr;
2362
2363 // Small amounts of horizontal whitespace is very common between tokens.
2364 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2365 ++CurPtr;
2366 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2367 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Chris Lattnerd88dc482008-10-12 04:05:48 +00002369 // If we are keeping whitespace and other tokens, just return what we just
2370 // skipped. The next lexer invocation will return the token after the
2371 // whitespace.
2372 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002373 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002374 return;
2375 }
Mike Stump1eb44332009-09-09 15:08:12 +00002376
Reid Spencer5f016e22007-07-11 17:01:13 +00002377 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002378 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 }
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 // Read a character, advancing over it.
2384 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002385 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 switch (Char) {
2388 case 0: // Null.
2389 // Found end of file?
2390 if (CurPtr-1 == BufferEnd) {
2391 // Read the PP instance variable into an automatic variable, because
2392 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002393 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2395 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002396 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2397 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 }
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002400 // Check if we are performing code completion.
2401 if (isCodeCompletionPoint(CurPtr-1)) {
2402 // Return the code-completion token.
2403 Result.startToken();
2404 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2405 return;
2406 }
2407
Chris Lattner74d15df2008-11-22 02:02:22 +00002408 if (!isLexingRawMode())
2409 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002410 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002411 if (SkipWhitespace(Result, CurPtr))
2412 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002415
2416 case 26: // DOS & CP/M EOF: "^Z".
2417 // If we're in Microsoft extensions mode, treat this as end of file.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002418 if (Features.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002419 // Read the PP instance variable into an automatic variable, because
2420 // LexEndOfFile will often delete 'this'.
2421 Preprocessor *PPCache = PP;
2422 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2423 return; // Got a token to return.
2424 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2425 return PPCache->Lex(Result);
2426 }
2427 // If Microsoft extensions are disabled, this is just random garbage.
2428 Kind = tok::unknown;
2429 break;
2430
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 case '\n':
2432 case '\r':
2433 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002434 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 if (ParsingPreprocessorDirective) {
2436 // Done parsing the "line".
2437 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Reid Spencer5f016e22007-07-11 17:01:13 +00002439 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002440 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Reid Spencer5f016e22007-07-11 17:01:13 +00002442 // Since we consumed a newline, we are back at the start of a line.
2443 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Peter Collingbourne84021552011-02-28 02:37:51 +00002445 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 break;
2447 }
2448 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002449 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002451 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Chris Lattnerd88dc482008-10-12 04:05:48 +00002453 if (SkipWhitespace(Result, CurPtr))
2454 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002455 goto LexNextToken; // GCC isn't tail call eliminating.
2456 case ' ':
2457 case '\t':
2458 case '\f':
2459 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002460 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002461 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002462 if (SkipWhitespace(Result, CurPtr))
2463 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002464
2465 SkipIgnoredUnits:
2466 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Chris Lattner8133cfc2007-07-22 06:29:05 +00002468 // If the next token is obviously a // or /* */ comment, skip it efficiently
2469 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002470 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002471 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002472 if (SkipBCPLComment(Result, CurPtr+2))
2473 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002474 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002475 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002476 if (SkipBlockComment(Result, CurPtr+2))
2477 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002478 goto SkipIgnoredUnits;
2479 } else if (isHorizontalWhitespace(*CurPtr)) {
2480 goto SkipHorizontalWhitespace;
2481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002483
Chris Lattner3a570772008-01-03 17:58:54 +00002484 // C99 6.4.4.1: Integer Constants.
2485 // C99 6.4.4.2: Floating Constants.
2486 case '0': case '1': case '2': case '3': case '4':
2487 case '5': case '6': case '7': case '8': case '9':
2488 // Notify MIOpt that we read a non-whitespace/non-comment token.
2489 MIOpt.ReadToken();
2490 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Douglas Gregor5cee1192011-07-27 05:40:30 +00002492 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2493 // Notify MIOpt that we read a non-whitespace/non-comment token.
2494 MIOpt.ReadToken();
2495
2496 if (Features.CPlusPlus0x) {
2497 Char = getCharAndSize(CurPtr, SizeTmp);
2498
2499 // UTF-16 string literal
2500 if (Char == '"')
2501 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2502 tok::utf16_string_literal);
2503
2504 // UTF-16 character constant
2505 if (Char == '\'')
2506 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2507 tok::utf16_char_constant);
2508
Craig Topper2fa4e862011-08-11 04:06:15 +00002509 // UTF-16 raw string literal
2510 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2511 return LexRawStringLiteral(Result,
2512 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2513 SizeTmp2, Result),
2514 tok::utf16_string_literal);
2515
2516 if (Char == '8') {
2517 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2518
2519 // UTF-8 string literal
2520 if (Char2 == '"')
2521 return LexStringLiteral(Result,
2522 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2523 SizeTmp2, Result),
2524 tok::utf8_string_literal);
2525
2526 if (Char2 == 'R') {
2527 unsigned SizeTmp3;
2528 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2529 // UTF-8 raw string literal
2530 if (Char3 == '"') {
2531 return LexRawStringLiteral(Result,
2532 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2533 SizeTmp2, Result),
2534 SizeTmp3, Result),
2535 tok::utf8_string_literal);
2536 }
2537 }
2538 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002539 }
2540
2541 // treat u like the start of an identifier.
2542 return LexIdentifier(Result, CurPtr);
2543
2544 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2545 // Notify MIOpt that we read a non-whitespace/non-comment token.
2546 MIOpt.ReadToken();
2547
2548 if (Features.CPlusPlus0x) {
2549 Char = getCharAndSize(CurPtr, SizeTmp);
2550
2551 // UTF-32 string literal
2552 if (Char == '"')
2553 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2554 tok::utf32_string_literal);
2555
2556 // UTF-32 character constant
2557 if (Char == '\'')
2558 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2559 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002560
2561 // UTF-32 raw string literal
2562 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2563 return LexRawStringLiteral(Result,
2564 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2565 SizeTmp2, Result),
2566 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002567 }
2568
2569 // treat U like the start of an identifier.
2570 return LexIdentifier(Result, CurPtr);
2571
Craig Topper2fa4e862011-08-11 04:06:15 +00002572 case 'R': // Identifier or C++0x raw string literal
2573 // Notify MIOpt that we read a non-whitespace/non-comment token.
2574 MIOpt.ReadToken();
2575
2576 if (Features.CPlusPlus0x) {
2577 Char = getCharAndSize(CurPtr, SizeTmp);
2578
2579 if (Char == '"')
2580 return LexRawStringLiteral(Result,
2581 ConsumeChar(CurPtr, SizeTmp, Result),
2582 tok::string_literal);
2583 }
2584
2585 // treat R like the start of an identifier.
2586 return LexIdentifier(Result, CurPtr);
2587
Chris Lattner3a570772008-01-03 17:58:54 +00002588 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 // Notify MIOpt that we read a non-whitespace/non-comment token.
2590 MIOpt.ReadToken();
2591 Char = getCharAndSize(CurPtr, SizeTmp);
2592
2593 // Wide string literal.
2594 if (Char == '"')
2595 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002596 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002597
Craig Topper2fa4e862011-08-11 04:06:15 +00002598 // Wide raw string literal.
2599 if (Features.CPlusPlus0x && Char == 'R' &&
2600 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2601 return LexRawStringLiteral(Result,
2602 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2603 SizeTmp2, Result),
2604 tok::wide_string_literal);
2605
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 // Wide character constant.
2607 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002608 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2609 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 // C99 6.4.2: Identifiers.
2613 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2614 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002615 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2617 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2618 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002619 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 case 'v': case 'w': case 'x': case 'y': case 'z':
2621 case '_':
2622 // Notify MIOpt that we read a non-whitespace/non-comment token.
2623 MIOpt.ReadToken();
2624 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002625
2626 case '$': // $ in identifiers.
2627 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002628 if (!isLexingRawMode())
2629 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002630 // Notify MIOpt that we read a non-whitespace/non-comment token.
2631 MIOpt.ReadToken();
2632 return LexIdentifier(Result, CurPtr);
2633 }
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Chris Lattner9e6293d2008-10-12 04:51:35 +00002635 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002636 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // C99 6.4.4: Character Constants.
2639 case '\'':
2640 // Notify MIOpt that we read a non-whitespace/non-comment token.
2641 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002642 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002643
2644 // C99 6.4.5: String Literals.
2645 case '"':
2646 // Notify MIOpt that we read a non-whitespace/non-comment token.
2647 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002648 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002649
2650 // C99 6.4.6: Punctuators.
2651 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002652 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 break;
2654 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002655 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 break;
2657 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002658 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 break;
2660 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002661 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 break;
2663 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002664 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 break;
2666 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002667 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 break;
2669 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002670 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 break;
2672 case '.':
2673 Char = getCharAndSize(CurPtr, SizeTmp);
2674 if (Char >= '0' && Char <= '9') {
2675 // Notify MIOpt that we read a non-whitespace/non-comment token.
2676 MIOpt.ReadToken();
2677
2678 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2679 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002680 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 CurPtr += SizeTmp;
2682 } else if (Char == '.' &&
2683 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002684 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2686 SizeTmp2, Result);
2687 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002688 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 }
2690 break;
2691 case '&':
2692 Char = getCharAndSize(CurPtr, SizeTmp);
2693 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002694 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2696 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002697 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2699 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002700 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 }
2702 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002705 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2707 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002708 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002709 }
2710 break;
2711 case '+':
2712 Char = getCharAndSize(CurPtr, SizeTmp);
2713 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002715 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002718 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002719 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002720 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002721 }
2722 break;
2723 case '-':
2724 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002725 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002727 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002728 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002729 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2731 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002732 Kind = tok::arrowstar;
2733 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002735 Kind = tok::arrow;
2736 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002738 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002740 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 }
2742 break;
2743 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002744 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 break;
2746 case '!':
2747 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002748 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2750 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002751 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 }
2753 break;
2754 case '/':
2755 // 6.4.9: Comments
2756 Char = getCharAndSize(CurPtr, SizeTmp);
2757 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002758 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2759 // want to lex this as a comment. There is one problem with this though,
2760 // that in one particular corner case, this can change the behavior of the
2761 // resultant program. For example, In "foo //**/ bar", C89 would lex
2762 // this as "foo / bar" and langauges with BCPL comments would lex it as
2763 // "foo". Check to see if the character after the second slash is a '*'.
2764 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002765 // However, we never do this in -traditional-cpp mode.
2766 if ((Features.BCPLComment ||
2767 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2768 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002769 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002770 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Chris Lattner8402c732009-01-16 22:39:25 +00002772 // It is common for the tokens immediately after a // comment to be
2773 // whitespace (indentation for the next line). Instead of going through
2774 // the big switch, handle it efficiently now.
2775 goto SkipIgnoredUnits;
2776 }
2777 }
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Chris Lattner8402c732009-01-16 22:39:25 +00002779 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002781 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002782 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002783 }
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Chris Lattner8402c732009-01-16 22:39:25 +00002785 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002787 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 }
2791 break;
2792 case '%':
2793 Char = getCharAndSize(CurPtr, SizeTmp);
2794 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002795 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2797 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002798 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2800 } else if (Features.Digraphs && Char == ':') {
2801 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2802 Char = getCharAndSize(CurPtr, SizeTmp);
2803 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002804 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2806 SizeTmp2, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002807 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002809 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002810 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002811 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002812 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // We parsed a # character. If this occurs at the start of the line,
2814 // it's actually the start of a preprocessing directive. Callback to
2815 // the preprocessor to handle it.
2816 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002817 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002818 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002819 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 // As an optimization, if the preprocessor didn't switch lexers, tail
2822 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002823 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 // Start a new token. If this is a #include or something, the PP may
2825 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002826 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002828 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002829 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 IsAtStartOfLine = false;
2831 }
2832 goto LexNextToken; // GCC isn't tail call eliminating.
2833 }
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Chris Lattner168ae2d2007-10-17 20:41:00 +00002835 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 }
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Chris Lattnere91e9322009-03-18 20:58:27 +00002838 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 }
2840 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002841 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 }
2843 break;
2844 case '<':
2845 Char = getCharAndSize(CurPtr, SizeTmp);
2846 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002847 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002849 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2850 if (After == '=') {
2851 Kind = tok::lesslessequal;
2852 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2853 SizeTmp2, Result);
2854 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2855 // If this is actually a '<<<<<<<' version control conflict marker,
2856 // recognize it as such and recover nicely.
2857 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00002858 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
2859 // If this is '<<<<' and we're in a Perforce-style conflict marker,
2860 // ignore it.
2861 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002862 } else if (Features.CUDA && After == '<') {
2863 Kind = tok::lesslessless;
2864 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2865 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002866 } else {
2867 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2868 Kind = tok::lessless;
2869 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002872 Kind = tok::lessequal;
2873 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002874 if (Features.CPlusPlus0x &&
2875 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2876 // C++0x [lex.pptoken]p3:
2877 // Otherwise, if the next three characters are <:: and the subsequent
2878 // character is neither : nor >, the < is treated as a preprocessor
2879 // token by itself and not as the first character of the alternative
2880 // token <:.
2881 unsigned SizeTmp3;
2882 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2883 if (After != ':' && After != '>') {
2884 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00002885 if (!isLexingRawMode())
2886 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00002887 break;
2888 }
2889 }
2890
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002892 Kind = tok::l_square;
2893 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002895 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002897 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002898 }
2899 break;
2900 case '>':
2901 Char = getCharAndSize(CurPtr, SizeTmp);
2902 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002904 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002906 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2907 if (After == '=') {
2908 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2909 SizeTmp2, Result);
2910 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00002911 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
2912 // If this is actually a '>>>>' conflict marker, recognize it as such
2913 // and recover nicely.
2914 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00002915 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2916 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2917 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002918 } else if (Features.CUDA && After == '>') {
2919 Kind = tok::greatergreatergreater;
2920 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2921 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002922 } else {
2923 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2924 Kind = tok::greatergreater;
2925 }
2926
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002928 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 }
2930 break;
2931 case '^':
2932 Char = getCharAndSize(CurPtr, SizeTmp);
2933 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002935 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002936 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002937 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002938 }
2939 break;
2940 case '|':
2941 Char = getCharAndSize(CurPtr, SizeTmp);
2942 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002943 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002944 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2945 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002946 // If this is '|||||||' and we're in a conflict marker, ignore it.
2947 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2948 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002949 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2951 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002952 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 }
2954 break;
2955 case ':':
2956 Char = getCharAndSize(CurPtr, SizeTmp);
2957 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002958 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2960 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002961 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002963 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002964 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 }
2966 break;
2967 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002968 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 break;
2970 case '=':
2971 Char = getCharAndSize(CurPtr, SizeTmp);
2972 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002973 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00002974 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2975 goto LexNextToken;
2976
Chris Lattner9e6293d2008-10-12 04:51:35 +00002977 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002978 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002979 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002980 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 }
2982 break;
2983 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002984 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 break;
2986 case '#':
2987 Char = getCharAndSize(CurPtr, SizeTmp);
2988 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002989 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002991 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002992 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002993 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002994 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2996 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 // We parsed a # character. If this occurs at the start of the line,
2998 // it's actually the start of a preprocessing directive. Callback to
2999 // the preprocessor to handle it.
3000 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003001 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003002 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003003 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 // As an optimization, if the preprocessor didn't switch lexers, tail
3006 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003007 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003008 // Start a new token. If this is a #include or something, the PP may
3009 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003010 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003012 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003013 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003014 IsAtStartOfLine = false;
3015 }
3016 goto LexNextToken; // GCC isn't tail call eliminating.
3017 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00003018 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 }
Mike Stump1eb44332009-09-09 15:08:12 +00003020
Chris Lattnere91e9322009-03-18 20:58:27 +00003021 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 }
3023 break;
3024
Chris Lattner3a570772008-01-03 17:58:54 +00003025 case '@':
3026 // Objective C support.
3027 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003028 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003029 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003030 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003031 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003032
Reid Spencer5f016e22007-07-11 17:01:13 +00003033 case '\\':
3034 // FIXME: UCN's.
3035 // FALL THROUGH.
3036 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003037 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 break;
3039 }
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 // Notify MIOpt that we read a non-whitespace/non-comment token.
3042 MIOpt.ReadToken();
3043
3044 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003045 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003046}