blob: ea2a2deb0f5a287f3053eb08cd2d393f5f125591 [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.
79 size_t BOMLength = llvm::StringSwitch<size_t>(BufferStart)
80 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
81 .Default(0);
82
83 // Skip the BOM.
84 BufferPtr += BOMLength;
85 }
86
Chris Lattner22d91ca2009-01-17 06:55:17 +000087 Is_PragmaLexer = false;
Chris Lattner34f349d2009-12-14 06:16:57 +000088 IsInConflictMarker = false;
Eric Christopher156119d2011-04-09 00:01:04 +000089
Chris Lattner22d91ca2009-01-17 06:55:17 +000090 // Start of the file is a start of line.
91 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattner22d91ca2009-01-17 06:55:17 +000093 // We are not after parsing a #.
94 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner22d91ca2009-01-17 06:55:17 +000096 // We are not after parsing #include.
97 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner22d91ca2009-01-17 06:55:17 +000099 // We are not in raw mode. Raw mode disables diagnostics and interpretation
100 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
101 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
102 // or otherwise skipping over tokens.
103 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Chris Lattner22d91ca2009-01-17 06:55:17 +0000105 // Default to not keeping comments.
106 ExtendedTokenMode = 0;
107}
108
Chris Lattner0770dab2009-01-17 07:56:59 +0000109/// Lexer constructor - Create a new lexer object for the specified buffer
110/// with the specified preprocessor managing the lexing process. This lexer
111/// assumes that the associated file buffer and Preprocessor objects will
112/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000113Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000114 : PreprocessorLexer(&PP, FID),
115 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
116 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Chris Lattner0770dab2009-01-17 07:56:59 +0000118 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
119 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner0770dab2009-01-17 07:56:59 +0000121 // Default to keeping comments if the preprocessor wants them.
122 SetCommentRetentionState(PP.getCommentRetentionState());
123}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000124
Chris Lattner168ae2d2007-10-17 20:41:00 +0000125/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000126/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
127/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000128Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000129 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000130 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000131
Chris Lattner22d91ca2009-01-17 06:55:17 +0000132 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattner168ae2d2007-10-17 20:41:00 +0000134 // We *are* in raw mode.
135 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000136}
137
Chris Lattner025c3a62009-01-17 07:35:14 +0000138/// Lexer constructor - Create a new raw lexer object. This object is only
139/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
140/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000141Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
142 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000143 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000144
Mike Stump1eb44332009-09-09 15:08:12 +0000145 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000146 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattner025c3a62009-01-17 07:35:14 +0000148 // We *are* in raw mode.
149 LexingRawMode = true;
150}
151
Chris Lattner42e00d12009-01-17 08:27:52 +0000152/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
153/// _Pragma expansion. This has a variety of magic semantics that this method
154/// sets up. It returns a new'd Lexer that must be delete'd when done.
155///
156/// On entrance to this routine, TokStartLoc is a macro location which has a
157/// spelling loc that indicates the bytes to be lexed for the token and an
158/// instantiation location that indicates where all lexed tokens should be
159/// "expanded from".
160///
161/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
162/// normal lexer that remaps tokens as they fly by. This would require making
163/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
164/// interface that could handle this stuff. This would pull GetMappedTokenLoc
165/// out of the critical path of the lexer!
166///
Mike Stump1eb44332009-09-09 15:08:12 +0000167Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000168 SourceLocation InstantiationLocStart,
169 SourceLocation InstantiationLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000170 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000171 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000172
173 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000174 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000175 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
176 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Chris Lattner42e00d12009-01-17 08:27:52 +0000178 // Now that the lexer is created, change the start/end locations so that we
179 // just lex the subsection of the file that we want. This is lexing from a
180 // scratch buffer.
181 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattner42e00d12009-01-17 08:27:52 +0000183 L->BufferPtr = StrData;
184 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000185 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000186
187 // Set the SourceLocation with the remapping information. This ensures that
188 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000189 L->FileLoc = SM.createInstantiationLoc(SM.getLocForStartOfFile(SpellingFID),
Chris Lattnere7fb4842009-02-15 20:52:18 +0000190 InstantiationLocStart,
191 InstantiationLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner42e00d12009-01-17 08:27:52 +0000193 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000194 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000195 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 // This lexer really is for _Pragma.
198 L->Is_PragmaLexer = true;
199 return L;
200}
201
Chris Lattner168ae2d2007-10-17 20:41:00 +0000202
Reid Spencer5f016e22007-07-11 17:01:13 +0000203/// Stringify - Convert the specified string into a C string, with surrounding
204/// ""'s, and with escaped \ and " characters.
205std::string Lexer::Stringify(const std::string &Str, bool Charify) {
206 std::string Result = Str;
207 char Quote = Charify ? '\'' : '"';
208 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
209 if (Result[i] == '\\' || Result[i] == Quote) {
210 Result.insert(Result.begin()+i, '\\');
211 ++i; ++e;
212 }
213 }
214 return Result;
215}
216
Chris Lattnerd8e30832007-07-24 06:57:14 +0000217/// Stringify - Convert the specified string into a C string by escaping '\'
218/// and " characters. This does not add surrounding ""'s to the string.
219void Lexer::Stringify(llvm::SmallVectorImpl<char> &Str) {
220 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
221 if (Str[i] == '\\' || Str[i] == '"') {
222 Str.insert(Str.begin()+i, '\\');
223 ++i; ++e;
224 }
225 }
226}
227
Chris Lattnerb0607272010-11-17 07:26:20 +0000228//===----------------------------------------------------------------------===//
229// Token Spelling
230//===----------------------------------------------------------------------===//
231
232/// getSpelling() - Return the 'spelling' of this token. The spelling of a
233/// token are the characters used to represent the token in the source file
234/// after trigraph expansion and escaped-newline folding. In particular, this
235/// wants to get the true, uncanonicalized, spelling of things like digraphs
236/// UCNs, etc.
John McCall834e3f62011-03-08 07:59:04 +0000237llvm::StringRef Lexer::getSpelling(SourceLocation loc,
238 llvm::SmallVectorImpl<char> &buffer,
239 const SourceManager &SM,
240 const LangOptions &options,
241 bool *invalid) {
242 // Break down the source location.
243 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
244
245 // Try to the load the file buffer.
246 bool invalidTemp = false;
247 llvm::StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
248 if (invalidTemp) {
249 if (invalid) *invalid = true;
250 return llvm::StringRef();
251 }
252
253 const char *tokenBegin = file.data() + locInfo.second;
254
255 // Lex from the start of the given location.
256 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
257 file.begin(), tokenBegin, file.end());
258 Token token;
259 lexer.LexFromRawLexer(token);
260
261 unsigned length = token.getLength();
262
263 // Common case: no need for cleaning.
264 if (!token.needsCleaning())
265 return llvm::StringRef(tokenBegin, length);
266
267 // Hard case, we need to relex the characters into the string.
268 buffer.clear();
269 buffer.reserve(length);
270
271 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
272 unsigned charSize;
273 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
274 ti += charSize;
275 }
276
277 return llvm::StringRef(buffer.data(), buffer.size());
278}
279
280/// getSpelling() - Return the 'spelling' of this token. The spelling of a
281/// token are the characters used to represent the token in the source file
282/// after trigraph expansion and escaped-newline folding. In particular, this
283/// wants to get the true, uncanonicalized, spelling of things like digraphs
284/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000285std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
286 const LangOptions &Features, bool *Invalid) {
287 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
288
289 // If this token contains nothing interesting, return it directly.
290 bool CharDataInvalid = false;
291 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
292 &CharDataInvalid);
293 if (Invalid)
294 *Invalid = CharDataInvalid;
295 if (CharDataInvalid)
296 return std::string();
297
298 if (!Tok.needsCleaning())
299 return std::string(TokStart, TokStart+Tok.getLength());
300
301 std::string Result;
302 Result.reserve(Tok.getLength());
303
304 // Otherwise, hard case, relex the characters into the string.
305 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
306 Ptr != End; ) {
307 unsigned CharSize;
308 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
309 Ptr += CharSize;
310 }
311 assert(Result.size() != unsigned(Tok.getLength()) &&
312 "NeedsCleaning flag set on something that didn't need cleaning!");
313 return Result;
314}
315
316/// getSpelling - This method is used to get the spelling of a token into a
317/// preallocated buffer, instead of as an std::string. The caller is required
318/// to allocate enough space for the token, which is guaranteed to be at least
319/// Tok.getLength() bytes long. The actual length of the token is returned.
320///
321/// Note that this method may do two possible things: it may either fill in
322/// the buffer specified with characters, or it may *change the input pointer*
323/// to point to a constant buffer with the data already in it (avoiding a
324/// copy). The caller is not allowed to modify the returned buffer pointer
325/// if an internal buffer is returned.
326unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
327 const SourceManager &SourceMgr,
328 const LangOptions &Features, bool *Invalid) {
329 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000330
331 const char *TokStart = 0;
332 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
333 if (Tok.is(tok::raw_identifier))
334 TokStart = Tok.getRawIdentifierData();
335 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
336 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000337 Buffer = II->getNameStart();
338 return II->getLength();
339 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000340
341 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000342 if (Tok.isLiteral())
343 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000344
Chris Lattnerb0607272010-11-17 07:26:20 +0000345 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000346 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000347 bool CharDataInvalid = false;
348 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
349 if (Invalid)
350 *Invalid = CharDataInvalid;
351 if (CharDataInvalid) {
352 Buffer = "";
353 return 0;
354 }
355 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000356
Chris Lattnerb0607272010-11-17 07:26:20 +0000357 // If this token contains nothing interesting, return it directly.
358 if (!Tok.needsCleaning()) {
359 Buffer = TokStart;
360 return Tok.getLength();
361 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000362
Chris Lattnerb0607272010-11-17 07:26:20 +0000363 // Otherwise, hard case, relex the characters into the string.
364 char *OutBuf = const_cast<char*>(Buffer);
365 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
366 Ptr != End; ) {
367 unsigned CharSize;
368 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
369 Ptr += CharSize;
370 }
371 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
372 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000373
Chris Lattnerb0607272010-11-17 07:26:20 +0000374 return OutBuf-Buffer;
375}
376
377
378
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000379static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
Chris Lattner9a611942007-10-17 21:18:47 +0000381/// MeasureTokenLength - Relex the token at the specified location and return
382/// its length in bytes in the input file. If the token needs cleaning (e.g.
383/// includes a trigraph or an escaped newline) then this count includes bytes
384/// that are part of that.
385unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000386 const SourceManager &SM,
387 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000388 // TODO: this could be special cased for common tokens like identifiers, ')',
389 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000390 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000391 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
392 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000393
394 // If this comes from a macro expansion, we really do want the macro name, not
395 // the token this macro expanded to.
Chris Lattner363fdc22009-01-26 22:24:27 +0000396 Loc = SM.getInstantiationLoc(Loc);
397 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000398 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000399 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000400 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000401 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000402
403 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000404
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 if (isWhitespace(StrData[0]))
406 return 0;
407
Chris Lattner9a611942007-10-17 21:18:47 +0000408 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000409 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
410 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000411 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000412 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000413 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000414 return TheTok.getLength();
415}
416
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000417SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
418 const SourceManager &SM,
419 const LangOptions &LangOpts) {
420 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000421 if (LocInfo.first.isInvalid())
422 return Loc;
423
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000424 bool Invalid = false;
425 llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
426 if (Invalid)
427 return Loc;
428
429 // Back up from the current location until we hit the beginning of a line
430 // (or the buffer). We'll relex from that point.
431 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000432 if (LocInfo.second >= Buffer.size())
433 return Loc;
434
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000435 const char *StrData = BufStart+LocInfo.second;
436 if (StrData[0] == '\n' || StrData[0] == '\r')
437 return Loc;
438
439 const char *LexStart = StrData;
440 while (LexStart != BufStart) {
441 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
442 ++LexStart;
443 break;
444 }
445
446 --LexStart;
447 }
448
449 // Create a lexer starting at the beginning of this token.
450 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
451 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
452 TheLexer.SetCommentRetentionState(true);
453
454 // Lex tokens until we find the token that contains the source location.
455 Token TheTok;
456 do {
457 TheLexer.LexFromRawLexer(TheTok);
458
459 if (TheLexer.getBufferLocation() > StrData) {
460 // Lexing this token has taken the lexer past the source location we're
461 // looking for. If the current token encompasses our source location,
462 // return the beginning of that token.
463 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
464 return TheTok.getLocation();
465
466 // We ended up skipping over the source location entirely, which means
467 // that it points into whitespace. We're done here.
468 break;
469 }
470 } while (TheTok.getKind() != tok::eof);
471
472 // We've passed our source location; just return the original source location.
473 return Loc;
474}
475
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000476namespace {
477 enum PreambleDirectiveKind {
478 PDK_Skipped,
479 PDK_StartIf,
480 PDK_EndIf,
481 PDK_Unknown
482 };
483}
484
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000485std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000486Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000487 // Create a lexer starting at the beginning of the file. Note that we use a
488 // "fake" file source location at offset 1 so that the lexer will track our
489 // position within the file.
490 const unsigned StartOffset = 1;
491 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
492 LangOptions LangOpts;
493 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
494 Buffer->getBufferStart(), Buffer->getBufferEnd());
495
496 bool InPreprocessorDirective = false;
497 Token TheTok;
498 Token IfStartTok;
499 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000500 unsigned Line = 0;
501
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000502 do {
503 TheLexer.LexFromRawLexer(TheTok);
504
505 if (InPreprocessorDirective) {
506 // If we've hit the end of the file, we're done.
507 if (TheTok.getKind() == tok::eof) {
508 InPreprocessorDirective = false;
509 break;
510 }
511
512 // If we haven't hit the end of the preprocessor directive, skip this
513 // token.
514 if (!TheTok.isAtStartOfLine())
515 continue;
516
517 // We've passed the end of the preprocessor directive, and will look
518 // at this token again below.
519 InPreprocessorDirective = false;
520 }
521
Douglas Gregordf95a132010-08-09 20:45:32 +0000522 // Keep track of the # of lines in the preamble.
523 if (TheTok.isAtStartOfLine()) {
524 ++Line;
525
526 // If we were asked to limit the number of lines in the preamble,
527 // and we're about to exceed that limit, we're done.
528 if (MaxLines && Line >= MaxLines)
529 break;
530 }
531
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000532 // Comments are okay; skip over them.
533 if (TheTok.getKind() == tok::comment)
534 continue;
535
536 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
537 // This is the start of a preprocessor directive.
538 Token HashTok = TheTok;
539 InPreprocessorDirective = true;
540
541 // Figure out which direective this is. Since we're lexing raw tokens,
542 // we don't have an identifier table available. Instead, just look at
543 // the raw identifier to recognize and categorize preprocessor directives.
544 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000545 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
546 llvm::StringRef Keyword(TheTok.getRawIdentifierData(),
547 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000548 PreambleDirectiveKind PDK
549 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
550 .Case("include", PDK_Skipped)
551 .Case("__include_macros", PDK_Skipped)
552 .Case("define", PDK_Skipped)
553 .Case("undef", PDK_Skipped)
554 .Case("line", PDK_Skipped)
555 .Case("error", PDK_Skipped)
556 .Case("pragma", PDK_Skipped)
557 .Case("import", PDK_Skipped)
558 .Case("include_next", PDK_Skipped)
559 .Case("warning", PDK_Skipped)
560 .Case("ident", PDK_Skipped)
561 .Case("sccs", PDK_Skipped)
562 .Case("assert", PDK_Skipped)
563 .Case("unassert", PDK_Skipped)
564 .Case("if", PDK_StartIf)
565 .Case("ifdef", PDK_StartIf)
566 .Case("ifndef", PDK_StartIf)
567 .Case("elif", PDK_Skipped)
568 .Case("else", PDK_Skipped)
569 .Case("endif", PDK_EndIf)
570 .Default(PDK_Unknown);
571
572 switch (PDK) {
573 case PDK_Skipped:
574 continue;
575
576 case PDK_StartIf:
577 if (IfCount == 0)
578 IfStartTok = HashTok;
579
580 ++IfCount;
581 continue;
582
583 case PDK_EndIf:
584 // Mismatched #endif. The preamble ends here.
585 if (IfCount == 0)
586 break;
587
588 --IfCount;
589 continue;
590
591 case PDK_Unknown:
592 // We don't know what this directive is; stop at the '#'.
593 break;
594 }
595 }
596
597 // We only end up here if we didn't recognize the preprocessor
598 // directive or it was one that can't occur in the preamble at this
599 // point. Roll back the current token to the location of the '#'.
600 InPreprocessorDirective = false;
601 TheTok = HashTok;
602 }
603
Douglas Gregordf95a132010-08-09 20:45:32 +0000604 // We hit a token that we don't recognize as being in the
605 // "preprocessing only" part of the file, so we're no longer in
606 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000607 break;
608 } while (true);
609
610 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000611 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
612 IfCount? IfStartTok.isAtStartOfLine()
613 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000614}
615
Chris Lattner7ef5c272010-11-17 07:05:50 +0000616
617/// AdvanceToTokenCharacter - Given a location that specifies the start of a
618/// token, return a new location that specifies a character within the token.
619SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
620 unsigned CharNo,
621 const SourceManager &SM,
622 const LangOptions &Features) {
623 // Figure out how many physical characters away the specified instantiation
624 // character is. This needs to take into consideration newlines and
625 // trigraphs.
626 bool Invalid = false;
627 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
628
629 // If they request the first char of the token, we're trivially done.
630 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
631 return TokStart;
632
633 unsigned PhysOffset = 0;
634
635 // The usual case is that tokens don't contain anything interesting. Skip
636 // over the uninteresting characters. If a token only consists of simple
637 // chars, this method is extremely fast.
638 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
639 if (CharNo == 0)
640 return TokStart.getFileLocWithOffset(PhysOffset);
641 ++TokPtr, --CharNo, ++PhysOffset;
642 }
643
644 // If we have a character that may be a trigraph or escaped newline, use a
645 // lexer to parse it correctly.
646 for (; CharNo; --CharNo) {
647 unsigned Size;
648 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
649 TokPtr += Size;
650 PhysOffset += Size;
651 }
652
653 // Final detail: if we end up on an escaped newline, we want to return the
654 // location of the actual byte of the token. For example foo\<newline>bar
655 // advanced by 3 should return the location of b, not of \\. One compounding
656 // detail of this is that the escape may be made by a trigraph.
657 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
658 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
659
660 return TokStart.getFileLocWithOffset(PhysOffset);
661}
662
663/// \brief Computes the source location just past the end of the
664/// token at this source location.
665///
666/// This routine can be used to produce a source location that
667/// points just past the end of the token referenced by \p Loc, and
668/// is generally used when a diagnostic needs to point just after a
669/// token where it expected something different that it received. If
670/// the returned source location would not be meaningful (e.g., if
671/// it points into a macro), this routine returns an invalid
672/// source location.
673///
674/// \param Offset an offset from the end of the token, where the source
675/// location should refer to. The default offset (0) produces a source
676/// location pointing just past the end of the token; an offset of 1 produces
677/// a source location pointing to the last character in the token, etc.
678SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
679 const SourceManager &SM,
680 const LangOptions &Features) {
681 if (Loc.isInvalid() || !Loc.isFileID())
682 return SourceLocation();
683
684 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
685 if (Len > Offset)
686 Len = Len - Offset;
687 else
688 return Loc;
689
John McCall77ebb382011-04-06 01:50:22 +0000690 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000691}
692
Reid Spencer5f016e22007-07-11 17:01:13 +0000693//===----------------------------------------------------------------------===//
694// Character information.
695//===----------------------------------------------------------------------===//
696
Reid Spencer5f016e22007-07-11 17:01:13 +0000697enum {
698 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
699 CHAR_VERT_WS = 0x02, // '\r', '\n'
700 CHAR_LETTER = 0x04, // a-z,A-Z
701 CHAR_NUMBER = 0x08, // 0-9
702 CHAR_UNDER = 0x10, // _
703 CHAR_PERIOD = 0x20 // .
704};
705
Chris Lattner03b98662009-07-07 17:09:54 +0000706// Statically initialize CharInfo table based on ASCII character set
707// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000708static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000709{
710// 0 NUL 1 SOH 2 STX 3 ETX
711// 4 EOT 5 ENQ 6 ACK 7 BEL
712 0 , 0 , 0 , 0 ,
713 0 , 0 , 0 , 0 ,
714// 8 BS 9 HT 10 NL 11 VT
715//12 NP 13 CR 14 SO 15 SI
716 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
717 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
718//16 DLE 17 DC1 18 DC2 19 DC3
719//20 DC4 21 NAK 22 SYN 23 ETB
720 0 , 0 , 0 , 0 ,
721 0 , 0 , 0 , 0 ,
722//24 CAN 25 EM 26 SUB 27 ESC
723//28 FS 29 GS 30 RS 31 US
724 0 , 0 , 0 , 0 ,
725 0 , 0 , 0 , 0 ,
726//32 SP 33 ! 34 " 35 #
727//36 $ 37 % 38 & 39 '
728 CHAR_HORZ_WS, 0 , 0 , 0 ,
729 0 , 0 , 0 , 0 ,
730//40 ( 41 ) 42 * 43 +
731//44 , 45 - 46 . 47 /
732 0 , 0 , 0 , 0 ,
733 0 , 0 , CHAR_PERIOD , 0 ,
734//48 0 49 1 50 2 51 3
735//52 4 53 5 54 6 55 7
736 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
737 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
738//56 8 57 9 58 : 59 ;
739//60 < 61 = 62 > 63 ?
740 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
741 0 , 0 , 0 , 0 ,
742//64 @ 65 A 66 B 67 C
743//68 D 69 E 70 F 71 G
744 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
745 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
746//72 H 73 I 74 J 75 K
747//76 L 77 M 78 N 79 O
748 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
749 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
750//80 P 81 Q 82 R 83 S
751//84 T 85 U 86 V 87 W
752 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
753 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
754//88 X 89 Y 90 Z 91 [
755//92 \ 93 ] 94 ^ 95 _
756 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
757 0 , 0 , 0 , CHAR_UNDER ,
758//96 ` 97 a 98 b 99 c
759//100 d 101 e 102 f 103 g
760 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
761 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
762//104 h 105 i 106 j 107 k
763//108 l 109 m 110 n 111 o
764 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
765 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
766//112 p 113 q 114 r 115 s
767//116 t 117 u 118 v 119 w
768 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
769 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
770//120 x 121 y 122 z 123 {
771//124 | 125 } 126 ~ 127 DEL
772 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
773 0 , 0 , 0 , 0
774};
775
Chris Lattnera2bf1052009-12-17 05:29:40 +0000776static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 static bool isInited = false;
778 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000779 // check the statically-initialized CharInfo table
780 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
781 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
782 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
783 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
784 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
785 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
786 assert(CHAR_UNDER == CharInfo[(int)'_']);
787 assert(CHAR_PERIOD == CharInfo[(int)'.']);
788 for (unsigned i = 'a'; i <= 'z'; ++i) {
789 assert(CHAR_LETTER == CharInfo[i]);
790 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
791 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000793 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000794
Chris Lattner03b98662009-07-07 17:09:54 +0000795 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796}
797
Chris Lattner03b98662009-07-07 17:09:54 +0000798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799/// isIdentifierBody - Return true if this is the body character of an
800/// identifier, which is [a-zA-Z0-9_].
801static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000802 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000803}
804
805/// isHorizontalWhitespace - Return true if this character is horizontal
806/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
807static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000808 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000809}
810
811/// isWhitespace - Return true if this character is horizontal or vertical
812/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
813/// for '\0'.
814static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000815 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000816}
817
818/// isNumberBody - Return true if this is the body character of an
819/// preprocessing number, which is [a-zA-Z0-9_.].
820static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000821 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000822 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000823}
824
825
826//===----------------------------------------------------------------------===//
827// Diagnostics forwarding code.
828//===----------------------------------------------------------------------===//
829
Chris Lattner409a0362007-07-22 18:38:25 +0000830/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
831/// lexer buffer was all instantiated at a single point, perform the mapping.
832/// This is currently only used for _Pragma implementation, so it is the slow
833/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000834static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
835 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000836static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
837 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000838 unsigned CharNo, unsigned TokLen) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000839 assert(FileLoc.isMacroID() && "Must be an instantiation");
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Chris Lattner409a0362007-07-22 18:38:25 +0000841 // Otherwise, we're lexing "mapped tokens". This is used for things like
842 // _Pragma handling. Combine the instantiation location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000843 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000844 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000846 // Create a new SLoc which is expanded from Instantiation(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000847 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000848 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000849 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattnere7fb4842009-02-15 20:52:18 +0000851 // Figure out the expansion loc range, which is the range covered by the
852 // original _Pragma(...) sequence.
853 std::pair<SourceLocation,SourceLocation> II =
854 SM.getImmediateInstantiationRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattnere7fb4842009-02-15 20:52:18 +0000856 return SM.createInstantiationLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000857}
858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859/// getSourceLocation - Return a source location identifier for the specified
860/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000861SourceLocation Lexer::getSourceLocation(const char *Loc,
862 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000863 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000865
866 // In the normal case, we're just lexing from a simple file buffer, return
867 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000868 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000869 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000870 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner2b2453a2009-01-17 06:22:33 +0000872 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
873 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000874 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000875 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}
877
Reid Spencer5f016e22007-07-11 17:01:13 +0000878/// Diag - Forwarding function for diagnostics. This translate a source
879/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000880DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000881 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000882}
Reid Spencer5f016e22007-07-11 17:01:13 +0000883
884//===----------------------------------------------------------------------===//
885// Trigraph and Escaped Newline Handling Code.
886//===----------------------------------------------------------------------===//
887
888/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
889/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
890static char GetTrigraphCharForLetter(char Letter) {
891 switch (Letter) {
892 default: return 0;
893 case '=': return '#';
894 case ')': return ']';
895 case '(': return '[';
896 case '!': return '|';
897 case '\'': return '^';
898 case '>': return '}';
899 case '/': return '\\';
900 case '<': return '{';
901 case '-': return '~';
902 }
903}
904
905/// DecodeTrigraphChar - If the specified character is a legal trigraph when
906/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
907/// return the result character. Finally, emit a warning about trigraph use
908/// whether trigraphs are enabled or not.
909static char DecodeTrigraphChar(const char *CP, Lexer *L) {
910 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000911 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chris Lattner3692b092008-11-18 07:59:24 +0000913 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000914 if (!L->isLexingRawMode())
915 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000916 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattner74d15df2008-11-22 02:02:22 +0000919 if (!L->isLexingRawMode())
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000920 L->Diag(CP-2, diag::trigraph_converted) << llvm::StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 return Res;
922}
923
Chris Lattner24f0e482009-04-18 22:05:41 +0000924/// getEscapedNewLineSize - Return the size of the specified escaped newline,
925/// 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 +0000926/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000927unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
928 unsigned Size = 0;
929 while (isWhitespace(Ptr[Size])) {
930 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Chris Lattner24f0e482009-04-18 22:05:41 +0000932 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
933 continue;
934
935 // If this is a \r\n or \n\r, skip the other half.
936 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
937 Ptr[Size-1] != Ptr[Size])
938 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattner24f0e482009-04-18 22:05:41 +0000940 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000941 }
942
Chris Lattner24f0e482009-04-18 22:05:41 +0000943 // Not an escaped newline, must be a \t or something else.
944 return 0;
945}
946
Chris Lattner03374952009-04-18 22:27:02 +0000947/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
948/// them), skip over them and return the first non-escaped-newline found,
949/// otherwise return P.
950const char *Lexer::SkipEscapedNewLines(const char *P) {
951 while (1) {
952 const char *AfterEscape;
953 if (*P == '\\') {
954 AfterEscape = P+1;
955 } else if (*P == '?') {
956 // If not a trigraph for escape, bail out.
957 if (P[1] != '?' || P[2] != '/')
958 return P;
959 AfterEscape = P+3;
960 } else {
961 return P;
962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Chris Lattner03374952009-04-18 22:27:02 +0000964 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
965 if (NewLineSize == 0) return P;
966 P = AfterEscape+NewLineSize;
967 }
968}
969
Chris Lattner24f0e482009-04-18 22:05:41 +0000970
Reid Spencer5f016e22007-07-11 17:01:13 +0000971/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
972/// get its size, and return it. This is tricky in several cases:
973/// 1. If currently at the start of a trigraph, we warn about the trigraph,
974/// then either return the trigraph (skipping 3 chars) or the '?',
975/// depending on whether trigraphs are enabled or not.
976/// 2. If this is an escaped newline (potentially with whitespace between
977/// the backslash and newline), implicitly skip the newline and return
978/// the char after it.
979/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
980///
981/// This handles the slow/uncommon case of the getCharAndSize method. Here we
982/// know that we can accumulate into Size, and that we have already incremented
983/// Ptr by Size bytes.
984///
985/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
986/// be updated to match.
987///
988char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +0000989 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 // If we have a slash, look for an escaped newline.
991 if (Ptr[0] == '\\') {
992 ++Size;
993 ++Ptr;
994Slash:
995 // Common case, backslash-char where the char is not whitespace.
996 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner5636a3b2009-06-23 05:15:06 +0000998 // See if we have optional whitespace characters between the slash and
999 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001000 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1001 // Remember that this token needs to be cleaned.
1002 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001003
Chris Lattner24f0e482009-04-18 22:05:41 +00001004 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001005 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001006 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner24f0e482009-04-18 22:05:41 +00001008 // Found backslash<whitespace><newline>. Parse the char after it.
1009 Size += EscapedNewLineSize;
1010 Ptr += EscapedNewLineSize;
1011 // Use slow version to accumulate a correct size field.
1012 return getCharAndSizeSlow(Ptr, Size, Tok);
1013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 // Otherwise, this is not an escaped newline, just return the slash.
1016 return '\\';
1017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 // If this is a trigraph, process it.
1020 if (Ptr[0] == '?' && Ptr[1] == '?') {
1021 // If this is actually a legal trigraph (not something like "??x"), emit
1022 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1023 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1024 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001025 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001026
1027 Ptr += 3;
1028 Size += 3;
1029 if (C == '\\') goto Slash;
1030 return C;
1031 }
1032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 // If this is neither, return a single character.
1035 ++Size;
1036 return *Ptr;
1037}
1038
1039
1040/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1041/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1042/// and that we have already incremented Ptr by Size bytes.
1043///
1044/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1045/// be updated to match.
1046char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1047 const LangOptions &Features) {
1048 // If we have a slash, look for an escaped newline.
1049 if (Ptr[0] == '\\') {
1050 ++Size;
1051 ++Ptr;
1052Slash:
1053 // Common case, backslash-char where the char is not whitespace.
1054 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001057 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1058 // Found backslash<whitespace><newline>. Parse the char after it.
1059 Size += EscapedNewLineSize;
1060 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner24f0e482009-04-18 22:05:41 +00001062 // Use slow version to accumulate a correct size field.
1063 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Reid Spencer5f016e22007-07-11 17:01:13 +00001066 // Otherwise, this is not an escaped newline, just return the slash.
1067 return '\\';
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // If this is a trigraph, process it.
1071 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1072 // If this is actually a legal trigraph (not something like "??x"), return
1073 // it.
1074 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1075 Ptr += 3;
1076 Size += 3;
1077 if (C == '\\') goto Slash;
1078 return C;
1079 }
1080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 // If this is neither, return a single character.
1083 ++Size;
1084 return *Ptr;
1085}
1086
1087//===----------------------------------------------------------------------===//
1088// Helper methods for lexing.
1089//===----------------------------------------------------------------------===//
1090
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001091/// \brief Routine that indiscriminately skips bytes in the source file.
1092void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1093 BufferPtr += Bytes;
1094 if (BufferPtr > BufferEnd)
1095 BufferPtr = BufferEnd;
1096 IsAtStartOfLine = StartOfLine;
1097}
1098
Chris Lattnerd2177732007-07-20 16:59:19 +00001099void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1101 unsigned Size;
1102 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001103 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001104 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 --CurPtr; // Back up over the skipped character.
1107
1108 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1109 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1110 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001111 //
1112 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1113 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1115FinishIdentifier:
1116 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001117 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1118 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // If we are in raw mode, return this identifier raw. There is no need to
1121 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001122 if (LexingRawMode)
1123 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001125 // Fill in Result.IdentifierInfo and update the token kind,
1126 // looking up the identifier in the identifier table.
1127 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 // Finally, now that we know we have an identifier, pass this off to the
1130 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001131 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001132 PP->HandleIdentifier(Result);
1133 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 C = getCharAndSize(CurPtr, Size);
1139 while (1) {
1140 if (C == '$') {
1141 // If we hit a $ and they are not supported in identifiers, we are done.
1142 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001145 if (!isLexingRawMode())
1146 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 CurPtr = ConsumeChar(CurPtr, Size, Result);
1148 C = getCharAndSize(CurPtr, Size);
1149 continue;
1150 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1151 // Found end of identifier.
1152 goto FinishIdentifier;
1153 }
1154
1155 // Otherwise, this character is good, consume it.
1156 CurPtr = ConsumeChar(CurPtr, Size, Result);
1157
1158 C = getCharAndSize(CurPtr, Size);
1159 while (isIdentifierBody(C)) { // FIXME: UCNs.
1160 CurPtr = ConsumeChar(CurPtr, Size, Result);
1161 C = getCharAndSize(CurPtr, Size);
1162 }
1163 }
1164}
1165
Douglas Gregora75ec432010-08-30 14:50:47 +00001166/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001167/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001168static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1169 unsigned Size;
1170 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1171 if (C1 != '0')
1172 return false;
1173 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1174 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001175}
Reid Spencer5f016e22007-07-11 17:01:13 +00001176
Nate Begeman5253c7f2008-04-14 02:26:39 +00001177/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001178/// constant. From[-1] is the first character lexed. Return the end of the
1179/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001180void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 unsigned Size;
1182 char C = getCharAndSize(CurPtr, Size);
1183 char PrevCh = 0;
1184 while (isNumberBody(C)) { // FIXME: UCNs?
1185 CurPtr = ConsumeChar(CurPtr, Size, Result);
1186 PrevCh = C;
1187 C = getCharAndSize(CurPtr, Size);
1188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001191 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1192 // If we are in Microsoft mode, don't continue if the constant is hex.
1193 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001194 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001195 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1196 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001197
1198 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001199 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001200 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001204 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001205 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001206 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001207}
1208
1209/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1210/// either " or L".
Chris Lattnerd88dc482008-10-12 04:05:48 +00001211void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, bool Wide) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 char C = getAndAdvanceChar(CurPtr, Result);
1215 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001216 // Skip escaped characters. Escaped newlines will already be processed by
1217 // getAndAdvanceChar.
1218 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001220
Chris Lattner571339c2010-05-30 23:27:38 +00001221 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001222 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001223 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1224 PP->CodeCompleteNaturalLanguage();
1225 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001226 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001227 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 }
Chris Lattner571339c2010-05-30 23:27:38 +00001230
1231 if (C == 0)
1232 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 C = getAndAdvanceChar(CurPtr, Result);
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001237 if (NulCharacter && !isLexingRawMode())
1238 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001241 const char *TokStart = BufferPtr;
Sean Hunt6cf75022010-08-30 17:47:05 +00001242 FormTokenWithChars(Result, CurPtr,
1243 Wide ? tok::wide_string_literal : tok::string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001244 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001245}
1246
1247/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1248/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001249void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001251 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 char C = getAndAdvanceChar(CurPtr, Result);
1253 while (C != '>') {
1254 // Skip escaped characters.
1255 if (C == '\\') {
1256 // Skip the escaped character.
1257 C = getAndAdvanceChar(CurPtr, Result);
1258 } else if (C == '\n' || C == '\r' || // Newline.
1259 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001260 // If the filename is unterminated, then it must just be a lone <
1261 // character. Return this as such.
1262 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 return;
1264 } else if (C == 0) {
1265 NulCharacter = CurPtr-1;
1266 }
1267 C = getAndAdvanceChar(CurPtr, Result);
1268 }
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001271 if (NulCharacter && !isLexingRawMode())
1272 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001275 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001276 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001277 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278}
1279
1280
1281/// LexCharConstant - Lex the remainder of a character constant, after having
1282/// lexed either ' or L'.
Chris Lattnerd2177732007-07-20 16:59:19 +00001283void Lexer::LexCharConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 const char *NulCharacter = 0; // Does this character contain the \0 character?
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 char C = getAndAdvanceChar(CurPtr, Result);
1287 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001288 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001289 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001290 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001292 }
1293
1294 while (C != '\'') {
1295 // Skip escaped characters.
1296 if (C == '\\') {
1297 // Skip the escaped character.
1298 // FIXME: UCN's
1299 C = getAndAdvanceChar(CurPtr, Result);
1300 } else if (C == '\n' || C == '\r' || // Newline.
1301 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001302 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1303 PP->CodeCompleteNaturalLanguage();
1304 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001305 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001306 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1307 return;
1308 } else if (C == 0) {
1309 NulCharacter = CurPtr-1;
1310 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 C = getAndAdvanceChar(CurPtr, Result);
1312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattnerd80f7862010-07-07 23:24:27 +00001314 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001315 if (NulCharacter && !isLexingRawMode())
1316 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001319 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001320 FormTokenWithChars(Result, CurPtr, tok::char_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001321 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322}
1323
1324/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1325/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001326///
1327/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1328///
1329bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 // Whitespace - Skip it, then return the token after the whitespace.
1331 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1332 while (1) {
1333 // Skip horizontal whitespace very aggressively.
1334 while (isHorizontalWhitespace(Char))
1335 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001337 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 if (Char != '\n' && Char != '\r')
1339 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 if (ParsingPreprocessorDirective) {
1342 // End of preprocessor directive line, let LexTokenInternal handle this.
1343 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001344 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 }
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // ok, but handle newline.
1348 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001349 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001351 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 Char = *++CurPtr;
1353 }
1354
1355 // If this isn't immediately after a newline, there is leading space.
1356 char PrevChar = CurPtr[-1];
1357 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001358 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359
Chris Lattnerd88dc482008-10-12 04:05:48 +00001360 // If the client wants us to return whitespace, return it now.
1361 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001362 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001363 return true;
1364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001367 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001368}
1369
1370// SkipBCPLComment - We have just read the // characters from input. Skip until
1371// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001372/// BufferPtr and return.
1373///
1374/// If we're in KeepCommentMode or any CommentHandler has inserted
1375/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001376bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // If BCPL comments aren't explicitly enabled for this language, emit an
1378 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001379 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // Mark them enabled so we only emit one warning for this translation
1383 // unit.
1384 Features.BCPLComment = true;
1385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // Scan over the body of the comment. The common case, when scanning, is that
1388 // the comment contains normal ascii characters with nothing interesting in
1389 // them. As such, optimize for this case with the inner loop.
1390 char C;
1391 do {
1392 C = *CurPtr;
1393 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1394 // If we find a \n character, scan backwards, checking to see if it's an
1395 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 // Skip over characters in the fast loop.
1398 while (C != 0 && // Potentially EOF.
1399 C != '\\' && // Potentially escaped newline.
1400 C != '?' && // Potentially trigraph.
1401 C != '\n' && C != '\r') // Newline or DOS-style newline.
1402 C = *++CurPtr;
1403
1404 // If this is a newline, we're done.
1405 if (C == '\n' || C == '\r')
1406 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001409 // properly decode the character. Read it in raw mode to avoid emitting
1410 // diagnostics about things like trigraphs. If we see an escaped newline,
1411 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001413 bool OldRawMode = isLexingRawMode();
1414 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001415 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001416 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001417
1418 // If the char that we finally got was a \n, then we must have had something
1419 // like \<newline><newline>. We don't want to have consumed the second
1420 // newline, we want CurPtr, to end up pointing to it down below.
1421 if (C == '\n' || C == '\r') {
1422 --CurPtr;
1423 C = 'x'; // doesn't matter what this is.
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 // If we read multiple characters, and one of those characters was a \r or
1427 // \n, then we had an escaped newline within the comment. Emit diagnostic
1428 // unless the next line is also a // comment.
1429 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1430 for (; OldPtr != CurPtr; ++OldPtr)
1431 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1432 // Okay, we found a // comment that ends in a newline, if the next
1433 // line is also a // comment, but has spaces, don't emit a diagnostic.
1434 if (isspace(C)) {
1435 const char *ForwardPtr = CurPtr;
1436 while (isspace(*ForwardPtr)) // Skip whitespace.
1437 ++ForwardPtr;
1438 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1439 break;
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Chris Lattner74d15df2008-11-22 02:02:22 +00001442 if (!isLexingRawMode())
1443 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 break;
1445 }
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregor55817af2010-08-25 17:04:25 +00001448 if (CurPtr == BufferEnd+1) {
1449 if (PP && PP->isCodeCompletionFile(FileLoc))
1450 PP->CodeCompleteNaturalLanguage();
1451
1452 --CurPtr;
1453 break;
1454 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 } while (C != '\n' && C != '\r');
1456
Chris Lattner3d0ad582010-02-03 21:06:21 +00001457 // Found but did not consume the newline. Notify comment handlers about the
1458 // comment unless we're in a #if 0 block.
1459 if (PP && !isLexingRawMode() &&
1460 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1461 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001462 BufferPtr = CurPtr;
1463 return true; // A token has to be returned.
1464 }
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001467 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 return SaveBCPLComment(Result, CurPtr);
1469
1470 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001471 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1473 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001474 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001478 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001479 // contribute to another token), it isn't needed for correctness. Note that
1480 // this is ok even in KeepWhitespaceMode, because we would have returned the
1481 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001485 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001487 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001489 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490}
1491
1492/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1493/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001494bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001495 // If we're not in a preprocessor directive, just return the // comment
1496 // directly.
1497 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Chris Lattner9e6293d2008-10-12 04:51:35 +00001499 if (!ParsingPreprocessorDirective)
1500 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattner9e6293d2008-10-12 04:51:35 +00001502 // If this BCPL-style comment is in a macro definition, transmogrify it into
1503 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001504 bool Invalid = false;
1505 std::string Spelling = PP->getSpelling(Result, &Invalid);
1506 if (Invalid)
1507 return true;
1508
Chris Lattner9e6293d2008-10-12 04:51:35 +00001509 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1510 Spelling[1] = '*'; // Change prefix to "/*".
1511 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Chris Lattner9e6293d2008-10-12 04:51:35 +00001513 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001514 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1515 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001516 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001517}
1518
1519/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1520/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001521/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001522static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 Lexer *L) {
1524 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // Back up off the newline.
1527 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 // If this is a two-character newline sequence, skip the other character.
1530 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1531 // \n\n or \r\r -> not escaped newline.
1532 if (CurPtr[0] == CurPtr[1])
1533 return false;
1534 // \n\r or \r\n -> skip the newline.
1535 --CurPtr;
1536 }
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // If we have horizontal whitespace, skip over it. We allow whitespace
1539 // between the slash and newline.
1540 bool HasSpace = false;
1541 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1542 --CurPtr;
1543 HasSpace = true;
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 // If we have a slash, we know this is an escaped newline.
1547 if (*CurPtr == '\\') {
1548 if (CurPtr[-1] != '*') return false;
1549 } else {
1550 // It isn't a slash, is it the ?? / trigraph?
1551 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1552 CurPtr[-3] != '*')
1553 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // This is the trigraph ending the comment. Emit a stern warning!
1556 CurPtr -= 2;
1557
1558 // If no trigraphs are enabled, warn that we ignored this trigraph and
1559 // ignore this * character.
1560 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001561 if (!L->isLexingRawMode())
1562 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 return false;
1564 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001565 if (!L->isLexingRawMode())
1566 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001570 if (!L->isLexingRawMode())
1571 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001574 if (HasSpace && !L->isLexingRawMode())
1575 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 return true;
1578}
1579
1580#ifdef __SSE2__
1581#include <emmintrin.h>
1582#elif __ALTIVEC__
1583#include <altivec.h>
1584#undef bool
1585#endif
1586
1587/// SkipBlockComment - We have just read the /* characters from input. Read
1588/// until we find the */ characters that terminate the comment. Note that we
1589/// don't bother decoding trigraphs or escaped newlines in block comments,
1590/// because they cannot cause the comment to end. The only thing that can
1591/// happen is the comment could end with an escaped newline between the */ end
1592/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001593///
Chris Lattner046c2272010-01-18 22:35:47 +00001594/// If we're in KeepCommentMode or any CommentHandler has inserted
1595/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001596bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Scan one character past where we should, looking for a '/' character. Once
1598 // we find it, check to see if it was preceeded by a *. This common
1599 // optimization helps people who like to put a lot of * characters in their
1600 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001601
1602 // The first character we get with newlines and trigraphs skipped to handle
1603 // the degenerate /*/ case below correctly if the * has an escaped newline
1604 // after it.
1605 unsigned CharSize;
1606 unsigned char C = getCharAndSize(CurPtr, CharSize);
1607 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001609 if (!isLexingRawMode() &&
1610 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001611 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001612 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattner31f0eca2008-10-12 04:19:49 +00001614 // KeepWhitespaceMode should return this broken comment as a token. Since
1615 // it isn't a well formed comment, just return it as an 'unknown' token.
1616 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001617 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001618 return true;
1619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Chris Lattner31f0eca2008-10-12 04:19:49 +00001621 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001622 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner8146b682007-07-21 23:43:37 +00001625 // Check to see if the first character after the '/*' is another /. If so,
1626 // then this slash does not end the block comment, it is part of it.
1627 if (C == '/')
1628 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 while (1) {
1631 // Skip over all non-interesting characters until we find end of buffer or a
1632 // (probably ending) '/' character.
1633 if (CurPtr + 24 < BufferEnd) {
1634 // While not aligned to a 16-byte boundary.
1635 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1636 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 if (C == '/') goto FoundSlash;
1639
1640#ifdef __SSE2__
1641 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1642 '/', '/', '/', '/', '/', '/', '/', '/');
1643 while (CurPtr+16 <= BufferEnd &&
1644 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1645 CurPtr += 16;
1646#elif __ALTIVEC__
1647 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001648 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 '/', '/', '/', '/', '/', '/', '/', '/'
1650 };
1651 while (CurPtr+16 <= BufferEnd &&
1652 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1653 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001654#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 // Scan for '/' quickly. Many block comments are very large.
1656 while (CurPtr[0] != '/' &&
1657 CurPtr[1] != '/' &&
1658 CurPtr[2] != '/' &&
1659 CurPtr[3] != '/' &&
1660 CurPtr+4 < BufferEnd) {
1661 CurPtr += 4;
1662 }
1663#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 // It has to be one of the bytes scanned, increment to it and read one.
1666 C = *CurPtr++;
1667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 // Loop to scan the remainder.
1670 while (C != '/' && C != '\0')
1671 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 FoundSlash:
1674 if (C == '/') {
1675 if (CurPtr[-2] == '*') // We found the final */. We're done!
1676 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1679 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1680 // We found the final */, though it had an escaped newline between the
1681 // * and /. We're done!
1682 break;
1683 }
1684 }
1685 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1686 // If this is a /* inside of the comment, emit a warning. Don't do this
1687 // if this is a /*/, which will end the comment. This misses cases with
1688 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001689 if (!isLexingRawMode())
1690 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
1692 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001693 if (PP && PP->isCodeCompletionFile(FileLoc))
1694 PP->CodeCompleteNaturalLanguage();
1695 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001696 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 // Note: the user probably forgot a */. We could continue immediately
1698 // after the /*, but this would involve lexing a lot of what really is the
1699 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001700 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Chris Lattner31f0eca2008-10-12 04:19:49 +00001702 // KeepWhitespaceMode should return this broken comment as a token. Since
1703 // it isn't a well formed comment, just return it as an 'unknown' token.
1704 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001705 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001706 return true;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Chris Lattner31f0eca2008-10-12 04:19:49 +00001709 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001710 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
1712 C = *CurPtr++;
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Chris Lattner3d0ad582010-02-03 21:06:21 +00001715 // Notify comment handlers about the comment unless we're in a #if 0 block.
1716 if (PP && !isLexingRawMode() &&
1717 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1718 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001719 BufferPtr = CurPtr;
1720 return true; // A token has to be returned.
1721 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001722
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001724 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001725 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001726 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 }
1728
1729 // It is common for the tokens immediately after a /**/ comment to be
1730 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001731 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1732 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001734 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001736 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 }
1738
1739 // Otherwise, just return so that the next character will be lexed as a token.
1740 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001741 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001742 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001743}
1744
1745//===----------------------------------------------------------------------===//
1746// Primary Lexing Entry Points
1747//===----------------------------------------------------------------------===//
1748
Reid Spencer5f016e22007-07-11 17:01:13 +00001749/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1750/// uninterpreted string. This switches the lexer out of directive mode.
1751std::string Lexer::ReadToEndOfLine() {
1752 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1753 "Must be in a preprocessing directive!");
1754 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001755 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001756
1757 // CurPtr - Cache BufferPtr in an automatic variable.
1758 const char *CurPtr = BufferPtr;
1759 while (1) {
1760 char Char = getAndAdvanceChar(CurPtr, Tmp);
1761 switch (Char) {
1762 default:
1763 Result += Char;
1764 break;
1765 case 0: // Null.
1766 // Found end of file?
1767 if (CurPtr-1 != BufferEnd) {
1768 // Nope, normal character, continue.
1769 Result += Char;
1770 break;
1771 }
1772 // FALL THROUGH.
1773 case '\r':
1774 case '\n':
1775 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1776 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1777 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Peter Collingbourne84021552011-02-28 02:37:51 +00001779 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001781 if (Tmp.is(tok::code_completion)) {
1782 if (PP && PP->getCodeCompletionHandler())
1783 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1784 Lex(Tmp);
1785 }
Peter Collingbourne84021552011-02-28 02:37:51 +00001786 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 // Finally, we're done, return the string we found.
1789 return Result;
1790 }
1791 }
1792}
1793
1794/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1795/// condition, reporting diagnostics and handling other edge cases as required.
1796/// This returns true if Result contains a token, false if PP.Lex should be
1797/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001798bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001799 // Check if we are performing code completion.
1800 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1801 // We're at the end of the file, but we've been asked to consider the
1802 // end of the file to be a code-completion token. Return the
1803 // code-completion token.
1804 Result.startToken();
1805 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1806
1807 // Only do the eof -> code_completion translation once.
1808 PP->SetCodeCompletionPoint(0, 0, 0);
1809
1810 // Silence any diagnostics that occur once we hit the code-completion point.
1811 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1812 return true;
1813 }
1814
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 // If we hit the end of the file while parsing a preprocessor directive,
1816 // end the preprocessor directive first. The next token returned will
1817 // then be the end of file.
1818 if (ParsingPreprocessorDirective) {
1819 // Done parsing the "line".
1820 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00001822 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001825 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001827 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001828
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 // If we are in raw mode, return this event as an EOF token. Let the caller
1830 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001831 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 Result.startToken();
1833 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001834 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 return true;
1836 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001837
Douglas Gregorf44e8542010-08-24 19:08:16 +00001838 // Issue diagnostics for unterminated #if and missing newline.
1839
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 // If we are in a #if directive, emit an error.
1841 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001842 if (!PP->isCodeCompletionFile(FileLoc))
1843 PP->Diag(ConditionalStack.back().IfLoc,
1844 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 ConditionalStack.pop_back();
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001848 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1849 // a pedwarn.
1850 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001851 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001852 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 BufferPtr = CurPtr;
1855
1856 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001857 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001858}
1859
1860/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1861/// the specified lexer will return a tok::l_paren token, 0 if it is something
1862/// else and 2 if there are no more tokens in the buffer controlled by the
1863/// lexer.
1864unsigned Lexer::isNextPPTokenLParen() {
1865 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 // Switch to 'skipping' mode. This will ensure that we can lex a token
1868 // without emitting diagnostics, disables macro expansion, and will cause EOF
1869 // to return an EOF token instead of popping the include stack.
1870 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 // Save state that can be changed while lexing so that we can restore it.
1873 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001874 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Chris Lattnerd2177732007-07-20 16:59:19 +00001876 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 Tok.startToken();
1878 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 // Restore state that may have changed.
1881 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001882 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 // Restore the lexer back to non-skipping mode.
1885 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001887 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00001889 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001890}
1891
Chris Lattner34f349d2009-12-14 06:16:57 +00001892/// FindConflictEnd - Find the end of a version control conflict marker.
1893static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
1894 llvm::StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
1895 size_t Pos = RestOfBuffer.find(">>>>>>>");
1896 while (Pos != llvm::StringRef::npos) {
1897 // Must occur at start of line.
1898 if (RestOfBuffer[Pos-1] != '\r' &&
1899 RestOfBuffer[Pos-1] != '\n') {
1900 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00001901 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00001902 continue;
1903 }
1904 return RestOfBuffer.data()+Pos;
1905 }
1906 return 0;
1907}
1908
1909/// IsStartOfConflictMarker - If the specified pointer is the start of a version
1910/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
1911/// and recover nicely. This returns true if it is a conflict marker and false
1912/// if not.
1913bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
1914 // Only a conflict marker if it starts at the beginning of a line.
1915 if (CurPtr != BufferStart &&
1916 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1917 return false;
1918
1919 // Check to see if we have <<<<<<<.
1920 if (BufferEnd-CurPtr < 8 ||
1921 llvm::StringRef(CurPtr, 7) != "<<<<<<<")
1922 return false;
1923
1924 // If we have a situation where we don't care about conflict markers, ignore
1925 // it.
1926 if (IsInConflictMarker || isLexingRawMode())
1927 return false;
1928
1929 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
1930 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00001931 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00001932 // We found a match. We are really in a conflict marker.
1933 // Diagnose this, and ignore to the end of line.
1934 Diag(CurPtr, diag::err_conflict_marker);
1935 IsInConflictMarker = true;
1936
1937 // Skip ahead to the end of line. We know this exists because the
1938 // end-of-conflict marker starts with \r or \n.
1939 while (*CurPtr != '\r' && *CurPtr != '\n') {
1940 assert(CurPtr != BufferEnd && "Didn't find end of line");
1941 ++CurPtr;
1942 }
1943 BufferPtr = CurPtr;
1944 return true;
1945 }
1946
1947 // No end of conflict marker found.
1948 return false;
1949}
1950
1951
1952/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
1953/// marker, then it is the end of a conflict marker. Handle it by ignoring up
1954/// until the end of the line. This returns true if it is a conflict marker and
1955/// false if not.
1956bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
1957 // Only a conflict marker if it starts at the beginning of a line.
1958 if (CurPtr != BufferStart &&
1959 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
1960 return false;
1961
1962 // If we have a situation where we don't care about conflict markers, ignore
1963 // it.
1964 if (!IsInConflictMarker || isLexingRawMode())
1965 return false;
1966
1967 // Check to see if we have the marker (7 characters in a row).
1968 for (unsigned i = 1; i != 7; ++i)
1969 if (CurPtr[i] != CurPtr[0])
1970 return false;
1971
1972 // If we do have it, search for the end of the conflict marker. This could
1973 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
1974 // be the end of conflict marker.
1975 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
1976 CurPtr = End;
1977
1978 // Skip ahead to the end of line.
1979 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
1980 ++CurPtr;
1981
1982 BufferPtr = CurPtr;
1983
1984 // No longer in the conflict marker.
1985 IsInConflictMarker = false;
1986 return true;
1987 }
1988
1989 return false;
1990}
1991
Reid Spencer5f016e22007-07-11 17:01:13 +00001992
1993/// LexTokenInternal - This implements a simple C family lexer. It is an
1994/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00001995/// has a null character at the end of the file. This returns a preprocessing
1996/// token, not a normal token, as such, it is an internal interface. It assumes
1997/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00001998void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001999LexNextToken:
2000 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002001 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // CurPtr - Cache BufferPtr in an automatic variable.
2005 const char *CurPtr = BufferPtr;
2006
2007 // Small amounts of horizontal whitespace is very common between tokens.
2008 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2009 ++CurPtr;
2010 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2011 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Chris Lattnerd88dc482008-10-12 04:05:48 +00002013 // If we are keeping whitespace and other tokens, just return what we just
2014 // skipped. The next lexer invocation will return the token after the
2015 // whitespace.
2016 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002017 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002018 return;
2019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002022 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 // Read a character, advancing over it.
2028 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002029 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 switch (Char) {
2032 case 0: // Null.
2033 // Found end of file?
2034 if (CurPtr-1 == BufferEnd) {
2035 // Read the PP instance variable into an automatic variable, because
2036 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002037 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2039 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002040 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2041 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Chris Lattner74d15df2008-11-22 02:02:22 +00002044 if (!isLexingRawMode())
2045 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002046 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002047 if (SkipWhitespace(Result, CurPtr))
2048 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002051
2052 case 26: // DOS & CP/M EOF: "^Z".
2053 // If we're in Microsoft extensions mode, treat this as end of file.
2054 if (Features.Microsoft) {
2055 // Read the PP instance variable into an automatic variable, because
2056 // LexEndOfFile will often delete 'this'.
2057 Preprocessor *PPCache = PP;
2058 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2059 return; // Got a token to return.
2060 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2061 return PPCache->Lex(Result);
2062 }
2063 // If Microsoft extensions are disabled, this is just random garbage.
2064 Kind = tok::unknown;
2065 break;
2066
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 case '\n':
2068 case '\r':
2069 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002070 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 if (ParsingPreprocessorDirective) {
2072 // Done parsing the "line".
2073 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002076 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 // Since we consumed a newline, we are back at the start of a line.
2079 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Peter Collingbourne84021552011-02-28 02:37:51 +00002081 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 break;
2083 }
2084 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002085 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002087 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Chris Lattnerd88dc482008-10-12 04:05:48 +00002089 if (SkipWhitespace(Result, CurPtr))
2090 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 goto LexNextToken; // GCC isn't tail call eliminating.
2092 case ' ':
2093 case '\t':
2094 case '\f':
2095 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002096 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002097 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002098 if (SkipWhitespace(Result, CurPtr))
2099 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002100
2101 SkipIgnoredUnits:
2102 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Chris Lattner8133cfc2007-07-22 06:29:05 +00002104 // If the next token is obviously a // or /* */ comment, skip it efficiently
2105 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002106 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002107 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002108 if (SkipBCPLComment(Result, CurPtr+2))
2109 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002110 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002111 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002112 if (SkipBlockComment(Result, CurPtr+2))
2113 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002114 goto SkipIgnoredUnits;
2115 } else if (isHorizontalWhitespace(*CurPtr)) {
2116 goto SkipHorizontalWhitespace;
2117 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002119
Chris Lattner3a570772008-01-03 17:58:54 +00002120 // C99 6.4.4.1: Integer Constants.
2121 // C99 6.4.4.2: Floating Constants.
2122 case '0': case '1': case '2': case '3': case '4':
2123 case '5': case '6': case '7': case '8': case '9':
2124 // Notify MIOpt that we read a non-whitespace/non-comment token.
2125 MIOpt.ReadToken();
2126 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Chris Lattner3a570772008-01-03 17:58:54 +00002128 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // Notify MIOpt that we read a non-whitespace/non-comment token.
2130 MIOpt.ReadToken();
2131 Char = getCharAndSize(CurPtr, SizeTmp);
2132
2133 // Wide string literal.
2134 if (Char == '"')
2135 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2136 true);
2137
2138 // Wide character constant.
2139 if (Char == '\'')
2140 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2141 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 // C99 6.4.2: Identifiers.
2144 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2145 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2146 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
2147 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2148 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2149 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2150 case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
2151 case 'v': case 'w': case 'x': case 'y': case 'z':
2152 case '_':
2153 // Notify MIOpt that we read a non-whitespace/non-comment token.
2154 MIOpt.ReadToken();
2155 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002156
2157 case '$': // $ in identifiers.
2158 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002159 if (!isLexingRawMode())
2160 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002161 // Notify MIOpt that we read a non-whitespace/non-comment token.
2162 MIOpt.ReadToken();
2163 return LexIdentifier(Result, CurPtr);
2164 }
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Chris Lattner9e6293d2008-10-12 04:51:35 +00002166 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002167 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 // C99 6.4.4: Character Constants.
2170 case '\'':
2171 // Notify MIOpt that we read a non-whitespace/non-comment token.
2172 MIOpt.ReadToken();
2173 return LexCharConstant(Result, CurPtr);
2174
2175 // C99 6.4.5: String Literals.
2176 case '"':
2177 // Notify MIOpt that we read a non-whitespace/non-comment token.
2178 MIOpt.ReadToken();
2179 return LexStringLiteral(Result, CurPtr, false);
2180
2181 // C99 6.4.6: Punctuators.
2182 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002183 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 break;
2185 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002186 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 break;
2188 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002189 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 break;
2191 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002192 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 break;
2194 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002195 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 break;
2197 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002198 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 break;
2200 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002201 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 break;
2203 case '.':
2204 Char = getCharAndSize(CurPtr, SizeTmp);
2205 if (Char >= '0' && Char <= '9') {
2206 // Notify MIOpt that we read a non-whitespace/non-comment token.
2207 MIOpt.ReadToken();
2208
2209 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2210 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002211 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 CurPtr += SizeTmp;
2213 } else if (Char == '.' &&
2214 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002215 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2217 SizeTmp2, Result);
2218 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002219 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 }
2221 break;
2222 case '&':
2223 Char = getCharAndSize(CurPtr, SizeTmp);
2224 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002225 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2227 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002228 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2230 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002231 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 }
2233 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002234 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002236 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2238 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002239 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 }
2241 break;
2242 case '+':
2243 Char = getCharAndSize(CurPtr, SizeTmp);
2244 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002246 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002249 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002251 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 }
2253 break;
2254 case '-':
2255 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002256 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::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002259 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002260 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2262 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002263 Kind = tok::arrowstar;
2264 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002266 Kind = tok::arrow;
2267 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002268 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002269 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002271 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 }
2273 break;
2274 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002275 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002276 break;
2277 case '!':
2278 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002279 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2281 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002282 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 }
2284 break;
2285 case '/':
2286 // 6.4.9: Comments
2287 Char = getCharAndSize(CurPtr, SizeTmp);
2288 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002289 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2290 // want to lex this as a comment. There is one problem with this though,
2291 // that in one particular corner case, this can change the behavior of the
2292 // resultant program. For example, In "foo //**/ bar", C89 would lex
2293 // this as "foo / bar" and langauges with BCPL comments would lex it as
2294 // "foo". Check to see if the character after the second slash is a '*'.
2295 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002296 // However, we never do this in -traditional-cpp mode.
2297 if ((Features.BCPLComment ||
2298 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2299 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002300 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002301 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Chris Lattner8402c732009-01-16 22:39:25 +00002303 // It is common for the tokens immediately after a // comment to be
2304 // whitespace (indentation for the next line). Instead of going through
2305 // the big switch, handle it efficiently now.
2306 goto SkipIgnoredUnits;
2307 }
2308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Chris Lattner8402c732009-01-16 22:39:25 +00002310 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002312 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002313 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002314 }
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Chris Lattner8402c732009-01-16 22:39:25 +00002316 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002318 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002320 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 }
2322 break;
2323 case '%':
2324 Char = getCharAndSize(CurPtr, SizeTmp);
2325 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002326 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2328 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002329 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2331 } else if (Features.Digraphs && Char == ':') {
2332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2333 Char = getCharAndSize(CurPtr, SizeTmp);
2334 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002335 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2337 SizeTmp2, Result);
2338 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002340 if (!isLexingRawMode())
2341 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002342 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002343 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 // We parsed a # character. If this occurs at the start of the line,
2345 // it's actually the start of a preprocessing directive. Callback to
2346 // the preprocessor to handle it.
2347 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002348 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002349 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002350 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 // As an optimization, if the preprocessor didn't switch lexers, tail
2353 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002354 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 // Start a new token. If this is a #include or something, the PP may
2356 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002357 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002359 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002360 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 IsAtStartOfLine = false;
2362 }
2363 goto LexNextToken; // GCC isn't tail call eliminating.
2364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Chris Lattner168ae2d2007-10-17 20:41:00 +00002366 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 }
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Chris Lattnere91e9322009-03-18 20:58:27 +00002369 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 }
2371 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002372 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
2374 break;
2375 case '<':
2376 Char = getCharAndSize(CurPtr, SizeTmp);
2377 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002378 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002380 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2381 if (After == '=') {
2382 Kind = tok::lesslessequal;
2383 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2384 SizeTmp2, Result);
2385 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2386 // If this is actually a '<<<<<<<' version control conflict marker,
2387 // recognize it as such and recover nicely.
2388 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002389 } else if (Features.CUDA && After == '<') {
2390 Kind = tok::lesslessless;
2391 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2392 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002393 } else {
2394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2395 Kind = tok::lessless;
2396 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002399 Kind = tok::lessequal;
2400 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002402 Kind = tok::l_square;
2403 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002404 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002405 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002407 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 }
2409 break;
2410 case '>':
2411 Char = getCharAndSize(CurPtr, SizeTmp);
2412 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002414 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002416 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2417 if (After == '=') {
2418 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2419 SizeTmp2, Result);
2420 Kind = tok::greatergreaterequal;
2421 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2422 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2423 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002424 } else if (Features.CUDA && After == '>') {
2425 Kind = tok::greatergreatergreater;
2426 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2427 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002428 } else {
2429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2430 Kind = tok::greatergreater;
2431 }
2432
Reid Spencer5f016e22007-07-11 17:01:13 +00002433 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002434 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 }
2436 break;
2437 case '^':
2438 Char = getCharAndSize(CurPtr, SizeTmp);
2439 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002441 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002442 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002443 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 }
2445 break;
2446 case '|':
2447 Char = getCharAndSize(CurPtr, SizeTmp);
2448 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002449 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2451 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002452 // If this is '|||||||' and we're in a conflict marker, ignore it.
2453 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2454 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002455 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2457 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002458 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 }
2460 break;
2461 case ':':
2462 Char = getCharAndSize(CurPtr, SizeTmp);
2463 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002464 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002465 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2466 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002467 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002469 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002470 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 }
2472 break;
2473 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002474 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 break;
2476 case '=':
2477 Char = getCharAndSize(CurPtr, SizeTmp);
2478 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002479 // If this is '=======' and we're in a conflict marker, ignore it.
2480 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2481 goto LexNextToken;
2482
Chris Lattner9e6293d2008-10-12 04:51:35 +00002483 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002485 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002486 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 }
2488 break;
2489 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002490 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 break;
2492 case '#':
2493 Char = getCharAndSize(CurPtr, SizeTmp);
2494 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002495 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2497 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002498 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002499 if (!isLexingRawMode())
2500 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2502 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 // We parsed a # character. If this occurs at the start of the line,
2504 // it's actually the start of a preprocessing directive. Callback to
2505 // the preprocessor to handle it.
2506 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002507 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002508 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002509 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 // As an optimization, if the preprocessor didn't switch lexers, tail
2512 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002513 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 // Start a new token. If this is a #include or something, the PP may
2515 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002516 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002518 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002519 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 IsAtStartOfLine = false;
2521 }
2522 goto LexNextToken; // GCC isn't tail call eliminating.
2523 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002524 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 }
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Chris Lattnere91e9322009-03-18 20:58:27 +00002527 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 }
2529 break;
2530
Chris Lattner3a570772008-01-03 17:58:54 +00002531 case '@':
2532 // Objective C support.
2533 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002534 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002535 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002536 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002537 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 case '\\':
2540 // FIXME: UCN's.
2541 // FALL THROUGH.
2542 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002543 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 break;
2545 }
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 // Notify MIOpt that we read a non-whitespace/non-comment token.
2548 MIOpt.ReadToken();
2549
2550 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002551 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002552}