blob: 0664cbc21b81b9ebbcfa5e51a98680bf13d9ac3b [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.
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000080 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000081 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
82 .Default(0);
83
84 // Skip the BOM.
85 BufferPtr += BOMLength;
86 }
87
Chris Lattner22d91ca2009-01-17 06:55:17 +000088 Is_PragmaLexer = false;
Chris Lattner34f349d2009-12-14 06:16:57 +000089 IsInConflictMarker = false;
Eric Christopher156119d2011-04-09 00:01:04 +000090
Chris Lattner22d91ca2009-01-17 06:55:17 +000091 // Start of the file is a start of line.
92 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner22d91ca2009-01-17 06:55:17 +000094 // We are not after parsing a #.
95 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Chris Lattner22d91ca2009-01-17 06:55:17 +000097 // We are not after parsing #include.
98 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner22d91ca2009-01-17 06:55:17 +0000100 // We are not in raw mode. Raw mode disables diagnostics and interpretation
101 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
102 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
103 // or otherwise skipping over tokens.
104 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Chris Lattner22d91ca2009-01-17 06:55:17 +0000106 // Default to not keeping comments.
107 ExtendedTokenMode = 0;
108}
109
Chris Lattner0770dab2009-01-17 07:56:59 +0000110/// Lexer constructor - Create a new lexer object for the specified buffer
111/// with the specified preprocessor managing the lexing process. This lexer
112/// assumes that the associated file buffer and Preprocessor objects will
113/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000114Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000115 : PreprocessorLexer(&PP, FID),
116 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
117 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Chris Lattner0770dab2009-01-17 07:56:59 +0000119 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
120 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner0770dab2009-01-17 07:56:59 +0000122 // Default to keeping comments if the preprocessor wants them.
123 SetCommentRetentionState(PP.getCommentRetentionState());
124}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000125
Chris Lattner168ae2d2007-10-17 20:41:00 +0000126/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000127/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
128/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000129Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000130 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000131 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000132
Chris Lattner22d91ca2009-01-17 06:55:17 +0000133 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Chris Lattner168ae2d2007-10-17 20:41:00 +0000135 // We *are* in raw mode.
136 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000137}
138
Chris Lattner025c3a62009-01-17 07:35:14 +0000139/// Lexer constructor - Create a new raw lexer object. This object is only
140/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
141/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000142Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
143 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000144 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000145
Mike Stump1eb44332009-09-09 15:08:12 +0000146 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000147 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner025c3a62009-01-17 07:35:14 +0000149 // We *are* in raw mode.
150 LexingRawMode = true;
151}
152
Chris Lattner42e00d12009-01-17 08:27:52 +0000153/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
154/// _Pragma expansion. This has a variety of magic semantics that this method
155/// sets up. It returns a new'd Lexer that must be delete'd when done.
156///
157/// On entrance to this routine, TokStartLoc is a macro location which has a
158/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000159/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000160/// "expanded from".
161///
162/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
163/// normal lexer that remaps tokens as they fly by. This would require making
164/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
165/// interface that could handle this stuff. This would pull GetMappedTokenLoc
166/// out of the critical path of the lexer!
167///
Mike Stump1eb44332009-09-09 15:08:12 +0000168Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000169 SourceLocation ExpansionLocStart,
170 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000171 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000172 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000173
174 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000175 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000176 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
177 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner42e00d12009-01-17 08:27:52 +0000179 // Now that the lexer is created, change the start/end locations so that we
180 // just lex the subsection of the file that we want. This is lexing from a
181 // scratch buffer.
182 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner42e00d12009-01-17 08:27:52 +0000184 L->BufferPtr = StrData;
185 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000186 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000187
188 // Set the SourceLocation with the remapping information. This ensures that
189 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000190 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
191 ExpansionLocStart,
192 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner42e00d12009-01-17 08:27:52 +0000194 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000195 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000196 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner42e00d12009-01-17 08:27:52 +0000198 // This lexer really is for _Pragma.
199 L->Is_PragmaLexer = true;
200 return L;
201}
202
Chris Lattner168ae2d2007-10-17 20:41:00 +0000203
Reid Spencer5f016e22007-07-11 17:01:13 +0000204/// Stringify - Convert the specified string into a C string, with surrounding
205/// ""'s, and with escaped \ and " characters.
206std::string Lexer::Stringify(const std::string &Str, bool Charify) {
207 std::string Result = Str;
208 char Quote = Charify ? '\'' : '"';
209 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
210 if (Result[i] == '\\' || Result[i] == Quote) {
211 Result.insert(Result.begin()+i, '\\');
212 ++i; ++e;
213 }
214 }
215 return Result;
216}
217
Chris Lattnerd8e30832007-07-24 06:57:14 +0000218/// Stringify - Convert the specified string into a C string by escaping '\'
219/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000220void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
222 if (Str[i] == '\\' || Str[i] == '"') {
223 Str.insert(Str.begin()+i, '\\');
224 ++i; ++e;
225 }
226 }
227}
228
Chris Lattnerb0607272010-11-17 07:26:20 +0000229//===----------------------------------------------------------------------===//
230// Token Spelling
231//===----------------------------------------------------------------------===//
232
233/// getSpelling() - Return the 'spelling' of this token. The spelling of a
234/// token are the characters used to represent the token in the source file
235/// after trigraph expansion and escaped-newline folding. In particular, this
236/// wants to get the true, uncanonicalized, spelling of things like digraphs
237/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238StringRef Lexer::getSpelling(SourceLocation loc,
239 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000240 const SourceManager &SM,
241 const LangOptions &options,
242 bool *invalid) {
243 // Break down the source location.
244 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
245
246 // Try to the load the file buffer.
247 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000249 if (invalidTemp) {
250 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000252 }
253
254 const char *tokenBegin = file.data() + locInfo.second;
255
256 // Lex from the start of the given location.
257 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
258 file.begin(), tokenBegin, file.end());
259 Token token;
260 lexer.LexFromRawLexer(token);
261
262 unsigned length = token.getLength();
263
264 // Common case: no need for cleaning.
265 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000267
268 // Hard case, we need to relex the characters into the string.
269 buffer.clear();
270 buffer.reserve(length);
271
272 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
273 unsigned charSize;
274 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
275 ti += charSize;
276 }
277
Chris Lattner5f9e2722011-07-23 10:55:15 +0000278 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000279}
280
281/// getSpelling() - Return the 'spelling' of this token. The spelling of a
282/// token are the characters used to represent the token in the source file
283/// after trigraph expansion and escaped-newline folding. In particular, this
284/// wants to get the true, uncanonicalized, spelling of things like digraphs
285/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000286std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
287 const LangOptions &Features, bool *Invalid) {
288 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
289
290 // If this token contains nothing interesting, return it directly.
291 bool CharDataInvalid = false;
292 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
293 &CharDataInvalid);
294 if (Invalid)
295 *Invalid = CharDataInvalid;
296 if (CharDataInvalid)
297 return std::string();
298
299 if (!Tok.needsCleaning())
300 return std::string(TokStart, TokStart+Tok.getLength());
301
302 std::string Result;
303 Result.reserve(Tok.getLength());
304
305 // Otherwise, hard case, relex the characters into the string.
306 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
307 Ptr != End; ) {
308 unsigned CharSize;
309 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
310 Ptr += CharSize;
311 }
312 assert(Result.size() != unsigned(Tok.getLength()) &&
313 "NeedsCleaning flag set on something that didn't need cleaning!");
314 return Result;
315}
316
317/// getSpelling - This method is used to get the spelling of a token into a
318/// preallocated buffer, instead of as an std::string. The caller is required
319/// to allocate enough space for the token, which is guaranteed to be at least
320/// Tok.getLength() bytes long. The actual length of the token is returned.
321///
322/// Note that this method may do two possible things: it may either fill in
323/// the buffer specified with characters, or it may *change the input pointer*
324/// to point to a constant buffer with the data already in it (avoiding a
325/// copy). The caller is not allowed to modify the returned buffer pointer
326/// if an internal buffer is returned.
327unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
328 const SourceManager &SourceMgr,
329 const LangOptions &Features, bool *Invalid) {
330 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000331
332 const char *TokStart = 0;
333 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
334 if (Tok.is(tok::raw_identifier))
335 TokStart = Tok.getRawIdentifierData();
336 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
337 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000338 Buffer = II->getNameStart();
339 return II->getLength();
340 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000341
342 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000343 if (Tok.isLiteral())
344 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000345
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000347 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000348 bool CharDataInvalid = false;
349 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
350 if (Invalid)
351 *Invalid = CharDataInvalid;
352 if (CharDataInvalid) {
353 Buffer = "";
354 return 0;
355 }
356 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000357
Chris Lattnerb0607272010-11-17 07:26:20 +0000358 // If this token contains nothing interesting, return it directly.
359 if (!Tok.needsCleaning()) {
360 Buffer = TokStart;
361 return Tok.getLength();
362 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000363
Chris Lattnerb0607272010-11-17 07:26:20 +0000364 // Otherwise, hard case, relex the characters into the string.
365 char *OutBuf = const_cast<char*>(Buffer);
366 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
367 Ptr != End; ) {
368 unsigned CharSize;
369 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
370 Ptr += CharSize;
371 }
372 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
373 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000374
Chris Lattnerb0607272010-11-17 07:26:20 +0000375 return OutBuf-Buffer;
376}
377
378
379
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000380static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
Chris Lattner9a611942007-10-17 21:18:47 +0000382/// MeasureTokenLength - Relex the token at the specified location and return
383/// its length in bytes in the input file. If the token needs cleaning (e.g.
384/// includes a trigraph or an escaped newline) then this count includes bytes
385/// that are part of that.
386unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000387 const SourceManager &SM,
388 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000389 // TODO: this could be special cased for common tokens like identifiers, ')',
390 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000391 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000392 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
393 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000394
395 // If this comes from a macro expansion, we really do want the macro name, not
396 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000397 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000398 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000399 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000400 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000401 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000402 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000403
404 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000405
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000406 if (isWhitespace(StrData[0]))
407 return 0;
408
Chris Lattner9a611942007-10-17 21:18:47 +0000409 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000410 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
411 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000412 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000413 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000414 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000415 return TheTok.getLength();
416}
417
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000418SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
419 const SourceManager &SM,
420 const LangOptions &LangOpts) {
421 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000422 if (LocInfo.first.isInvalid())
423 return Loc;
424
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000425 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000426 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000427 if (Invalid)
428 return Loc;
429
430 // Back up from the current location until we hit the beginning of a line
431 // (or the buffer). We'll relex from that point.
432 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000433 if (LocInfo.second >= Buffer.size())
434 return Loc;
435
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000436 const char *StrData = BufStart+LocInfo.second;
437 if (StrData[0] == '\n' || StrData[0] == '\r')
438 return Loc;
439
440 const char *LexStart = StrData;
441 while (LexStart != BufStart) {
442 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
443 ++LexStart;
444 break;
445 }
446
447 --LexStart;
448 }
449
450 // Create a lexer starting at the beginning of this token.
451 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
452 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
453 TheLexer.SetCommentRetentionState(true);
454
455 // Lex tokens until we find the token that contains the source location.
456 Token TheTok;
457 do {
458 TheLexer.LexFromRawLexer(TheTok);
459
460 if (TheLexer.getBufferLocation() > StrData) {
461 // Lexing this token has taken the lexer past the source location we're
462 // looking for. If the current token encompasses our source location,
463 // return the beginning of that token.
464 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
465 return TheTok.getLocation();
466
467 // We ended up skipping over the source location entirely, which means
468 // that it points into whitespace. We're done here.
469 break;
470 }
471 } while (TheTok.getKind() != tok::eof);
472
473 // We've passed our source location; just return the original source location.
474 return Loc;
475}
476
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000477namespace {
478 enum PreambleDirectiveKind {
479 PDK_Skipped,
480 PDK_StartIf,
481 PDK_EndIf,
482 PDK_Unknown
483 };
484}
485
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000486std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000487Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000488 // Create a lexer starting at the beginning of the file. Note that we use a
489 // "fake" file source location at offset 1 so that the lexer will track our
490 // position within the file.
491 const unsigned StartOffset = 1;
492 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
493 LangOptions LangOpts;
494 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
495 Buffer->getBufferStart(), Buffer->getBufferEnd());
496
497 bool InPreprocessorDirective = false;
498 Token TheTok;
499 Token IfStartTok;
500 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000501 unsigned Line = 0;
502
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000503 do {
504 TheLexer.LexFromRawLexer(TheTok);
505
506 if (InPreprocessorDirective) {
507 // If we've hit the end of the file, we're done.
508 if (TheTok.getKind() == tok::eof) {
509 InPreprocessorDirective = false;
510 break;
511 }
512
513 // If we haven't hit the end of the preprocessor directive, skip this
514 // token.
515 if (!TheTok.isAtStartOfLine())
516 continue;
517
518 // We've passed the end of the preprocessor directive, and will look
519 // at this token again below.
520 InPreprocessorDirective = false;
521 }
522
Douglas Gregordf95a132010-08-09 20:45:32 +0000523 // Keep track of the # of lines in the preamble.
524 if (TheTok.isAtStartOfLine()) {
525 ++Line;
526
527 // If we were asked to limit the number of lines in the preamble,
528 // and we're about to exceed that limit, we're done.
529 if (MaxLines && Line >= MaxLines)
530 break;
531 }
532
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000533 // Comments are okay; skip over them.
534 if (TheTok.getKind() == tok::comment)
535 continue;
536
537 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
538 // This is the start of a preprocessor directive.
539 Token HashTok = TheTok;
540 InPreprocessorDirective = true;
541
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000542 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000543 // we don't have an identifier table available. Instead, just look at
544 // the raw identifier to recognize and categorize preprocessor directives.
545 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000546 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000547 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000548 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000549 PreambleDirectiveKind PDK
550 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
551 .Case("include", PDK_Skipped)
552 .Case("__include_macros", PDK_Skipped)
553 .Case("define", PDK_Skipped)
554 .Case("undef", PDK_Skipped)
555 .Case("line", PDK_Skipped)
556 .Case("error", PDK_Skipped)
557 .Case("pragma", PDK_Skipped)
558 .Case("import", PDK_Skipped)
559 .Case("include_next", PDK_Skipped)
560 .Case("warning", PDK_Skipped)
561 .Case("ident", PDK_Skipped)
562 .Case("sccs", PDK_Skipped)
563 .Case("assert", PDK_Skipped)
564 .Case("unassert", PDK_Skipped)
565 .Case("if", PDK_StartIf)
566 .Case("ifdef", PDK_StartIf)
567 .Case("ifndef", PDK_StartIf)
568 .Case("elif", PDK_Skipped)
569 .Case("else", PDK_Skipped)
570 .Case("endif", PDK_EndIf)
571 .Default(PDK_Unknown);
572
573 switch (PDK) {
574 case PDK_Skipped:
575 continue;
576
577 case PDK_StartIf:
578 if (IfCount == 0)
579 IfStartTok = HashTok;
580
581 ++IfCount;
582 continue;
583
584 case PDK_EndIf:
585 // Mismatched #endif. The preamble ends here.
586 if (IfCount == 0)
587 break;
588
589 --IfCount;
590 continue;
591
592 case PDK_Unknown:
593 // We don't know what this directive is; stop at the '#'.
594 break;
595 }
596 }
597
598 // We only end up here if we didn't recognize the preprocessor
599 // directive or it was one that can't occur in the preamble at this
600 // point. Roll back the current token to the location of the '#'.
601 InPreprocessorDirective = false;
602 TheTok = HashTok;
603 }
604
Douglas Gregordf95a132010-08-09 20:45:32 +0000605 // We hit a token that we don't recognize as being in the
606 // "preprocessing only" part of the file, so we're no longer in
607 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000608 break;
609 } while (true);
610
611 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000612 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
613 IfCount? IfStartTok.isAtStartOfLine()
614 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000615}
616
Chris Lattner7ef5c272010-11-17 07:05:50 +0000617
618/// AdvanceToTokenCharacter - Given a location that specifies the start of a
619/// token, return a new location that specifies a character within the token.
620SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
621 unsigned CharNo,
622 const SourceManager &SM,
623 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000624 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000625 // character is. This needs to take into consideration newlines and
626 // trigraphs.
627 bool Invalid = false;
628 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
629
630 // If they request the first char of the token, we're trivially done.
631 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
632 return TokStart;
633
634 unsigned PhysOffset = 0;
635
636 // The usual case is that tokens don't contain anything interesting. Skip
637 // over the uninteresting characters. If a token only consists of simple
638 // chars, this method is extremely fast.
639 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
640 if (CharNo == 0)
641 return TokStart.getFileLocWithOffset(PhysOffset);
642 ++TokPtr, --CharNo, ++PhysOffset;
643 }
644
645 // If we have a character that may be a trigraph or escaped newline, use a
646 // lexer to parse it correctly.
647 for (; CharNo; --CharNo) {
648 unsigned Size;
649 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
650 TokPtr += Size;
651 PhysOffset += Size;
652 }
653
654 // Final detail: if we end up on an escaped newline, we want to return the
655 // location of the actual byte of the token. For example foo\<newline>bar
656 // advanced by 3 should return the location of b, not of \\. One compounding
657 // detail of this is that the escape may be made by a trigraph.
658 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
659 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
660
661 return TokStart.getFileLocWithOffset(PhysOffset);
662}
663
664/// \brief Computes the source location just past the end of the
665/// token at this source location.
666///
667/// This routine can be used to produce a source location that
668/// points just past the end of the token referenced by \p Loc, and
669/// is generally used when a diagnostic needs to point just after a
670/// token where it expected something different that it received. If
671/// the returned source location would not be meaningful (e.g., if
672/// it points into a macro), this routine returns an invalid
673/// source location.
674///
675/// \param Offset an offset from the end of the token, where the source
676/// location should refer to. The default offset (0) produces a source
677/// location pointing just past the end of the token; an offset of 1 produces
678/// a source location pointing to the last character in the token, etc.
679SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
680 const SourceManager &SM,
681 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000682 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000683 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000684
685 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000686 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
687 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000688
Chandler Carruth433db062011-07-14 08:20:40 +0000689 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000690 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000691 }
692
Chris Lattner7ef5c272010-11-17 07:05:50 +0000693 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
694 if (Len > Offset)
695 Len = Len - Offset;
696 else
697 return Loc;
698
John McCall77ebb382011-04-06 01:50:22 +0000699 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000700}
701
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000702/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000703/// token of the macro expansion.
704bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000705 const SourceManager &SM,
706 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000707 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
708
709 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
710 // FIXME: If the token comes from the macro token paste operator ('##')
711 // this function will always return false;
712 if (infoLoc.second > 0)
713 return false; // Does not point at the start of token.
714
Chandler Carruth433db062011-07-14 08:20:40 +0000715 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000716 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000717 if (expansionLoc.isFileID())
718 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000719
Chandler Carruth433db062011-07-14 08:20:40 +0000720 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000721}
722
723/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000724/// token of the macro expansion.
725bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000726 const SourceManager &SM,
727 const LangOptions &LangOpts) {
728 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
729
730 SourceLocation spellLoc = SM.getSpellingLoc(loc);
731 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
732 if (tokLen == 0)
733 return false;
734
735 FileID FID = SM.getFileID(loc);
736 SourceLocation afterLoc = loc.getFileLocWithOffset(tokLen+1);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000737 if (!SM.isBeforeInSourceLocationOffset(afterLoc, SM.getNextLocalOffset()))
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000738 return true; // We got past the last FileID, this points to the last token.
739
740 // FIXME: If the token comes from the macro token paste operator ('##')
741 // or the stringify operator ('#') this function will always return false;
742 if (FID == SM.getFileID(afterLoc))
743 return false; // Still in the same FileID, does not point to the last token.
744
Chandler Carruth433db062011-07-14 08:20:40 +0000745 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000746 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000747 if (expansionLoc.isFileID())
748 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000749
Chandler Carruth433db062011-07-14 08:20:40 +0000750 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000751}
752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753//===----------------------------------------------------------------------===//
754// Character information.
755//===----------------------------------------------------------------------===//
756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757enum {
758 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
759 CHAR_VERT_WS = 0x02, // '\r', '\n'
760 CHAR_LETTER = 0x04, // a-z,A-Z
761 CHAR_NUMBER = 0x08, // 0-9
762 CHAR_UNDER = 0x10, // _
763 CHAR_PERIOD = 0x20 // .
764};
765
Chris Lattner03b98662009-07-07 17:09:54 +0000766// Statically initialize CharInfo table based on ASCII character set
767// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000768static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000769{
770// 0 NUL 1 SOH 2 STX 3 ETX
771// 4 EOT 5 ENQ 6 ACK 7 BEL
772 0 , 0 , 0 , 0 ,
773 0 , 0 , 0 , 0 ,
774// 8 BS 9 HT 10 NL 11 VT
775//12 NP 13 CR 14 SO 15 SI
776 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
777 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
778//16 DLE 17 DC1 18 DC2 19 DC3
779//20 DC4 21 NAK 22 SYN 23 ETB
780 0 , 0 , 0 , 0 ,
781 0 , 0 , 0 , 0 ,
782//24 CAN 25 EM 26 SUB 27 ESC
783//28 FS 29 GS 30 RS 31 US
784 0 , 0 , 0 , 0 ,
785 0 , 0 , 0 , 0 ,
786//32 SP 33 ! 34 " 35 #
787//36 $ 37 % 38 & 39 '
788 CHAR_HORZ_WS, 0 , 0 , 0 ,
789 0 , 0 , 0 , 0 ,
790//40 ( 41 ) 42 * 43 +
791//44 , 45 - 46 . 47 /
792 0 , 0 , 0 , 0 ,
793 0 , 0 , CHAR_PERIOD , 0 ,
794//48 0 49 1 50 2 51 3
795//52 4 53 5 54 6 55 7
796 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
797 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
798//56 8 57 9 58 : 59 ;
799//60 < 61 = 62 > 63 ?
800 CHAR_NUMBER , CHAR_NUMBER , 0 , 0 ,
801 0 , 0 , 0 , 0 ,
802//64 @ 65 A 66 B 67 C
803//68 D 69 E 70 F 71 G
804 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
805 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
806//72 H 73 I 74 J 75 K
807//76 L 77 M 78 N 79 O
808 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
809 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
810//80 P 81 Q 82 R 83 S
811//84 T 85 U 86 V 87 W
812 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
813 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
814//88 X 89 Y 90 Z 91 [
815//92 \ 93 ] 94 ^ 95 _
816 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
817 0 , 0 , 0 , CHAR_UNDER ,
818//96 ` 97 a 98 b 99 c
819//100 d 101 e 102 f 103 g
820 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
821 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
822//104 h 105 i 106 j 107 k
823//108 l 109 m 110 n 111 o
824 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
825 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
826//112 p 113 q 114 r 115 s
827//116 t 117 u 118 v 119 w
828 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
829 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
830//120 x 121 y 122 z 123 {
831//124 | 125 } 126 ~ 127 DEL
832 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 0 ,
833 0 , 0 , 0 , 0
834};
835
Chris Lattnera2bf1052009-12-17 05:29:40 +0000836static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 static bool isInited = false;
838 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000839 // check the statically-initialized CharInfo table
840 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
841 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
842 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
843 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
844 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
845 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
846 assert(CHAR_UNDER == CharInfo[(int)'_']);
847 assert(CHAR_PERIOD == CharInfo[(int)'.']);
848 for (unsigned i = 'a'; i <= 'z'; ++i) {
849 assert(CHAR_LETTER == CharInfo[i]);
850 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
851 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000853 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000854
Chris Lattner03b98662009-07-07 17:09:54 +0000855 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000856}
857
Chris Lattner03b98662009-07-07 17:09:54 +0000858
Reid Spencer5f016e22007-07-11 17:01:13 +0000859/// isIdentifierBody - Return true if this is the body character of an
860/// identifier, which is [a-zA-Z0-9_].
861static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000862 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000863}
864
865/// isHorizontalWhitespace - Return true if this character is horizontal
866/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
867static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000868 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000869}
870
Anna Zaksaca25bc2011-07-27 21:43:43 +0000871/// isVerticalWhitespace - Return true if this character is vertical
872/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
873static inline bool isVerticalWhitespace(unsigned char c) {
874 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
875}
876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877/// isWhitespace - Return true if this character is horizontal or vertical
878/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
879/// for '\0'.
880static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000881 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000882}
883
884/// isNumberBody - Return true if this is the body character of an
885/// preprocessing number, which is [a-zA-Z0-9_.].
886static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000887 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000888 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000889}
890
891
892//===----------------------------------------------------------------------===//
893// Diagnostics forwarding code.
894//===----------------------------------------------------------------------===//
895
Chris Lattner409a0362007-07-22 18:38:25 +0000896/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000897/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000898/// This is currently only used for _Pragma implementation, so it is the slow
899/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000900static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
901 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000902static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
903 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000904 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000905 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner409a0362007-07-22 18:38:25 +0000907 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000908 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000909 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000910 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chandler Carruth433db062011-07-14 08:20:40 +0000912 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000913 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000914 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000915 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattnere7fb4842009-02-15 20:52:18 +0000917 // Figure out the expansion loc range, which is the range covered by the
918 // original _Pragma(...) sequence.
919 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000920 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chandler Carruthbf340e42011-07-26 03:03:05 +0000922 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000923}
924
Reid Spencer5f016e22007-07-11 17:01:13 +0000925/// getSourceLocation - Return a source location identifier for the specified
926/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000927SourceLocation Lexer::getSourceLocation(const char *Loc,
928 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000929 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000931
932 // In the normal case, we're just lexing from a simple file buffer, return
933 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000934 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000935 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000936 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner2b2453a2009-01-17 06:22:33 +0000938 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
939 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000940 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000941 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000942}
943
Reid Spencer5f016e22007-07-11 17:01:13 +0000944/// Diag - Forwarding function for diagnostics. This translate a source
945/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000946DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000947 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000948}
Reid Spencer5f016e22007-07-11 17:01:13 +0000949
950//===----------------------------------------------------------------------===//
951// Trigraph and Escaped Newline Handling Code.
952//===----------------------------------------------------------------------===//
953
954/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
955/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
956static char GetTrigraphCharForLetter(char Letter) {
957 switch (Letter) {
958 default: return 0;
959 case '=': return '#';
960 case ')': return ']';
961 case '(': return '[';
962 case '!': return '|';
963 case '\'': return '^';
964 case '>': return '}';
965 case '/': return '\\';
966 case '<': return '{';
967 case '-': return '~';
968 }
969}
970
971/// DecodeTrigraphChar - If the specified character is a legal trigraph when
972/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
973/// return the result character. Finally, emit a warning about trigraph use
974/// whether trigraphs are enabled or not.
975static char DecodeTrigraphChar(const char *CP, Lexer *L) {
976 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000977 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattner3692b092008-11-18 07:59:24 +0000979 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000980 if (!L->isLexingRawMode())
981 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000982 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner74d15df2008-11-22 02:02:22 +0000985 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000986 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 return Res;
988}
989
Chris Lattner24f0e482009-04-18 22:05:41 +0000990/// getEscapedNewLineSize - Return the size of the specified escaped newline,
991/// 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 +0000992/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +0000993unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
994 unsigned Size = 0;
995 while (isWhitespace(Ptr[Size])) {
996 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner24f0e482009-04-18 22:05:41 +0000998 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
999 continue;
1000
1001 // If this is a \r\n or \n\r, skip the other half.
1002 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1003 Ptr[Size-1] != Ptr[Size])
1004 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner24f0e482009-04-18 22:05:41 +00001006 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001007 }
1008
Chris Lattner24f0e482009-04-18 22:05:41 +00001009 // Not an escaped newline, must be a \t or something else.
1010 return 0;
1011}
1012
Chris Lattner03374952009-04-18 22:27:02 +00001013/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1014/// them), skip over them and return the first non-escaped-newline found,
1015/// otherwise return P.
1016const char *Lexer::SkipEscapedNewLines(const char *P) {
1017 while (1) {
1018 const char *AfterEscape;
1019 if (*P == '\\') {
1020 AfterEscape = P+1;
1021 } else if (*P == '?') {
1022 // If not a trigraph for escape, bail out.
1023 if (P[1] != '?' || P[2] != '/')
1024 return P;
1025 AfterEscape = P+3;
1026 } else {
1027 return P;
1028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Chris Lattner03374952009-04-18 22:27:02 +00001030 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1031 if (NewLineSize == 0) return P;
1032 P = AfterEscape+NewLineSize;
1033 }
1034}
1035
Anna Zaksaca25bc2011-07-27 21:43:43 +00001036/// \brief Checks that the given token is the first token that occurs after the
1037/// given location (this excludes comments and whitespace). Returns the location
1038/// immediately after the specified token. If the token is not found or the
1039/// location is inside a macro, the returned source location will be invalid.
1040SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1041 tok::TokenKind TKind,
1042 const SourceManager &SM,
1043 const LangOptions &LangOpts,
1044 bool SkipTrailingWhitespaceAndNewLine) {
1045 if (Loc.isMacroID()) {
1046 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1047 return SourceLocation();
1048 Loc = SM.getExpansionRange(Loc).second;
1049 }
1050 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1051
1052 // Break down the source location.
1053 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1054
1055 // Try to load the file buffer.
1056 bool InvalidTemp = false;
1057 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1058 if (InvalidTemp)
1059 return SourceLocation();
1060
1061 const char *TokenBegin = File.data() + LocInfo.second;
1062
1063 // Lex from the start of the given location.
1064 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1065 TokenBegin, File.end());
1066 // Find the token.
1067 Token Tok;
1068 lexer.LexFromRawLexer(Tok);
1069 if (Tok.isNot(TKind))
1070 return SourceLocation();
1071 SourceLocation TokenLoc = Tok.getLocation();
1072
1073 // Calculate how much whitespace needs to be skipped if any.
1074 unsigned NumWhitespaceChars = 0;
1075 if (SkipTrailingWhitespaceAndNewLine) {
1076 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1077 Tok.getLength();
1078 unsigned char C = *TokenEnd;
1079 while (isHorizontalWhitespace(C)) {
1080 C = *(++TokenEnd);
1081 NumWhitespaceChars++;
1082 }
1083 if (isVerticalWhitespace(C))
1084 NumWhitespaceChars++;
1085 }
1086
1087 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1088}
Chris Lattner24f0e482009-04-18 22:05:41 +00001089
Reid Spencer5f016e22007-07-11 17:01:13 +00001090/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1091/// get its size, and return it. This is tricky in several cases:
1092/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1093/// then either return the trigraph (skipping 3 chars) or the '?',
1094/// depending on whether trigraphs are enabled or not.
1095/// 2. If this is an escaped newline (potentially with whitespace between
1096/// the backslash and newline), implicitly skip the newline and return
1097/// the char after it.
1098/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1099///
1100/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1101/// know that we can accumulate into Size, and that we have already incremented
1102/// Ptr by Size bytes.
1103///
1104/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1105/// be updated to match.
1106///
1107char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001108 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // If we have a slash, look for an escaped newline.
1110 if (Ptr[0] == '\\') {
1111 ++Size;
1112 ++Ptr;
1113Slash:
1114 // Common case, backslash-char where the char is not whitespace.
1115 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner5636a3b2009-06-23 05:15:06 +00001117 // See if we have optional whitespace characters between the slash and
1118 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001119 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1120 // Remember that this token needs to be cleaned.
1121 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001122
Chris Lattner24f0e482009-04-18 22:05:41 +00001123 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001124 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001125 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattner24f0e482009-04-18 22:05:41 +00001127 // Found backslash<whitespace><newline>. Parse the char after it.
1128 Size += EscapedNewLineSize;
1129 Ptr += EscapedNewLineSize;
1130 // Use slow version to accumulate a correct size field.
1131 return getCharAndSizeSlow(Ptr, Size, Tok);
1132 }
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // Otherwise, this is not an escaped newline, just return the slash.
1135 return '\\';
1136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 // If this is a trigraph, process it.
1139 if (Ptr[0] == '?' && Ptr[1] == '?') {
1140 // If this is actually a legal trigraph (not something like "??x"), emit
1141 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1142 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1143 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001144 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001145
1146 Ptr += 3;
1147 Size += 3;
1148 if (C == '\\') goto Slash;
1149 return C;
1150 }
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 // If this is neither, return a single character.
1154 ++Size;
1155 return *Ptr;
1156}
1157
1158
1159/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1160/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1161/// and that we have already incremented Ptr by Size bytes.
1162///
1163/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1164/// be updated to match.
1165char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1166 const LangOptions &Features) {
1167 // If we have a slash, look for an escaped newline.
1168 if (Ptr[0] == '\\') {
1169 ++Size;
1170 ++Ptr;
1171Slash:
1172 // Common case, backslash-char where the char is not whitespace.
1173 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001176 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1177 // Found backslash<whitespace><newline>. Parse the char after it.
1178 Size += EscapedNewLineSize;
1179 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Chris Lattner24f0e482009-04-18 22:05:41 +00001181 // Use slow version to accumulate a correct size field.
1182 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1183 }
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 // Otherwise, this is not an escaped newline, just return the slash.
1186 return '\\';
1187 }
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 // If this is a trigraph, process it.
1190 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1191 // If this is actually a legal trigraph (not something like "??x"), return
1192 // it.
1193 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1194 Ptr += 3;
1195 Size += 3;
1196 if (C == '\\') goto Slash;
1197 return C;
1198 }
1199 }
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 // If this is neither, return a single character.
1202 ++Size;
1203 return *Ptr;
1204}
1205
1206//===----------------------------------------------------------------------===//
1207// Helper methods for lexing.
1208//===----------------------------------------------------------------------===//
1209
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001210/// \brief Routine that indiscriminately skips bytes in the source file.
1211void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1212 BufferPtr += Bytes;
1213 if (BufferPtr > BufferEnd)
1214 BufferPtr = BufferEnd;
1215 IsAtStartOfLine = StartOfLine;
1216}
1217
Chris Lattnerd2177732007-07-20 16:59:19 +00001218void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1220 unsigned Size;
1221 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001222 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 --CurPtr; // Back up over the skipped character.
1226
1227 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1228 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1229 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001230 //
1231 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1232 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1234FinishIdentifier:
1235 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001236 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1237 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // If we are in raw mode, return this identifier raw. There is no need to
1240 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001241 if (LexingRawMode)
1242 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001244 // Fill in Result.IdentifierInfo and update the token kind,
1245 // looking up the identifier in the identifier table.
1246 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 // Finally, now that we know we have an identifier, pass this off to the
1249 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001250 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001251 PP->HandleIdentifier(Result);
1252 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 }
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 C = getCharAndSize(CurPtr, Size);
1258 while (1) {
1259 if (C == '$') {
1260 // If we hit a $ and they are not supported in identifiers, we are done.
1261 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001264 if (!isLexingRawMode())
1265 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 CurPtr = ConsumeChar(CurPtr, Size, Result);
1267 C = getCharAndSize(CurPtr, Size);
1268 continue;
1269 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1270 // Found end of identifier.
1271 goto FinishIdentifier;
1272 }
1273
1274 // Otherwise, this character is good, consume it.
1275 CurPtr = ConsumeChar(CurPtr, Size, Result);
1276
1277 C = getCharAndSize(CurPtr, Size);
1278 while (isIdentifierBody(C)) { // FIXME: UCNs.
1279 CurPtr = ConsumeChar(CurPtr, Size, Result);
1280 C = getCharAndSize(CurPtr, Size);
1281 }
1282 }
1283}
1284
Douglas Gregora75ec432010-08-30 14:50:47 +00001285/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001286/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001287static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1288 unsigned Size;
1289 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1290 if (C1 != '0')
1291 return false;
1292 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1293 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001294}
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
Nate Begeman5253c7f2008-04-14 02:26:39 +00001296/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001297/// constant. From[-1] is the first character lexed. Return the end of the
1298/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001299void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 unsigned Size;
1301 char C = getCharAndSize(CurPtr, Size);
1302 char PrevCh = 0;
1303 while (isNumberBody(C)) { // FIXME: UCNs?
1304 CurPtr = ConsumeChar(CurPtr, Size, Result);
1305 PrevCh = C;
1306 C = getCharAndSize(CurPtr, Size);
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001310 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1311 // If we are in Microsoft mode, don't continue if the constant is hex.
1312 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001313 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001314 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1315 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001316
1317 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001318 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001319 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001323 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001324 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001325 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001326}
1327
1328/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001329/// either " or L" or u8" or u" or U".
1330void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1331 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 char C = getAndAdvanceChar(CurPtr, Result);
1335 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001336 // Skip escaped characters. Escaped newlines will already be processed by
1337 // getAndAdvanceChar.
1338 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001340
Chris Lattner571339c2010-05-30 23:27:38 +00001341 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001342 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001343 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1344 PP->CodeCompleteNaturalLanguage();
1345 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001346 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001347 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 }
Chris Lattner571339c2010-05-30 23:27:38 +00001350
1351 if (C == 0)
1352 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 C = getAndAdvanceChar(CurPtr, Result);
1354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001357 if (NulCharacter && !isLexingRawMode())
1358 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001361 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001362 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001363 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001364}
1365
1366/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1367/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001368void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001370 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 char C = getAndAdvanceChar(CurPtr, Result);
1372 while (C != '>') {
1373 // Skip escaped characters.
1374 if (C == '\\') {
1375 // Skip the escaped character.
1376 C = getAndAdvanceChar(CurPtr, Result);
1377 } else if (C == '\n' || C == '\r' || // Newline.
1378 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001379 // If the filename is unterminated, then it must just be a lone <
1380 // character. Return this as such.
1381 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 return;
1383 } else if (C == 0) {
1384 NulCharacter = CurPtr-1;
1385 }
1386 C = getAndAdvanceChar(CurPtr, Result);
1387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001390 if (NulCharacter && !isLexingRawMode())
1391 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001394 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001395 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001396 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001397}
1398
1399
1400/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001401/// lexed either ' or L' or u' or U'.
1402void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1403 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 const char *NulCharacter = 0; // Does this character contain the \0 character?
1405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 char C = getAndAdvanceChar(CurPtr, Result);
1407 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001408 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001409 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001410 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001412 }
1413
1414 while (C != '\'') {
1415 // Skip escaped characters.
1416 if (C == '\\') {
1417 // Skip the escaped character.
1418 // FIXME: UCN's
1419 C = getAndAdvanceChar(CurPtr, Result);
1420 } else if (C == '\n' || C == '\r' || // Newline.
1421 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001422 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1423 PP->CodeCompleteNaturalLanguage();
1424 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001425 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001426 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1427 return;
1428 } else if (C == 0) {
1429 NulCharacter = CurPtr-1;
1430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 C = getAndAdvanceChar(CurPtr, Result);
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Chris Lattnerd80f7862010-07-07 23:24:27 +00001434 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001435 if (NulCharacter && !isLexingRawMode())
1436 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001439 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001440 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001441 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001442}
1443
1444/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1445/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001446///
1447/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1448///
1449bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // Whitespace - Skip it, then return the token after the whitespace.
1451 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1452 while (1) {
1453 // Skip horizontal whitespace very aggressively.
1454 while (isHorizontalWhitespace(Char))
1455 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001457 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 if (Char != '\n' && Char != '\r')
1459 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 if (ParsingPreprocessorDirective) {
1462 // End of preprocessor directive line, let LexTokenInternal handle this.
1463 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001464 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // ok, but handle newline.
1468 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001469 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001471 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 Char = *++CurPtr;
1473 }
1474
1475 // If this isn't immediately after a newline, there is leading space.
1476 char PrevChar = CurPtr[-1];
1477 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001478 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001479
Chris Lattnerd88dc482008-10-12 04:05:48 +00001480 // If the client wants us to return whitespace, return it now.
1481 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001482 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001483 return true;
1484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001487 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001488}
1489
1490// SkipBCPLComment - We have just read the // characters from input. Skip until
1491// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001492/// BufferPtr and return.
1493///
1494/// If we're in KeepCommentMode or any CommentHandler has inserted
1495/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001496bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // If BCPL comments aren't explicitly enabled for this language, emit an
1498 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001499 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // Mark them enabled so we only emit one warning for this translation
1503 // unit.
1504 Features.BCPLComment = true;
1505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 // Scan over the body of the comment. The common case, when scanning, is that
1508 // the comment contains normal ascii characters with nothing interesting in
1509 // them. As such, optimize for this case with the inner loop.
1510 char C;
1511 do {
1512 C = *CurPtr;
1513 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1514 // If we find a \n character, scan backwards, checking to see if it's an
1515 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 // Skip over characters in the fast loop.
1518 while (C != 0 && // Potentially EOF.
1519 C != '\\' && // Potentially escaped newline.
1520 C != '?' && // Potentially trigraph.
1521 C != '\n' && C != '\r') // Newline or DOS-style newline.
1522 C = *++CurPtr;
1523
1524 // If this is a newline, we're done.
1525 if (C == '\n' || C == '\r')
1526 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001529 // properly decode the character. Read it in raw mode to avoid emitting
1530 // diagnostics about things like trigraphs. If we see an escaped newline,
1531 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001533 bool OldRawMode = isLexingRawMode();
1534 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001536 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001537
1538 // If the char that we finally got was a \n, then we must have had something
1539 // like \<newline><newline>. We don't want to have consumed the second
1540 // newline, we want CurPtr, to end up pointing to it down below.
1541 if (C == '\n' || C == '\r') {
1542 --CurPtr;
1543 C = 'x'; // doesn't matter what this is.
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 // If we read multiple characters, and one of those characters was a \r or
1547 // \n, then we had an escaped newline within the comment. Emit diagnostic
1548 // unless the next line is also a // comment.
1549 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1550 for (; OldPtr != CurPtr; ++OldPtr)
1551 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1552 // Okay, we found a // comment that ends in a newline, if the next
1553 // line is also a // comment, but has spaces, don't emit a diagnostic.
1554 if (isspace(C)) {
1555 const char *ForwardPtr = CurPtr;
1556 while (isspace(*ForwardPtr)) // Skip whitespace.
1557 ++ForwardPtr;
1558 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1559 break;
1560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Chris Lattner74d15df2008-11-22 02:02:22 +00001562 if (!isLexingRawMode())
1563 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 break;
1565 }
1566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Douglas Gregor55817af2010-08-25 17:04:25 +00001568 if (CurPtr == BufferEnd+1) {
1569 if (PP && PP->isCodeCompletionFile(FileLoc))
1570 PP->CodeCompleteNaturalLanguage();
1571
1572 --CurPtr;
1573 break;
1574 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 } while (C != '\n' && C != '\r');
1576
Chris Lattner3d0ad582010-02-03 21:06:21 +00001577 // Found but did not consume the newline. Notify comment handlers about the
1578 // comment unless we're in a #if 0 block.
1579 if (PP && !isLexingRawMode() &&
1580 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1581 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001582 BufferPtr = CurPtr;
1583 return true; // A token has to be returned.
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001587 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 return SaveBCPLComment(Result, CurPtr);
1589
1590 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001591 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1593 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001594 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 }
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001598 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001599 // contribute to another token), it isn't needed for correctness. Note that
1600 // this is ok even in KeepWhitespaceMode, because we would have returned the
1601 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001605 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001607 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001609 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001610}
1611
1612/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1613/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001614bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001615 // If we're not in a preprocessor directive, just return the // comment
1616 // directly.
1617 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattner9e6293d2008-10-12 04:51:35 +00001619 if (!ParsingPreprocessorDirective)
1620 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Chris Lattner9e6293d2008-10-12 04:51:35 +00001622 // If this BCPL-style comment is in a macro definition, transmogrify it into
1623 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001624 bool Invalid = false;
1625 std::string Spelling = PP->getSpelling(Result, &Invalid);
1626 if (Invalid)
1627 return true;
1628
Chris Lattner9e6293d2008-10-12 04:51:35 +00001629 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1630 Spelling[1] = '*'; // Change prefix to "/*".
1631 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner9e6293d2008-10-12 04:51:35 +00001633 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001634 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1635 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001636 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001637}
1638
1639/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1640/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001641/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001642static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 Lexer *L) {
1644 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // Back up off the newline.
1647 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 // If this is a two-character newline sequence, skip the other character.
1650 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1651 // \n\n or \r\r -> not escaped newline.
1652 if (CurPtr[0] == CurPtr[1])
1653 return false;
1654 // \n\r or \r\n -> skip the newline.
1655 --CurPtr;
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // If we have horizontal whitespace, skip over it. We allow whitespace
1659 // between the slash and newline.
1660 bool HasSpace = false;
1661 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1662 --CurPtr;
1663 HasSpace = true;
1664 }
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // If we have a slash, we know this is an escaped newline.
1667 if (*CurPtr == '\\') {
1668 if (CurPtr[-1] != '*') return false;
1669 } else {
1670 // It isn't a slash, is it the ?? / trigraph?
1671 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1672 CurPtr[-3] != '*')
1673 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 // This is the trigraph ending the comment. Emit a stern warning!
1676 CurPtr -= 2;
1677
1678 // If no trigraphs are enabled, warn that we ignored this trigraph and
1679 // ignore this * character.
1680 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001681 if (!L->isLexingRawMode())
1682 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 return false;
1684 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001685 if (!L->isLexingRawMode())
1686 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001690 if (!L->isLexingRawMode())
1691 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001694 if (HasSpace && !L->isLexingRawMode())
1695 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 return true;
1698}
1699
1700#ifdef __SSE2__
1701#include <emmintrin.h>
1702#elif __ALTIVEC__
1703#include <altivec.h>
1704#undef bool
1705#endif
1706
1707/// SkipBlockComment - We have just read the /* characters from input. Read
1708/// until we find the */ characters that terminate the comment. Note that we
1709/// don't bother decoding trigraphs or escaped newlines in block comments,
1710/// because they cannot cause the comment to end. The only thing that can
1711/// happen is the comment could end with an escaped newline between the */ end
1712/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001713///
Chris Lattner046c2272010-01-18 22:35:47 +00001714/// If we're in KeepCommentMode or any CommentHandler has inserted
1715/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001716bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001718 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 // optimization helps people who like to put a lot of * characters in their
1720 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001721
1722 // The first character we get with newlines and trigraphs skipped to handle
1723 // the degenerate /*/ case below correctly if the * has an escaped newline
1724 // after it.
1725 unsigned CharSize;
1726 unsigned char C = getCharAndSize(CurPtr, CharSize);
1727 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001729 if (!isLexingRawMode() &&
1730 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001731 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001732 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattner31f0eca2008-10-12 04:19:49 +00001734 // KeepWhitespaceMode should return this broken comment as a token. Since
1735 // it isn't a well formed comment, just return it as an 'unknown' token.
1736 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001737 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001738 return true;
1739 }
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Chris Lattner31f0eca2008-10-12 04:19:49 +00001741 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001742 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 }
Mike Stump1eb44332009-09-09 15:08:12 +00001744
Chris Lattner8146b682007-07-21 23:43:37 +00001745 // Check to see if the first character after the '/*' is another /. If so,
1746 // then this slash does not end the block comment, it is part of it.
1747 if (C == '/')
1748 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 while (1) {
1751 // Skip over all non-interesting characters until we find end of buffer or a
1752 // (probably ending) '/' character.
1753 if (CurPtr + 24 < BufferEnd) {
1754 // While not aligned to a 16-byte boundary.
1755 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1756 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 if (C == '/') goto FoundSlash;
1759
1760#ifdef __SSE2__
1761 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1762 '/', '/', '/', '/', '/', '/', '/', '/');
1763 while (CurPtr+16 <= BufferEnd &&
1764 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1765 CurPtr += 16;
1766#elif __ALTIVEC__
1767 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001768 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 '/', '/', '/', '/', '/', '/', '/', '/'
1770 };
1771 while (CurPtr+16 <= BufferEnd &&
1772 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1773 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001774#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 // Scan for '/' quickly. Many block comments are very large.
1776 while (CurPtr[0] != '/' &&
1777 CurPtr[1] != '/' &&
1778 CurPtr[2] != '/' &&
1779 CurPtr[3] != '/' &&
1780 CurPtr+4 < BufferEnd) {
1781 CurPtr += 4;
1782 }
1783#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 // It has to be one of the bytes scanned, increment to it and read one.
1786 C = *CurPtr++;
1787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // Loop to scan the remainder.
1790 while (C != '/' && C != '\0')
1791 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 FoundSlash:
1794 if (C == '/') {
1795 if (CurPtr[-2] == '*') // We found the final */. We're done!
1796 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1799 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1800 // We found the final */, though it had an escaped newline between the
1801 // * and /. We're done!
1802 break;
1803 }
1804 }
1805 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1806 // If this is a /* inside of the comment, emit a warning. Don't do this
1807 // if this is a /*/, which will end the comment. This misses cases with
1808 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001809 if (!isLexingRawMode())
1810 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 }
1812 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001813 if (PP && PP->isCodeCompletionFile(FileLoc))
1814 PP->CodeCompleteNaturalLanguage();
1815 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001816 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 // Note: the user probably forgot a */. We could continue immediately
1818 // after the /*, but this would involve lexing a lot of what really is the
1819 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001820 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Chris Lattner31f0eca2008-10-12 04:19:49 +00001822 // KeepWhitespaceMode should return this broken comment as a token. Since
1823 // it isn't a well formed comment, just return it as an 'unknown' token.
1824 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001825 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001826 return true;
1827 }
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Chris Lattner31f0eca2008-10-12 04:19:49 +00001829 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001830 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 }
1832 C = *CurPtr++;
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Chris Lattner3d0ad582010-02-03 21:06:21 +00001835 // Notify comment handlers about the comment unless we're in a #if 0 block.
1836 if (PP && !isLexingRawMode() &&
1837 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1838 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001839 BufferPtr = CurPtr;
1840 return true; // A token has to be returned.
1841 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001842
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001844 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001845 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001846 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 }
1848
1849 // It is common for the tokens immediately after a /**/ comment to be
1850 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001851 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1852 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001854 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001856 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 }
1858
1859 // Otherwise, just return so that the next character will be lexed as a token.
1860 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001861 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001862 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001863}
1864
1865//===----------------------------------------------------------------------===//
1866// Primary Lexing Entry Points
1867//===----------------------------------------------------------------------===//
1868
Reid Spencer5f016e22007-07-11 17:01:13 +00001869/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1870/// uninterpreted string. This switches the lexer out of directive mode.
1871std::string Lexer::ReadToEndOfLine() {
1872 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1873 "Must be in a preprocessing directive!");
1874 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001875 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001876
1877 // CurPtr - Cache BufferPtr in an automatic variable.
1878 const char *CurPtr = BufferPtr;
1879 while (1) {
1880 char Char = getAndAdvanceChar(CurPtr, Tmp);
1881 switch (Char) {
1882 default:
1883 Result += Char;
1884 break;
1885 case 0: // Null.
1886 // Found end of file?
1887 if (CurPtr-1 != BufferEnd) {
1888 // Nope, normal character, continue.
1889 Result += Char;
1890 break;
1891 }
1892 // FALL THROUGH.
1893 case '\r':
1894 case '\n':
1895 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1896 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1897 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Peter Collingbourne84021552011-02-28 02:37:51 +00001899 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001901 if (Tmp.is(tok::code_completion)) {
1902 if (PP && PP->getCodeCompletionHandler())
1903 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1904 Lex(Tmp);
1905 }
Peter Collingbourne84021552011-02-28 02:37:51 +00001906 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Finally, we're done, return the string we found.
1909 return Result;
1910 }
1911 }
1912}
1913
1914/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1915/// condition, reporting diagnostics and handling other edge cases as required.
1916/// This returns true if Result contains a token, false if PP.Lex should be
1917/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00001918bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00001919 // Check if we are performing code completion.
1920 if (PP && PP->isCodeCompletionFile(FileLoc)) {
1921 // We're at the end of the file, but we've been asked to consider the
1922 // end of the file to be a code-completion token. Return the
1923 // code-completion token.
1924 Result.startToken();
1925 FormTokenWithChars(Result, CurPtr, tok::code_completion);
1926
1927 // Only do the eof -> code_completion translation once.
1928 PP->SetCodeCompletionPoint(0, 0, 0);
1929
1930 // Silence any diagnostics that occur once we hit the code-completion point.
1931 PP->getDiagnostics().setSuppressAllDiagnostics(true);
1932 return true;
1933 }
1934
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 // If we hit the end of the file while parsing a preprocessor directive,
1936 // end the preprocessor directive first. The next token returned will
1937 // then be the end of file.
1938 if (ParsingPreprocessorDirective) {
1939 // Done parsing the "line".
1940 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00001942 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00001945 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00001947 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001948
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 // If we are in raw mode, return this event as an EOF token. Let the caller
1950 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00001951 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 Result.startToken();
1953 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001954 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 return true;
1956 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00001957
Douglas Gregorf44e8542010-08-24 19:08:16 +00001958 // Issue diagnostics for unterminated #if and missing newline.
1959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // If we are in a #if directive, emit an error.
1961 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00001962 if (!PP->isCodeCompletionFile(FileLoc))
1963 PP->Diag(ConditionalStack.back().IfLoc,
1964 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 ConditionalStack.pop_back();
1966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Chris Lattnerb25e5d72008-04-12 05:54:25 +00001968 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
1969 // a pedwarn.
1970 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00001971 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00001972 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 BufferPtr = CurPtr;
1975
1976 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001977 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001978}
1979
1980/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
1981/// the specified lexer will return a tok::l_paren token, 0 if it is something
1982/// else and 2 if there are no more tokens in the buffer controlled by the
1983/// lexer.
1984unsigned Lexer::isNextPPTokenLParen() {
1985 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 // Switch to 'skipping' mode. This will ensure that we can lex a token
1988 // without emitting diagnostics, disables macro expansion, and will cause EOF
1989 // to return an EOF token instead of popping the include stack.
1990 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 // Save state that can be changed while lexing so that we can restore it.
1993 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00001994 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattnerd2177732007-07-20 16:59:19 +00001996 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 Tok.startToken();
1998 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 // Restore state that may have changed.
2001 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002002 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // Restore the lexer back to non-skipping mode.
2005 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002007 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002009 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002010}
2011
Chris Lattner34f349d2009-12-14 06:16:57 +00002012/// FindConflictEnd - Find the end of a version control conflict marker.
2013static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002014 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002015 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002017 // Must occur at start of line.
2018 if (RestOfBuffer[Pos-1] != '\r' &&
2019 RestOfBuffer[Pos-1] != '\n') {
2020 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002021 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002022 continue;
2023 }
2024 return RestOfBuffer.data()+Pos;
2025 }
2026 return 0;
2027}
2028
2029/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2030/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2031/// and recover nicely. This returns true if it is a conflict marker and false
2032/// if not.
2033bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2034 // Only a conflict marker if it starts at the beginning of a line.
2035 if (CurPtr != BufferStart &&
2036 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2037 return false;
2038
2039 // Check to see if we have <<<<<<<.
2040 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002041 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002042 return false;
2043
2044 // If we have a situation where we don't care about conflict markers, ignore
2045 // it.
2046 if (IsInConflictMarker || isLexingRawMode())
2047 return false;
2048
2049 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2050 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002051 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002052 // We found a match. We are really in a conflict marker.
2053 // Diagnose this, and ignore to the end of line.
2054 Diag(CurPtr, diag::err_conflict_marker);
2055 IsInConflictMarker = true;
2056
2057 // Skip ahead to the end of line. We know this exists because the
2058 // end-of-conflict marker starts with \r or \n.
2059 while (*CurPtr != '\r' && *CurPtr != '\n') {
2060 assert(CurPtr != BufferEnd && "Didn't find end of line");
2061 ++CurPtr;
2062 }
2063 BufferPtr = CurPtr;
2064 return true;
2065 }
2066
2067 // No end of conflict marker found.
2068 return false;
2069}
2070
2071
2072/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2073/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2074/// until the end of the line. This returns true if it is a conflict marker and
2075/// false if not.
2076bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2077 // Only a conflict marker if it starts at the beginning of a line.
2078 if (CurPtr != BufferStart &&
2079 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2080 return false;
2081
2082 // If we have a situation where we don't care about conflict markers, ignore
2083 // it.
2084 if (!IsInConflictMarker || isLexingRawMode())
2085 return false;
2086
2087 // Check to see if we have the marker (7 characters in a row).
2088 for (unsigned i = 1; i != 7; ++i)
2089 if (CurPtr[i] != CurPtr[0])
2090 return false;
2091
2092 // If we do have it, search for the end of the conflict marker. This could
2093 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2094 // be the end of conflict marker.
2095 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2096 CurPtr = End;
2097
2098 // Skip ahead to the end of line.
2099 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2100 ++CurPtr;
2101
2102 BufferPtr = CurPtr;
2103
2104 // No longer in the conflict marker.
2105 IsInConflictMarker = false;
2106 return true;
2107 }
2108
2109 return false;
2110}
2111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112
2113/// LexTokenInternal - This implements a simple C family lexer. It is an
2114/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002115/// has a null character at the end of the file. This returns a preprocessing
2116/// token, not a normal token, as such, it is an internal interface. It assumes
2117/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002118void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002119LexNextToken:
2120 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002121 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 // CurPtr - Cache BufferPtr in an automatic variable.
2125 const char *CurPtr = BufferPtr;
2126
2127 // Small amounts of horizontal whitespace is very common between tokens.
2128 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2129 ++CurPtr;
2130 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2131 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Chris Lattnerd88dc482008-10-12 04:05:48 +00002133 // If we are keeping whitespace and other tokens, just return what we just
2134 // skipped. The next lexer invocation will return the token after the
2135 // whitespace.
2136 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002137 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002138 return;
2139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002142 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 }
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 // Read a character, advancing over it.
2148 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002149 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 switch (Char) {
2152 case 0: // Null.
2153 // Found end of file?
2154 if (CurPtr-1 == BufferEnd) {
2155 // Read the PP instance variable into an automatic variable, because
2156 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002157 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2159 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002160 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2161 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Chris Lattner74d15df2008-11-22 02:02:22 +00002164 if (!isLexingRawMode())
2165 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002166 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002167 if (SkipWhitespace(Result, CurPtr))
2168 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002171
2172 case 26: // DOS & CP/M EOF: "^Z".
2173 // If we're in Microsoft extensions mode, treat this as end of file.
2174 if (Features.Microsoft) {
2175 // Read the PP instance variable into an automatic variable, because
2176 // LexEndOfFile will often delete 'this'.
2177 Preprocessor *PPCache = PP;
2178 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2179 return; // Got a token to return.
2180 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2181 return PPCache->Lex(Result);
2182 }
2183 // If Microsoft extensions are disabled, this is just random garbage.
2184 Kind = tok::unknown;
2185 break;
2186
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 case '\n':
2188 case '\r':
2189 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002190 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002191 if (ParsingPreprocessorDirective) {
2192 // Done parsing the "line".
2193 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002196 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // Since we consumed a newline, we are back at the start of a line.
2199 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Peter Collingbourne84021552011-02-28 02:37:51 +00002201 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 break;
2203 }
2204 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002205 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002207 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Chris Lattnerd88dc482008-10-12 04:05:48 +00002209 if (SkipWhitespace(Result, CurPtr))
2210 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 goto LexNextToken; // GCC isn't tail call eliminating.
2212 case ' ':
2213 case '\t':
2214 case '\f':
2215 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002216 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002217 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002218 if (SkipWhitespace(Result, CurPtr))
2219 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002220
2221 SkipIgnoredUnits:
2222 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Chris Lattner8133cfc2007-07-22 06:29:05 +00002224 // If the next token is obviously a // or /* */ comment, skip it efficiently
2225 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002226 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002227 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002228 if (SkipBCPLComment(Result, CurPtr+2))
2229 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002230 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002231 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002232 if (SkipBlockComment(Result, CurPtr+2))
2233 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002234 goto SkipIgnoredUnits;
2235 } else if (isHorizontalWhitespace(*CurPtr)) {
2236 goto SkipHorizontalWhitespace;
2237 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002239
Chris Lattner3a570772008-01-03 17:58:54 +00002240 // C99 6.4.4.1: Integer Constants.
2241 // C99 6.4.4.2: Floating Constants.
2242 case '0': case '1': case '2': case '3': case '4':
2243 case '5': case '6': case '7': case '8': case '9':
2244 // Notify MIOpt that we read a non-whitespace/non-comment token.
2245 MIOpt.ReadToken();
2246 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Douglas Gregor5cee1192011-07-27 05:40:30 +00002248 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2249 // Notify MIOpt that we read a non-whitespace/non-comment token.
2250 MIOpt.ReadToken();
2251
2252 if (Features.CPlusPlus0x) {
2253 Char = getCharAndSize(CurPtr, SizeTmp);
2254
2255 // UTF-16 string literal
2256 if (Char == '"')
2257 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2258 tok::utf16_string_literal);
2259
2260 // UTF-16 character constant
2261 if (Char == '\'')
2262 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2263 tok::utf16_char_constant);
2264
2265 // UTF-8 string literal
2266 if (Char == '8' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2267 return LexStringLiteral(Result,
2268 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2269 SizeTmp2, Result),
2270 tok::utf8_string_literal);
2271 }
2272
2273 // treat u like the start of an identifier.
2274 return LexIdentifier(Result, CurPtr);
2275
2276 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2277 // Notify MIOpt that we read a non-whitespace/non-comment token.
2278 MIOpt.ReadToken();
2279
2280 if (Features.CPlusPlus0x) {
2281 Char = getCharAndSize(CurPtr, SizeTmp);
2282
2283 // UTF-32 string literal
2284 if (Char == '"')
2285 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2286 tok::utf32_string_literal);
2287
2288 // UTF-32 character constant
2289 if (Char == '\'')
2290 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2291 tok::utf32_char_constant);
2292 }
2293
2294 // treat U like the start of an identifier.
2295 return LexIdentifier(Result, CurPtr);
2296
Chris Lattner3a570772008-01-03 17:58:54 +00002297 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 // Notify MIOpt that we read a non-whitespace/non-comment token.
2299 MIOpt.ReadToken();
2300 Char = getCharAndSize(CurPtr, SizeTmp);
2301
2302 // Wide string literal.
2303 if (Char == '"')
2304 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002305 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002306
2307 // Wide character constant.
2308 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002309 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2310 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 // C99 6.4.2: Identifiers.
2314 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2315 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002316 case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2318 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2319 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002320 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 case 'v': case 'w': case 'x': case 'y': case 'z':
2322 case '_':
2323 // Notify MIOpt that we read a non-whitespace/non-comment token.
2324 MIOpt.ReadToken();
2325 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002326
2327 case '$': // $ in identifiers.
2328 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002329 if (!isLexingRawMode())
2330 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002331 // Notify MIOpt that we read a non-whitespace/non-comment token.
2332 MIOpt.ReadToken();
2333 return LexIdentifier(Result, CurPtr);
2334 }
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Chris Lattner9e6293d2008-10-12 04:51:35 +00002336 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002337 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 // C99 6.4.4: Character Constants.
2340 case '\'':
2341 // Notify MIOpt that we read a non-whitespace/non-comment token.
2342 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002343 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002344
2345 // C99 6.4.5: String Literals.
2346 case '"':
2347 // Notify MIOpt that we read a non-whitespace/non-comment token.
2348 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002349 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002350
2351 // C99 6.4.6: Punctuators.
2352 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002353 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 break;
2355 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002356 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 break;
2358 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002359 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 break;
2361 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002362 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 break;
2364 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002365 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 break;
2367 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002368 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 break;
2370 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002371 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 break;
2373 case '.':
2374 Char = getCharAndSize(CurPtr, SizeTmp);
2375 if (Char >= '0' && Char <= '9') {
2376 // Notify MIOpt that we read a non-whitespace/non-comment token.
2377 MIOpt.ReadToken();
2378
2379 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2380 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002381 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 CurPtr += SizeTmp;
2383 } else if (Char == '.' &&
2384 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002385 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2387 SizeTmp2, Result);
2388 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002389 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002390 }
2391 break;
2392 case '&':
2393 Char = getCharAndSize(CurPtr, SizeTmp);
2394 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002395 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002396 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2397 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002398 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2400 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002401 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 }
2403 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002404 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002405 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002406 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2408 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002409 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 }
2411 break;
2412 case '+':
2413 Char = getCharAndSize(CurPtr, SizeTmp);
2414 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002416 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002417 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002418 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002419 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002421 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 }
2423 break;
2424 case '-':
2425 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002426 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002428 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002429 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002430 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2432 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002433 Kind = tok::arrowstar;
2434 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002436 Kind = tok::arrow;
2437 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002438 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002439 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002440 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002441 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002442 }
2443 break;
2444 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002445 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 break;
2447 case '!':
2448 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002449 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2451 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002452 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002453 }
2454 break;
2455 case '/':
2456 // 6.4.9: Comments
2457 Char = getCharAndSize(CurPtr, SizeTmp);
2458 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002459 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2460 // want to lex this as a comment. There is one problem with this though,
2461 // that in one particular corner case, this can change the behavior of the
2462 // resultant program. For example, In "foo //**/ bar", C89 would lex
2463 // this as "foo / bar" and langauges with BCPL comments would lex it as
2464 // "foo". Check to see if the character after the second slash is a '*'.
2465 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002466 // However, we never do this in -traditional-cpp mode.
2467 if ((Features.BCPLComment ||
2468 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2469 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002470 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002471 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Chris Lattner8402c732009-01-16 22:39:25 +00002473 // It is common for the tokens immediately after a // comment to be
2474 // whitespace (indentation for the next line). Instead of going through
2475 // the big switch, handle it efficiently now.
2476 goto SkipIgnoredUnits;
2477 }
2478 }
Mike Stump1eb44332009-09-09 15:08:12 +00002479
Chris Lattner8402c732009-01-16 22:39:25 +00002480 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002481 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002482 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002483 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002484 }
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Chris Lattner8402c732009-01-16 22:39:25 +00002486 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002488 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002489 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002490 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 }
2492 break;
2493 case '%':
2494 Char = getCharAndSize(CurPtr, SizeTmp);
2495 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002496 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2498 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002499 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2501 } else if (Features.Digraphs && Char == ':') {
2502 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2503 Char = getCharAndSize(CurPtr, SizeTmp);
2504 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002505 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2507 SizeTmp2, Result);
2508 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002510 if (!isLexingRawMode())
2511 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002512 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002513 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 // We parsed a # character. If this occurs at the start of the line,
2515 // it's actually the start of a preprocessing directive. Callback to
2516 // the preprocessor to handle it.
2517 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002518 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002519 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002520 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Reid Spencer5f016e22007-07-11 17:01:13 +00002522 // As an optimization, if the preprocessor didn't switch lexers, tail
2523 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002524 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 // Start a new token. If this is a #include or something, the PP may
2526 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002527 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002529 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002530 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 IsAtStartOfLine = false;
2532 }
2533 goto LexNextToken; // GCC isn't tail call eliminating.
2534 }
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Chris Lattner168ae2d2007-10-17 20:41:00 +00002536 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 }
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnere91e9322009-03-18 20:58:27 +00002539 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002540 }
2541 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002542 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 }
2544 break;
2545 case '<':
2546 Char = getCharAndSize(CurPtr, SizeTmp);
2547 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002548 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002549 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002550 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2551 if (After == '=') {
2552 Kind = tok::lesslessequal;
2553 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2554 SizeTmp2, Result);
2555 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2556 // If this is actually a '<<<<<<<' version control conflict marker,
2557 // recognize it as such and recover nicely.
2558 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002559 } else if (Features.CUDA && After == '<') {
2560 Kind = tok::lesslessless;
2561 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2562 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002563 } else {
2564 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2565 Kind = tok::lessless;
2566 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002569 Kind = tok::lessequal;
2570 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002571 if (Features.CPlusPlus0x &&
2572 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2573 // C++0x [lex.pptoken]p3:
2574 // Otherwise, if the next three characters are <:: and the subsequent
2575 // character is neither : nor >, the < is treated as a preprocessor
2576 // token by itself and not as the first character of the alternative
2577 // token <:.
2578 unsigned SizeTmp3;
2579 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2580 if (After != ':' && After != '>') {
2581 Kind = tok::less;
2582 break;
2583 }
2584 }
2585
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002587 Kind = tok::l_square;
2588 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002590 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002592 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 }
2594 break;
2595 case '>':
2596 Char = getCharAndSize(CurPtr, SizeTmp);
2597 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002599 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002601 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2602 if (After == '=') {
2603 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2604 SizeTmp2, Result);
2605 Kind = tok::greatergreaterequal;
2606 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2607 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2608 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002609 } else if (Features.CUDA && After == '>') {
2610 Kind = tok::greatergreatergreater;
2611 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2612 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002613 } else {
2614 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2615 Kind = tok::greatergreater;
2616 }
2617
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002619 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 }
2621 break;
2622 case '^':
2623 Char = getCharAndSize(CurPtr, SizeTmp);
2624 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002625 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002626 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002628 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 }
2630 break;
2631 case '|':
2632 Char = getCharAndSize(CurPtr, SizeTmp);
2633 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002634 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2636 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002637 // If this is '|||||||' and we're in a conflict marker, ignore it.
2638 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2639 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002640 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2642 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002643 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 }
2645 break;
2646 case ':':
2647 Char = getCharAndSize(CurPtr, SizeTmp);
2648 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002649 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2651 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002652 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002654 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002655 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 }
2657 break;
2658 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002659 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 break;
2661 case '=':
2662 Char = getCharAndSize(CurPtr, SizeTmp);
2663 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002664 // If this is '=======' and we're in a conflict marker, ignore it.
2665 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2666 goto LexNextToken;
2667
Chris Lattner9e6293d2008-10-12 04:51:35 +00002668 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002670 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002671 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 }
2673 break;
2674 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002675 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 break;
2677 case '#':
2678 Char = getCharAndSize(CurPtr, SizeTmp);
2679 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002680 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2682 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002683 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002684 if (!isLexingRawMode())
2685 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2687 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 // We parsed a # character. If this occurs at the start of the line,
2689 // it's actually the start of a preprocessing directive. Callback to
2690 // the preprocessor to handle it.
2691 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002692 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002693 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002694 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 // As an optimization, if the preprocessor didn't switch lexers, tail
2697 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002698 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // Start a new token. If this is a #include or something, the PP may
2700 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002701 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002703 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002704 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 IsAtStartOfLine = false;
2706 }
2707 goto LexNextToken; // GCC isn't tail call eliminating.
2708 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002709 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 }
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Chris Lattnere91e9322009-03-18 20:58:27 +00002712 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 }
2714 break;
2715
Chris Lattner3a570772008-01-03 17:58:54 +00002716 case '@':
2717 // Objective C support.
2718 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002719 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002720 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002721 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002722 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 case '\\':
2725 // FIXME: UCN's.
2726 // FALL THROUGH.
2727 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002728 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 break;
2730 }
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 // Notify MIOpt that we read a non-whitespace/non-comment token.
2733 MIOpt.ReadToken();
2734
2735 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002736 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002737}