blob: 3b1149c08af3545992b9d0873b081b7def47b30f [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"
35#include <cctype>
36using 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.
Eli Friedman969f9d42011-05-10 17:11:21 +000079 llvm::StringRef Buf(BufferStart, BufferEnd - BufferStart);
80 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;
Chris Lattner34f349d2009-12-14 06:16:57 +000089 IsInConflictMarker = false;
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
159/// instantiation location that indicates where all lexed tokens should be
160/// "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,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000169 SourceLocation InstantiationLocStart,
170 SourceLocation InstantiationLocEnd,
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.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000190 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000191 InstantiationLocStart,
192 InstantiationLocEnd, 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.
220void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
221 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.
John McCall834e3f62011-03-08 07:59:04 +0000238llvm::StringRef Lexer::getSpelling(SourceLocation loc,
239 llvm::SmallVectorImpl<char> &buffer,
240 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;
248 llvm::StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
249 if (invalidTemp) {
250 if (invalid) *invalid = true;
251 return llvm::StringRef();
252 }
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())
266 return llvm::StringRef(tokenBegin, length);
267
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
278 return llvm::StringRef(buffer.data(), buffer.size());
279}
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.
Chris Lattner363fdc22009-01-26 22:24:27 +0000397 Loc = SM.getInstantiationLoc(Loc);
398 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000399 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000400 llvm::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
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000418SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
419 const SourceManager &SM,
420 const LangOptions &LangOpts) {
421 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000422 if (LocInfo.first.isInvalid())
423 return Loc;
424
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000425 bool Invalid = false;
426 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
427 if (Invalid)
428 return Loc;
429
430 // Back up from the current location until we hit the beginning of a line
431 // (or the buffer). We'll relex from that point.
432 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000433 if (LocInfo.second >= Buffer.size())
434 return Loc;
435
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000436 const char *StrData = BufStart+LocInfo.second;
437 if (StrData[0] == '\n' || StrData[0] == '\r')
438 return Loc;
439
440 const char *LexStart = StrData;
441 while (LexStart != BufStart) {
442 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
443 ++LexStart;
444 break;
445 }
446
447 --LexStart;
448 }
449
450 // Create a lexer starting at the beginning of this token.
451 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
452 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
453 TheLexer.SetCommentRetentionState(true);
454
455 // Lex tokens until we find the token that contains the source location.
456 Token TheTok;
457 do {
458 TheLexer.LexFromRawLexer(TheTok);
459
460 if (TheLexer.getBufferLocation() > StrData) {
461 // Lexing this token has taken the lexer past the source location we're
462 // looking for. If the current token encompasses our source location,
463 // return the beginning of that token.
464 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
465 return TheTok.getLocation();
466
467 // We ended up skipping over the source location entirely, which means
468 // that it points into whitespace. We're done here.
469 break;
470 }
471 } while (TheTok.getKind() != tok::eof);
472
473 // We've passed our source location; just return the original source location.
474 return Loc;
475}
476
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000477namespace {
478 enum PreambleDirectiveKind {
479 PDK_Skipped,
480 PDK_StartIf,
481 PDK_EndIf,
482 PDK_Unknown
483 };
484}
485
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000486std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000487Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000488 // Create a lexer starting at the beginning of the file. Note that we use a
489 // "fake" file source location at offset 1 so that the lexer will track our
490 // position within the file.
491 const unsigned StartOffset = 1;
492 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
493 LangOptions LangOpts;
494 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
495 Buffer->getBufferStart(), Buffer->getBufferEnd());
496
497 bool InPreprocessorDirective = false;
498 Token TheTok;
499 Token IfStartTok;
500 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000501 unsigned Line = 0;
502
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000503 do {
504 TheLexer.LexFromRawLexer(TheTok);
505
506 if (InPreprocessorDirective) {
507 // If we've hit the end of the file, we're done.
508 if (TheTok.getKind() == tok::eof) {
509 InPreprocessorDirective = false;
510 break;
511 }
512
513 // If we haven't hit the end of the preprocessor directive, skip this
514 // token.
515 if (!TheTok.isAtStartOfLine())
516 continue;
517
518 // We've passed the end of the preprocessor directive, and will look
519 // at this token again below.
520 InPreprocessorDirective = false;
521 }
522
Douglas Gregordf95a132010-08-09 20:45:32 +0000523 // Keep track of the # of lines in the preamble.
524 if (TheTok.isAtStartOfLine()) {
525 ++Line;
526
527 // If we were asked to limit the number of lines in the preamble,
528 // and we're about to exceed that limit, we're done.
529 if (MaxLines && Line >= MaxLines)
530 break;
531 }
532
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000533 // Comments are okay; skip over them.
534 if (TheTok.getKind() == tok::comment)
535 continue;
536
537 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
538 // This is the start of a preprocessor directive.
539 Token HashTok = TheTok;
540 InPreprocessorDirective = true;
541
542 // Figure out which direective this is. Since we're lexing raw tokens,
543 // we don't have an identifier table available. Instead, just look at
544 // the raw identifier to recognize and categorize preprocessor directives.
545 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000546 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
547 llvm::StringRef Keyword(TheTok.getRawIdentifierData(),
548 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000549 PreambleDirectiveKind PDK
550 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
551 .Case("include", PDK_Skipped)
552 .Case("__include_macros", PDK_Skipped)
553 .Case("define", PDK_Skipped)
554 .Case("undef", PDK_Skipped)
555 .Case("line", PDK_Skipped)
556 .Case("error", PDK_Skipped)
557 .Case("pragma", PDK_Skipped)
558 .Case("import", PDK_Skipped)
559 .Case("include_next", PDK_Skipped)
560 .Case("warning", PDK_Skipped)
561 .Case("ident", PDK_Skipped)
562 .Case("sccs", PDK_Skipped)
563 .Case("assert", PDK_Skipped)
564 .Case("unassert", PDK_Skipped)
565 .Case("if", PDK_StartIf)
566 .Case("ifdef", PDK_StartIf)
567 .Case("ifndef", PDK_StartIf)
568 .Case("elif", PDK_Skipped)
569 .Case("else", PDK_Skipped)
570 .Case("endif", PDK_EndIf)
571 .Default(PDK_Unknown);
572
573 switch (PDK) {
574 case PDK_Skipped:
575 continue;
576
577 case PDK_StartIf:
578 if (IfCount == 0)
579 IfStartTok = HashTok;
580
581 ++IfCount;
582 continue;
583
584 case PDK_EndIf:
585 // Mismatched #endif. The preamble ends here.
586 if (IfCount == 0)
587 break;
588
589 --IfCount;
590 continue;
591
592 case PDK_Unknown:
593 // We don't know what this directive is; stop at the '#'.
594 break;
595 }
596 }
597
598 // We only end up here if we didn't recognize the preprocessor
599 // directive or it was one that can't occur in the preamble at this
600 // point. Roll back the current token to the location of the '#'.
601 InPreprocessorDirective = false;
602 TheTok = HashTok;
603 }
604
Douglas Gregordf95a132010-08-09 20:45:32 +0000605 // We hit a token that we don't recognize as being in the
606 // "preprocessing only" part of the file, so we're no longer in
607 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000608 break;
609 } while (true);
610
611 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000612 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
613 IfCount? IfStartTok.isAtStartOfLine()
614 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000615}
616
Chris Lattner7ef5c272010-11-17 07:05:50 +0000617
618/// AdvanceToTokenCharacter - Given a location that specifies the start of a
619/// token, return a new location that specifies a character within the token.
620SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
621 unsigned CharNo,
622 const SourceManager &SM,
623 const LangOptions &Features) {
624 // Figure out how many physical characters away the specified instantiation
625 // character is. This needs to take into consideration newlines and
626 // trigraphs.
627 bool Invalid = false;
628 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
629
630 // If they request the first char of the token, we're trivially done.
631 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
632 return TokStart;
633
634 unsigned PhysOffset = 0;
635
636 // The usual case is that tokens don't contain anything interesting. Skip
637 // over the uninteresting characters. If a token only consists of simple
638 // chars, this method is extremely fast.
639 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
640 if (CharNo == 0)
641 return TokStart.getFileLocWithOffset(PhysOffset);
642 ++TokPtr, --CharNo, ++PhysOffset;
643 }
644
645 // If we have a character that may be a trigraph or escaped newline, use a
646 // lexer to parse it correctly.
647 for (; CharNo; --CharNo) {
648 unsigned Size;
649 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
650 TokPtr += Size;
651 PhysOffset += Size;
652 }
653
654 // Final detail: if we end up on an escaped newline, we want to return the
655 // location of the actual byte of the token. For example foo\<newline>bar
656 // advanced by 3 should return the location of b, not of \\. One compounding
657 // detail of this is that the escape may be made by a trigraph.
658 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
659 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
660
661 return TokStart.getFileLocWithOffset(PhysOffset);
662}
663
664/// \brief Computes the source location just past the end of the
665/// token at this source location.
666///
667/// This routine can be used to produce a source location that
668/// points just past the end of the token referenced by \p Loc, and
669/// is generally used when a diagnostic needs to point just after a
670/// token where it expected something different that it received. If
671/// the returned source location would not be meaningful (e.g., if
672/// it points into a macro), this routine returns an invalid
673/// source location.
674///
675/// \param Offset an offset from the end of the token, where the source
676/// location should refer to. The default offset (0) produces a source
677/// location pointing just past the end of the token; an offset of 1 produces
678/// a source location pointing to the last character in the token, etc.
679SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
680 const SourceManager &SM,
681 const LangOptions &Features) {
682 if (Loc.isInvalid() || !Loc.isFileID())
683 return SourceLocation();
684
685 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
686 if (Len > Offset)
687 Len = Len - Offset;
688 else
689 return Loc;
690
John McCall77ebb382011-04-06 01:50:22 +0000691 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000692}
693
Reid Spencer5f016e22007-07-11 17:01:13 +0000694//===----------------------------------------------------------------------===//
695// Character information.
696//===----------------------------------------------------------------------===//
697
Reid Spencer5f016e22007-07-11 17:01:13 +0000698enum {
699 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
700 CHAR_VERT_WS = 0x02, // '\r', '\n'
701 CHAR_LETTER = 0x04, // a-z,A-Z
702 CHAR_NUMBER = 0x08, // 0-9
703 CHAR_UNDER = 0x10, // _
704 CHAR_PERIOD = 0x20 // .
705};
706
Chris Lattner03b98662009-07-07 17:09:54 +0000707// Statically initialize CharInfo table based on ASCII character set
708// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000709static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000710{
711// 0 NUL 1 SOH 2 STX 3 ETX
712// 4 EOT 5 ENQ 6 ACK 7 BEL
713 0 , 0 , 0 , 0 ,
714 0 , 0 , 0 , 0 ,
715// 8 BS 9 HT 10 NL 11 VT
716//12 NP 13 CR 14 SO 15 SI
717 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
718 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
719//16 DLE 17 DC1 18 DC2 19 DC3
720//20 DC4 21 NAK 22 SYN 23 ETB
721 0 , 0 , 0 , 0 ,
722 0 , 0 , 0 , 0 ,
723//24 CAN 25 EM 26 SUB 27 ESC
724//28 FS 29 GS 30 RS 31 US
725 0 , 0 , 0 , 0 ,
726 0 , 0 , 0 , 0 ,
727//32 SP 33 ! 34 " 35 #
728//36 $ 37 % 38 & 39 '
729 CHAR_HORZ_WS, 0 , 0 , 0 ,
730 0 , 0 , 0 , 0 ,
731//40 ( 41 ) 42 * 43 +
732//44 , 45 - 46 . 47 /
733 0 , 0 , 0 , 0 ,
734 0 , 0 , CHAR_PERIOD , 0 ,
735//48 0 49 1 50 2 51 3
736//52 4 53 5 54 6 55 7
737 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
738 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
739//56 8 57 9 58 : 59 ;
740//60 < 61 = 62 > 63 ?
741 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
742 0 , 0 , 0 , 0 ,
743//64 @ 65 A 66 B 67 C
744//68 D 69 E 70 F 71 G
745 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
746 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
747//72 H 73 I 74 J 75 K
748//76 L 77 M 78 N 79 O
749 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
750 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
751//80 P 81 Q 82 R 83 S
752//84 T 85 U 86 V 87 W
753 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
754 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
755//88 X 89 Y 90 Z 91 [
756//92 \ 93 ] 94 ^ 95 _
757 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
758 0 , 0 , 0 , CHAR_UNDER ,
759//96 ` 97 a 98 b 99 c
760//100 d 101 e 102 f 103 g
761 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
762 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
763//104 h 105 i 106 j 107 k
764//108 l 109 m 110 n 111 o
765 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
766 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
767//112 p 113 q 114 r 115 s
768//116 t 117 u 118 v 119 w
769 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
770 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
771//120 x 121 y 122 z 123 {
772//124 | 125 } 126 ~ 127 DEL
773 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
774 0 , 0 , 0 , 0
775};
776
Chris Lattnera2bf1052009-12-17 05:29:40 +0000777static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 static bool isInited = false;
779 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000780 // check the statically-initialized CharInfo table
781 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
782 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
783 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
784 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
785 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
786 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
787 assert(CHAR_UNDER == CharInfo[(int)'_']);
788 assert(CHAR_PERIOD == CharInfo[(int)'.']);
789 for (unsigned i = 'a'; i <= 'z'; ++i) {
790 assert(CHAR_LETTER == CharInfo[i]);
791 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
792 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000794 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000795
Chris Lattner03b98662009-07-07 17:09:54 +0000796 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000797}
798
Chris Lattner03b98662009-07-07 17:09:54 +0000799
Reid Spencer5f016e22007-07-11 17:01:13 +0000800/// isIdentifierBody - Return true if this is the body character of an
801/// identifier, which is [a-zA-Z0-9_].
802static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000803 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000804}
805
806/// isHorizontalWhitespace - Return true if this character is horizontal
807/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
808static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000809 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810}
811
812/// isWhitespace - Return true if this character is horizontal or vertical
813/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
814/// for '\0'.
815static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000816 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000817}
818
819/// isNumberBody - Return true if this is the body character of an
820/// preprocessing number, which is [a-zA-Z0-9_.].
821static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000822 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000823 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000824}
825
826
827//===----------------------------------------------------------------------===//
828// Diagnostics forwarding code.
829//===----------------------------------------------------------------------===//
830
Chris Lattner409a0362007-07-22 18:38:25 +0000831/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
832/// lexer buffer was all instantiated at a single point, perform the mapping.
833/// This is currently only used for _Pragma implementation, so it is the slow
834/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000835static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
836 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000837static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
838 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000839 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000840 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattner409a0362007-07-22 18:38:25 +0000842 // Otherwise, we're lexing "mapped tokens". This is used for things like
843 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000844 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000845 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000847 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000848 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000849 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000850 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Chris Lattnere7fb4842009-02-15 20:52:18 +0000852 // Figure out the expansion loc range, which is the range covered by the
853 // original _Pragma(...) sequence.
854 std::pair<SourceLocation,SourceLocation> II =
855 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chris Lattnere7fb4842009-02-15 20:52:18 +0000857 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000858}
859
Reid Spencer5f016e22007-07-11 17:01:13 +0000860/// getSourceLocation - Return a source location identifier for the specified
861/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000862SourceLocation Lexer::getSourceLocation(const char *Loc,
863 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000864 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000866
867 // In the normal case, we're just lexing from a simple file buffer, return
868 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000869 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000870 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000871 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Chris Lattner2b2453a2009-01-17 06:22:33 +0000873 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
874 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000875 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000876 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000877}
878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// Diag - Forwarding function for diagnostics. This translate a source
880/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000881DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000882 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000883}
Reid Spencer5f016e22007-07-11 17:01:13 +0000884
885//===----------------------------------------------------------------------===//
886// Trigraph and Escaped Newline Handling Code.
887//===----------------------------------------------------------------------===//
888
889/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
890/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
891static char GetTrigraphCharForLetter(char Letter) {
892 switch (Letter) {
893 default: return 0;
894 case '=': return '#';
895 case ')': return ']';
896 case '(': return '[';
897 case '!': return '|';
898 case '\'': return '^';
899 case '>': return '}';
900 case '/': return '\\';
901 case '<': return '{';
902 case '-': return '~';
903 }
904}
905
906/// DecodeTrigraphChar - If the specified character is a legal trigraph when
907/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
908/// return the result character. Finally, emit a warning about trigraph use
909/// whether trigraphs are enabled or not.
910static char DecodeTrigraphChar(const char *CP, Lexer *L) {
911 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000912 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Chris Lattner3692b092008-11-18 07:59:24 +0000914 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000915 if (!L->isLexingRawMode())
916 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000917 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 }
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattner74d15df2008-11-22 02:02:22 +0000920 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000921 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 return Res;
923}
924
Chris Lattner24f0e482009-04-18 22:05:41 +0000925/// getEscapedNewLineSize - Return the size of the specified escaped newline,
926/// 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 +0000927/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000928unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
929 unsigned Size = 0;
930 while (isWhitespace(Ptr[Size])) {
931 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner24f0e482009-04-18 22:05:41 +0000933 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
934 continue;
935
936 // If this is a \r\n or \n\r, skip the other half.
937 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
938 Ptr[Size-1] != Ptr[Size])
939 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner24f0e482009-04-18 22:05:41 +0000941 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000942 }
943
Chris Lattner24f0e482009-04-18 22:05:41 +0000944 // Not an escaped newline, must be a \t or something else.
945 return 0;
946}
947
Chris Lattner03374952009-04-18 22:27:02 +0000948/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
949/// them), skip over them and return the first non-escaped-newline found,
950/// otherwise return P.
951const char *Lexer::SkipEscapedNewLines(const char *P) {
952 while (1) {
953 const char *AfterEscape;
954 if (*P == '\\') {
955 AfterEscape = P+1;
956 } else if (*P == '?') {
957 // If not a trigraph for escape, bail out.
958 if (P[1] != '?' || P[2] != '/')
959 return P;
960 AfterEscape = P+3;
961 } else {
962 return P;
963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattner03374952009-04-18 22:27:02 +0000965 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
966 if (NewLineSize == 0) return P;
967 P = AfterEscape+NewLineSize;
968 }
969}
970
Chris Lattner24f0e482009-04-18 22:05:41 +0000971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
973/// get its size, and return it. This is tricky in several cases:
974/// 1. If currently at the start of a trigraph, we warn about the trigraph,
975/// then either return the trigraph (skipping 3 chars) or the '?',
976/// depending on whether trigraphs are enabled or not.
977/// 2. If this is an escaped newline (potentially with whitespace between
978/// the backslash and newline), implicitly skip the newline and return
979/// the char after it.
980/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
981///
982/// This handles the slow/uncommon case of the getCharAndSize method. Here we
983/// know that we can accumulate into Size, and that we have already incremented
984/// Ptr by Size bytes.
985///
986/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
987/// be updated to match.
988///
989char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000990 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 // If we have a slash, look for an escaped newline.
992 if (Ptr[0] == '\\') {
993 ++Size;
994 ++Ptr;
995Slash:
996 // Common case, backslash-char where the char is not whitespace.
997 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner5636a3b2009-06-23 05:15:06 +0000999 // See if we have optional whitespace characters between the slash and
1000 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001001 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1002 // Remember that this token needs to be cleaned.
1003 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001004
Chris Lattner24f0e482009-04-18 22:05:41 +00001005 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001006 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001007 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner24f0e482009-04-18 22:05:41 +00001009 // Found backslash<whitespace><newline>. Parse the char after it.
1010 Size += EscapedNewLineSize;
1011 Ptr += EscapedNewLineSize;
1012 // Use slow version to accumulate a correct size field.
1013 return getCharAndSizeSlow(Ptr, Size, Tok);
1014 }
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 // Otherwise, this is not an escaped newline, just return the slash.
1017 return '\\';
1018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 // If this is a trigraph, process it.
1021 if (Ptr[0] == '?' && Ptr[1] == '?') {
1022 // If this is actually a legal trigraph (not something like "??x"), emit
1023 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1024 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1025 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001026 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001027
1028 Ptr += 3;
1029 Size += 3;
1030 if (C == '\\') goto Slash;
1031 return C;
1032 }
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 // If this is neither, return a single character.
1036 ++Size;
1037 return *Ptr;
1038}
1039
1040
1041/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1042/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1043/// and that we have already incremented Ptr by Size bytes.
1044///
1045/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1046/// be updated to match.
1047char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1048 const LangOptions &Features) {
1049 // If we have a slash, look for an escaped newline.
1050 if (Ptr[0] == '\\') {
1051 ++Size;
1052 ++Ptr;
1053Slash:
1054 // Common case, backslash-char where the char is not whitespace.
1055 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001058 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1059 // Found backslash<whitespace><newline>. Parse the char after it.
1060 Size += EscapedNewLineSize;
1061 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattner24f0e482009-04-18 22:05:41 +00001063 // Use slow version to accumulate a correct size field.
1064 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1065 }
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 // Otherwise, this is not an escaped newline, just return the slash.
1068 return '\\';
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 // If this is a trigraph, process it.
1072 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1073 // If this is actually a legal trigraph (not something like "??x"), return
1074 // it.
1075 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1076 Ptr += 3;
1077 Size += 3;
1078 if (C == '\\') goto Slash;
1079 return C;
1080 }
1081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 // If this is neither, return a single character.
1084 ++Size;
1085 return *Ptr;
1086}
1087
1088//===----------------------------------------------------------------------===//
1089// Helper methods for lexing.
1090//===----------------------------------------------------------------------===//
1091
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001092/// \brief Routine that indiscriminately skips bytes in the source file.
1093void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1094 BufferPtr += Bytes;
1095 if (BufferPtr > BufferEnd)
1096 BufferPtr = BufferEnd;
1097 IsAtStartOfLine = StartOfLine;
1098}
1099
Chris Lattnerd2177732007-07-20 16:59:19 +00001100void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1102 unsigned Size;
1103 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001104 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 --CurPtr; // Back up over the skipped character.
1108
1109 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1110 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1111 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001112 //
1113 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1114 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1116FinishIdentifier:
1117 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001118 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1119 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Reid Spencer5f016e22007-07-11 17:01:13 +00001121 // If we are in raw mode, return this identifier raw. There is no need to
1122 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001123 if (LexingRawMode)
1124 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001126 // Fill in Result.IdentifierInfo and update the token kind,
1127 // looking up the identifier in the identifier table.
1128 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 // Finally, now that we know we have an identifier, pass this off to the
1131 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001132 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001133 PP->HandleIdentifier(Result);
1134 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 C = getCharAndSize(CurPtr, Size);
1140 while (1) {
1141 if (C == '$') {
1142 // If we hit a $ and they are not supported in identifiers, we are done.
1143 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001146 if (!isLexingRawMode())
1147 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 CurPtr = ConsumeChar(CurPtr, Size, Result);
1149 C = getCharAndSize(CurPtr, Size);
1150 continue;
1151 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1152 // Found end of identifier.
1153 goto FinishIdentifier;
1154 }
1155
1156 // Otherwise, this character is good, consume it.
1157 CurPtr = ConsumeChar(CurPtr, Size, Result);
1158
1159 C = getCharAndSize(CurPtr, Size);
1160 while (isIdentifierBody(C)) { // FIXME: UCNs.
1161 CurPtr = ConsumeChar(CurPtr, Size, Result);
1162 C = getCharAndSize(CurPtr, Size);
1163 }
1164 }
1165}
1166
Douglas Gregora75ec432010-08-30 14:50:47 +00001167/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001168/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001169static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1170 unsigned Size;
1171 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1172 if (C1 != '0')
1173 return false;
1174 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1175 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001176}
Reid Spencer5f016e22007-07-11 17:01:13 +00001177
Nate Begeman5253c7f2008-04-14 02:26:39 +00001178/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001179/// constant. From[-1] is the first character lexed. Return the end of the
1180/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001181void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001182 unsigned Size;
1183 char C = getCharAndSize(CurPtr, Size);
1184 char PrevCh = 0;
1185 while (isNumberBody(C)) { // FIXME: UCNs?
1186 CurPtr = ConsumeChar(CurPtr, Size, Result);
1187 PrevCh = C;
1188 C = getCharAndSize(CurPtr, Size);
1189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001192 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1193 // If we are in Microsoft mode, don't continue if the constant is hex.
1194 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001195 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001196 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1197 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001198
1199 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001200 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001201 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001205 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001206 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001207 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001208}
1209
1210/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1211/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +00001212void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 char C = getAndAdvanceChar(CurPtr, Result);
1216 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001217 // Skip escaped characters. Escaped newlines will already be processed by
1218 // getAndAdvanceChar.
1219 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001221
Chris Lattner571339c2010-05-30 23:27:38 +00001222 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001223 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001224 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1225 PP->CodeCompleteNaturalLanguage();
1226 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001227 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001228 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 }
Chris Lattner571339c2010-05-30 23:27:38 +00001231
1232 if (C == 0)
1233 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 C = getAndAdvanceChar(CurPtr, Result);
1235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001238 if (NulCharacter && !isLexingRawMode())
1239 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001242 const char *TokStart = BufferPtr;
Sean Hunt6cf75022010-08-30 17:47:05 +00001243 FormTokenWithChars(Result, CurPtr,
1244 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001245 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001246}
1247
1248/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1249/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001250void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001252 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 char C = getAndAdvanceChar(CurPtr, Result);
1254 while (C != '>') {
1255 // Skip escaped characters.
1256 if (C == '\\') {
1257 // Skip the escaped character.
1258 C = getAndAdvanceChar(CurPtr, Result);
1259 } else if (C == '\n' || C == '\r' || // Newline.
1260 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001261 // If the filename is unterminated, then it must just be a lone <
1262 // character. Return this as such.
1263 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 return;
1265 } else if (C == 0) {
1266 NulCharacter = CurPtr-1;
1267 }
1268 C = getAndAdvanceChar(CurPtr, Result);
1269 }
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001272 if (NulCharacter && !isLexingRawMode())
1273 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001276 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001277 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001278 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001279}
1280
1281
1282/// LexCharConstant - Lex the remainder of a character constant, after having
1283/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001284void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 const char *NulCharacter = 0; // Does this character contain the \0 character?
1286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 char C = getAndAdvanceChar(CurPtr, Result);
1288 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001289 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001290 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001291 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001293 }
1294
1295 while (C != '\'') {
1296 // Skip escaped characters.
1297 if (C == '\\') {
1298 // Skip the escaped character.
1299 // FIXME: UCN's
1300 C = getAndAdvanceChar(CurPtr, Result);
1301 } else if (C == '\n' || C == '\r' || // Newline.
1302 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001303 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1304 PP->CodeCompleteNaturalLanguage();
1305 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001306 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001307 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1308 return;
1309 } else if (C == 0) {
1310 NulCharacter = CurPtr-1;
1311 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 C = getAndAdvanceChar(CurPtr, Result);
1313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattnerd80f7862010-07-07 23:24:27 +00001315 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001316 if (NulCharacter && !isLexingRawMode())
1317 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001320 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001321 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001322 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001323}
1324
1325/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1326/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001327///
1328/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1329///
1330bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Whitespace - Skip it, then return the token after the whitespace.
1332 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1333 while (1) {
1334 // Skip horizontal whitespace very aggressively.
1335 while (isHorizontalWhitespace(Char))
1336 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001338 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 if (Char != '\n' && Char != '\r')
1340 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 if (ParsingPreprocessorDirective) {
1343 // End of preprocessor directive line, let LexTokenInternal handle this.
1344 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001345 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 }
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 // ok, but handle newline.
1349 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001350 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001352 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 Char = *++CurPtr;
1354 }
1355
1356 // If this isn't immediately after a newline, there is leading space.
1357 char PrevChar = CurPtr[-1];
1358 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001359 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001360
Chris Lattnerd88dc482008-10-12 04:05:48 +00001361 // If the client wants us to return whitespace, return it now.
1362 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001363 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001364 return true;
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001368 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001369}
1370
1371// SkipBCPLComment - We have just read the // characters from input. Skip until
1372// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001373/// BufferPtr and return.
1374///
1375/// If we're in KeepCommentMode or any CommentHandler has inserted
1376/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001377bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // If BCPL comments aren't explicitly enabled for this language, emit an
1379 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001380 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // Mark them enabled so we only emit one warning for this translation
1384 // unit.
1385 Features.BCPLComment = true;
1386 }
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // Scan over the body of the comment. The common case, when scanning, is that
1389 // the comment contains normal ascii characters with nothing interesting in
1390 // them. As such, optimize for this case with the inner loop.
1391 char C;
1392 do {
1393 C = *CurPtr;
1394 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1395 // If we find a \n character, scan backwards, checking to see if it's an
1396 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 // Skip over characters in the fast loop.
1399 while (C != 0 && // Potentially EOF.
1400 C != '\\' && // Potentially escaped newline.
1401 C != '?' && // Potentially trigraph.
1402 C != '\n' && C != '\r') // Newline or DOS-style newline.
1403 C = *++CurPtr;
1404
1405 // If this is a newline, we're done.
1406 if (C == '\n' || C == '\r')
1407 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001410 // properly decode the character. Read it in raw mode to avoid emitting
1411 // diagnostics about things like trigraphs. If we see an escaped newline,
1412 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001414 bool OldRawMode = isLexingRawMode();
1415 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001417 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001418
1419 // If the char that we finally got was a \n, then we must have had something
1420 // like \<newline><newline>. We don't want to have consumed the second
1421 // newline, we want CurPtr, to end up pointing to it down below.
1422 if (C == '\n' || C == '\r') {
1423 --CurPtr;
1424 C = 'x'; // doesn't matter what this is.
1425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 // If we read multiple characters, and one of those characters was a \r or
1428 // \n, then we had an escaped newline within the comment. Emit diagnostic
1429 // unless the next line is also a // comment.
1430 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1431 for (; OldPtr != CurPtr; ++OldPtr)
1432 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1433 // Okay, we found a // comment that ends in a newline, if the next
1434 // line is also a // comment, but has spaces, don't emit a diagnostic.
1435 if (isspace(C)) {
1436 const char *ForwardPtr = CurPtr;
1437 while (isspace(*ForwardPtr)) // Skip whitespace.
1438 ++ForwardPtr;
1439 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1440 break;
1441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner74d15df2008-11-22 02:02:22 +00001443 if (!isLexingRawMode())
1444 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 break;
1446 }
1447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Douglas Gregor55817af2010-08-25 17:04:25 +00001449 if (CurPtr == BufferEnd+1) {
1450 if (PP && PP->isCodeCompletionFile(FileLoc))
1451 PP->CodeCompleteNaturalLanguage();
1452
1453 --CurPtr;
1454 break;
1455 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 } while (C != '\n' && C != '\r');
1457
Chris Lattner3d0ad582010-02-03 21:06:21 +00001458 // Found but did not consume the newline. Notify comment handlers about the
1459 // comment unless we're in a #if 0 block.
1460 if (PP && !isLexingRawMode() &&
1461 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1462 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001463 BufferPtr = CurPtr;
1464 return true; // A token has to be returned.
1465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001468 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 return SaveBCPLComment(Result, CurPtr);
1470
1471 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001472 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1474 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001475 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001479 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001480 // contribute to another token), it isn't needed for correctness. Note that
1481 // this is ok even in KeepWhitespaceMode, because we would have returned the
1482 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001486 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001488 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001490 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001491}
1492
1493/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1494/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001495bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001496 // If we're not in a preprocessor directive, just return the // comment
1497 // directly.
1498 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattner9e6293d2008-10-12 04:51:35 +00001500 if (!ParsingPreprocessorDirective)
1501 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Chris Lattner9e6293d2008-10-12 04:51:35 +00001503 // If this BCPL-style comment is in a macro definition, transmogrify it into
1504 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001505 bool Invalid = false;
1506 std::string Spelling = PP->getSpelling(Result, &Invalid);
1507 if (Invalid)
1508 return true;
1509
Chris Lattner9e6293d2008-10-12 04:51:35 +00001510 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1511 Spelling[1] = '*'; // Change prefix to "/*".
1512 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Chris Lattner9e6293d2008-10-12 04:51:35 +00001514 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001515 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1516 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001517 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001518}
1519
1520/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1521/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001522/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001523static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 Lexer *L) {
1525 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 // Back up off the newline.
1528 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // If this is a two-character newline sequence, skip the other character.
1531 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1532 // \n\n or \r\r -> not escaped newline.
1533 if (CurPtr[0] == CurPtr[1])
1534 return false;
1535 // \n\r or \r\n -> skip the newline.
1536 --CurPtr;
1537 }
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 // If we have horizontal whitespace, skip over it. We allow whitespace
1540 // between the slash and newline.
1541 bool HasSpace = false;
1542 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1543 --CurPtr;
1544 HasSpace = true;
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // If we have a slash, we know this is an escaped newline.
1548 if (*CurPtr == '\\') {
1549 if (CurPtr[-1] != '*') return false;
1550 } else {
1551 // It isn't a slash, is it the ?? / trigraph?
1552 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1553 CurPtr[-3] != '*')
1554 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // This is the trigraph ending the comment. Emit a stern warning!
1557 CurPtr -= 2;
1558
1559 // If no trigraphs are enabled, warn that we ignored this trigraph and
1560 // ignore this * character.
1561 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001562 if (!L->isLexingRawMode())
1563 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 return false;
1565 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001566 if (!L->isLexingRawMode())
1567 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 }
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001571 if (!L->isLexingRawMode())
1572 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001575 if (HasSpace && !L->isLexingRawMode())
1576 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 return true;
1579}
1580
1581#ifdef __SSE2__
1582#include <emmintrin.h>
1583#elif __ALTIVEC__
1584#include <altivec.h>
1585#undef bool
1586#endif
1587
1588/// SkipBlockComment - We have just read the /* characters from input. Read
1589/// until we find the */ characters that terminate the comment. Note that we
1590/// don't bother decoding trigraphs or escaped newlines in block comments,
1591/// because they cannot cause the comment to end. The only thing that can
1592/// happen is the comment could end with an escaped newline between the */ end
1593/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001594///
Chris Lattner046c2272010-01-18 22:35:47 +00001595/// If we're in KeepCommentMode or any CommentHandler has inserted
1596/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001597bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001599 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 // optimization helps people who like to put a lot of * characters in their
1601 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001602
1603 // The first character we get with newlines and trigraphs skipped to handle
1604 // the degenerate /*/ case below correctly if the * has an escaped newline
1605 // after it.
1606 unsigned CharSize;
1607 unsigned char C = getCharAndSize(CurPtr, CharSize);
1608 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001610 if (!isLexingRawMode() &&
1611 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001612 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001613 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Chris Lattner31f0eca2008-10-12 04:19:49 +00001615 // KeepWhitespaceMode should return this broken comment as a token. Since
1616 // it isn't a well formed comment, just return it as an 'unknown' token.
1617 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001618 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001619 return true;
1620 }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner31f0eca2008-10-12 04:19:49 +00001622 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001623 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner8146b682007-07-21 23:43:37 +00001626 // Check to see if the first character after the '/*' is another /. If so,
1627 // then this slash does not end the block comment, it is part of it.
1628 if (C == '/')
1629 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 while (1) {
1632 // Skip over all non-interesting characters until we find end of buffer or a
1633 // (probably ending) '/' character.
1634 if (CurPtr + 24 < BufferEnd) {
1635 // While not aligned to a 16-byte boundary.
1636 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1637 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 if (C == '/') goto FoundSlash;
1640
1641#ifdef __SSE2__
1642 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1643 '/', '/', '/', '/', '/', '/', '/', '/');
1644 while (CurPtr+16 <= BufferEnd &&
1645 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1646 CurPtr += 16;
1647#elif __ALTIVEC__
1648 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001649 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 '/', '/', '/', '/', '/', '/', '/', '/'
1651 };
1652 while (CurPtr+16 <= BufferEnd &&
1653 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1654 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001655#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 // Scan for '/' quickly. Many block comments are very large.
1657 while (CurPtr[0] != '/' &&
1658 CurPtr[1] != '/' &&
1659 CurPtr[2] != '/' &&
1660 CurPtr[3] != '/' &&
1661 CurPtr+4 < BufferEnd) {
1662 CurPtr += 4;
1663 }
1664#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // It has to be one of the bytes scanned, increment to it and read one.
1667 C = *CurPtr++;
1668 }
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // Loop to scan the remainder.
1671 while (C != '/' && C != '\0')
1672 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 FoundSlash:
1675 if (C == '/') {
1676 if (CurPtr[-2] == '*') // We found the final */. We're done!
1677 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1680 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1681 // We found the final */, though it had an escaped newline between the
1682 // * and /. We're done!
1683 break;
1684 }
1685 }
1686 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1687 // If this is a /* inside of the comment, emit a warning. Don't do this
1688 // if this is a /*/, which will end the comment. This misses cases with
1689 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001690 if (!isLexingRawMode())
1691 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 }
1693 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001694 if (PP && PP->isCodeCompletionFile(FileLoc))
1695 PP->CodeCompleteNaturalLanguage();
1696 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001697 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 // Note: the user probably forgot a */. We could continue immediately
1699 // after the /*, but this would involve lexing a lot of what really is the
1700 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001701 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Chris Lattner31f0eca2008-10-12 04:19:49 +00001703 // KeepWhitespaceMode should return this broken comment as a token. Since
1704 // it isn't a well formed comment, just return it as an 'unknown' token.
1705 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001706 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001707 return true;
1708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Chris Lattner31f0eca2008-10-12 04:19:49 +00001710 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001711 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 }
1713 C = *CurPtr++;
1714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Chris Lattner3d0ad582010-02-03 21:06:21 +00001716 // Notify comment handlers about the comment unless we're in a #if 0 block.
1717 if (PP && !isLexingRawMode() &&
1718 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1719 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001720 BufferPtr = CurPtr;
1721 return true; // A token has to be returned.
1722 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001723
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001725 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001726 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001727 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 }
1729
1730 // It is common for the tokens immediately after a /**/ comment to be
1731 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001732 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1733 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001735 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001737 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 }
1739
1740 // Otherwise, just return so that the next character will be lexed as a token.
1741 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001742 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001743 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001744}
1745
1746//===----------------------------------------------------------------------===//
1747// Primary Lexing Entry Points
1748//===----------------------------------------------------------------------===//
1749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1751/// uninterpreted string. This switches the lexer out of directive mode.
1752std::string Lexer::ReadToEndOfLine() {
1753 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1754 "Must be in a preprocessing directive!");
1755 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001756 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001757
1758 // CurPtr - Cache BufferPtr in an automatic variable.
1759 const char *CurPtr = BufferPtr;
1760 while (1) {
1761 char Char = getAndAdvanceChar(CurPtr, Tmp);
1762 switch (Char) {
1763 default:
1764 Result += Char;
1765 break;
1766 case 0: // Null.
1767 // Found end of file?
1768 if (CurPtr-1 != BufferEnd) {
1769 // Nope, normal character, continue.
1770 Result += Char;
1771 break;
1772 }
1773 // FALL THROUGH.
1774 case '\r':
1775 case '\n':
1776 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1777 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1778 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Peter Collingbourne84021552011-02-28 02:37:51 +00001780 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001782 if (Tmp.is(tok::code_completion)) {
1783 if (PP && PP->getCodeCompletionHandler())
1784 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1785 Lex(Tmp);
1786 }
Peter Collingbourne84021552011-02-28 02:37:51 +00001787 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // Finally, we're done, return the string we found.
1790 return Result;
1791 }
1792 }
1793}
1794
1795/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1796/// condition, reporting diagnostics and handling other edge cases as required.
1797/// This returns true if Result contains a token, false if PP.Lex should be
1798/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001799bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001800 // Check if we are performing code completion.
1801 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1802 // We're at the end of the file, but we've been asked to consider the
1803 // end of the file to be a code-completion token. Return the
1804 // code-completion token.
1805 Result.startToken();
1806 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1807
1808 // Only do the eof -> code_completion translation once.
1809 PP->SetCodeCompletionPoint(0, 0, 0);
1810
1811 // Silence any diagnostics that occur once we hit the code-completion point.
1812 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1813 return true;
1814 }
1815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 // If we hit the end of the file while parsing a preprocessor directive,
1817 // end the preprocessor directive first. The next token returned will
1818 // then be the end of file.
1819 if (ParsingPreprocessorDirective) {
1820 // Done parsing the "line".
1821 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001822 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00001823 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001826 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001828 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001829
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // If we are in raw mode, return this event as an EOF token. Let the caller
1831 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001832 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 Result.startToken();
1834 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001835 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 return true;
1837 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001838
Douglas Gregorf44e8542010-08-24 19:08:16 +00001839 // Issue diagnostics for unterminated #if and missing newline.
1840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 // If we are in a #if directive, emit an error.
1842 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001843 if (!PP->isCodeCompletionFile(FileLoc))
1844 PP->Diag(ConditionalStack.back().IfLoc,
1845 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 ConditionalStack.pop_back();
1847 }
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001849 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1850 // a pedwarn.
1851 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001852 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001853 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 BufferPtr = CurPtr;
1856
1857 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001858 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001859}
1860
1861/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1862/// the specified lexer will return a tok::l_paren token, 0 if it is something
1863/// else and 2 if there are no more tokens in the buffer controlled by the
1864/// lexer.
1865unsigned Lexer::isNextPPTokenLParen() {
1866 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 // Switch to 'skipping' mode. This will ensure that we can lex a token
1869 // without emitting diagnostics, disables macro expansion, and will cause EOF
1870 // to return an EOF token instead of popping the include stack.
1871 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 // Save state that can be changed while lexing so that we can restore it.
1874 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001875 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Chris Lattnerd2177732007-07-20 16:59:19 +00001877 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 Tok.startToken();
1879 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 // Restore state that may have changed.
1882 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001883 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // Restore the lexer back to non-skipping mode.
1886 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001888 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001890 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001891}
1892
Chris Lattner34f349d2009-12-14 06:16:57 +00001893/// FindConflictEnd - Find the end of a version control conflict marker.
1894static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1895 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1896 size_t Pos = RestOfBuffer.find(">>>>>>>");
1897 while (Pos != llvm::StringRef::npos) {
1898 // Must occur at start of line.
1899 if (RestOfBuffer[Pos-1] != '\r' &&
1900 RestOfBuffer[Pos-1] != '\n') {
1901 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001902 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001903 continue;
1904 }
1905 return RestOfBuffer.data()+Pos;
1906 }
1907 return 0;
1908}
1909
1910/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1911/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1912/// and recover nicely. This returns true if it is a conflict marker and false
1913/// if not.
1914bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1915 // Only a conflict marker if it starts at the beginning of a line.
1916 if (CurPtr != BufferStart &&
1917 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1918 return false;
1919
1920 // Check to see if we have <<<<<<<.
1921 if (BufferEnd-CurPtr < 8 ||
1922 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1923 return false;
1924
1925 // If we have a situation where we don't care about conflict markers, ignore
1926 // it.
1927 if (IsInConflictMarker || isLexingRawMode())
1928 return false;
1929
1930 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1931 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001932 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001933 // We found a match. We are really in a conflict marker.
1934 // Diagnose this, and ignore to the end of line.
1935 Diag(CurPtr, diag::err_conflict_marker);
1936 IsInConflictMarker = true;
1937
1938 // Skip ahead to the end of line. We know this exists because the
1939 // end-of-conflict marker starts with \r or \n.
1940 while (*CurPtr != '\r' && *CurPtr != '\n') {
1941 assert(CurPtr != BufferEnd && "Didn't find end of line");
1942 ++CurPtr;
1943 }
1944 BufferPtr = CurPtr;
1945 return true;
1946 }
1947
1948 // No end of conflict marker found.
1949 return false;
1950}
1951
1952
1953/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1954/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1955/// until the end of the line. This returns true if it is a conflict marker and
1956/// false if not.
1957bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1958 // Only a conflict marker if it starts at the beginning of a line.
1959 if (CurPtr != BufferStart &&
1960 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1961 return false;
1962
1963 // If we have a situation where we don't care about conflict markers, ignore
1964 // it.
1965 if (!IsInConflictMarker || isLexingRawMode())
1966 return false;
1967
1968 // Check to see if we have the marker (7 characters in a row).
1969 for (unsigned i = 1; i != 7; ++i)
1970 if (CurPtr[i] != CurPtr[0])
1971 return false;
1972
1973 // If we do have it, search for the end of the conflict marker. This could
1974 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1975 // be the end of conflict marker.
1976 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1977 CurPtr = End;
1978
1979 // Skip ahead to the end of line.
1980 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1981 ++CurPtr;
1982
1983 BufferPtr = CurPtr;
1984
1985 // No longer in the conflict marker.
1986 IsInConflictMarker = false;
1987 return true;
1988 }
1989
1990 return false;
1991}
1992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993
1994/// LexTokenInternal - This implements a simple C family lexer. It is an
1995/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001996/// has a null character at the end of the file. This returns a preprocessing
1997/// token, not a normal token, as such, it is an internal interface. It assumes
1998/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001999void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002000LexNextToken:
2001 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002002 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // CurPtr - Cache BufferPtr in an automatic variable.
2006 const char *CurPtr = BufferPtr;
2007
2008 // Small amounts of horizontal whitespace is very common between tokens.
2009 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2010 ++CurPtr;
2011 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2012 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Chris Lattnerd88dc482008-10-12 04:05:48 +00002014 // If we are keeping whitespace and other tokens, just return what we just
2015 // skipped. The next lexer invocation will return the token after the
2016 // whitespace.
2017 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002018 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002019 return;
2020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002023 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Read a character, advancing over it.
2029 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002030 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 switch (Char) {
2033 case 0: // Null.
2034 // Found end of file?
2035 if (CurPtr-1 == BufferEnd) {
2036 // Read the PP instance variable into an automatic variable, because
2037 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002038 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2040 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002041 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2042 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Chris Lattner74d15df2008-11-22 02:02:22 +00002045 if (!isLexingRawMode())
2046 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002047 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002048 if (SkipWhitespace(Result, CurPtr))
2049 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002052
2053 case 26: // DOS & CP/M EOF: "^Z".
2054 // If we're in Microsoft extensions mode, treat this as end of file.
2055 if (Features.Microsoft) {
2056 // Read the PP instance variable into an automatic variable, because
2057 // LexEndOfFile will often delete 'this'.
2058 Preprocessor *PPCache = PP;
2059 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2060 return; // Got a token to return.
2061 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2062 return PPCache->Lex(Result);
2063 }
2064 // If Microsoft extensions are disabled, this is just random garbage.
2065 Kind = tok::unknown;
2066 break;
2067
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 case '\n':
2069 case '\r':
2070 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002071 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002072 if (ParsingPreprocessorDirective) {
2073 // Done parsing the "line".
2074 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002077 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 // Since we consumed a newline, we are back at the start of a line.
2080 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Peter Collingbourne84021552011-02-28 02:37:51 +00002082 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 break;
2084 }
2085 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002086 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002088 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Chris Lattnerd88dc482008-10-12 04:05:48 +00002090 if (SkipWhitespace(Result, CurPtr))
2091 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 goto LexNextToken; // GCC isn't tail call eliminating.
2093 case ' ':
2094 case '\t':
2095 case '\f':
2096 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002097 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002098 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002099 if (SkipWhitespace(Result, CurPtr))
2100 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002101
2102 SkipIgnoredUnits:
2103 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Chris Lattner8133cfc2007-07-22 06:29:05 +00002105 // If the next token is obviously a // or /* */ comment, skip it efficiently
2106 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002107 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002108 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002109 if (SkipBCPLComment(Result, CurPtr+2))
2110 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002111 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002112 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002113 if (SkipBlockComment(Result, CurPtr+2))
2114 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002115 goto SkipIgnoredUnits;
2116 } else if (isHorizontalWhitespace(*CurPtr)) {
2117 goto SkipHorizontalWhitespace;
2118 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002120
Chris Lattner3a570772008-01-03 17:58:54 +00002121 // C99 6.4.4.1: Integer Constants.
2122 // C99 6.4.4.2: Floating Constants.
2123 case '0': case '1': case '2': case '3': case '4':
2124 case '5': case '6': case '7': case '8': case '9':
2125 // Notify MIOpt that we read a non-whitespace/non-comment token.
2126 MIOpt.ReadToken();
2127 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Chris Lattner3a570772008-01-03 17:58:54 +00002129 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Notify MIOpt that we read a non-whitespace/non-comment token.
2131 MIOpt.ReadToken();
2132 Char = getCharAndSize(CurPtr, SizeTmp);
2133
2134 // Wide string literal.
2135 if (Char == '"')
2136 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2137 true);
2138
2139 // Wide character constant.
2140 if (Char == '\'')
2141 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2142 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 // C99 6.4.2: Identifiers.
2145 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2146 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2147 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
2148 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2149 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2150 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2151 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
2152 case 'v': case 'w': case 'x': case 'y': case 'z':
2153 case '_':
2154 // Notify MIOpt that we read a non-whitespace/non-comment token.
2155 MIOpt.ReadToken();
2156 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002157
2158 case '$': // $ in identifiers.
2159 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002160 if (!isLexingRawMode())
2161 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002162 // Notify MIOpt that we read a non-whitespace/non-comment token.
2163 MIOpt.ReadToken();
2164 return LexIdentifier(Result, CurPtr);
2165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Chris Lattner9e6293d2008-10-12 04:51:35 +00002167 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002168 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 // C99 6.4.4: Character Constants.
2171 case '\'':
2172 // Notify MIOpt that we read a non-whitespace/non-comment token.
2173 MIOpt.ReadToken();
2174 return LexCharConstant(Result, CurPtr);
2175
2176 // C99 6.4.5: String Literals.
2177 case '"':
2178 // Notify MIOpt that we read a non-whitespace/non-comment token.
2179 MIOpt.ReadToken();
2180 return LexStringLiteral(Result, CurPtr, false);
2181
2182 // C99 6.4.6: Punctuators.
2183 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002184 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002185 break;
2186 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002187 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 break;
2189 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002190 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 break;
2192 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002193 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 break;
2195 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002196 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 break;
2198 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002199 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 break;
2201 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002202 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 break;
2204 case '.':
2205 Char = getCharAndSize(CurPtr, SizeTmp);
2206 if (Char >= '0' && Char <= '9') {
2207 // Notify MIOpt that we read a non-whitespace/non-comment token.
2208 MIOpt.ReadToken();
2209
2210 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2211 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002212 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 CurPtr += SizeTmp;
2214 } else if (Char == '.' &&
2215 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002216 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2218 SizeTmp2, Result);
2219 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002220 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 }
2222 break;
2223 case '&':
2224 Char = getCharAndSize(CurPtr, SizeTmp);
2225 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002226 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2228 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002229 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2231 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002232 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 }
2234 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002235 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002237 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2239 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002240 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 }
2242 break;
2243 case '+':
2244 Char = getCharAndSize(CurPtr, SizeTmp);
2245 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002247 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002250 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002252 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 }
2254 break;
2255 case '-':
2256 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002257 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002259 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002260 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002261 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2263 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002264 Kind = tok::arrowstar;
2265 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002267 Kind = tok::arrow;
2268 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002270 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002272 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 }
2274 break;
2275 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002276 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 break;
2278 case '!':
2279 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002280 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2282 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002283 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 }
2285 break;
2286 case '/':
2287 // 6.4.9: Comments
2288 Char = getCharAndSize(CurPtr, SizeTmp);
2289 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002290 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2291 // want to lex this as a comment. There is one problem with this though,
2292 // that in one particular corner case, this can change the behavior of the
2293 // resultant program. For example, In "foo //**/ bar", C89 would lex
2294 // this as "foo / bar" and langauges with BCPL comments would lex it as
2295 // "foo". Check to see if the character after the second slash is a '*'.
2296 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002297 // However, we never do this in -traditional-cpp mode.
2298 if ((Features.BCPLComment ||
2299 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2300 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002301 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002302 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Chris Lattner8402c732009-01-16 22:39:25 +00002304 // It is common for the tokens immediately after a // comment to be
2305 // whitespace (indentation for the next line). Instead of going through
2306 // the big switch, handle it efficiently now.
2307 goto SkipIgnoredUnits;
2308 }
2309 }
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattner8402c732009-01-16 22:39:25 +00002311 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002313 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002314 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002315 }
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Chris Lattner8402c732009-01-16 22:39:25 +00002317 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002319 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002321 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002322 }
2323 break;
2324 case '%':
2325 Char = getCharAndSize(CurPtr, SizeTmp);
2326 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002327 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2329 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002330 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2332 } else if (Features.Digraphs && Char == ':') {
2333 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2334 Char = getCharAndSize(CurPtr, SizeTmp);
2335 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002336 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2338 SizeTmp2, Result);
2339 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002341 if (!isLexingRawMode())
2342 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002343 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002344 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 // We parsed a # character. If this occurs at the start of the line,
2346 // it's actually the start of a preprocessing directive. Callback to
2347 // the preprocessor to handle it.
2348 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002349 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002350 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002351 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 // As an optimization, if the preprocessor didn't switch lexers, tail
2354 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002355 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 // Start a new token. If this is a #include or something, the PP may
2357 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002358 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002360 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002361 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002362 IsAtStartOfLine = false;
2363 }
2364 goto LexNextToken; // GCC isn't tail call eliminating.
2365 }
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Chris Lattner168ae2d2007-10-17 20:41:00 +00002367 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002368 }
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Chris Lattnere91e9322009-03-18 20:58:27 +00002370 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002371 }
2372 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002373 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 }
2375 break;
2376 case '<':
2377 Char = getCharAndSize(CurPtr, SizeTmp);
2378 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002379 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002381 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2382 if (After == '=') {
2383 Kind = tok::lesslessequal;
2384 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2385 SizeTmp2, Result);
2386 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2387 // If this is actually a '<<<<<<<' version control conflict marker,
2388 // recognize it as such and recover nicely.
2389 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002390 } else if (Features.CUDA && After == '<') {
2391 Kind = tok::lesslessless;
2392 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2393 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002394 } else {
2395 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2396 Kind = tok::lessless;
2397 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002400 Kind = tok::lessequal;
2401 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002402 if (Features.CPlusPlus0x &&
2403 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2404 // C++0x [lex.pptoken]p3:
2405 // Otherwise, if the next three characters are <:: and the subsequent
2406 // character is neither : nor >, the < is treated as a preprocessor
2407 // token by itself and not as the first character of the alternative
2408 // token <:.
2409 unsigned SizeTmp3;
2410 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2411 if (After != ':' && After != '>') {
2412 Kind = tok::less;
2413 break;
2414 }
2415 }
2416
Reid Spencer5f016e22007-07-11 17:01:13 +00002417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002418 Kind = tok::l_square;
2419 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002421 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002423 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 }
2425 break;
2426 case '>':
2427 Char = getCharAndSize(CurPtr, SizeTmp);
2428 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002430 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002432 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2433 if (After == '=') {
2434 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2435 SizeTmp2, Result);
2436 Kind = tok::greatergreaterequal;
2437 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2438 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2439 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002440 } else if (Features.CUDA && After == '>') {
2441 Kind = tok::greatergreatergreater;
2442 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2443 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002444 } else {
2445 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2446 Kind = tok::greatergreater;
2447 }
2448
Reid Spencer5f016e22007-07-11 17:01:13 +00002449 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002450 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002451 }
2452 break;
2453 case '^':
2454 Char = getCharAndSize(CurPtr, SizeTmp);
2455 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002457 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002458 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002459 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002460 }
2461 break;
2462 case '|':
2463 Char = getCharAndSize(CurPtr, SizeTmp);
2464 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002465 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2467 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002468 // If this is '|||||||' and we're in a conflict marker, ignore it.
2469 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2470 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002471 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2473 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002474 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 }
2476 break;
2477 case ':':
2478 Char = getCharAndSize(CurPtr, SizeTmp);
2479 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002480 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2482 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002483 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002485 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002486 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 }
2488 break;
2489 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002490 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 break;
2492 case '=':
2493 Char = getCharAndSize(CurPtr, SizeTmp);
2494 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002495 // If this is '=======' and we're in a conflict marker, ignore it.
2496 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2497 goto LexNextToken;
2498
Chris Lattner9e6293d2008-10-12 04:51:35 +00002499 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002501 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002502 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 }
2504 break;
2505 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002506 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002507 break;
2508 case '#':
2509 Char = getCharAndSize(CurPtr, SizeTmp);
2510 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002511 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2513 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002514 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002515 if (!isLexingRawMode())
2516 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2518 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 // We parsed a # character. If this occurs at the start of the line,
2520 // it's actually the start of a preprocessing directive. Callback to
2521 // the preprocessor to handle it.
2522 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002523 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002524 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002525 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 // As an optimization, if the preprocessor didn't switch lexers, tail
2528 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002529 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 // Start a new token. If this is a #include or something, the PP may
2531 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002532 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002534 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002535 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 IsAtStartOfLine = false;
2537 }
2538 goto LexNextToken; // GCC isn't tail call eliminating.
2539 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002540 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 }
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Chris Lattnere91e9322009-03-18 20:58:27 +00002543 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 }
2545 break;
2546
Chris Lattner3a570772008-01-03 17:58:54 +00002547 case '@':
2548 // Objective C support.
2549 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002550 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002551 else
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 case '\\':
2556 // FIXME: UCN's.
2557 // FALL THROUGH.
2558 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002559 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 break;
2561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 // Notify MIOpt that we read a non-whitespace/non-comment token.
2564 MIOpt.ReadToken();
2565
2566 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002567 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002568}