blob: 6d25d2b2cf52947e9bb9b0d9acc1605d8ac822eb [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) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000682 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000683 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000684
685 if (Loc.isMacroID()) {
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +0000686 if (Offset > 0 || !SM.isAtEndOfMacroInstantiation(Loc, Features))
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000687 return SourceLocation(); // Points inside the macro instantiation.
688
689 // Continue and find the location just after the macro instantiation.
690 Loc = SM.getInstantiationRange(Loc).second;
691 }
692
Chris Lattner7ef5c272010-11-17 07:05:50 +0000693 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
694 if (Len > Offset)
695 Len = Len - Offset;
696 else
697 return Loc;
698
John McCall77ebb382011-04-06 01:50:22 +0000699 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000700}
701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702//===----------------------------------------------------------------------===//
703// Character information.
704//===----------------------------------------------------------------------===//
705
Reid Spencer5f016e22007-07-11 17:01:13 +0000706enum {
707 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
708 CHAR_VERT_WS = 0x02, // '\r', '\n'
709 CHAR_LETTER = 0x04, // a-z,A-Z
710 CHAR_NUMBER = 0x08, // 0-9
711 CHAR_UNDER = 0x10, // _
712 CHAR_PERIOD = 0x20 // .
713};
714
Chris Lattner03b98662009-07-07 17:09:54 +0000715// Statically initialize CharInfo table based on ASCII character set
716// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000717static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000718{
719// 0 NUL 1 SOH 2 STX 3 ETX
720// 4 EOT 5 ENQ 6 ACK 7 BEL
721 0 , 0 , 0 , 0 ,
722 0 , 0 , 0 , 0 ,
723// 8 BS 9 HT 10 NL 11 VT
724//12 NP 13 CR 14 SO 15 SI
725 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
726 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
727//16 DLE 17 DC1 18 DC2 19 DC3
728//20 DC4 21 NAK 22 SYN 23 ETB
729 0 , 0 , 0 , 0 ,
730 0 , 0 , 0 , 0 ,
731//24 CAN 25 EM 26 SUB 27 ESC
732//28 FS 29 GS 30 RS 31 US
733 0 , 0 , 0 , 0 ,
734 0 , 0 , 0 , 0 ,
735//32 SP 33 ! 34 " 35 #
736//36 $ 37 % 38 & 39 '
737 CHAR_HORZ_WS, 0 , 0 , 0 ,
738 0 , 0 , 0 , 0 ,
739//40 ( 41 ) 42 * 43 +
740//44 , 45 - 46 . 47 /
741 0 , 0 , 0 , 0 ,
742 0 , 0 , CHAR_PERIOD , 0 ,
743//48 0 49 1 50 2 51 3
744//52 4 53 5 54 6 55 7
745 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
746 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
747//56 8 57 9 58 : 59 ;
748//60 < 61 = 62 > 63 ?
749 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
750 0 , 0 , 0 , 0 ,
751//64 @ 65 A 66 B 67 C
752//68 D 69 E 70 F 71 G
753 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
754 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
755//72 H 73 I 74 J 75 K
756//76 L 77 M 78 N 79 O
757 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
758 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
759//80 P 81 Q 82 R 83 S
760//84 T 85 U 86 V 87 W
761 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
762 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
763//88 X 89 Y 90 Z 91 [
764//92 \ 93 ] 94 ^ 95 _
765 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
766 0 , 0 , 0 , CHAR_UNDER ,
767//96 ` 97 a 98 b 99 c
768//100 d 101 e 102 f 103 g
769 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
770 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
771//104 h 105 i 106 j 107 k
772//108 l 109 m 110 n 111 o
773 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
774 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
775//112 p 113 q 114 r 115 s
776//116 t 117 u 118 v 119 w
777 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
778 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
779//120 x 121 y 122 z 123 {
780//124 | 125 } 126 ~ 127 DEL
781 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
782 0 , 0 , 0 , 0
783};
784
Chris Lattnera2bf1052009-12-17 05:29:40 +0000785static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 static bool isInited = false;
787 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000788 // check the statically-initialized CharInfo table
789 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
790 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
791 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
792 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
793 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
794 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
795 assert(CHAR_UNDER == CharInfo[(int)'_']);
796 assert(CHAR_PERIOD == CharInfo[(int)'.']);
797 for (unsigned i = 'a'; i <= 'z'; ++i) {
798 assert(CHAR_LETTER == CharInfo[i]);
799 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
800 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000802 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000803
Chris Lattner03b98662009-07-07 17:09:54 +0000804 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000805}
806
Chris Lattner03b98662009-07-07 17:09:54 +0000807
Reid Spencer5f016e22007-07-11 17:01:13 +0000808/// isIdentifierBody - Return true if this is the body character of an
809/// identifier, which is [a-zA-Z0-9_].
810static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000811 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000812}
813
814/// isHorizontalWhitespace - Return true if this character is horizontal
815/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
816static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000817 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000818}
819
820/// isWhitespace - Return true if this character is horizontal or vertical
821/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
822/// for '\0'.
823static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000824 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000825}
826
827/// isNumberBody - Return true if this is the body character of an
828/// preprocessing number, which is [a-zA-Z0-9_.].
829static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000830 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000831 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000832}
833
834
835//===----------------------------------------------------------------------===//
836// Diagnostics forwarding code.
837//===----------------------------------------------------------------------===//
838
Chris Lattner409a0362007-07-22 18:38:25 +0000839/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
840/// lexer buffer was all instantiated at a single point, perform the mapping.
841/// This is currently only used for _Pragma implementation, so it is the slow
842/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000843static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
844 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000845static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
846 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000847 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000848 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner409a0362007-07-22 18:38:25 +0000850 // Otherwise, we're lexing "mapped tokens". This is used for things like
851 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000852 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000853 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000855 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000856 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000857 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000858 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Chris Lattnere7fb4842009-02-15 20:52:18 +0000860 // Figure out the expansion loc range, which is the range covered by the
861 // original _Pragma(...) sequence.
862 std::pair<SourceLocation,SourceLocation> II =
863 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattnere7fb4842009-02-15 20:52:18 +0000865 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000866}
867
Reid Spencer5f016e22007-07-11 17:01:13 +0000868/// getSourceLocation - Return a source location identifier for the specified
869/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000870SourceLocation Lexer::getSourceLocation(const char *Loc,
871 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000872 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000874
875 // In the normal case, we're just lexing from a simple file buffer, return
876 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000877 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000878 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000879 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner2b2453a2009-01-17 06:22:33 +0000881 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
882 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000883 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000884 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
Reid Spencer5f016e22007-07-11 17:01:13 +0000887/// Diag - Forwarding function for diagnostics. This translate a source
888/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000889DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000890 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
893//===----------------------------------------------------------------------===//
894// Trigraph and Escaped Newline Handling Code.
895//===----------------------------------------------------------------------===//
896
897/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
898/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
899static char GetTrigraphCharForLetter(char Letter) {
900 switch (Letter) {
901 default: return 0;
902 case '=': return '#';
903 case ')': return ']';
904 case '(': return '[';
905 case '!': return '|';
906 case '\'': return '^';
907 case '>': return '}';
908 case '/': return '\\';
909 case '<': return '{';
910 case '-': return '~';
911 }
912}
913
914/// DecodeTrigraphChar - If the specified character is a legal trigraph when
915/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
916/// return the result character. Finally, emit a warning about trigraph use
917/// whether trigraphs are enabled or not.
918static char DecodeTrigraphChar(const char *CP, Lexer *L) {
919 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000920 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattner3692b092008-11-18 07:59:24 +0000922 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000923 if (!L->isLexingRawMode())
924 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000925 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Chris Lattner74d15df2008-11-22 02:02:22 +0000928 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000929 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 return Res;
931}
932
Chris Lattner24f0e482009-04-18 22:05:41 +0000933/// getEscapedNewLineSize - Return the size of the specified escaped newline,
934/// 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 +0000935/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000936unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
937 unsigned Size = 0;
938 while (isWhitespace(Ptr[Size])) {
939 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner24f0e482009-04-18 22:05:41 +0000941 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
942 continue;
943
944 // If this is a \r\n or \n\r, skip the other half.
945 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
946 Ptr[Size-1] != Ptr[Size])
947 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner24f0e482009-04-18 22:05:41 +0000949 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000950 }
951
Chris Lattner24f0e482009-04-18 22:05:41 +0000952 // Not an escaped newline, must be a \t or something else.
953 return 0;
954}
955
Chris Lattner03374952009-04-18 22:27:02 +0000956/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
957/// them), skip over them and return the first non-escaped-newline found,
958/// otherwise return P.
959const char *Lexer::SkipEscapedNewLines(const char *P) {
960 while (1) {
961 const char *AfterEscape;
962 if (*P == '\\') {
963 AfterEscape = P+1;
964 } else if (*P == '?') {
965 // If not a trigraph for escape, bail out.
966 if (P[1] != '?' || P[2] != '/')
967 return P;
968 AfterEscape = P+3;
969 } else {
970 return P;
971 }
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Chris Lattner03374952009-04-18 22:27:02 +0000973 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
974 if (NewLineSize == 0) return P;
975 P = AfterEscape+NewLineSize;
976 }
977}
978
Chris Lattner24f0e482009-04-18 22:05:41 +0000979
Reid Spencer5f016e22007-07-11 17:01:13 +0000980/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
981/// get its size, and return it. This is tricky in several cases:
982/// 1. If currently at the start of a trigraph, we warn about the trigraph,
983/// then either return the trigraph (skipping 3 chars) or the '?',
984/// depending on whether trigraphs are enabled or not.
985/// 2. If this is an escaped newline (potentially with whitespace between
986/// the backslash and newline), implicitly skip the newline and return
987/// the char after it.
988/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
989///
990/// This handles the slow/uncommon case of the getCharAndSize method. Here we
991/// know that we can accumulate into Size, and that we have already incremented
992/// Ptr by Size bytes.
993///
994/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
995/// be updated to match.
996///
997char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000998 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 // If we have a slash, look for an escaped newline.
1000 if (Ptr[0] == '\\') {
1001 ++Size;
1002 ++Ptr;
1003Slash:
1004 // Common case, backslash-char where the char is not whitespace.
1005 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner5636a3b2009-06-23 05:15:06 +00001007 // See if we have optional whitespace characters between the slash and
1008 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001009 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1010 // Remember that this token needs to be cleaned.
1011 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001012
Chris Lattner24f0e482009-04-18 22:05:41 +00001013 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001014 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001015 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Chris Lattner24f0e482009-04-18 22:05:41 +00001017 // Found backslash<whitespace><newline>. Parse the char after it.
1018 Size += EscapedNewLineSize;
1019 Ptr += EscapedNewLineSize;
1020 // Use slow version to accumulate a correct size field.
1021 return getCharAndSizeSlow(Ptr, Size, Tok);
1022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 // Otherwise, this is not an escaped newline, just return the slash.
1025 return '\\';
1026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 // If this is a trigraph, process it.
1029 if (Ptr[0] == '?' && Ptr[1] == '?') {
1030 // If this is actually a legal trigraph (not something like "??x"), emit
1031 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1032 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1033 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001034 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001035
1036 Ptr += 3;
1037 Size += 3;
1038 if (C == '\\') goto Slash;
1039 return C;
1040 }
1041 }
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 // If this is neither, return a single character.
1044 ++Size;
1045 return *Ptr;
1046}
1047
1048
1049/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1050/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1051/// and that we have already incremented Ptr by Size bytes.
1052///
1053/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1054/// be updated to match.
1055char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1056 const LangOptions &Features) {
1057 // If we have a slash, look for an escaped newline.
1058 if (Ptr[0] == '\\') {
1059 ++Size;
1060 ++Ptr;
1061Slash:
1062 // Common case, backslash-char where the char is not whitespace.
1063 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001066 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1067 // Found backslash<whitespace><newline>. Parse the char after it.
1068 Size += EscapedNewLineSize;
1069 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner24f0e482009-04-18 22:05:41 +00001071 // Use slow version to accumulate a correct size field.
1072 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 // Otherwise, this is not an escaped newline, just return the slash.
1076 return '\\';
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 // If this is a trigraph, process it.
1080 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1081 // If this is actually a legal trigraph (not something like "??x"), return
1082 // it.
1083 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1084 Ptr += 3;
1085 Size += 3;
1086 if (C == '\\') goto Slash;
1087 return C;
1088 }
1089 }
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // If this is neither, return a single character.
1092 ++Size;
1093 return *Ptr;
1094}
1095
1096//===----------------------------------------------------------------------===//
1097// Helper methods for lexing.
1098//===----------------------------------------------------------------------===//
1099
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001100/// \brief Routine that indiscriminately skips bytes in the source file.
1101void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1102 BufferPtr += Bytes;
1103 if (BufferPtr > BufferEnd)
1104 BufferPtr = BufferEnd;
1105 IsAtStartOfLine = StartOfLine;
1106}
1107
Chris Lattnerd2177732007-07-20 16:59:19 +00001108void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1110 unsigned Size;
1111 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001112 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001114
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 --CurPtr; // Back up over the skipped character.
1116
1117 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1118 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1119 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001120 //
1121 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1122 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1124FinishIdentifier:
1125 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001126 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1127 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // If we are in raw mode, return this identifier raw. There is no need to
1130 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001131 if (LexingRawMode)
1132 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001134 // Fill in Result.IdentifierInfo and update the token kind,
1135 // looking up the identifier in the identifier table.
1136 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 // Finally, now that we know we have an identifier, pass this off to the
1139 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001140 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001141 PP->HandleIdentifier(Result);
1142 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 C = getCharAndSize(CurPtr, Size);
1148 while (1) {
1149 if (C == '$') {
1150 // If we hit a $ and they are not supported in identifiers, we are done.
1151 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001154 if (!isLexingRawMode())
1155 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 CurPtr = ConsumeChar(CurPtr, Size, Result);
1157 C = getCharAndSize(CurPtr, Size);
1158 continue;
1159 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1160 // Found end of identifier.
1161 goto FinishIdentifier;
1162 }
1163
1164 // Otherwise, this character is good, consume it.
1165 CurPtr = ConsumeChar(CurPtr, Size, Result);
1166
1167 C = getCharAndSize(CurPtr, Size);
1168 while (isIdentifierBody(C)) { // FIXME: UCNs.
1169 CurPtr = ConsumeChar(CurPtr, Size, Result);
1170 C = getCharAndSize(CurPtr, Size);
1171 }
1172 }
1173}
1174
Douglas Gregora75ec432010-08-30 14:50:47 +00001175/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001176/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001177static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1178 unsigned Size;
1179 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1180 if (C1 != '0')
1181 return false;
1182 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1183 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001184}
Reid Spencer5f016e22007-07-11 17:01:13 +00001185
Nate Begeman5253c7f2008-04-14 02:26:39 +00001186/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001187/// constant. From[-1] is the first character lexed. Return the end of the
1188/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001189void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 unsigned Size;
1191 char C = getCharAndSize(CurPtr, Size);
1192 char PrevCh = 0;
1193 while (isNumberBody(C)) { // FIXME: UCNs?
1194 CurPtr = ConsumeChar(CurPtr, Size, Result);
1195 PrevCh = C;
1196 C = getCharAndSize(CurPtr, Size);
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001200 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1201 // If we are in Microsoft mode, don't continue if the constant is hex.
1202 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001203 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001204 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1205 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001206
1207 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001208 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001209 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001213 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001214 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001215 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001216}
1217
1218/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1219/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +00001220void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 char C = getAndAdvanceChar(CurPtr, Result);
1224 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001225 // Skip escaped characters. Escaped newlines will already be processed by
1226 // getAndAdvanceChar.
1227 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001229
Chris Lattner571339c2010-05-30 23:27:38 +00001230 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001231 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001232 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1233 PP->CodeCompleteNaturalLanguage();
1234 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001235 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001236 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 }
Chris Lattner571339c2010-05-30 23:27:38 +00001239
1240 if (C == 0)
1241 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 C = getAndAdvanceChar(CurPtr, Result);
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001246 if (NulCharacter && !isLexingRawMode())
1247 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001250 const char *TokStart = BufferPtr;
Sean Hunt6cf75022010-08-30 17:47:05 +00001251 FormTokenWithChars(Result, CurPtr,
1252 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001253 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001254}
1255
1256/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1257/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001258void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001260 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 char C = getAndAdvanceChar(CurPtr, Result);
1262 while (C != '>') {
1263 // Skip escaped characters.
1264 if (C == '\\') {
1265 // Skip the escaped character.
1266 C = getAndAdvanceChar(CurPtr, Result);
1267 } else if (C == '\n' || C == '\r' || // Newline.
1268 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001269 // If the filename is unterminated, then it must just be a lone <
1270 // character. Return this as such.
1271 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 return;
1273 } else if (C == 0) {
1274 NulCharacter = CurPtr-1;
1275 }
1276 C = getAndAdvanceChar(CurPtr, Result);
1277 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001280 if (NulCharacter && !isLexingRawMode())
1281 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001284 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001285 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001286 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001287}
1288
1289
1290/// LexCharConstant - Lex the remainder of a character constant, after having
1291/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001292void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 const char *NulCharacter = 0; // Does this character contain the \0 character?
1294
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 char C = getAndAdvanceChar(CurPtr, Result);
1296 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001297 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001298 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001299 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001301 }
1302
1303 while (C != '\'') {
1304 // Skip escaped characters.
1305 if (C == '\\') {
1306 // Skip the escaped character.
1307 // FIXME: UCN's
1308 C = getAndAdvanceChar(CurPtr, Result);
1309 } else if (C == '\n' || C == '\r' || // Newline.
1310 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001311 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1312 PP->CodeCompleteNaturalLanguage();
1313 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001314 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001315 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1316 return;
1317 } else if (C == 0) {
1318 NulCharacter = CurPtr-1;
1319 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 C = getAndAdvanceChar(CurPtr, Result);
1321 }
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattnerd80f7862010-07-07 23:24:27 +00001323 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001324 if (NulCharacter && !isLexingRawMode())
1325 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001328 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001329 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001330 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
1332
1333/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1334/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001335///
1336/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1337///
1338bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 // Whitespace - Skip it, then return the token after the whitespace.
1340 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1341 while (1) {
1342 // Skip horizontal whitespace very aggressively.
1343 while (isHorizontalWhitespace(Char))
1344 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001346 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 if (Char != '\n' && Char != '\r')
1348 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 if (ParsingPreprocessorDirective) {
1351 // End of preprocessor directive line, let LexTokenInternal handle this.
1352 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001353 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // ok, but handle newline.
1357 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001358 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001360 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 Char = *++CurPtr;
1362 }
1363
1364 // If this isn't immediately after a newline, there is leading space.
1365 char PrevChar = CurPtr[-1];
1366 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001367 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
Chris Lattnerd88dc482008-10-12 04:05:48 +00001369 // If the client wants us to return whitespace, return it now.
1370 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001371 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001372 return true;
1373 }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001376 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001377}
1378
1379// SkipBCPLComment - We have just read the // characters from input. Skip until
1380// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001381/// BufferPtr and return.
1382///
1383/// If we're in KeepCommentMode or any CommentHandler has inserted
1384/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001385bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 // If BCPL comments aren't explicitly enabled for this language, emit an
1387 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001388 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 // Mark them enabled so we only emit one warning for this translation
1392 // unit.
1393 Features.BCPLComment = true;
1394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 // Scan over the body of the comment. The common case, when scanning, is that
1397 // the comment contains normal ascii characters with nothing interesting in
1398 // them. As such, optimize for this case with the inner loop.
1399 char C;
1400 do {
1401 C = *CurPtr;
1402 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1403 // If we find a \n character, scan backwards, checking to see if it's an
1404 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 // Skip over characters in the fast loop.
1407 while (C != 0 && // Potentially EOF.
1408 C != '\\' && // Potentially escaped newline.
1409 C != '?' && // Potentially trigraph.
1410 C != '\n' && C != '\r') // Newline or DOS-style newline.
1411 C = *++CurPtr;
1412
1413 // If this is a newline, we're done.
1414 if (C == '\n' || C == '\r')
1415 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001418 // properly decode the character. Read it in raw mode to avoid emitting
1419 // diagnostics about things like trigraphs. If we see an escaped newline,
1420 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001422 bool OldRawMode = isLexingRawMode();
1423 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001425 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001426
1427 // If the char that we finally got was a \n, then we must have had something
1428 // like \<newline><newline>. We don't want to have consumed the second
1429 // newline, we want CurPtr, to end up pointing to it down below.
1430 if (C == '\n' || C == '\r') {
1431 --CurPtr;
1432 C = 'x'; // doesn't matter what this is.
1433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 // If we read multiple characters, and one of those characters was a \r or
1436 // \n, then we had an escaped newline within the comment. Emit diagnostic
1437 // unless the next line is also a // comment.
1438 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1439 for (; OldPtr != CurPtr; ++OldPtr)
1440 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1441 // Okay, we found a // comment that ends in a newline, if the next
1442 // line is also a // comment, but has spaces, don't emit a diagnostic.
1443 if (isspace(C)) {
1444 const char *ForwardPtr = CurPtr;
1445 while (isspace(*ForwardPtr)) // Skip whitespace.
1446 ++ForwardPtr;
1447 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1448 break;
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Chris Lattner74d15df2008-11-22 02:02:22 +00001451 if (!isLexingRawMode())
1452 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 break;
1454 }
1455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Douglas Gregor55817af2010-08-25 17:04:25 +00001457 if (CurPtr == BufferEnd+1) {
1458 if (PP && PP->isCodeCompletionFile(FileLoc))
1459 PP->CodeCompleteNaturalLanguage();
1460
1461 --CurPtr;
1462 break;
1463 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 } while (C != '\n' && C != '\r');
1465
Chris Lattner3d0ad582010-02-03 21:06:21 +00001466 // Found but did not consume the newline. Notify comment handlers about the
1467 // comment unless we're in a #if 0 block.
1468 if (PP && !isLexingRawMode() &&
1469 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1470 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001471 BufferPtr = CurPtr;
1472 return true; // A token has to be returned.
1473 }
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001476 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 return SaveBCPLComment(Result, CurPtr);
1478
1479 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001480 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1482 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001483 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001487 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001488 // contribute to another token), it isn't needed for correctness. Note that
1489 // this is ok even in KeepWhitespaceMode, because we would have returned the
1490 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001494 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001496 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001498 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001499}
1500
1501/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1502/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001503bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001504 // If we're not in a preprocessor directive, just return the // comment
1505 // directly.
1506 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Chris Lattner9e6293d2008-10-12 04:51:35 +00001508 if (!ParsingPreprocessorDirective)
1509 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Chris Lattner9e6293d2008-10-12 04:51:35 +00001511 // If this BCPL-style comment is in a macro definition, transmogrify it into
1512 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001513 bool Invalid = false;
1514 std::string Spelling = PP->getSpelling(Result, &Invalid);
1515 if (Invalid)
1516 return true;
1517
Chris Lattner9e6293d2008-10-12 04:51:35 +00001518 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1519 Spelling[1] = '*'; // Change prefix to "/*".
1520 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Chris Lattner9e6293d2008-10-12 04:51:35 +00001522 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001523 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1524 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001525 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001526}
1527
1528/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1529/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001530/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001531static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 Lexer *L) {
1533 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Back up off the newline.
1536 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // If this is a two-character newline sequence, skip the other character.
1539 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1540 // \n\n or \r\r -> not escaped newline.
1541 if (CurPtr[0] == CurPtr[1])
1542 return false;
1543 // \n\r or \r\n -> skip the newline.
1544 --CurPtr;
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // If we have horizontal whitespace, skip over it. We allow whitespace
1548 // between the slash and newline.
1549 bool HasSpace = false;
1550 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1551 --CurPtr;
1552 HasSpace = true;
1553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // If we have a slash, we know this is an escaped newline.
1556 if (*CurPtr == '\\') {
1557 if (CurPtr[-1] != '*') return false;
1558 } else {
1559 // It isn't a slash, is it the ?? / trigraph?
1560 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1561 CurPtr[-3] != '*')
1562 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // This is the trigraph ending the comment. Emit a stern warning!
1565 CurPtr -= 2;
1566
1567 // If no trigraphs are enabled, warn that we ignored this trigraph and
1568 // ignore this * character.
1569 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001570 if (!L->isLexingRawMode())
1571 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 return false;
1573 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001574 if (!L->isLexingRawMode())
1575 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001579 if (!L->isLexingRawMode())
1580 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001583 if (HasSpace && !L->isLexingRawMode())
1584 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 return true;
1587}
1588
1589#ifdef __SSE2__
1590#include <emmintrin.h>
1591#elif __ALTIVEC__
1592#include <altivec.h>
1593#undef bool
1594#endif
1595
1596/// SkipBlockComment - We have just read the /* characters from input. Read
1597/// until we find the */ characters that terminate the comment. Note that we
1598/// don't bother decoding trigraphs or escaped newlines in block comments,
1599/// because they cannot cause the comment to end. The only thing that can
1600/// happen is the comment could end with an escaped newline between the */ end
1601/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001602///
Chris Lattner046c2272010-01-18 22:35:47 +00001603/// If we're in KeepCommentMode or any CommentHandler has inserted
1604/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001605bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001607 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // optimization helps people who like to put a lot of * characters in their
1609 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001610
1611 // The first character we get with newlines and trigraphs skipped to handle
1612 // the degenerate /*/ case below correctly if the * has an escaped newline
1613 // after it.
1614 unsigned CharSize;
1615 unsigned char C = getCharAndSize(CurPtr, CharSize);
1616 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001618 if (!isLexingRawMode() &&
1619 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001620 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001621 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Chris Lattner31f0eca2008-10-12 04:19:49 +00001623 // KeepWhitespaceMode should return this broken comment as a token. Since
1624 // it isn't a well formed comment, just return it as an 'unknown' token.
1625 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001626 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001627 return true;
1628 }
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Chris Lattner31f0eca2008-10-12 04:19:49 +00001630 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001631 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner8146b682007-07-21 23:43:37 +00001634 // Check to see if the first character after the '/*' is another /. If so,
1635 // then this slash does not end the block comment, it is part of it.
1636 if (C == '/')
1637 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 while (1) {
1640 // Skip over all non-interesting characters until we find end of buffer or a
1641 // (probably ending) '/' character.
1642 if (CurPtr + 24 < BufferEnd) {
1643 // While not aligned to a 16-byte boundary.
1644 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1645 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 if (C == '/') goto FoundSlash;
1648
1649#ifdef __SSE2__
1650 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1651 '/', '/', '/', '/', '/', '/', '/', '/');
1652 while (CurPtr+16 <= BufferEnd &&
1653 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1654 CurPtr += 16;
1655#elif __ALTIVEC__
1656 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001657 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 '/', '/', '/', '/', '/', '/', '/', '/'
1659 };
1660 while (CurPtr+16 <= BufferEnd &&
1661 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1662 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001663#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 // Scan for '/' quickly. Many block comments are very large.
1665 while (CurPtr[0] != '/' &&
1666 CurPtr[1] != '/' &&
1667 CurPtr[2] != '/' &&
1668 CurPtr[3] != '/' &&
1669 CurPtr+4 < BufferEnd) {
1670 CurPtr += 4;
1671 }
1672#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 // It has to be one of the bytes scanned, increment to it and read one.
1675 C = *CurPtr++;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 // Loop to scan the remainder.
1679 while (C != '/' && C != '\0')
1680 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 FoundSlash:
1683 if (C == '/') {
1684 if (CurPtr[-2] == '*') // We found the final */. We're done!
1685 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1688 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1689 // We found the final */, though it had an escaped newline between the
1690 // * and /. We're done!
1691 break;
1692 }
1693 }
1694 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1695 // If this is a /* inside of the comment, emit a warning. Don't do this
1696 // if this is a /*/, which will end the comment. This misses cases with
1697 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001698 if (!isLexingRawMode())
1699 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 }
1701 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001702 if (PP && PP->isCodeCompletionFile(FileLoc))
1703 PP->CodeCompleteNaturalLanguage();
1704 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001705 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // Note: the user probably forgot a */. We could continue immediately
1707 // after the /*, but this would involve lexing a lot of what really is the
1708 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001709 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Chris Lattner31f0eca2008-10-12 04:19:49 +00001711 // KeepWhitespaceMode should return this broken comment as a token. Since
1712 // it isn't a well formed comment, just return it as an 'unknown' token.
1713 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001714 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001715 return true;
1716 }
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Chris Lattner31f0eca2008-10-12 04:19:49 +00001718 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001719 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 }
1721 C = *CurPtr++;
1722 }
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Chris Lattner3d0ad582010-02-03 21:06:21 +00001724 // Notify comment handlers about the comment unless we're in a #if 0 block.
1725 if (PP && !isLexingRawMode() &&
1726 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1727 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001728 BufferPtr = CurPtr;
1729 return true; // A token has to be returned.
1730 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001731
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001733 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001734 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001735 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 }
1737
1738 // It is common for the tokens immediately after a /**/ comment to be
1739 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001740 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1741 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001743 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001745 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 }
1747
1748 // Otherwise, just return so that the next character will be lexed as a token.
1749 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001750 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001751 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001752}
1753
1754//===----------------------------------------------------------------------===//
1755// Primary Lexing Entry Points
1756//===----------------------------------------------------------------------===//
1757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1759/// uninterpreted string. This switches the lexer out of directive mode.
1760std::string Lexer::ReadToEndOfLine() {
1761 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1762 "Must be in a preprocessing directive!");
1763 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001764 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001765
1766 // CurPtr - Cache BufferPtr in an automatic variable.
1767 const char *CurPtr = BufferPtr;
1768 while (1) {
1769 char Char = getAndAdvanceChar(CurPtr, Tmp);
1770 switch (Char) {
1771 default:
1772 Result += Char;
1773 break;
1774 case 0: // Null.
1775 // Found end of file?
1776 if (CurPtr-1 != BufferEnd) {
1777 // Nope, normal character, continue.
1778 Result += Char;
1779 break;
1780 }
1781 // FALL THROUGH.
1782 case '\r':
1783 case '\n':
1784 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1785 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1786 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Peter Collingbourne84021552011-02-28 02:37:51 +00001788 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001790 if (Tmp.is(tok::code_completion)) {
1791 if (PP && PP->getCodeCompletionHandler())
1792 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1793 Lex(Tmp);
1794 }
Peter Collingbourne84021552011-02-28 02:37:51 +00001795 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 // Finally, we're done, return the string we found.
1798 return Result;
1799 }
1800 }
1801}
1802
1803/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1804/// condition, reporting diagnostics and handling other edge cases as required.
1805/// This returns true if Result contains a token, false if PP.Lex should be
1806/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001807bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001808 // Check if we are performing code completion.
1809 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1810 // We're at the end of the file, but we've been asked to consider the
1811 // end of the file to be a code-completion token. Return the
1812 // code-completion token.
1813 Result.startToken();
1814 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1815
1816 // Only do the eof -> code_completion translation once.
1817 PP->SetCodeCompletionPoint(0, 0, 0);
1818
1819 // Silence any diagnostics that occur once we hit the code-completion point.
1820 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1821 return true;
1822 }
1823
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 // If we hit the end of the file while parsing a preprocessor directive,
1825 // end the preprocessor directive first. The next token returned will
1826 // then be the end of file.
1827 if (ParsingPreprocessorDirective) {
1828 // Done parsing the "line".
1829 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00001831 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001834 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001836 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001837
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 // If we are in raw mode, return this event as an EOF token. Let the caller
1839 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001840 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 Result.startToken();
1842 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001843 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 return true;
1845 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001846
Douglas Gregorf44e8542010-08-24 19:08:16 +00001847 // Issue diagnostics for unterminated #if and missing newline.
1848
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // If we are in a #if directive, emit an error.
1850 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001851 if (!PP->isCodeCompletionFile(FileLoc))
1852 PP->Diag(ConditionalStack.back().IfLoc,
1853 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 ConditionalStack.pop_back();
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001857 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1858 // a pedwarn.
1859 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001860 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001861 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 BufferPtr = CurPtr;
1864
1865 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001866 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001867}
1868
1869/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1870/// the specified lexer will return a tok::l_paren token, 0 if it is something
1871/// else and 2 if there are no more tokens in the buffer controlled by the
1872/// lexer.
1873unsigned Lexer::isNextPPTokenLParen() {
1874 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 // Switch to 'skipping' mode. This will ensure that we can lex a token
1877 // without emitting diagnostics, disables macro expansion, and will cause EOF
1878 // to return an EOF token instead of popping the include stack.
1879 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 // Save state that can be changed while lexing so that we can restore it.
1882 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001883 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Chris Lattnerd2177732007-07-20 16:59:19 +00001885 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 Tok.startToken();
1887 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 // Restore state that may have changed.
1890 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001891 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 // Restore the lexer back to non-skipping mode.
1894 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001896 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001898 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001899}
1900
Chris Lattner34f349d2009-12-14 06:16:57 +00001901/// FindConflictEnd - Find the end of a version control conflict marker.
1902static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1903 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1904 size_t Pos = RestOfBuffer.find(">>>>>>>");
1905 while (Pos != llvm::StringRef::npos) {
1906 // Must occur at start of line.
1907 if (RestOfBuffer[Pos-1] != '\r' &&
1908 RestOfBuffer[Pos-1] != '\n') {
1909 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001910 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001911 continue;
1912 }
1913 return RestOfBuffer.data()+Pos;
1914 }
1915 return 0;
1916}
1917
1918/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1919/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1920/// and recover nicely. This returns true if it is a conflict marker and false
1921/// if not.
1922bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1923 // Only a conflict marker if it starts at the beginning of a line.
1924 if (CurPtr != BufferStart &&
1925 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1926 return false;
1927
1928 // Check to see if we have <<<<<<<.
1929 if (BufferEnd-CurPtr < 8 ||
1930 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1931 return false;
1932
1933 // If we have a situation where we don't care about conflict markers, ignore
1934 // it.
1935 if (IsInConflictMarker || isLexingRawMode())
1936 return false;
1937
1938 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1939 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001940 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001941 // We found a match. We are really in a conflict marker.
1942 // Diagnose this, and ignore to the end of line.
1943 Diag(CurPtr, diag::err_conflict_marker);
1944 IsInConflictMarker = true;
1945
1946 // Skip ahead to the end of line. We know this exists because the
1947 // end-of-conflict marker starts with \r or \n.
1948 while (*CurPtr != '\r' && *CurPtr != '\n') {
1949 assert(CurPtr != BufferEnd && "Didn't find end of line");
1950 ++CurPtr;
1951 }
1952 BufferPtr = CurPtr;
1953 return true;
1954 }
1955
1956 // No end of conflict marker found.
1957 return false;
1958}
1959
1960
1961/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1962/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1963/// until the end of the line. This returns true if it is a conflict marker and
1964/// false if not.
1965bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1966 // Only a conflict marker if it starts at the beginning of a line.
1967 if (CurPtr != BufferStart &&
1968 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1969 return false;
1970
1971 // If we have a situation where we don't care about conflict markers, ignore
1972 // it.
1973 if (!IsInConflictMarker || isLexingRawMode())
1974 return false;
1975
1976 // Check to see if we have the marker (7 characters in a row).
1977 for (unsigned i = 1; i != 7; ++i)
1978 if (CurPtr[i] != CurPtr[0])
1979 return false;
1980
1981 // If we do have it, search for the end of the conflict marker. This could
1982 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1983 // be the end of conflict marker.
1984 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1985 CurPtr = End;
1986
1987 // Skip ahead to the end of line.
1988 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1989 ++CurPtr;
1990
1991 BufferPtr = CurPtr;
1992
1993 // No longer in the conflict marker.
1994 IsInConflictMarker = false;
1995 return true;
1996 }
1997
1998 return false;
1999}
2000
Reid Spencer5f016e22007-07-11 17:01:13 +00002001
2002/// LexTokenInternal - This implements a simple C family lexer. It is an
2003/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002004/// has a null character at the end of the file. This returns a preprocessing
2005/// token, not a normal token, as such, it is an internal interface. It assumes
2006/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002007void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002008LexNextToken:
2009 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002010 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 // CurPtr - Cache BufferPtr in an automatic variable.
2014 const char *CurPtr = BufferPtr;
2015
2016 // Small amounts of horizontal whitespace is very common between tokens.
2017 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2018 ++CurPtr;
2019 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2020 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Chris Lattnerd88dc482008-10-12 04:05:48 +00002022 // If we are keeping whitespace and other tokens, just return what we just
2023 // skipped. The next lexer invocation will return the token after the
2024 // whitespace.
2025 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002026 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002027 return;
2028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002031 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 // Read a character, advancing over it.
2037 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002038 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 switch (Char) {
2041 case 0: // Null.
2042 // Found end of file?
2043 if (CurPtr-1 == BufferEnd) {
2044 // Read the PP instance variable into an automatic variable, because
2045 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002046 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2048 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002049 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2050 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Chris Lattner74d15df2008-11-22 02:02:22 +00002053 if (!isLexingRawMode())
2054 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002055 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002056 if (SkipWhitespace(Result, CurPtr))
2057 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002060
2061 case 26: // DOS & CP/M EOF: "^Z".
2062 // If we're in Microsoft extensions mode, treat this as end of file.
2063 if (Features.Microsoft) {
2064 // Read the PP instance variable into an automatic variable, because
2065 // LexEndOfFile will often delete 'this'.
2066 Preprocessor *PPCache = PP;
2067 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2068 return; // Got a token to return.
2069 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2070 return PPCache->Lex(Result);
2071 }
2072 // If Microsoft extensions are disabled, this is just random garbage.
2073 Kind = tok::unknown;
2074 break;
2075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 case '\n':
2077 case '\r':
2078 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002079 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 if (ParsingPreprocessorDirective) {
2081 // Done parsing the "line".
2082 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002085 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Since we consumed a newline, we are back at the start of a line.
2088 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Peter Collingbourne84021552011-02-28 02:37:51 +00002090 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 break;
2092 }
2093 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002094 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002096 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Chris Lattnerd88dc482008-10-12 04:05:48 +00002098 if (SkipWhitespace(Result, CurPtr))
2099 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 goto LexNextToken; // GCC isn't tail call eliminating.
2101 case ' ':
2102 case '\t':
2103 case '\f':
2104 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002105 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002106 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002107 if (SkipWhitespace(Result, CurPtr))
2108 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002109
2110 SkipIgnoredUnits:
2111 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Chris Lattner8133cfc2007-07-22 06:29:05 +00002113 // If the next token is obviously a // or /* */ comment, skip it efficiently
2114 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002115 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002116 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002117 if (SkipBCPLComment(Result, CurPtr+2))
2118 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002119 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002120 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002121 if (SkipBlockComment(Result, CurPtr+2))
2122 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002123 goto SkipIgnoredUnits;
2124 } else if (isHorizontalWhitespace(*CurPtr)) {
2125 goto SkipHorizontalWhitespace;
2126 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002128
Chris Lattner3a570772008-01-03 17:58:54 +00002129 // C99 6.4.4.1: Integer Constants.
2130 // C99 6.4.4.2: Floating Constants.
2131 case '0': case '1': case '2': case '3': case '4':
2132 case '5': case '6': case '7': case '8': case '9':
2133 // Notify MIOpt that we read a non-whitespace/non-comment token.
2134 MIOpt.ReadToken();
2135 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Chris Lattner3a570772008-01-03 17:58:54 +00002137 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 // Notify MIOpt that we read a non-whitespace/non-comment token.
2139 MIOpt.ReadToken();
2140 Char = getCharAndSize(CurPtr, SizeTmp);
2141
2142 // Wide string literal.
2143 if (Char == '"')
2144 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2145 true);
2146
2147 // Wide character constant.
2148 if (Char == '\'')
2149 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2150 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 // C99 6.4.2: Identifiers.
2153 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2154 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2155 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
2156 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2157 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2158 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2159 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
2160 case 'v': case 'w': case 'x': case 'y': case 'z':
2161 case '_':
2162 // Notify MIOpt that we read a non-whitespace/non-comment token.
2163 MIOpt.ReadToken();
2164 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002165
2166 case '$': // $ in identifiers.
2167 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002168 if (!isLexingRawMode())
2169 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002170 // Notify MIOpt that we read a non-whitespace/non-comment token.
2171 MIOpt.ReadToken();
2172 return LexIdentifier(Result, CurPtr);
2173 }
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Chris Lattner9e6293d2008-10-12 04:51:35 +00002175 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002176 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 // C99 6.4.4: Character Constants.
2179 case '\'':
2180 // Notify MIOpt that we read a non-whitespace/non-comment token.
2181 MIOpt.ReadToken();
2182 return LexCharConstant(Result, CurPtr);
2183
2184 // C99 6.4.5: String Literals.
2185 case '"':
2186 // Notify MIOpt that we read a non-whitespace/non-comment token.
2187 MIOpt.ReadToken();
2188 return LexStringLiteral(Result, CurPtr, false);
2189
2190 // C99 6.4.6: Punctuators.
2191 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002192 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 break;
2194 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002195 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 break;
2197 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002198 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 break;
2200 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002201 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 break;
2203 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002204 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 break;
2206 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002207 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 break;
2209 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002210 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 break;
2212 case '.':
2213 Char = getCharAndSize(CurPtr, SizeTmp);
2214 if (Char >= '0' && Char <= '9') {
2215 // Notify MIOpt that we read a non-whitespace/non-comment token.
2216 MIOpt.ReadToken();
2217
2218 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2219 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002220 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 CurPtr += SizeTmp;
2222 } else if (Char == '.' &&
2223 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002224 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2226 SizeTmp2, Result);
2227 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002228 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 }
2230 break;
2231 case '&':
2232 Char = getCharAndSize(CurPtr, SizeTmp);
2233 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002234 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2236 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002237 Kind = tok::ampequal;
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::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 }
2242 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002243 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002245 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2247 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002248 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 }
2250 break;
2251 case '+':
2252 Char = getCharAndSize(CurPtr, SizeTmp);
2253 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002255 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002258 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002260 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 }
2262 break;
2263 case '-':
2264 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002265 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::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002268 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002269 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2271 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002272 Kind = tok::arrowstar;
2273 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002275 Kind = tok::arrow;
2276 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002278 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002280 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 }
2282 break;
2283 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002284 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 break;
2286 case '!':
2287 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002288 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002289 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2290 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002291 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 }
2293 break;
2294 case '/':
2295 // 6.4.9: Comments
2296 Char = getCharAndSize(CurPtr, SizeTmp);
2297 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002298 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2299 // want to lex this as a comment. There is one problem with this though,
2300 // that in one particular corner case, this can change the behavior of the
2301 // resultant program. For example, In "foo //**/ bar", C89 would lex
2302 // this as "foo / bar" and langauges with BCPL comments would lex it as
2303 // "foo". Check to see if the character after the second slash is a '*'.
2304 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002305 // However, we never do this in -traditional-cpp mode.
2306 if ((Features.BCPLComment ||
2307 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2308 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002309 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002310 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Chris Lattner8402c732009-01-16 22:39:25 +00002312 // It is common for the tokens immediately after a // comment to be
2313 // whitespace (indentation for the next line). Instead of going through
2314 // the big switch, handle it efficiently now.
2315 goto SkipIgnoredUnits;
2316 }
2317 }
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Chris Lattner8402c732009-01-16 22:39:25 +00002319 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002321 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002322 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002323 }
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Chris Lattner8402c732009-01-16 22:39:25 +00002325 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002327 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002329 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002330 }
2331 break;
2332 case '%':
2333 Char = getCharAndSize(CurPtr, SizeTmp);
2334 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002335 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2337 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002338 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2340 } else if (Features.Digraphs && Char == ':') {
2341 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2342 Char = getCharAndSize(CurPtr, SizeTmp);
2343 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002344 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2346 SizeTmp2, Result);
2347 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002349 if (!isLexingRawMode())
2350 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002351 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002352 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 // We parsed a # character. If this occurs at the start of the line,
2354 // it's actually the start of a preprocessing directive. Callback to
2355 // the preprocessor to handle it.
2356 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002357 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002358 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002359 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 // As an optimization, if the preprocessor didn't switch lexers, tail
2362 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002363 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 // Start a new token. If this is a #include or something, the PP may
2365 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002366 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002368 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002369 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 IsAtStartOfLine = false;
2371 }
2372 goto LexNextToken; // GCC isn't tail call eliminating.
2373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Chris Lattner168ae2d2007-10-17 20:41:00 +00002375 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Chris Lattnere91e9322009-03-18 20:58:27 +00002378 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 }
2380 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002381 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 }
2383 break;
2384 case '<':
2385 Char = getCharAndSize(CurPtr, SizeTmp);
2386 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002387 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002389 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2390 if (After == '=') {
2391 Kind = tok::lesslessequal;
2392 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2393 SizeTmp2, Result);
2394 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2395 // If this is actually a '<<<<<<<' version control conflict marker,
2396 // recognize it as such and recover nicely.
2397 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002398 } else if (Features.CUDA && After == '<') {
2399 Kind = tok::lesslessless;
2400 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2401 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002402 } else {
2403 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2404 Kind = tok::lessless;
2405 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002408 Kind = tok::lessequal;
2409 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002410 if (Features.CPlusPlus0x &&
2411 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2412 // C++0x [lex.pptoken]p3:
2413 // Otherwise, if the next three characters are <:: and the subsequent
2414 // character is neither : nor >, the < is treated as a preprocessor
2415 // token by itself and not as the first character of the alternative
2416 // token <:.
2417 unsigned SizeTmp3;
2418 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2419 if (After != ':' && After != '>') {
2420 Kind = tok::less;
2421 break;
2422 }
2423 }
2424
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002426 Kind = tok::l_square;
2427 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002429 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002431 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 }
2433 break;
2434 case '>':
2435 Char = getCharAndSize(CurPtr, SizeTmp);
2436 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002438 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002439 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002440 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2441 if (After == '=') {
2442 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2443 SizeTmp2, Result);
2444 Kind = tok::greatergreaterequal;
2445 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2446 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2447 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002448 } else if (Features.CUDA && After == '>') {
2449 Kind = tok::greatergreatergreater;
2450 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2451 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002452 } else {
2453 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2454 Kind = tok::greatergreater;
2455 }
2456
Reid Spencer5f016e22007-07-11 17:01:13 +00002457 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002458 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 }
2460 break;
2461 case '^':
2462 Char = getCharAndSize(CurPtr, SizeTmp);
2463 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002465 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002467 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 }
2469 break;
2470 case '|':
2471 Char = getCharAndSize(CurPtr, SizeTmp);
2472 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002473 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002474 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2475 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002476 // If this is '|||||||' and we're in a conflict marker, ignore it.
2477 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2478 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002479 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2481 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002482 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 }
2484 break;
2485 case ':':
2486 Char = getCharAndSize(CurPtr, SizeTmp);
2487 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002488 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2490 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002491 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002493 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002494 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 }
2496 break;
2497 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002498 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 break;
2500 case '=':
2501 Char = getCharAndSize(CurPtr, SizeTmp);
2502 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002503 // If this is '=======' and we're in a conflict marker, ignore it.
2504 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2505 goto LexNextToken;
2506
Chris Lattner9e6293d2008-10-12 04:51:35 +00002507 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002509 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002510 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 }
2512 break;
2513 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002514 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 break;
2516 case '#':
2517 Char = getCharAndSize(CurPtr, SizeTmp);
2518 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002519 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2521 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002522 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002523 if (!isLexingRawMode())
2524 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2526 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 // We parsed a # character. If this occurs at the start of the line,
2528 // it's actually the start of a preprocessing directive. Callback to
2529 // the preprocessor to handle it.
2530 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002531 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002532 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002533 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002534
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 // As an optimization, if the preprocessor didn't switch lexers, tail
2536 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002537 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 // Start a new token. If this is a #include or something, the PP may
2539 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002540 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002542 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002543 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 IsAtStartOfLine = false;
2545 }
2546 goto LexNextToken; // GCC isn't tail call eliminating.
2547 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002548 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002549 }
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Chris Lattnere91e9322009-03-18 20:58:27 +00002551 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 }
2553 break;
2554
Chris Lattner3a570772008-01-03 17:58:54 +00002555 case '@':
2556 // Objective C support.
2557 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002558 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002559 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002560 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002561 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 case '\\':
2564 // FIXME: UCN's.
2565 // FALL THROUGH.
2566 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002567 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 break;
2569 }
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Notify MIOpt that we read a non-whitespace/non-comment token.
2572 MIOpt.ReadToken();
2573
2574 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002575 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002576}