blob: 802024f79b6f92d33f109a8826c9d731a7fb90e6 [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
Mike Stump1eb44332009-09-09 15:08:12 +000062void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000063 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000064 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner22d91ca2009-01-17 06:55:17 +000066 BufferStart = BufStart;
67 BufferPtr = BufPtr;
68 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner22d91ca2009-01-17 06:55:17 +000070 assert(BufEnd[0] == 0 &&
71 "We assume that the input buffer has a null character at the end"
72 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000073
Eric Christopher156119d2011-04-09 00:01:04 +000074 // Check whether we have a BOM in the beginning of the buffer. If yes - act
75 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
76 // skip the UTF-8 BOM if it's present.
77 if (BufferStart == BufferPtr) {
78 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000080 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000081 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
82 .Default(0);
83
84 // Skip the BOM.
85 BufferPtr += BOMLength;
86 }
87
Chris Lattner22d91ca2009-01-17 06:55:17 +000088 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000089 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000090
Chris Lattner22d91ca2009-01-17 06:55:17 +000091 // Start of the file is a start of line.
92 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner22d91ca2009-01-17 06:55:17 +000094 // We are not after parsing a #.
95 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Chris Lattner22d91ca2009-01-17 06:55:17 +000097 // We are not after parsing #include.
98 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner22d91ca2009-01-17 06:55:17 +0000100 // We are not in raw mode. Raw mode disables diagnostics and interpretation
101 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
102 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
103 // or otherwise skipping over tokens.
104 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Chris Lattner22d91ca2009-01-17 06:55:17 +0000106 // Default to not keeping comments.
107 ExtendedTokenMode = 0;
108}
109
Chris Lattner0770dab2009-01-17 07:56:59 +0000110/// Lexer constructor - Create a new lexer object for the specified buffer
111/// with the specified preprocessor managing the lexing process. This lexer
112/// assumes that the associated file buffer and Preprocessor objects will
113/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000114Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000115 : PreprocessorLexer(&PP, FID),
116 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
117 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Chris Lattner0770dab2009-01-17 07:56:59 +0000119 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
120 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner0770dab2009-01-17 07:56:59 +0000122 // Default to keeping comments if the preprocessor wants them.
123 SetCommentRetentionState(PP.getCommentRetentionState());
124}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000125
Chris Lattner168ae2d2007-10-17 20:41:00 +0000126/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000127/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
128/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000129Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000130 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000131 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000132
Chris Lattner22d91ca2009-01-17 06:55:17 +0000133 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Chris Lattner168ae2d2007-10-17 20:41:00 +0000135 // We *are* in raw mode.
136 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000137}
138
Chris Lattner025c3a62009-01-17 07:35:14 +0000139/// Lexer constructor - Create a new raw lexer object. This object is only
140/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
141/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000142Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
143 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000144 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000145
Mike Stump1eb44332009-09-09 15:08:12 +0000146 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000147 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner025c3a62009-01-17 07:35:14 +0000149 // We *are* in raw mode.
150 LexingRawMode = true;
151}
152
Chris Lattner42e00d12009-01-17 08:27:52 +0000153/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
154/// _Pragma expansion. This has a variety of magic semantics that this method
155/// sets up. It returns a new'd Lexer that must be delete'd when done.
156///
157/// On entrance to this routine, TokStartLoc is a macro location which has a
158/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000159/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000160/// "expanded from".
161///
162/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
163/// normal lexer that remaps tokens as they fly by. This would require making
164/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
165/// interface that could handle this stuff. This would pull GetMappedTokenLoc
166/// out of the critical path of the lexer!
167///
Mike Stump1eb44332009-09-09 15:08:12 +0000168Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000169 SourceLocation ExpansionLocStart,
170 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000171 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000172 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000173
174 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000175 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000176 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
177 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner42e00d12009-01-17 08:27:52 +0000179 // Now that the lexer is created, change the start/end locations so that we
180 // just lex the subsection of the file that we want. This is lexing from a
181 // scratch buffer.
182 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner42e00d12009-01-17 08:27:52 +0000184 L->BufferPtr = StrData;
185 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000186 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000187
188 // Set the SourceLocation with the remapping information. This ensures that
189 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000190 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
191 ExpansionLocStart,
192 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner42e00d12009-01-17 08:27:52 +0000194 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000195 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000196 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner42e00d12009-01-17 08:27:52 +0000198 // This lexer really is for _Pragma.
199 L->Is_PragmaLexer = true;
200 return L;
201}
202
Chris Lattner168ae2d2007-10-17 20:41:00 +0000203
Reid Spencer5f016e22007-07-11 17:01:13 +0000204/// Stringify - Convert the specified string into a C string, with surrounding
205/// ""'s, and with escaped \ and " characters.
206std::string Lexer::Stringify(const std::string &Str, bool Charify) {
207 std::string Result = Str;
208 char Quote = Charify ? '\'' : '"';
209 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
210 if (Result[i] == '\\' || Result[i] == Quote) {
211 Result.insert(Result.begin()+i, '\\');
212 ++i; ++e;
213 }
214 }
215 return Result;
216}
217
Chris Lattnerd8e30832007-07-24 06:57:14 +0000218/// Stringify - Convert the specified string into a C string by escaping '\'
219/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000220void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
222 if (Str[i] == '\\' || Str[i] == '"') {
223 Str.insert(Str.begin()+i, '\\');
224 ++i; ++e;
225 }
226 }
227}
228
Chris Lattnerb0607272010-11-17 07:26:20 +0000229//===----------------------------------------------------------------------===//
230// Token Spelling
231//===----------------------------------------------------------------------===//
232
233/// getSpelling() - Return the 'spelling' of this token. The spelling of a
234/// token are the characters used to represent the token in the source file
235/// after trigraph expansion and escaped-newline folding. In particular, this
236/// wants to get the true, uncanonicalized, spelling of things like digraphs
237/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238StringRef Lexer::getSpelling(SourceLocation loc,
239 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000240 const SourceManager &SM,
241 const LangOptions &options,
242 bool *invalid) {
243 // Break down the source location.
244 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
245
246 // Try to the load the file buffer.
247 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000249 if (invalidTemp) {
250 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000252 }
253
254 const char *tokenBegin = file.data() + locInfo.second;
255
256 // Lex from the start of the given location.
257 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
258 file.begin(), tokenBegin, file.end());
259 Token token;
260 lexer.LexFromRawLexer(token);
261
262 unsigned length = token.getLength();
263
264 // Common case: no need for cleaning.
265 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000267
268 // Hard case, we need to relex the characters into the string.
269 buffer.clear();
270 buffer.reserve(length);
271
272 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
273 unsigned charSize;
274 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
275 ti += charSize;
276 }
277
Chris Lattner5f9e2722011-07-23 10:55:15 +0000278 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000279}
280
281/// getSpelling() - Return the 'spelling' of this token. The spelling of a
282/// token are the characters used to represent the token in the source file
283/// after trigraph expansion and escaped-newline folding. In particular, this
284/// wants to get the true, uncanonicalized, spelling of things like digraphs
285/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000286std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
287 const LangOptions &Features, bool *Invalid) {
288 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
289
290 // If this token contains nothing interesting, return it directly.
291 bool CharDataInvalid = false;
292 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
293 &CharDataInvalid);
294 if (Invalid)
295 *Invalid = CharDataInvalid;
296 if (CharDataInvalid)
297 return std::string();
298
299 if (!Tok.needsCleaning())
300 return std::string(TokStart, TokStart+Tok.getLength());
301
302 std::string Result;
303 Result.reserve(Tok.getLength());
304
305 // Otherwise, hard case, relex the characters into the string.
306 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
307 Ptr != End; ) {
308 unsigned CharSize;
309 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
310 Ptr += CharSize;
311 }
312 assert(Result.size() != unsigned(Tok.getLength()) &&
313 "NeedsCleaning flag set on something that didn't need cleaning!");
314 return Result;
315}
316
317/// getSpelling - This method is used to get the spelling of a token into a
318/// preallocated buffer, instead of as an std::string. The caller is required
319/// to allocate enough space for the token, which is guaranteed to be at least
320/// Tok.getLength() bytes long. The actual length of the token is returned.
321///
322/// Note that this method may do two possible things: it may either fill in
323/// the buffer specified with characters, or it may *change the input pointer*
324/// to point to a constant buffer with the data already in it (avoiding a
325/// copy). The caller is not allowed to modify the returned buffer pointer
326/// if an internal buffer is returned.
327unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
328 const SourceManager &SourceMgr,
329 const LangOptions &Features, bool *Invalid) {
330 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000331
332 const char *TokStart = 0;
333 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
334 if (Tok.is(tok::raw_identifier))
335 TokStart = Tok.getRawIdentifierData();
336 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
337 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000338 Buffer = II->getNameStart();
339 return II->getLength();
340 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000341
342 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000343 if (Tok.isLiteral())
344 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000345
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000347 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000348 bool CharDataInvalid = false;
349 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
350 if (Invalid)
351 *Invalid = CharDataInvalid;
352 if (CharDataInvalid) {
353 Buffer = "";
354 return 0;
355 }
356 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000357
Chris Lattnerb0607272010-11-17 07:26:20 +0000358 // If this token contains nothing interesting, return it directly.
359 if (!Tok.needsCleaning()) {
360 Buffer = TokStart;
361 return Tok.getLength();
362 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000363
Chris Lattnerb0607272010-11-17 07:26:20 +0000364 // Otherwise, hard case, relex the characters into the string.
365 char *OutBuf = const_cast<char*>(Buffer);
366 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
367 Ptr != End; ) {
368 unsigned CharSize;
369 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
370 Ptr += CharSize;
371 }
372 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
373 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000374
Chris Lattnerb0607272010-11-17 07:26:20 +0000375 return OutBuf-Buffer;
376}
377
378
379
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
Chris Lattner9a611942007-10-17 21:18:47 +0000382/// MeasureTokenLength - Relex the token at the specified location and return
383/// its length in bytes in the input file. If the token needs cleaning (e.g.
384/// includes a trigraph or an escaped newline) then this count includes bytes
385/// that are part of that.
386unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000387 const SourceManager &SM,
388 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000389 // TODO: this could be special cased for common tokens like identifiers, ')',
390 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000391 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000392 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
393 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000394
395 // If this comes from a macro expansion, we really do want the macro name, not
396 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000397 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000398 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000399 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000400 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000401 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000402 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000403
404 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000405
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 if (isWhitespace(StrData[0]))
407 return 0;
408
Chris Lattner9a611942007-10-17 21:18:47 +0000409 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000410 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
411 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000412 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000413 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000414 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000415 return TheTok.getLength();
416}
417
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000418static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
419 const SourceManager &SM,
420 const LangOptions &LangOpts) {
421 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000422 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000423 if (LocInfo.first.isInvalid())
424 return Loc;
425
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000426 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000427 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000428 if (Invalid)
429 return Loc;
430
431 // Back up from the current location until we hit the beginning of a line
432 // (or the buffer). We'll relex from that point.
433 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000434 if (LocInfo.second >= Buffer.size())
435 return Loc;
436
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000437 const char *StrData = BufStart+LocInfo.second;
438 if (StrData[0] == '\n' || StrData[0] == '\r')
439 return Loc;
440
441 const char *LexStart = StrData;
442 while (LexStart != BufStart) {
443 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
444 ++LexStart;
445 break;
446 }
447
448 --LexStart;
449 }
450
451 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000452 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000453 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
454 TheLexer.SetCommentRetentionState(true);
455
456 // Lex tokens until we find the token that contains the source location.
457 Token TheTok;
458 do {
459 TheLexer.LexFromRawLexer(TheTok);
460
461 if (TheLexer.getBufferLocation() > StrData) {
462 // Lexing this token has taken the lexer past the source location we're
463 // looking for. If the current token encompasses our source location,
464 // return the beginning of that token.
465 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
466 return TheTok.getLocation();
467
468 // We ended up skipping over the source location entirely, which means
469 // that it points into whitespace. We're done here.
470 break;
471 }
472 } while (TheTok.getKind() != tok::eof);
473
474 // We've passed our source location; just return the original source location.
475 return Loc;
476}
477
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000478SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
479 const SourceManager &SM,
480 const LangOptions &LangOpts) {
481 if (Loc.isFileID())
482 return getBeginningOfFileToken(Loc, SM, LangOpts);
483
484 if (!SM.isMacroArgExpansion(Loc))
485 return Loc;
486
487 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
488 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
489 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
490 std::pair<FileID, unsigned> BeginFileLocInfo= SM.getDecomposedLoc(BeginFileLoc);
491 assert(FileLocInfo.first == BeginFileLocInfo.first &&
492 FileLocInfo.second >= BeginFileLocInfo.second);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000493 return Loc.getLocWithOffset(SM.getDecomposedLoc(BeginFileLoc).second -
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000494 SM.getDecomposedLoc(FileLoc).second);
495}
496
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000497namespace {
498 enum PreambleDirectiveKind {
499 PDK_Skipped,
500 PDK_StartIf,
501 PDK_EndIf,
502 PDK_Unknown
503 };
504}
505
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000506std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000507Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
508 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000509 // Create a lexer starting at the beginning of the file. Note that we use a
510 // "fake" file source location at offset 1 so that the lexer will track our
511 // position within the file.
512 const unsigned StartOffset = 1;
513 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000514 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000515 Buffer->getBufferStart(), Buffer->getBufferEnd());
516
517 bool InPreprocessorDirective = false;
518 Token TheTok;
519 Token IfStartTok;
520 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000521
522 unsigned MaxLineOffset = 0;
523 if (MaxLines) {
524 const char *CurPtr = Buffer->getBufferStart();
525 unsigned CurLine = 0;
526 while (CurPtr != Buffer->getBufferEnd()) {
527 char ch = *CurPtr++;
528 if (ch == '\n') {
529 ++CurLine;
530 if (CurLine == MaxLines)
531 break;
532 }
533 }
534 if (CurPtr != Buffer->getBufferEnd())
535 MaxLineOffset = CurPtr - Buffer->getBufferStart();
536 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000537
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000538 do {
539 TheLexer.LexFromRawLexer(TheTok);
540
541 if (InPreprocessorDirective) {
542 // If we've hit the end of the file, we're done.
543 if (TheTok.getKind() == tok::eof) {
544 InPreprocessorDirective = false;
545 break;
546 }
547
548 // If we haven't hit the end of the preprocessor directive, skip this
549 // token.
550 if (!TheTok.isAtStartOfLine())
551 continue;
552
553 // We've passed the end of the preprocessor directive, and will look
554 // at this token again below.
555 InPreprocessorDirective = false;
556 }
557
Douglas Gregordf95a132010-08-09 20:45:32 +0000558 // Keep track of the # of lines in the preamble.
559 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000560 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000561
562 // If we were asked to limit the number of lines in the preamble,
563 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000564 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000565 break;
566 }
567
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000568 // Comments are okay; skip over them.
569 if (TheTok.getKind() == tok::comment)
570 continue;
571
572 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
573 // This is the start of a preprocessor directive.
574 Token HashTok = TheTok;
575 InPreprocessorDirective = true;
576
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000577 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000578 // we don't have an identifier table available. Instead, just look at
579 // the raw identifier to recognize and categorize preprocessor directives.
580 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000581 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000582 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000583 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000584 PreambleDirectiveKind PDK
585 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
586 .Case("include", PDK_Skipped)
587 .Case("__include_macros", PDK_Skipped)
588 .Case("define", PDK_Skipped)
589 .Case("undef", PDK_Skipped)
590 .Case("line", PDK_Skipped)
591 .Case("error", PDK_Skipped)
592 .Case("pragma", PDK_Skipped)
593 .Case("import", PDK_Skipped)
594 .Case("include_next", PDK_Skipped)
595 .Case("warning", PDK_Skipped)
596 .Case("ident", PDK_Skipped)
597 .Case("sccs", PDK_Skipped)
598 .Case("assert", PDK_Skipped)
599 .Case("unassert", PDK_Skipped)
600 .Case("if", PDK_StartIf)
601 .Case("ifdef", PDK_StartIf)
602 .Case("ifndef", PDK_StartIf)
603 .Case("elif", PDK_Skipped)
604 .Case("else", PDK_Skipped)
605 .Case("endif", PDK_EndIf)
606 .Default(PDK_Unknown);
607
608 switch (PDK) {
609 case PDK_Skipped:
610 continue;
611
612 case PDK_StartIf:
613 if (IfCount == 0)
614 IfStartTok = HashTok;
615
616 ++IfCount;
617 continue;
618
619 case PDK_EndIf:
620 // Mismatched #endif. The preamble ends here.
621 if (IfCount == 0)
622 break;
623
624 --IfCount;
625 continue;
626
627 case PDK_Unknown:
628 // We don't know what this directive is; stop at the '#'.
629 break;
630 }
631 }
632
633 // We only end up here if we didn't recognize the preprocessor
634 // directive or it was one that can't occur in the preamble at this
635 // point. Roll back the current token to the location of the '#'.
636 InPreprocessorDirective = false;
637 TheTok = HashTok;
638 }
639
Douglas Gregordf95a132010-08-09 20:45:32 +0000640 // We hit a token that we don't recognize as being in the
641 // "preprocessing only" part of the file, so we're no longer in
642 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000643 break;
644 } while (true);
645
646 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000647 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
648 IfCount? IfStartTok.isAtStartOfLine()
649 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000650}
651
Chris Lattner7ef5c272010-11-17 07:05:50 +0000652
653/// AdvanceToTokenCharacter - Given a location that specifies the start of a
654/// token, return a new location that specifies a character within the token.
655SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
656 unsigned CharNo,
657 const SourceManager &SM,
658 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000659 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000660 // character is. This needs to take into consideration newlines and
661 // trigraphs.
662 bool Invalid = false;
663 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
664
665 // If they request the first char of the token, we're trivially done.
666 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
667 return TokStart;
668
669 unsigned PhysOffset = 0;
670
671 // The usual case is that tokens don't contain anything interesting. Skip
672 // over the uninteresting characters. If a token only consists of simple
673 // chars, this method is extremely fast.
674 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
675 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000676 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000677 ++TokPtr, --CharNo, ++PhysOffset;
678 }
679
680 // If we have a character that may be a trigraph or escaped newline, use a
681 // lexer to parse it correctly.
682 for (; CharNo; --CharNo) {
683 unsigned Size;
684 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
685 TokPtr += Size;
686 PhysOffset += Size;
687 }
688
689 // Final detail: if we end up on an escaped newline, we want to return the
690 // location of the actual byte of the token. For example foo\<newline>bar
691 // advanced by 3 should return the location of b, not of \\. One compounding
692 // detail of this is that the escape may be made by a trigraph.
693 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
694 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
695
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000696 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000697}
698
699/// \brief Computes the source location just past the end of the
700/// token at this source location.
701///
702/// This routine can be used to produce a source location that
703/// points just past the end of the token referenced by \p Loc, and
704/// is generally used when a diagnostic needs to point just after a
705/// token where it expected something different that it received. If
706/// the returned source location would not be meaningful (e.g., if
707/// it points into a macro), this routine returns an invalid
708/// source location.
709///
710/// \param Offset an offset from the end of the token, where the source
711/// location should refer to. The default offset (0) produces a source
712/// location pointing just past the end of the token; an offset of 1 produces
713/// a source location pointing to the last character in the token, etc.
714SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
715 const SourceManager &SM,
716 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000717 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000718 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000719
720 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000721 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
722 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000723
Chandler Carruth433db062011-07-14 08:20:40 +0000724 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000725 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000726 }
727
Chris Lattner7ef5c272010-11-17 07:05:50 +0000728 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
729 if (Len > Offset)
730 Len = Len - Offset;
731 else
732 return Loc;
733
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000734 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000735}
736
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000737/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000738/// token of the macro expansion.
739bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000740 const SourceManager &SM,
741 const LangOptions &LangOpts) {
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();
Chandler Carruth433db062011-07-14 08:20:40 +0000752 if (expansionLoc.isFileID())
753 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000754
Chandler Carruth433db062011-07-14 08:20:40 +0000755 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000756}
757
758/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000759/// token of the macro expansion.
760bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000761 const SourceManager &SM,
762 const LangOptions &LangOpts) {
763 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
764
765 SourceLocation spellLoc = SM.getSpellingLoc(loc);
766 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
767 if (tokLen == 0)
768 return false;
769
770 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000771 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000772 if (SM.isInFileID(afterLoc, FID))
773 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000774
775 // FIXME: If the token comes from the macro token paste operator ('##')
776 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000777
Chandler Carruth433db062011-07-14 08:20:40 +0000778 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000779 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000780 if (expansionLoc.isFileID())
781 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000782
Chandler Carruth433db062011-07-14 08:20:40 +0000783 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000784}
785
Reid Spencer5f016e22007-07-11 17:01:13 +0000786//===----------------------------------------------------------------------===//
787// Character information.
788//===----------------------------------------------------------------------===//
789
Reid Spencer5f016e22007-07-11 17:01:13 +0000790enum {
791 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
792 CHAR_VERT_WS = 0x02, // '\r', '\n'
793 CHAR_LETTER = 0x04, // a-z,A-Z
794 CHAR_NUMBER = 0x08, // 0-9
795 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000796 CHAR_PERIOD = 0x20, // .
797 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000798};
799
Chris Lattner03b98662009-07-07 17:09:54 +0000800// Statically initialize CharInfo table based on ASCII character set
801// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000802static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000803{
804// 0 NUL 1 SOH 2 STX 3 ETX
805// 4 EOT 5 ENQ 6 ACK 7 BEL
806 0 , 0 , 0 , 0 ,
807 0 , 0 , 0 , 0 ,
808// 8 BS 9 HT 10 NL 11 VT
809//12 NP 13 CR 14 SO 15 SI
810 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
811 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
812//16 DLE 17 DC1 18 DC2 19 DC3
813//20 DC4 21 NAK 22 SYN 23 ETB
814 0 , 0 , 0 , 0 ,
815 0 , 0 , 0 , 0 ,
816//24 CAN 25 EM 26 SUB 27 ESC
817//28 FS 29 GS 30 RS 31 US
818 0 , 0 , 0 , 0 ,
819 0 , 0 , 0 , 0 ,
820//32 SP 33 ! 34 " 35 #
821//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000822 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
823 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000824//40 ( 41 ) 42 * 43 +
825//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000826 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
827 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000828//48 0 49 1 50 2 51 3
829//52 4 53 5 54 6 55 7
830 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
831 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
832//56 8 57 9 58 : 59 ;
833//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000834 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
835 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000836//64 @ 65 A 66 B 67 C
837//68 D 69 E 70 F 71 G
838 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
839 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
840//72 H 73 I 74 J 75 K
841//76 L 77 M 78 N 79 O
842 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
843 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
844//80 P 81 Q 82 R 83 S
845//84 T 85 U 86 V 87 W
846 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
847 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
848//88 X 89 Y 90 Z 91 [
849//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000850 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
851 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000852//96 ` 97 a 98 b 99 c
853//100 d 101 e 102 f 103 g
854 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
855 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
856//104 h 105 i 106 j 107 k
857//108 l 109 m 110 n 111 o
858 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
859 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
860//112 p 113 q 114 r 115 s
861//116 t 117 u 118 v 119 w
862 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
863 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
864//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000865//124 | 125 } 126 ~ 127 DEL
866 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
867 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000868};
869
Chris Lattnera2bf1052009-12-17 05:29:40 +0000870static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 static bool isInited = false;
872 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000873 // check the statically-initialized CharInfo table
874 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
875 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
876 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
877 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
878 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
879 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
880 assert(CHAR_UNDER == CharInfo[(int)'_']);
881 assert(CHAR_PERIOD == CharInfo[(int)'.']);
882 for (unsigned i = 'a'; i <= 'z'; ++i) {
883 assert(CHAR_LETTER == CharInfo[i]);
884 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
885 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000887 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000888
Chris Lattner03b98662009-07-07 17:09:54 +0000889 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000890}
891
Chris Lattner03b98662009-07-07 17:09:54 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893/// isIdentifierBody - Return true if this is the body character of an
894/// identifier, which is [a-zA-Z0-9_].
895static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000896 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000897}
898
899/// isHorizontalWhitespace - Return true if this character is horizontal
900/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
901static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000902 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000903}
904
Anna Zaksaca25bc2011-07-27 21:43:43 +0000905/// isVerticalWhitespace - Return true if this character is vertical
906/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
907static inline bool isVerticalWhitespace(unsigned char c) {
908 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
909}
910
Reid Spencer5f016e22007-07-11 17:01:13 +0000911/// isWhitespace - Return true if this character is horizontal or vertical
912/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
913/// for '\0'.
914static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000915 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000916}
917
918/// isNumberBody - Return true if this is the body character of an
919/// preprocessing number, which is [a-zA-Z0-9_.].
920static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000921 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000922 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000923}
924
Craig Topper2fa4e862011-08-11 04:06:15 +0000925/// isRawStringDelimBody - Return true if this is the body character of a
926/// raw string delimiter.
927static inline bool isRawStringDelimBody(unsigned char c) {
928 return (CharInfo[c] &
929 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
930 true : false;
931}
932
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
934//===----------------------------------------------------------------------===//
935// Diagnostics forwarding code.
936//===----------------------------------------------------------------------===//
937
Chris Lattner409a0362007-07-22 18:38:25 +0000938/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000939/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000940/// This is currently only used for _Pragma implementation, so it is the slow
941/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000942static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
943 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000944static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
945 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000946 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000947 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner409a0362007-07-22 18:38:25 +0000949 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000950 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000951 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000952 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Chandler Carruth433db062011-07-14 08:20:40 +0000954 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000955 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000956 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000957 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Chris Lattnere7fb4842009-02-15 20:52:18 +0000959 // Figure out the expansion loc range, which is the range covered by the
960 // original _Pragma(...) sequence.
961 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000962 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Chandler Carruthbf340e42011-07-26 03:03:05 +0000964 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000965}
966
Reid Spencer5f016e22007-07-11 17:01:13 +0000967/// getSourceLocation - Return a source location identifier for the specified
968/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000969SourceLocation Lexer::getSourceLocation(const char *Loc,
970 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000971 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000973
974 // In the normal case, we're just lexing from a simple file buffer, return
975 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000976 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000977 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000978 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner2b2453a2009-01-17 06:22:33 +0000980 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
981 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000982 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000983 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000984}
985
Reid Spencer5f016e22007-07-11 17:01:13 +0000986/// Diag - Forwarding function for diagnostics. This translate a source
987/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000988DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000989 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000990}
Reid Spencer5f016e22007-07-11 17:01:13 +0000991
992//===----------------------------------------------------------------------===//
993// Trigraph and Escaped Newline Handling Code.
994//===----------------------------------------------------------------------===//
995
996/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
997/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
998static char GetTrigraphCharForLetter(char Letter) {
999 switch (Letter) {
1000 default: return 0;
1001 case '=': return '#';
1002 case ')': return ']';
1003 case '(': return '[';
1004 case '!': return '|';
1005 case '\'': return '^';
1006 case '>': return '}';
1007 case '/': return '\\';
1008 case '<': return '{';
1009 case '-': return '~';
1010 }
1011}
1012
1013/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1014/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1015/// return the result character. Finally, emit a warning about trigraph use
1016/// whether trigraphs are enabled or not.
1017static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1018 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001019 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner3692b092008-11-18 07:59:24 +00001021 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001022 if (!L->isLexingRawMode())
1023 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001024 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattner74d15df2008-11-22 02:02:22 +00001027 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001028 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 return Res;
1030}
1031
Chris Lattner24f0e482009-04-18 22:05:41 +00001032/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1033/// 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 +00001034/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001035unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1036 unsigned Size = 0;
1037 while (isWhitespace(Ptr[Size])) {
1038 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner24f0e482009-04-18 22:05:41 +00001040 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1041 continue;
1042
1043 // If this is a \r\n or \n\r, skip the other half.
1044 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1045 Ptr[Size-1] != Ptr[Size])
1046 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Chris Lattner24f0e482009-04-18 22:05:41 +00001048 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001049 }
1050
Chris Lattner24f0e482009-04-18 22:05:41 +00001051 // Not an escaped newline, must be a \t or something else.
1052 return 0;
1053}
1054
Chris Lattner03374952009-04-18 22:27:02 +00001055/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1056/// them), skip over them and return the first non-escaped-newline found,
1057/// otherwise return P.
1058const char *Lexer::SkipEscapedNewLines(const char *P) {
1059 while (1) {
1060 const char *AfterEscape;
1061 if (*P == '\\') {
1062 AfterEscape = P+1;
1063 } else if (*P == '?') {
1064 // If not a trigraph for escape, bail out.
1065 if (P[1] != '?' || P[2] != '/')
1066 return P;
1067 AfterEscape = P+3;
1068 } else {
1069 return P;
1070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner03374952009-04-18 22:27:02 +00001072 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1073 if (NewLineSize == 0) return P;
1074 P = AfterEscape+NewLineSize;
1075 }
1076}
1077
Anna Zaksaca25bc2011-07-27 21:43:43 +00001078/// \brief Checks that the given token is the first token that occurs after the
1079/// given location (this excludes comments and whitespace). Returns the location
1080/// immediately after the specified token. If the token is not found or the
1081/// location is inside a macro, the returned source location will be invalid.
1082SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1083 tok::TokenKind TKind,
1084 const SourceManager &SM,
1085 const LangOptions &LangOpts,
1086 bool SkipTrailingWhitespaceAndNewLine) {
1087 if (Loc.isMacroID()) {
1088 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1089 return SourceLocation();
1090 Loc = SM.getExpansionRange(Loc).second;
1091 }
1092 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1093
1094 // Break down the source location.
1095 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1096
1097 // Try to load the file buffer.
1098 bool InvalidTemp = false;
1099 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1100 if (InvalidTemp)
1101 return SourceLocation();
1102
1103 const char *TokenBegin = File.data() + LocInfo.second;
1104
1105 // Lex from the start of the given location.
1106 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1107 TokenBegin, File.end());
1108 // Find the token.
1109 Token Tok;
1110 lexer.LexFromRawLexer(Tok);
1111 if (Tok.isNot(TKind))
1112 return SourceLocation();
1113 SourceLocation TokenLoc = Tok.getLocation();
1114
1115 // Calculate how much whitespace needs to be skipped if any.
1116 unsigned NumWhitespaceChars = 0;
1117 if (SkipTrailingWhitespaceAndNewLine) {
1118 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1119 Tok.getLength();
1120 unsigned char C = *TokenEnd;
1121 while (isHorizontalWhitespace(C)) {
1122 C = *(++TokenEnd);
1123 NumWhitespaceChars++;
1124 }
1125 if (isVerticalWhitespace(C))
1126 NumWhitespaceChars++;
1127 }
1128
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001129 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001130}
Chris Lattner24f0e482009-04-18 22:05:41 +00001131
Reid Spencer5f016e22007-07-11 17:01:13 +00001132/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1133/// get its size, and return it. This is tricky in several cases:
1134/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1135/// then either return the trigraph (skipping 3 chars) or the '?',
1136/// depending on whether trigraphs are enabled or not.
1137/// 2. If this is an escaped newline (potentially with whitespace between
1138/// the backslash and newline), implicitly skip the newline and return
1139/// the char after it.
1140/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1141///
1142/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1143/// know that we can accumulate into Size, and that we have already incremented
1144/// Ptr by Size bytes.
1145///
1146/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1147/// be updated to match.
1148///
1149char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001150 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 // If we have a slash, look for an escaped newline.
1152 if (Ptr[0] == '\\') {
1153 ++Size;
1154 ++Ptr;
1155Slash:
1156 // Common case, backslash-char where the char is not whitespace.
1157 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Chris Lattner5636a3b2009-06-23 05:15:06 +00001159 // See if we have optional whitespace characters between the slash and
1160 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001161 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1162 // Remember that this token needs to be cleaned.
1163 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001164
Chris Lattner24f0e482009-04-18 22:05:41 +00001165 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001166 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001167 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Chris Lattner24f0e482009-04-18 22:05:41 +00001169 // Found backslash<whitespace><newline>. Parse the char after it.
1170 Size += EscapedNewLineSize;
1171 Ptr += EscapedNewLineSize;
1172 // Use slow version to accumulate a correct size field.
1173 return getCharAndSizeSlow(Ptr, Size, Tok);
1174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 // Otherwise, this is not an escaped newline, just return the slash.
1177 return '\\';
1178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // If this is a trigraph, process it.
1181 if (Ptr[0] == '?' && Ptr[1] == '?') {
1182 // If this is actually a legal trigraph (not something like "??x"), emit
1183 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1184 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1185 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001186 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187
1188 Ptr += 3;
1189 Size += 3;
1190 if (C == '\\') goto Slash;
1191 return C;
1192 }
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // If this is neither, return a single character.
1196 ++Size;
1197 return *Ptr;
1198}
1199
1200
1201/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1202/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1203/// and that we have already incremented Ptr by Size bytes.
1204///
1205/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1206/// be updated to match.
1207char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1208 const LangOptions &Features) {
1209 // 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
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001218 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1219 // Found backslash<whitespace><newline>. Parse the char after it.
1220 Size += EscapedNewLineSize;
1221 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Chris Lattner24f0e482009-04-18 22:05:41 +00001223 // Use slow version to accumulate a correct size field.
1224 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 // Otherwise, this is not an escaped newline, just return the slash.
1228 return '\\';
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 // If this is a trigraph, process it.
1232 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1233 // If this is actually a legal trigraph (not something like "??x"), return
1234 // it.
1235 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1236 Ptr += 3;
1237 Size += 3;
1238 if (C == '\\') goto Slash;
1239 return C;
1240 }
1241 }
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 // If this is neither, return a single character.
1244 ++Size;
1245 return *Ptr;
1246}
1247
1248//===----------------------------------------------------------------------===//
1249// Helper methods for lexing.
1250//===----------------------------------------------------------------------===//
1251
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001252/// \brief Routine that indiscriminately skips bytes in the source file.
1253void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1254 BufferPtr += Bytes;
1255 if (BufferPtr > BufferEnd)
1256 BufferPtr = BufferEnd;
1257 IsAtStartOfLine = StartOfLine;
1258}
1259
Chris Lattnerd2177732007-07-20 16:59:19 +00001260void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1262 unsigned Size;
1263 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001264 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 --CurPtr; // Back up over the skipped character.
1268
1269 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1270 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1271 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001272 //
1273 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1274 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1276FinishIdentifier:
1277 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001278 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1279 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 // If we are in raw mode, return this identifier raw. There is no need to
1282 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001283 if (LexingRawMode)
1284 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001286 // Fill in Result.IdentifierInfo and update the token kind,
1287 // looking up the identifier in the identifier table.
1288 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 // Finally, now that we know we have an identifier, pass this off to the
1291 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001292 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001293 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001294
Chris Lattner6a170eb2009-01-21 07:43:11 +00001295 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 C = getCharAndSize(CurPtr, Size);
1301 while (1) {
1302 if (C == '$') {
1303 // If we hit a $ and they are not supported in identifiers, we are done.
1304 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001307 if (!isLexingRawMode())
1308 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 CurPtr = ConsumeChar(CurPtr, Size, Result);
1310 C = getCharAndSize(CurPtr, Size);
1311 continue;
1312 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1313 // Found end of identifier.
1314 goto FinishIdentifier;
1315 }
1316
1317 // Otherwise, this character is good, consume it.
1318 CurPtr = ConsumeChar(CurPtr, Size, Result);
1319
1320 C = getCharAndSize(CurPtr, Size);
1321 while (isIdentifierBody(C)) { // FIXME: UCNs.
1322 CurPtr = ConsumeChar(CurPtr, Size, Result);
1323 C = getCharAndSize(CurPtr, Size);
1324 }
1325 }
1326}
1327
Douglas Gregora75ec432010-08-30 14:50:47 +00001328/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001329/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001330static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1331 unsigned Size;
1332 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1333 if (C1 != '0')
1334 return false;
1335 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1336 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001337}
Reid Spencer5f016e22007-07-11 17:01:13 +00001338
Nate Begeman5253c7f2008-04-14 02:26:39 +00001339/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001340/// constant. From[-1] is the first character lexed. Return the end of the
1341/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001342void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 unsigned Size;
1344 char C = getCharAndSize(CurPtr, Size);
1345 char PrevCh = 0;
1346 while (isNumberBody(C)) { // FIXME: UCNs?
1347 CurPtr = ConsumeChar(CurPtr, Size, Result);
1348 PrevCh = C;
1349 C = getCharAndSize(CurPtr, Size);
1350 }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001353 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1354 // If we are in Microsoft mode, don't continue if the constant is hex.
1355 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Francois Pichet62ec1f22011-09-17 17:15:52 +00001356 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001357 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1358 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001359
1360 // If we have a hex FP constant, continue.
Douglas Gregor46717302011-10-12 18:51:02 +00001361 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001365 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001366 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001367 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368}
1369
1370/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001371/// either " or L" or u8" or u" or U".
1372void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1373 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 char C = getAndAdvanceChar(CurPtr, Result);
1377 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001378 // Skip escaped characters. Escaped newlines will already be processed by
1379 // getAndAdvanceChar.
1380 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001382
Chris Lattner571339c2010-05-30 23:27:38 +00001383 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001384 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001385 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001386 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001387 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
Chris Lattner571339c2010-05-30 23:27:38 +00001390
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001391 if (C == 0) {
1392 if (isCodeCompletionPoint(CurPtr-1)) {
1393 PP->CodeCompleteNaturalLanguage();
1394 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1395 return cutOffLexing();
1396 }
1397
Chris Lattner571339c2010-05-30 23:27:38 +00001398 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001399 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 C = getAndAdvanceChar(CurPtr, Result);
1401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001404 if (NulCharacter && !isLexingRawMode())
1405 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001406
Reid Spencer5f016e22007-07-11 17:01:13 +00001407 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001408 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001409 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001410 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001411}
1412
Craig Topper2fa4e862011-08-11 04:06:15 +00001413/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1414/// having lexed R", LR", u8R", uR", or UR".
1415void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1416 tok::TokenKind Kind) {
1417 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1418 // Between the initial and final double quote characters of the raw string,
1419 // any transformations performed in phases 1 and 2 (trigraphs,
1420 // universal-character-names, and line splicing) are reverted.
1421
1422 unsigned PrefixLen = 0;
1423
1424 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1425 ++PrefixLen;
1426
1427 // If the last character was not a '(', then we didn't lex a valid delimiter.
1428 if (CurPtr[PrefixLen] != '(') {
1429 if (!isLexingRawMode()) {
1430 const char *PrefixEnd = &CurPtr[PrefixLen];
1431 if (PrefixLen == 16) {
1432 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1433 } else {
1434 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1435 << StringRef(PrefixEnd, 1);
1436 }
1437 }
1438
1439 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1440 // it's possible the '"' was intended to be part of the raw string, but
1441 // there's not much we can do about that.
1442 while (1) {
1443 char C = *CurPtr++;
1444
1445 if (C == '"')
1446 break;
1447 if (C == 0 && CurPtr-1 == BufferEnd) {
1448 --CurPtr;
1449 break;
1450 }
1451 }
1452
1453 FormTokenWithChars(Result, CurPtr, tok::unknown);
1454 return;
1455 }
1456
1457 // Save prefix and move CurPtr past it
1458 const char *Prefix = CurPtr;
1459 CurPtr += PrefixLen + 1; // skip over prefix and '('
1460
1461 while (1) {
1462 char C = *CurPtr++;
1463
1464 if (C == ')') {
1465 // Check for prefix match and closing quote.
1466 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1467 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1468 break;
1469 }
1470 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1471 if (!isLexingRawMode())
1472 Diag(BufferPtr, diag::err_unterminated_raw_string)
1473 << StringRef(Prefix, PrefixLen);
1474 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1475 return;
1476 }
1477 }
1478
1479 // Update the location of token as well as BufferPtr.
1480 const char *TokStart = BufferPtr;
1481 FormTokenWithChars(Result, CurPtr, Kind);
1482 Result.setLiteralData(TokStart);
1483}
1484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1486/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001487void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001489 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 char C = getAndAdvanceChar(CurPtr, Result);
1491 while (C != '>') {
1492 // Skip escaped characters.
1493 if (C == '\\') {
1494 // Skip the escaped character.
1495 C = getAndAdvanceChar(CurPtr, Result);
1496 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001497 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1498 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001499 // If the filename is unterminated, then it must just be a lone <
1500 // character. Return this as such.
1501 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 return;
1503 } else if (C == 0) {
1504 NulCharacter = CurPtr-1;
1505 }
1506 C = getAndAdvanceChar(CurPtr, Result);
1507 }
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001510 if (NulCharacter && !isLexingRawMode())
1511 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001514 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001515 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001516 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001517}
1518
1519
1520/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001521/// lexed either ' or L' or u' or U'.
1522void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1523 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 const char *NulCharacter = 0; // Does this character contain the \0 character?
1525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 char C = getAndAdvanceChar(CurPtr, Result);
1527 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001528 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001529 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001530 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001532 }
1533
1534 while (C != '\'') {
1535 // Skip escaped characters.
1536 if (C == '\\') {
1537 // Skip the escaped character.
1538 // FIXME: UCN's
1539 C = getAndAdvanceChar(CurPtr, Result);
1540 } else if (C == '\n' || C == '\r' || // Newline.
1541 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001542 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001543 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001544 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1545 return;
1546 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001547 if (isCodeCompletionPoint(CurPtr-1)) {
1548 PP->CodeCompleteNaturalLanguage();
1549 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1550 return cutOffLexing();
1551 }
1552
Chris Lattnerd80f7862010-07-07 23:24:27 +00001553 NulCharacter = CurPtr-1;
1554 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 C = getAndAdvanceChar(CurPtr, Result);
1556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattnerd80f7862010-07-07 23:24:27 +00001558 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001559 if (NulCharacter && !isLexingRawMode())
1560 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001563 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001564 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001565 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001566}
1567
1568/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1569/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001570///
1571/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1572///
1573bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Whitespace - Skip it, then return the token after the whitespace.
1575 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1576 while (1) {
1577 // Skip horizontal whitespace very aggressively.
1578 while (isHorizontalWhitespace(Char))
1579 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001581 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 if (Char != '\n' && Char != '\r')
1583 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 if (ParsingPreprocessorDirective) {
1586 // End of preprocessor directive line, let LexTokenInternal handle this.
1587 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001588 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 // ok, but handle newline.
1592 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001593 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001595 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 Char = *++CurPtr;
1597 }
1598
1599 // If this isn't immediately after a newline, there is leading space.
1600 char PrevChar = CurPtr[-1];
1601 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001602 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001603
Chris Lattnerd88dc482008-10-12 04:05:48 +00001604 // If the client wants us to return whitespace, return it now.
1605 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001606 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001607 return true;
1608 }
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001611 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612}
1613
1614// SkipBCPLComment - We have just read the // characters from input. Skip until
1615// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001616/// BufferPtr and return.
1617///
1618/// If we're in KeepCommentMode or any CommentHandler has inserted
1619/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001620bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 // If BCPL comments aren't explicitly enabled for this language, emit an
1622 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001623 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Mark them enabled so we only emit one warning for this translation
1627 // unit.
1628 Features.BCPLComment = true;
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // Scan over the body of the comment. The common case, when scanning, is that
1632 // the comment contains normal ascii characters with nothing interesting in
1633 // them. As such, optimize for this case with the inner loop.
1634 char C;
1635 do {
1636 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 // Skip over characters in the fast loop.
1638 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 C != '\n' && C != '\r') // Newline or DOS-style newline.
1640 C = *++CurPtr;
1641
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001642 const char *NextLine = CurPtr;
1643 if (C != 0) {
1644 // We found a newline, see if it's escaped.
1645 const char *EscapePtr = CurPtr-1;
1646 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1647 --EscapePtr;
1648
1649 if (*EscapePtr == '\\') // Escaped newline.
1650 CurPtr = EscapePtr;
1651 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1652 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1653 CurPtr = EscapePtr-2;
1654 else
1655 break; // This is a newline, we're done.
1656
1657 C = *CurPtr;
1658 }
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001661 // properly decode the character. Read it in raw mode to avoid emitting
1662 // diagnostics about things like trigraphs. If we see an escaped newline,
1663 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001665 bool OldRawMode = isLexingRawMode();
1666 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001668 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001669
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001670 // If we only read only one character, then no special handling is needed.
1671 // We're done and can skip forward to the newline.
1672 if (C != 0 && CurPtr == OldPtr+1) {
1673 CurPtr = NextLine;
1674 break;
1675 }
1676
Chris Lattneread616c2009-04-05 00:26:41 +00001677 // If the char that we finally got was a \n, then we must have had something
1678 // like \<newline><newline>. We don't want to have consumed the second
1679 // newline, we want CurPtr, to end up pointing to it down below.
1680 if (C == '\n' || C == '\r') {
1681 --CurPtr;
1682 C = 'x'; // doesn't matter what this is.
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // If we read multiple characters, and one of those characters was a \r or
1686 // \n, then we had an escaped newline within the comment. Emit diagnostic
1687 // unless the next line is also a // comment.
1688 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1689 for (; OldPtr != CurPtr; ++OldPtr)
1690 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1691 // Okay, we found a // comment that ends in a newline, if the next
1692 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001693 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001695 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 ++ForwardPtr;
1697 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1698 break;
1699 }
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Chris Lattner74d15df2008-11-22 02:02:22 +00001701 if (!isLexingRawMode())
1702 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 break;
1704 }
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Douglas Gregor55817af2010-08-25 17:04:25 +00001707 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001708 --CurPtr;
1709 break;
1710 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001711
1712 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1713 PP->CodeCompleteNaturalLanguage();
1714 cutOffLexing();
1715 return false;
1716 }
1717
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 } while (C != '\n' && C != '\r');
1719
Chris Lattner3d0ad582010-02-03 21:06:21 +00001720 // Found but did not consume the newline. Notify comment handlers about the
1721 // comment unless we're in a #if 0 block.
1722 if (PP && !isLexingRawMode() &&
1723 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1724 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001725 BufferPtr = CurPtr;
1726 return true; // A token has to be returned.
1727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001730 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 return SaveBCPLComment(Result, CurPtr);
1732
1733 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001734 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1736 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001737 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001741 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001742 // contribute to another token), it isn't needed for correctness. Note that
1743 // this is ok even in KeepWhitespaceMode, because we would have returned the
1744 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001748 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001750 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001752 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753}
1754
1755/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1756/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001757bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001758 // If we're not in a preprocessor directive, just return the // comment
1759 // directly.
1760 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Chris Lattner9e6293d2008-10-12 04:51:35 +00001762 if (!ParsingPreprocessorDirective)
1763 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Chris Lattner9e6293d2008-10-12 04:51:35 +00001765 // If this BCPL-style comment is in a macro definition, transmogrify it into
1766 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001767 bool Invalid = false;
1768 std::string Spelling = PP->getSpelling(Result, &Invalid);
1769 if (Invalid)
1770 return true;
1771
Chris Lattner9e6293d2008-10-12 04:51:35 +00001772 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1773 Spelling[1] = '*'; // Change prefix to "/*".
1774 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Chris Lattner9e6293d2008-10-12 04:51:35 +00001776 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001777 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001778 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001779 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001780}
1781
1782/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1783/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001784/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001785static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 Lexer *L) {
1787 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // Back up off the newline.
1790 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 // If this is a two-character newline sequence, skip the other character.
1793 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1794 // \n\n or \r\r -> not escaped newline.
1795 if (CurPtr[0] == CurPtr[1])
1796 return false;
1797 // \n\r or \r\n -> skip the newline.
1798 --CurPtr;
1799 }
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 // If we have horizontal whitespace, skip over it. We allow whitespace
1802 // between the slash and newline.
1803 bool HasSpace = false;
1804 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1805 --CurPtr;
1806 HasSpace = true;
1807 }
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 // If we have a slash, we know this is an escaped newline.
1810 if (*CurPtr == '\\') {
1811 if (CurPtr[-1] != '*') return false;
1812 } else {
1813 // It isn't a slash, is it the ?? / trigraph?
1814 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1815 CurPtr[-3] != '*')
1816 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 // This is the trigraph ending the comment. Emit a stern warning!
1819 CurPtr -= 2;
1820
1821 // If no trigraphs are enabled, warn that we ignored this trigraph and
1822 // ignore this * character.
1823 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001824 if (!L->isLexingRawMode())
1825 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 return false;
1827 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001828 if (!L->isLexingRawMode())
1829 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001833 if (!L->isLexingRawMode())
1834 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001837 if (HasSpace && !L->isLexingRawMode())
1838 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 return true;
1841}
1842
1843#ifdef __SSE2__
1844#include <emmintrin.h>
1845#elif __ALTIVEC__
1846#include <altivec.h>
1847#undef bool
1848#endif
1849
1850/// SkipBlockComment - We have just read the /* characters from input. Read
1851/// until we find the */ characters that terminate the comment. Note that we
1852/// don't bother decoding trigraphs or escaped newlines in block comments,
1853/// because they cannot cause the comment to end. The only thing that can
1854/// happen is the comment could end with an escaped newline between the */ end
1855/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001856///
Chris Lattner046c2272010-01-18 22:35:47 +00001857/// If we're in KeepCommentMode or any CommentHandler has inserted
1858/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001859bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001861 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 // optimization helps people who like to put a lot of * characters in their
1863 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001864
1865 // The first character we get with newlines and trigraphs skipped to handle
1866 // the degenerate /*/ case below correctly if the * has an escaped newline
1867 // after it.
1868 unsigned CharSize;
1869 unsigned char C = getCharAndSize(CurPtr, CharSize);
1870 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001872 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001873 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001874 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Chris Lattner31f0eca2008-10-12 04:19:49 +00001876 // KeepWhitespaceMode should return this broken comment as a token. Since
1877 // it isn't a well formed comment, just return it as an 'unknown' token.
1878 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001879 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001880 return true;
1881 }
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Chris Lattner31f0eca2008-10-12 04:19:49 +00001883 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001884 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Chris Lattner8146b682007-07-21 23:43:37 +00001887 // Check to see if the first character after the '/*' is another /. If so,
1888 // then this slash does not end the block comment, it is part of it.
1889 if (C == '/')
1890 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Reid Spencer5f016e22007-07-11 17:01:13 +00001892 while (1) {
1893 // Skip over all non-interesting characters until we find end of buffer or a
1894 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001895 if (CurPtr + 24 < BufferEnd &&
1896 // If there is a code-completion point avoid the fast scan because it
1897 // doesn't check for '\0'.
1898 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // While not aligned to a 16-byte boundary.
1900 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1901 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 if (C == '/') goto FoundSlash;
1904
1905#ifdef __SSE2__
1906 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1907 '/', '/', '/', '/', '/', '/', '/', '/');
1908 while (CurPtr+16 <= BufferEnd &&
1909 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1910 CurPtr += 16;
1911#elif __ALTIVEC__
1912 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001913 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 '/', '/', '/', '/', '/', '/', '/', '/'
1915 };
1916 while (CurPtr+16 <= BufferEnd &&
1917 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1918 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001919#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 // Scan for '/' quickly. Many block comments are very large.
1921 while (CurPtr[0] != '/' &&
1922 CurPtr[1] != '/' &&
1923 CurPtr[2] != '/' &&
1924 CurPtr[3] != '/' &&
1925 CurPtr+4 < BufferEnd) {
1926 CurPtr += 4;
1927 }
1928#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // It has to be one of the bytes scanned, increment to it and read one.
1931 C = *CurPtr++;
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 // Loop to scan the remainder.
1935 while (C != '/' && C != '\0')
1936 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 FoundSlash:
1939 if (C == '/') {
1940 if (CurPtr[-2] == '*') // We found the final */. We're done!
1941 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1944 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1945 // We found the final */, though it had an escaped newline between the
1946 // * and /. We're done!
1947 break;
1948 }
1949 }
1950 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1951 // If this is a /* inside of the comment, emit a warning. Don't do this
1952 // if this is a /*/, which will end the comment. This misses cases with
1953 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001954 if (!isLexingRawMode())
1955 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 }
1957 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001958 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001959 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // Note: the user probably forgot a */. We could continue immediately
1961 // after the /*, but this would involve lexing a lot of what really is the
1962 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001963 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Chris Lattner31f0eca2008-10-12 04:19:49 +00001965 // KeepWhitespaceMode should return this broken comment as a token. Since
1966 // it isn't a well formed comment, just return it as an 'unknown' token.
1967 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001968 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001969 return true;
1970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Chris Lattner31f0eca2008-10-12 04:19:49 +00001972 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001973 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001974 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1975 PP->CodeCompleteNaturalLanguage();
1976 cutOffLexing();
1977 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001979
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 C = *CurPtr++;
1981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Chris Lattner3d0ad582010-02-03 21:06:21 +00001983 // Notify comment handlers about the comment unless we're in a #if 0 block.
1984 if (PP && !isLexingRawMode() &&
1985 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1986 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001987 BufferPtr = CurPtr;
1988 return true; // A token has to be returned.
1989 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001992 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001993 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001994 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 }
1996
1997 // It is common for the tokens immediately after a /**/ comment to be
1998 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001999 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2000 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002002 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002004 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 }
2006
2007 // Otherwise, just return so that the next character will be lexed as a token.
2008 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002009 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002010 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002011}
2012
2013//===----------------------------------------------------------------------===//
2014// Primary Lexing Entry Points
2015//===----------------------------------------------------------------------===//
2016
Reid Spencer5f016e22007-07-11 17:01:13 +00002017/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2018/// uninterpreted string. This switches the lexer out of directive mode.
2019std::string Lexer::ReadToEndOfLine() {
2020 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2021 "Must be in a preprocessing directive!");
2022 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002023 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002024
2025 // CurPtr - Cache BufferPtr in an automatic variable.
2026 const char *CurPtr = BufferPtr;
2027 while (1) {
2028 char Char = getAndAdvanceChar(CurPtr, Tmp);
2029 switch (Char) {
2030 default:
2031 Result += Char;
2032 break;
2033 case 0: // Null.
2034 // Found end of file?
2035 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002036 if (isCodeCompletionPoint(CurPtr-1)) {
2037 PP->CodeCompleteNaturalLanguage();
2038 cutOffLexing();
2039 return Result;
2040 }
2041
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // Nope, normal character, continue.
2043 Result += Char;
2044 break;
2045 }
2046 // FALL THROUGH.
2047 case '\r':
2048 case '\n':
2049 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2050 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2051 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Peter Collingbourne84021552011-02-28 02:37:51 +00002053 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002055 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002056 if (PP)
2057 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002058 Lex(Tmp);
2059 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002060 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 // Finally, we're done, return the string we found.
2063 return Result;
2064 }
2065 }
2066}
2067
2068/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2069/// condition, reporting diagnostics and handling other edge cases as required.
2070/// This returns true if Result contains a token, false if PP.Lex should be
2071/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002072bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 // If we hit the end of the file while parsing a preprocessor directive,
2074 // end the preprocessor directive first. The next token returned will
2075 // then be the end of file.
2076 if (ParsingPreprocessorDirective) {
2077 // Done parsing the "line".
2078 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002080 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002083 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002085 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // If we are in raw mode, return this event as an EOF token. Let the caller
2088 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002089 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 Result.startToken();
2091 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002092 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 return true;
2094 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002095
Douglas Gregorf44e8542010-08-24 19:08:16 +00002096 // Issue diagnostics for unterminated #if and missing newline.
2097
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // If we are in a #if directive, emit an error.
2099 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002100 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002101 PP->Diag(ConditionalStack.back().IfLoc,
2102 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 ConditionalStack.pop_back();
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002106 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2107 // a pedwarn.
2108 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002109 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002110 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 BufferPtr = CurPtr;
2113
2114 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002115 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002116}
2117
2118/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2119/// the specified lexer will return a tok::l_paren token, 0 if it is something
2120/// else and 2 if there are no more tokens in the buffer controlled by the
2121/// lexer.
2122unsigned Lexer::isNextPPTokenLParen() {
2123 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // Switch to 'skipping' mode. This will ensure that we can lex a token
2126 // without emitting diagnostics, disables macro expansion, and will cause EOF
2127 // to return an EOF token instead of popping the include stack.
2128 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Save state that can be changed while lexing so that we can restore it.
2131 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002132 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Chris Lattnerd2177732007-07-20 16:59:19 +00002134 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 Tok.startToken();
2136 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // Restore state that may have changed.
2139 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002140 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // Restore the lexer back to non-skipping mode.
2143 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002145 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002147 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002148}
2149
Chris Lattner34f349d2009-12-14 06:16:57 +00002150/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002151static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2152 ConflictMarkerKind CMK) {
2153 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2154 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2155 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2156 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002157 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002158 // Must occur at start of line.
2159 if (RestOfBuffer[Pos-1] != '\r' &&
2160 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002161 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2162 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002163 continue;
2164 }
2165 return RestOfBuffer.data()+Pos;
2166 }
2167 return 0;
2168}
2169
2170/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2171/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2172/// and recover nicely. This returns true if it is a conflict marker and false
2173/// if not.
2174bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2175 // Only a conflict marker if it starts at the beginning of a line.
2176 if (CurPtr != BufferStart &&
2177 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2178 return false;
2179
Richard Smithd5e1d602011-10-12 00:37:51 +00002180 // Check to see if we have <<<<<<< or >>>>.
2181 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2182 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002183 return false;
2184
2185 // If we have a situation where we don't care about conflict markers, ignore
2186 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002187 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002188 return false;
2189
Richard Smithd5e1d602011-10-12 00:37:51 +00002190 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2191
2192 // Check to see if there is an ending marker somewhere in the buffer at the
2193 // start of a line to terminate this conflict marker.
2194 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002195 // We found a match. We are really in a conflict marker.
2196 // Diagnose this, and ignore to the end of line.
2197 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002198 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002199
2200 // Skip ahead to the end of line. We know this exists because the
2201 // end-of-conflict marker starts with \r or \n.
2202 while (*CurPtr != '\r' && *CurPtr != '\n') {
2203 assert(CurPtr != BufferEnd && "Didn't find end of line");
2204 ++CurPtr;
2205 }
2206 BufferPtr = CurPtr;
2207 return true;
2208 }
2209
2210 // No end of conflict marker found.
2211 return false;
2212}
2213
2214
Richard Smithd5e1d602011-10-12 00:37:51 +00002215/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2216/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2217/// is the end of a conflict marker. Handle it by ignoring up until the end of
2218/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002219bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2220 // Only a conflict marker if it starts at the beginning of a line.
2221 if (CurPtr != BufferStart &&
2222 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2223 return false;
2224
2225 // If we have a situation where we don't care about conflict markers, ignore
2226 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002227 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002228 return false;
2229
Richard Smithd5e1d602011-10-12 00:37:51 +00002230 // Check to see if we have the marker (4 characters in a row).
2231 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002232 if (CurPtr[i] != CurPtr[0])
2233 return false;
2234
2235 // If we do have it, search for the end of the conflict marker. This could
2236 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2237 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002238 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2239 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002240 CurPtr = End;
2241
2242 // Skip ahead to the end of line.
2243 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2244 ++CurPtr;
2245
2246 BufferPtr = CurPtr;
2247
2248 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002249 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002250 return true;
2251 }
2252
2253 return false;
2254}
2255
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002256bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2257 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002258 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002259 return Loc == PP->getCodeCompletionLoc();
2260 }
2261
2262 return false;
2263}
2264
Reid Spencer5f016e22007-07-11 17:01:13 +00002265
2266/// LexTokenInternal - This implements a simple C family lexer. It is an
2267/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002268/// has a null character at the end of the file. This returns a preprocessing
2269/// token, not a normal token, as such, it is an internal interface. It assumes
2270/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002271void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002272LexNextToken:
2273 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002274 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 // CurPtr - Cache BufferPtr in an automatic variable.
2278 const char *CurPtr = BufferPtr;
2279
2280 // Small amounts of horizontal whitespace is very common between tokens.
2281 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2282 ++CurPtr;
2283 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2284 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Chris Lattnerd88dc482008-10-12 04:05:48 +00002286 // If we are keeping whitespace and other tokens, just return what we just
2287 // skipped. The next lexer invocation will return the token after the
2288 // whitespace.
2289 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002290 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002291 return;
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002295 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 // Read a character, advancing over it.
2301 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002302 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 switch (Char) {
2305 case 0: // Null.
2306 // Found end of file?
2307 if (CurPtr-1 == BufferEnd) {
2308 // Read the PP instance variable into an automatic variable, because
2309 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002310 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2312 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002313 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2314 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 }
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002317 // Check if we are performing code completion.
2318 if (isCodeCompletionPoint(CurPtr-1)) {
2319 // Return the code-completion token.
2320 Result.startToken();
2321 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2322 return;
2323 }
2324
Chris Lattner74d15df2008-11-22 02:02:22 +00002325 if (!isLexingRawMode())
2326 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002327 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002328 if (SkipWhitespace(Result, CurPtr))
2329 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002332
2333 case 26: // DOS & CP/M EOF: "^Z".
2334 // If we're in Microsoft extensions mode, treat this as end of file.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002335 if (Features.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002336 // Read the PP instance variable into an automatic variable, because
2337 // LexEndOfFile will often delete 'this'.
2338 Preprocessor *PPCache = PP;
2339 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2340 return; // Got a token to return.
2341 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2342 return PPCache->Lex(Result);
2343 }
2344 // If Microsoft extensions are disabled, this is just random garbage.
2345 Kind = tok::unknown;
2346 break;
2347
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 case '\n':
2349 case '\r':
2350 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002351 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 if (ParsingPreprocessorDirective) {
2353 // Done parsing the "line".
2354 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002357 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 // Since we consumed a newline, we are back at the start of a line.
2360 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Peter Collingbourne84021552011-02-28 02:37:51 +00002362 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 break;
2364 }
2365 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002366 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002368 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Chris Lattnerd88dc482008-10-12 04:05:48 +00002370 if (SkipWhitespace(Result, CurPtr))
2371 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 goto LexNextToken; // GCC isn't tail call eliminating.
2373 case ' ':
2374 case '\t':
2375 case '\f':
2376 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002377 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002378 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002379 if (SkipWhitespace(Result, CurPtr))
2380 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002381
2382 SkipIgnoredUnits:
2383 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Chris Lattner8133cfc2007-07-22 06:29:05 +00002385 // If the next token is obviously a // or /* */ comment, skip it efficiently
2386 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002387 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002388 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002389 if (SkipBCPLComment(Result, CurPtr+2))
2390 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002391 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002392 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002393 if (SkipBlockComment(Result, CurPtr+2))
2394 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002395 goto SkipIgnoredUnits;
2396 } else if (isHorizontalWhitespace(*CurPtr)) {
2397 goto SkipHorizontalWhitespace;
2398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002400
Chris Lattner3a570772008-01-03 17:58:54 +00002401 // C99 6.4.4.1: Integer Constants.
2402 // C99 6.4.4.2: Floating Constants.
2403 case '0': case '1': case '2': case '3': case '4':
2404 case '5': case '6': case '7': case '8': case '9':
2405 // Notify MIOpt that we read a non-whitespace/non-comment token.
2406 MIOpt.ReadToken();
2407 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Douglas Gregor5cee1192011-07-27 05:40:30 +00002409 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2410 // Notify MIOpt that we read a non-whitespace/non-comment token.
2411 MIOpt.ReadToken();
2412
2413 if (Features.CPlusPlus0x) {
2414 Char = getCharAndSize(CurPtr, SizeTmp);
2415
2416 // UTF-16 string literal
2417 if (Char == '"')
2418 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2419 tok::utf16_string_literal);
2420
2421 // UTF-16 character constant
2422 if (Char == '\'')
2423 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2424 tok::utf16_char_constant);
2425
Craig Topper2fa4e862011-08-11 04:06:15 +00002426 // UTF-16 raw string literal
2427 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2428 return LexRawStringLiteral(Result,
2429 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2430 SizeTmp2, Result),
2431 tok::utf16_string_literal);
2432
2433 if (Char == '8') {
2434 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2435
2436 // UTF-8 string literal
2437 if (Char2 == '"')
2438 return LexStringLiteral(Result,
2439 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2440 SizeTmp2, Result),
2441 tok::utf8_string_literal);
2442
2443 if (Char2 == 'R') {
2444 unsigned SizeTmp3;
2445 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2446 // UTF-8 raw string literal
2447 if (Char3 == '"') {
2448 return LexRawStringLiteral(Result,
2449 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2450 SizeTmp2, Result),
2451 SizeTmp3, Result),
2452 tok::utf8_string_literal);
2453 }
2454 }
2455 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002456 }
2457
2458 // treat u like the start of an identifier.
2459 return LexIdentifier(Result, CurPtr);
2460
2461 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2462 // Notify MIOpt that we read a non-whitespace/non-comment token.
2463 MIOpt.ReadToken();
2464
2465 if (Features.CPlusPlus0x) {
2466 Char = getCharAndSize(CurPtr, SizeTmp);
2467
2468 // UTF-32 string literal
2469 if (Char == '"')
2470 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2471 tok::utf32_string_literal);
2472
2473 // UTF-32 character constant
2474 if (Char == '\'')
2475 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2476 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002477
2478 // UTF-32 raw string literal
2479 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2480 return LexRawStringLiteral(Result,
2481 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2482 SizeTmp2, Result),
2483 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002484 }
2485
2486 // treat U like the start of an identifier.
2487 return LexIdentifier(Result, CurPtr);
2488
Craig Topper2fa4e862011-08-11 04:06:15 +00002489 case 'R': // Identifier or C++0x raw string literal
2490 // Notify MIOpt that we read a non-whitespace/non-comment token.
2491 MIOpt.ReadToken();
2492
2493 if (Features.CPlusPlus0x) {
2494 Char = getCharAndSize(CurPtr, SizeTmp);
2495
2496 if (Char == '"')
2497 return LexRawStringLiteral(Result,
2498 ConsumeChar(CurPtr, SizeTmp, Result),
2499 tok::string_literal);
2500 }
2501
2502 // treat R like the start of an identifier.
2503 return LexIdentifier(Result, CurPtr);
2504
Chris Lattner3a570772008-01-03 17:58:54 +00002505 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 // Notify MIOpt that we read a non-whitespace/non-comment token.
2507 MIOpt.ReadToken();
2508 Char = getCharAndSize(CurPtr, SizeTmp);
2509
2510 // Wide string literal.
2511 if (Char == '"')
2512 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002513 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002514
Craig Topper2fa4e862011-08-11 04:06:15 +00002515 // Wide raw string literal.
2516 if (Features.CPlusPlus0x && Char == 'R' &&
2517 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2518 return LexRawStringLiteral(Result,
2519 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2520 SizeTmp2, Result),
2521 tok::wide_string_literal);
2522
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 // Wide character constant.
2524 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002525 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2526 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 // C99 6.4.2: Identifiers.
2530 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2531 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002532 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2534 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2535 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002536 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 case 'v': case 'w': case 'x': case 'y': case 'z':
2538 case '_':
2539 // Notify MIOpt that we read a non-whitespace/non-comment token.
2540 MIOpt.ReadToken();
2541 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002542
2543 case '$': // $ in identifiers.
2544 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002545 if (!isLexingRawMode())
2546 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002547 // Notify MIOpt that we read a non-whitespace/non-comment token.
2548 MIOpt.ReadToken();
2549 return LexIdentifier(Result, CurPtr);
2550 }
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Chris Lattner9e6293d2008-10-12 04:51:35 +00002552 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002553 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 // C99 6.4.4: Character Constants.
2556 case '\'':
2557 // Notify MIOpt that we read a non-whitespace/non-comment token.
2558 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002559 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002560
2561 // C99 6.4.5: String Literals.
2562 case '"':
2563 // Notify MIOpt that we read a non-whitespace/non-comment token.
2564 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002565 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002566
2567 // C99 6.4.6: Punctuators.
2568 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002569 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 break;
2571 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002572 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 break;
2574 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002575 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 break;
2577 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002578 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 break;
2580 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002581 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 break;
2583 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002584 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 break;
2586 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002587 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 break;
2589 case '.':
2590 Char = getCharAndSize(CurPtr, SizeTmp);
2591 if (Char >= '0' && Char <= '9') {
2592 // Notify MIOpt that we read a non-whitespace/non-comment token.
2593 MIOpt.ReadToken();
2594
2595 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2596 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002597 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 CurPtr += SizeTmp;
2599 } else if (Char == '.' &&
2600 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002601 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2603 SizeTmp2, Result);
2604 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002605 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
2607 break;
2608 case '&':
2609 Char = getCharAndSize(CurPtr, SizeTmp);
2610 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002611 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2613 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002614 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2616 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002617 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 }
2619 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002620 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002622 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002623 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2624 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002625 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 }
2627 break;
2628 case '+':
2629 Char = getCharAndSize(CurPtr, SizeTmp);
2630 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002632 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002635 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002637 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 }
2639 break;
2640 case '-':
2641 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002642 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002644 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002645 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002646 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2648 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002649 Kind = tok::arrowstar;
2650 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002652 Kind = tok::arrow;
2653 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002655 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002657 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 }
2659 break;
2660 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002661 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 break;
2663 case '!':
2664 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002665 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2667 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002668 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 }
2670 break;
2671 case '/':
2672 // 6.4.9: Comments
2673 Char = getCharAndSize(CurPtr, SizeTmp);
2674 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002675 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2676 // want to lex this as a comment. There is one problem with this though,
2677 // that in one particular corner case, this can change the behavior of the
2678 // resultant program. For example, In "foo //**/ bar", C89 would lex
2679 // this as "foo / bar" and langauges with BCPL comments would lex it as
2680 // "foo". Check to see if the character after the second slash is a '*'.
2681 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002682 // However, we never do this in -traditional-cpp mode.
2683 if ((Features.BCPLComment ||
2684 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2685 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002686 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002687 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Chris Lattner8402c732009-01-16 22:39:25 +00002689 // It is common for the tokens immediately after a // comment to be
2690 // whitespace (indentation for the next line). Instead of going through
2691 // the big switch, handle it efficiently now.
2692 goto SkipIgnoredUnits;
2693 }
2694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Chris Lattner8402c732009-01-16 22:39:25 +00002696 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002698 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002699 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002700 }
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Chris Lattner8402c732009-01-16 22:39:25 +00002702 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002704 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002706 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 }
2708 break;
2709 case '%':
2710 Char = getCharAndSize(CurPtr, SizeTmp);
2711 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002712 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2714 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002715 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002716 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2717 } else if (Features.Digraphs && Char == ':') {
2718 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2719 Char = getCharAndSize(CurPtr, SizeTmp);
2720 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002721 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2723 SizeTmp2, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002724 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002726 if (!isLexingRawMode())
2727 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002728 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002729 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 // We parsed a # character. If this occurs at the start of the line,
2731 // it's actually the start of a preprocessing directive. Callback to
2732 // the preprocessor to handle it.
2733 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002734 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002735 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002736 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 // As an optimization, if the preprocessor didn't switch lexers, tail
2739 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002740 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 // Start a new token. If this is a #include or something, the PP may
2742 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002743 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002745 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002746 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 IsAtStartOfLine = false;
2748 }
2749 goto LexNextToken; // GCC isn't tail call eliminating.
2750 }
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Chris Lattner168ae2d2007-10-17 20:41:00 +00002752 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Chris Lattnere91e9322009-03-18 20:58:27 +00002755 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 }
2757 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002758 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 }
2760 break;
2761 case '<':
2762 Char = getCharAndSize(CurPtr, SizeTmp);
2763 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002764 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002766 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2767 if (After == '=') {
2768 Kind = tok::lesslessequal;
2769 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2770 SizeTmp2, Result);
2771 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2772 // If this is actually a '<<<<<<<' version control conflict marker,
2773 // recognize it as such and recover nicely.
2774 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00002775 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
2776 // If this is '<<<<' and we're in a Perforce-style conflict marker,
2777 // ignore it.
2778 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002779 } else if (Features.CUDA && After == '<') {
2780 Kind = tok::lesslessless;
2781 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2782 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002783 } else {
2784 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2785 Kind = tok::lessless;
2786 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::lessequal;
2790 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002791 if (Features.CPlusPlus0x &&
2792 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2793 // C++0x [lex.pptoken]p3:
2794 // Otherwise, if the next three characters are <:: and the subsequent
2795 // character is neither : nor >, the < is treated as a preprocessor
2796 // token by itself and not as the first character of the alternative
2797 // token <:.
2798 unsigned SizeTmp3;
2799 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2800 if (After != ':' && After != '>') {
2801 Kind = tok::less;
2802 break;
2803 }
2804 }
2805
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002807 Kind = tok::l_square;
2808 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002810 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002812 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 }
2814 break;
2815 case '>':
2816 Char = getCharAndSize(CurPtr, SizeTmp);
2817 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002819 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002821 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2822 if (After == '=') {
2823 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2824 SizeTmp2, Result);
2825 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00002826 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
2827 // If this is actually a '>>>>' conflict marker, recognize it as such
2828 // and recover nicely.
2829 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00002830 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2831 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2832 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002833 } else if (Features.CUDA && After == '>') {
2834 Kind = tok::greatergreatergreater;
2835 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2836 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002837 } else {
2838 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2839 Kind = tok::greatergreater;
2840 }
2841
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002843 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 }
2845 break;
2846 case '^':
2847 Char = getCharAndSize(CurPtr, SizeTmp);
2848 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002850 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002852 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 }
2854 break;
2855 case '|':
2856 Char = getCharAndSize(CurPtr, SizeTmp);
2857 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002858 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2860 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002861 // If this is '|||||||' and we're in a conflict marker, ignore it.
2862 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2863 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002864 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002865 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2866 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002867 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 }
2869 break;
2870 case ':':
2871 Char = getCharAndSize(CurPtr, SizeTmp);
2872 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002873 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2875 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002876 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002877 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002878 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002879 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 }
2881 break;
2882 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002883 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 break;
2885 case '=':
2886 Char = getCharAndSize(CurPtr, SizeTmp);
2887 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002888 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00002889 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2890 goto LexNextToken;
2891
Chris Lattner9e6293d2008-10-12 04:51:35 +00002892 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002893 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002894 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002895 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 }
2897 break;
2898 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002899 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 break;
2901 case '#':
2902 Char = getCharAndSize(CurPtr, SizeTmp);
2903 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002904 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002906 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002907 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002908 if (!isLexingRawMode())
2909 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2911 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 // We parsed a # character. If this occurs at the start of the line,
2913 // it's actually the start of a preprocessing directive. Callback to
2914 // the preprocessor to handle it.
2915 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002916 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002917 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002918 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 // As an optimization, if the preprocessor didn't switch lexers, tail
2921 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002922 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 // Start a new token. If this is a #include or something, the PP may
2924 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002925 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002926 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002927 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002928 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 IsAtStartOfLine = false;
2930 }
2931 goto LexNextToken; // GCC isn't tail call eliminating.
2932 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002933 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 }
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chris Lattnere91e9322009-03-18 20:58:27 +00002936 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 }
2938 break;
2939
Chris Lattner3a570772008-01-03 17:58:54 +00002940 case '@':
2941 // Objective C support.
2942 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002943 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002944 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002945 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002946 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 case '\\':
2949 // FIXME: UCN's.
2950 // FALL THROUGH.
2951 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002952 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 break;
2954 }
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 // Notify MIOpt that we read a non-whitespace/non-comment token.
2957 MIOpt.ReadToken();
2958
2959 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002960 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002961}