blob: bb1bbbbe7e64f2020737264abfbe7fdb51e1d41a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor55817af2010-08-25 17:04:25 +000030#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000032#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/Support/MemoryBuffer.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000035#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Chris Lattnera2bf1052009-12-17 05:29:40 +000038static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000039
Chris Lattnerdbf388b2007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump1eb44332009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000046 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
48 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000049}
50
51/// getObjCKeywordID - Return the ObjC keyword kind.
52tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55}
56
Chris Lattner53702cd2007-12-13 01:59:49 +000057
Chris Lattnerdbf388b2007-10-07 08:47:24 +000058//===----------------------------------------------------------------------===//
59// Lexer Class Implementation
60//===----------------------------------------------------------------------===//
61
David Blaikie99ba9e32011-12-20 02:48:34 +000062void Lexer::anchor() { }
63
Mike Stump1eb44332009-09-09 15:08:12 +000064void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000065 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000066 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner22d91ca2009-01-17 06:55:17 +000068 BufferStart = BufStart;
69 BufferPtr = BufPtr;
70 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner22d91ca2009-01-17 06:55:17 +000072 assert(BufEnd[0] == 0 &&
73 "We assume that the input buffer has a null character at the end"
74 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000075
Eric Christopher156119d2011-04-09 00:01:04 +000076 // Check whether we have a BOM in the beginning of the buffer. If yes - act
77 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
78 // skip the UTF-8 BOM if it's present.
79 if (BufferStart == BufferPtr) {
80 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000081 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000082 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000083 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
84 .Default(0);
85
86 // Skip the BOM.
87 BufferPtr += BOMLength;
88 }
89
Chris Lattner22d91ca2009-01-17 06:55:17 +000090 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000091 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000092
Chris Lattner22d91ca2009-01-17 06:55:17 +000093 // Start of the file is a start of line.
94 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner22d91ca2009-01-17 06:55:17 +000096 // We are not after parsing a #.
97 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner22d91ca2009-01-17 06:55:17 +000099 // We are not after parsing #include.
100 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner22d91ca2009-01-17 06:55:17 +0000102 // We are not in raw mode. Raw mode disables diagnostics and interpretation
103 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
104 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
105 // or otherwise skipping over tokens.
106 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattner22d91ca2009-01-17 06:55:17 +0000108 // Default to not keeping comments.
109 ExtendedTokenMode = 0;
110}
111
Chris Lattner0770dab2009-01-17 07:56:59 +0000112/// Lexer constructor - Create a new lexer object for the specified buffer
113/// with the specified preprocessor managing the lexing process. This lexer
114/// assumes that the associated file buffer and Preprocessor objects will
115/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000116Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000117 : PreprocessorLexer(&PP, FID),
118 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
119 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner0770dab2009-01-17 07:56:59 +0000121 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
122 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Chris Lattner0770dab2009-01-17 07:56:59 +0000124 // Default to keeping comments if the preprocessor wants them.
125 SetCommentRetentionState(PP.getCommentRetentionState());
126}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000127
Chris Lattner168ae2d2007-10-17 20:41:00 +0000128/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000129/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
130/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000131Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000132 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000133 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000134
Chris Lattner22d91ca2009-01-17 06:55:17 +0000135 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner168ae2d2007-10-17 20:41:00 +0000137 // We *are* in raw mode.
138 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000139}
140
Chris Lattner025c3a62009-01-17 07:35:14 +0000141/// Lexer constructor - Create a new raw lexer object. This object is only
142/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
143/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000144Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
145 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000146 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000147
Mike Stump1eb44332009-09-09 15:08:12 +0000148 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000149 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattner025c3a62009-01-17 07:35:14 +0000151 // We *are* in raw mode.
152 LexingRawMode = true;
153}
154
Chris Lattner42e00d12009-01-17 08:27:52 +0000155/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
156/// _Pragma expansion. This has a variety of magic semantics that this method
157/// sets up. It returns a new'd Lexer that must be delete'd when done.
158///
159/// On entrance to this routine, TokStartLoc is a macro location which has a
160/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000161/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000162/// "expanded from".
163///
164/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
165/// normal lexer that remaps tokens as they fly by. This would require making
166/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
167/// interface that could handle this stuff. This would pull GetMappedTokenLoc
168/// out of the critical path of the lexer!
169///
Mike Stump1eb44332009-09-09 15:08:12 +0000170Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000171 SourceLocation ExpansionLocStart,
172 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000173 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000174 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000175
176 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000177 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000178 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
179 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner42e00d12009-01-17 08:27:52 +0000181 // Now that the lexer is created, change the start/end locations so that we
182 // just lex the subsection of the file that we want. This is lexing from a
183 // scratch buffer.
184 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner42e00d12009-01-17 08:27:52 +0000186 L->BufferPtr = StrData;
187 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000188 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000189
190 // Set the SourceLocation with the remapping information. This ensures that
191 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000192 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
193 ExpansionLocStart,
194 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner42e00d12009-01-17 08:27:52 +0000196 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000197 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000198 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattner42e00d12009-01-17 08:27:52 +0000200 // This lexer really is for _Pragma.
201 L->Is_PragmaLexer = true;
202 return L;
203}
204
Chris Lattner168ae2d2007-10-17 20:41:00 +0000205
Reid Spencer5f016e22007-07-11 17:01:13 +0000206/// Stringify - Convert the specified string into a C string, with surrounding
207/// ""'s, and with escaped \ and " characters.
208std::string Lexer::Stringify(const std::string &Str, bool Charify) {
209 std::string Result = Str;
210 char Quote = Charify ? '\'' : '"';
211 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
212 if (Result[i] == '\\' || Result[i] == Quote) {
213 Result.insert(Result.begin()+i, '\\');
214 ++i; ++e;
215 }
216 }
217 return Result;
218}
219
Chris Lattnerd8e30832007-07-24 06:57:14 +0000220/// Stringify - Convert the specified string into a C string by escaping '\'
221/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000222void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000223 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
224 if (Str[i] == '\\' || Str[i] == '"') {
225 Str.insert(Str.begin()+i, '\\');
226 ++i; ++e;
227 }
228 }
229}
230
Chris Lattnerb0607272010-11-17 07:26:20 +0000231//===----------------------------------------------------------------------===//
232// Token Spelling
233//===----------------------------------------------------------------------===//
234
235/// getSpelling() - Return the 'spelling' of this token. The spelling of a
236/// token are the characters used to represent the token in the source file
237/// after trigraph expansion and escaped-newline folding. In particular, this
238/// wants to get the true, uncanonicalized, spelling of things like digraphs
239/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000240StringRef Lexer::getSpelling(SourceLocation loc,
241 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000242 const SourceManager &SM,
243 const LangOptions &options,
244 bool *invalid) {
245 // Break down the source location.
246 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
247
248 // Try to the load the file buffer.
249 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000250 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000251 if (invalidTemp) {
252 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000253 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000254 }
255
256 const char *tokenBegin = file.data() + locInfo.second;
257
258 // Lex from the start of the given location.
259 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
260 file.begin(), tokenBegin, file.end());
261 Token token;
262 lexer.LexFromRawLexer(token);
263
264 unsigned length = token.getLength();
265
266 // Common case: no need for cleaning.
267 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000268 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000269
270 // Hard case, we need to relex the characters into the string.
271 buffer.clear();
272 buffer.reserve(length);
273
274 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
275 unsigned charSize;
276 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
277 ti += charSize;
278 }
279
Chris Lattner5f9e2722011-07-23 10:55:15 +0000280 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000281}
282
283/// getSpelling() - Return the 'spelling' of this token. The spelling of a
284/// token are the characters used to represent the token in the source file
285/// after trigraph expansion and escaped-newline folding. In particular, this
286/// wants to get the true, uncanonicalized, spelling of things like digraphs
287/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000288std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
289 const LangOptions &Features, bool *Invalid) {
290 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
291
292 // If this token contains nothing interesting, return it directly.
293 bool CharDataInvalid = false;
294 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
295 &CharDataInvalid);
296 if (Invalid)
297 *Invalid = CharDataInvalid;
298 if (CharDataInvalid)
299 return std::string();
300
301 if (!Tok.needsCleaning())
302 return std::string(TokStart, TokStart+Tok.getLength());
303
304 std::string Result;
305 Result.reserve(Tok.getLength());
306
307 // Otherwise, hard case, relex the characters into the string.
308 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
309 Ptr != End; ) {
310 unsigned CharSize;
311 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
312 Ptr += CharSize;
313 }
314 assert(Result.size() != unsigned(Tok.getLength()) &&
315 "NeedsCleaning flag set on something that didn't need cleaning!");
316 return Result;
317}
318
319/// getSpelling - This method is used to get the spelling of a token into a
320/// preallocated buffer, instead of as an std::string. The caller is required
321/// to allocate enough space for the token, which is guaranteed to be at least
322/// Tok.getLength() bytes long. The actual length of the token is returned.
323///
324/// Note that this method may do two possible things: it may either fill in
325/// the buffer specified with characters, or it may *change the input pointer*
326/// to point to a constant buffer with the data already in it (avoiding a
327/// copy). The caller is not allowed to modify the returned buffer pointer
328/// if an internal buffer is returned.
329unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
330 const SourceManager &SourceMgr,
331 const LangOptions &Features, bool *Invalid) {
332 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000333
334 const char *TokStart = 0;
335 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
336 if (Tok.is(tok::raw_identifier))
337 TokStart = Tok.getRawIdentifierData();
338 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
339 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000340 Buffer = II->getNameStart();
341 return II->getLength();
342 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000343
344 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000345 if (Tok.isLiteral())
346 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000347
Chris Lattnerb0607272010-11-17 07:26:20 +0000348 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000349 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000350 bool CharDataInvalid = false;
351 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
352 if (Invalid)
353 *Invalid = CharDataInvalid;
354 if (CharDataInvalid) {
355 Buffer = "";
356 return 0;
357 }
358 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000359
Chris Lattnerb0607272010-11-17 07:26:20 +0000360 // If this token contains nothing interesting, return it directly.
361 if (!Tok.needsCleaning()) {
362 Buffer = TokStart;
363 return Tok.getLength();
364 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000365
Chris Lattnerb0607272010-11-17 07:26:20 +0000366 // Otherwise, hard case, relex the characters into the string.
367 char *OutBuf = const_cast<char*>(Buffer);
368 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
369 Ptr != End; ) {
370 unsigned CharSize;
371 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
372 Ptr += CharSize;
373 }
374 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
375 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000376
Chris Lattnerb0607272010-11-17 07:26:20 +0000377 return OutBuf-Buffer;
378}
379
380
381
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000382static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
Chris Lattner9a611942007-10-17 21:18:47 +0000384/// MeasureTokenLength - Relex the token at the specified location and return
385/// its length in bytes in the input file. If the token needs cleaning (e.g.
386/// includes a trigraph or an escaped newline) then this count includes bytes
387/// that are part of that.
388unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000389 const SourceManager &SM,
390 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000391 // TODO: this could be special cased for common tokens like identifiers, ')',
392 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000393 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000394 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
395 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000396
397 // If this comes from a macro expansion, we really do want the macro name, not
398 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000399 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000400 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000401 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000402 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000403 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000404 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000405
406 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408 if (isWhitespace(StrData[0]))
409 return 0;
410
Chris Lattner9a611942007-10-17 21:18:47 +0000411 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000412 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
413 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000414 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000415 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000416 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000417 return TheTok.getLength();
418}
419
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000420static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
423 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000424 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000425 if (LocInfo.first.isInvalid())
426 return Loc;
427
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000428 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000430 if (Invalid)
431 return Loc;
432
433 // Back up from the current location until we hit the beginning of a line
434 // (or the buffer). We'll relex from that point.
435 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000436 if (LocInfo.second >= Buffer.size())
437 return Loc;
438
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000439 const char *StrData = BufStart+LocInfo.second;
440 if (StrData[0] == '\n' || StrData[0] == '\r')
441 return Loc;
442
443 const char *LexStart = StrData;
444 while (LexStart != BufStart) {
445 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
446 ++LexStart;
447 break;
448 }
449
450 --LexStart;
451 }
452
453 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000454 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000455 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
456 TheLexer.SetCommentRetentionState(true);
457
458 // Lex tokens until we find the token that contains the source location.
459 Token TheTok;
460 do {
461 TheLexer.LexFromRawLexer(TheTok);
462
463 if (TheLexer.getBufferLocation() > StrData) {
464 // Lexing this token has taken the lexer past the source location we're
465 // looking for. If the current token encompasses our source location,
466 // return the beginning of that token.
467 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
468 return TheTok.getLocation();
469
470 // We ended up skipping over the source location entirely, which means
471 // that it points into whitespace. We're done here.
472 break;
473 }
474 } while (TheTok.getKind() != tok::eof);
475
476 // We've passed our source location; just return the original source location.
477 return Loc;
478}
479
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000480SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
481 const SourceManager &SM,
482 const LangOptions &LangOpts) {
483 if (Loc.isFileID())
484 return getBeginningOfFileToken(Loc, SM, LangOpts);
485
486 if (!SM.isMacroArgExpansion(Loc))
487 return Loc;
488
489 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
490 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
491 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000492 std::pair<FileID, unsigned> BeginFileLocInfo
493 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000494 assert(FileLocInfo.first == BeginFileLocInfo.first &&
495 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000496 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000497}
498
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000499namespace {
500 enum PreambleDirectiveKind {
501 PDK_Skipped,
502 PDK_StartIf,
503 PDK_EndIf,
504 PDK_Unknown
505 };
506}
507
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000508std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000509Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
510 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000511 // Create a lexer starting at the beginning of the file. Note that we use a
512 // "fake" file source location at offset 1 so that the lexer will track our
513 // position within the file.
514 const unsigned StartOffset = 1;
515 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000516 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000517 Buffer->getBufferStart(), Buffer->getBufferEnd());
518
519 bool InPreprocessorDirective = false;
520 Token TheTok;
521 Token IfStartTok;
522 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000523
524 unsigned MaxLineOffset = 0;
525 if (MaxLines) {
526 const char *CurPtr = Buffer->getBufferStart();
527 unsigned CurLine = 0;
528 while (CurPtr != Buffer->getBufferEnd()) {
529 char ch = *CurPtr++;
530 if (ch == '\n') {
531 ++CurLine;
532 if (CurLine == MaxLines)
533 break;
534 }
535 }
536 if (CurPtr != Buffer->getBufferEnd())
537 MaxLineOffset = CurPtr - Buffer->getBufferStart();
538 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000539
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000540 do {
541 TheLexer.LexFromRawLexer(TheTok);
542
543 if (InPreprocessorDirective) {
544 // If we've hit the end of the file, we're done.
545 if (TheTok.getKind() == tok::eof) {
546 InPreprocessorDirective = false;
547 break;
548 }
549
550 // If we haven't hit the end of the preprocessor directive, skip this
551 // token.
552 if (!TheTok.isAtStartOfLine())
553 continue;
554
555 // We've passed the end of the preprocessor directive, and will look
556 // at this token again below.
557 InPreprocessorDirective = false;
558 }
559
Douglas Gregordf95a132010-08-09 20:45:32 +0000560 // Keep track of the # of lines in the preamble.
561 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000562 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000563
564 // If we were asked to limit the number of lines in the preamble,
565 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000566 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000567 break;
568 }
569
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000570 // Comments are okay; skip over them.
571 if (TheTok.getKind() == tok::comment)
572 continue;
573
574 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
575 // This is the start of a preprocessor directive.
576 Token HashTok = TheTok;
577 InPreprocessorDirective = true;
578
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000579 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000580 // we don't have an identifier table available. Instead, just look at
581 // the raw identifier to recognize and categorize preprocessor directives.
582 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000583 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000585 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000586 PreambleDirectiveKind PDK
587 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
588 .Case("include", PDK_Skipped)
589 .Case("__include_macros", PDK_Skipped)
590 .Case("define", PDK_Skipped)
591 .Case("undef", PDK_Skipped)
592 .Case("line", PDK_Skipped)
593 .Case("error", PDK_Skipped)
594 .Case("pragma", PDK_Skipped)
595 .Case("import", PDK_Skipped)
596 .Case("include_next", PDK_Skipped)
597 .Case("warning", PDK_Skipped)
598 .Case("ident", PDK_Skipped)
599 .Case("sccs", PDK_Skipped)
600 .Case("assert", PDK_Skipped)
601 .Case("unassert", PDK_Skipped)
602 .Case("if", PDK_StartIf)
603 .Case("ifdef", PDK_StartIf)
604 .Case("ifndef", PDK_StartIf)
605 .Case("elif", PDK_Skipped)
606 .Case("else", PDK_Skipped)
607 .Case("endif", PDK_EndIf)
608 .Default(PDK_Unknown);
609
610 switch (PDK) {
611 case PDK_Skipped:
612 continue;
613
614 case PDK_StartIf:
615 if (IfCount == 0)
616 IfStartTok = HashTok;
617
618 ++IfCount;
619 continue;
620
621 case PDK_EndIf:
622 // Mismatched #endif. The preamble ends here.
623 if (IfCount == 0)
624 break;
625
626 --IfCount;
627 continue;
628
629 case PDK_Unknown:
630 // We don't know what this directive is; stop at the '#'.
631 break;
632 }
633 }
634
635 // We only end up here if we didn't recognize the preprocessor
636 // directive or it was one that can't occur in the preamble at this
637 // point. Roll back the current token to the location of the '#'.
638 InPreprocessorDirective = false;
639 TheTok = HashTok;
640 }
641
Douglas Gregordf95a132010-08-09 20:45:32 +0000642 // We hit a token that we don't recognize as being in the
643 // "preprocessing only" part of the file, so we're no longer in
644 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000645 break;
646 } while (true);
647
648 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000649 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
650 IfCount? IfStartTok.isAtStartOfLine()
651 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000652}
653
Chris Lattner7ef5c272010-11-17 07:05:50 +0000654
655/// AdvanceToTokenCharacter - Given a location that specifies the start of a
656/// token, return a new location that specifies a character within the token.
657SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
658 unsigned CharNo,
659 const SourceManager &SM,
660 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000661 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000662 // character is. This needs to take into consideration newlines and
663 // trigraphs.
664 bool Invalid = false;
665 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
666
667 // If they request the first char of the token, we're trivially done.
668 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
669 return TokStart;
670
671 unsigned PhysOffset = 0;
672
673 // The usual case is that tokens don't contain anything interesting. Skip
674 // over the uninteresting characters. If a token only consists of simple
675 // chars, this method is extremely fast.
676 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
677 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000678 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000679 ++TokPtr, --CharNo, ++PhysOffset;
680 }
681
682 // If we have a character that may be a trigraph or escaped newline, use a
683 // lexer to parse it correctly.
684 for (; CharNo; --CharNo) {
685 unsigned Size;
686 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
687 TokPtr += Size;
688 PhysOffset += Size;
689 }
690
691 // Final detail: if we end up on an escaped newline, we want to return the
692 // location of the actual byte of the token. For example foo\<newline>bar
693 // advanced by 3 should return the location of b, not of \\. One compounding
694 // detail of this is that the escape may be made by a trigraph.
695 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
696 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
697
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000698 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000699}
700
701/// \brief Computes the source location just past the end of the
702/// token at this source location.
703///
704/// This routine can be used to produce a source location that
705/// points just past the end of the token referenced by \p Loc, and
706/// is generally used when a diagnostic needs to point just after a
707/// token where it expected something different that it received. If
708/// the returned source location would not be meaningful (e.g., if
709/// it points into a macro), this routine returns an invalid
710/// source location.
711///
712/// \param Offset an offset from the end of the token, where the source
713/// location should refer to. The default offset (0) produces a source
714/// location pointing just past the end of the token; an offset of 1 produces
715/// a source location pointing to the last character in the token, etc.
716SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
717 const SourceManager &SM,
718 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000719 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000720 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000721
722 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000723 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
724 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000725
Chandler Carruth433db062011-07-14 08:20:40 +0000726 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000727 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000728 }
729
Chris Lattner7ef5c272010-11-17 07:05:50 +0000730 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
731 if (Len > Offset)
732 Len = Len - Offset;
733 else
734 return Loc;
735
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000736 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000737}
738
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000739/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000740/// token of the macro expansion.
741bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000742 const SourceManager &SM,
743 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000744 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
745
746 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
747 // FIXME: If the token comes from the macro token paste operator ('##')
748 // this function will always return false;
749 if (infoLoc.second > 0)
750 return false; // Does not point at the start of token.
751
Chandler Carruth433db062011-07-14 08:20:40 +0000752 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000753 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000754 if (expansionLoc.isFileID())
755 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000756
Chandler Carruth433db062011-07-14 08:20:40 +0000757 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000758}
759
760/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000761/// token of the macro expansion.
762bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000763 const SourceManager &SM,
764 const LangOptions &LangOpts) {
765 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
766
767 SourceLocation spellLoc = SM.getSpellingLoc(loc);
768 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
769 if (tokLen == 0)
770 return false;
771
772 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000773 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000774 if (SM.isInFileID(afterLoc, FID))
775 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000776
777 // FIXME: If the token comes from the macro token paste operator ('##')
778 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000779
Chandler Carruth433db062011-07-14 08:20:40 +0000780 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000781 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000782 if (expansionLoc.isFileID())
783 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000784
Chandler Carruth433db062011-07-14 08:20:40 +0000785 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000786}
787
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000788StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
789 const SourceManager &SM,
790 const LangOptions &LangOpts) {
791 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
792 // Walk past macro argument expanions.
793 while (SM.isMacroArgExpansion(Loc))
794 Loc = SM.getImmediateExpansionRange(Loc).first;
795
796 // Find the spelling location of the start of the non-argument expansion
797 // range. This is where the macro name was spelled in order to begin
798 // expanding this macro.
799 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
800
801 // Dig out the buffer where the macro name was spelled and the extents of the
802 // name so that we can render it into the expansion note.
803 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
804 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
805 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
806 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
807}
808
Reid Spencer5f016e22007-07-11 17:01:13 +0000809//===----------------------------------------------------------------------===//
810// Character information.
811//===----------------------------------------------------------------------===//
812
Reid Spencer5f016e22007-07-11 17:01:13 +0000813enum {
814 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
815 CHAR_VERT_WS = 0x02, // '\r', '\n'
816 CHAR_LETTER = 0x04, // a-z,A-Z
817 CHAR_NUMBER = 0x08, // 0-9
818 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000819 CHAR_PERIOD = 0x20, // .
820 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000821};
822
Chris Lattner03b98662009-07-07 17:09:54 +0000823// Statically initialize CharInfo table based on ASCII character set
824// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000825static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000826{
827// 0 NUL 1 SOH 2 STX 3 ETX
828// 4 EOT 5 ENQ 6 ACK 7 BEL
829 0 , 0 , 0 , 0 ,
830 0 , 0 , 0 , 0 ,
831// 8 BS 9 HT 10 NL 11 VT
832//12 NP 13 CR 14 SO 15 SI
833 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
834 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
835//16 DLE 17 DC1 18 DC2 19 DC3
836//20 DC4 21 NAK 22 SYN 23 ETB
837 0 , 0 , 0 , 0 ,
838 0 , 0 , 0 , 0 ,
839//24 CAN 25 EM 26 SUB 27 ESC
840//28 FS 29 GS 30 RS 31 US
841 0 , 0 , 0 , 0 ,
842 0 , 0 , 0 , 0 ,
843//32 SP 33 ! 34 " 35 #
844//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000845 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
846 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000847//40 ( 41 ) 42 * 43 +
848//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000849 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
850 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000851//48 0 49 1 50 2 51 3
852//52 4 53 5 54 6 55 7
853 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
854 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
855//56 8 57 9 58 : 59 ;
856//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000857 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
858 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000859//64 @ 65 A 66 B 67 C
860//68 D 69 E 70 F 71 G
861 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
862 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
863//72 H 73 I 74 J 75 K
864//76 L 77 M 78 N 79 O
865 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
866 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
867//80 P 81 Q 82 R 83 S
868//84 T 85 U 86 V 87 W
869 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
870 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
871//88 X 89 Y 90 Z 91 [
872//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000873 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
874 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000875//96 ` 97 a 98 b 99 c
876//100 d 101 e 102 f 103 g
877 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
878 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
879//104 h 105 i 106 j 107 k
880//108 l 109 m 110 n 111 o
881 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
882 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
883//112 p 113 q 114 r 115 s
884//116 t 117 u 118 v 119 w
885 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
886 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
887//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000888//124 | 125 } 126 ~ 127 DEL
889 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
890 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000891};
892
Chris Lattnera2bf1052009-12-17 05:29:40 +0000893static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 static bool isInited = false;
895 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000896 // check the statically-initialized CharInfo table
897 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
898 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
899 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
900 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
901 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
902 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
903 assert(CHAR_UNDER == CharInfo[(int)'_']);
904 assert(CHAR_PERIOD == CharInfo[(int)'.']);
905 for (unsigned i = 'a'; i <= 'z'; ++i) {
906 assert(CHAR_LETTER == CharInfo[i]);
907 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
908 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000910 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000911
Chris Lattner03b98662009-07-07 17:09:54 +0000912 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000913}
914
Chris Lattner03b98662009-07-07 17:09:54 +0000915
Reid Spencer5f016e22007-07-11 17:01:13 +0000916/// isIdentifierBody - Return true if this is the body character of an
917/// identifier, which is [a-zA-Z0-9_].
918static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000919 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000920}
921
922/// isHorizontalWhitespace - Return true if this character is horizontal
923/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
924static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000925 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000926}
927
Anna Zaksaca25bc2011-07-27 21:43:43 +0000928/// isVerticalWhitespace - Return true if this character is vertical
929/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
930static inline bool isVerticalWhitespace(unsigned char c) {
931 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
932}
933
Reid Spencer5f016e22007-07-11 17:01:13 +0000934/// isWhitespace - Return true if this character is horizontal or vertical
935/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
936/// for '\0'.
937static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000938 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000939}
940
941/// isNumberBody - Return true if this is the body character of an
942/// preprocessing number, which is [a-zA-Z0-9_.].
943static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000944 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000945 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000946}
947
Craig Topper2fa4e862011-08-11 04:06:15 +0000948/// isRawStringDelimBody - Return true if this is the body character of a
949/// raw string delimiter.
950static inline bool isRawStringDelimBody(unsigned char c) {
951 return (CharInfo[c] &
952 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
953 true : false;
954}
955
Reid Spencer5f016e22007-07-11 17:01:13 +0000956
957//===----------------------------------------------------------------------===//
958// Diagnostics forwarding code.
959//===----------------------------------------------------------------------===//
960
Chris Lattner409a0362007-07-22 18:38:25 +0000961/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000962/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000963/// This is currently only used for _Pragma implementation, so it is the slow
964/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000965static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
966 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000967static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
968 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000969 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000970 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattner409a0362007-07-22 18:38:25 +0000972 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000973 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000974 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000975 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Chandler Carruth433db062011-07-14 08:20:40 +0000977 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000978 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000979 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000980 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattnere7fb4842009-02-15 20:52:18 +0000982 // Figure out the expansion loc range, which is the range covered by the
983 // original _Pragma(...) sequence.
984 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000985 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chandler Carruthbf340e42011-07-26 03:03:05 +0000987 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000988}
989
Reid Spencer5f016e22007-07-11 17:01:13 +0000990/// getSourceLocation - Return a source location identifier for the specified
991/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000992SourceLocation Lexer::getSourceLocation(const char *Loc,
993 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000994 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000996
997 // In the normal case, we're just lexing from a simple file buffer, return
998 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000999 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001000 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001001 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattner2b2453a2009-01-17 06:22:33 +00001003 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1004 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001005 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001006 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007}
1008
Reid Spencer5f016e22007-07-11 17:01:13 +00001009/// Diag - Forwarding function for diagnostics. This translate a source
1010/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001011DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001012 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001013}
Reid Spencer5f016e22007-07-11 17:01:13 +00001014
1015//===----------------------------------------------------------------------===//
1016// Trigraph and Escaped Newline Handling Code.
1017//===----------------------------------------------------------------------===//
1018
1019/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1020/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1021static char GetTrigraphCharForLetter(char Letter) {
1022 switch (Letter) {
1023 default: return 0;
1024 case '=': return '#';
1025 case ')': return ']';
1026 case '(': return '[';
1027 case '!': return '|';
1028 case '\'': return '^';
1029 case '>': return '}';
1030 case '/': return '\\';
1031 case '<': return '{';
1032 case '-': return '~';
1033 }
1034}
1035
1036/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1037/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1038/// return the result character. Finally, emit a warning about trigraph use
1039/// whether trigraphs are enabled or not.
1040static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1041 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001042 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Chris Lattner3692b092008-11-18 07:59:24 +00001044 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001045 if (!L->isLexingRawMode())
1046 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 }
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Chris Lattner74d15df2008-11-22 02:02:22 +00001050 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001051 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001052 return Res;
1053}
1054
Chris Lattner24f0e482009-04-18 22:05:41 +00001055/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1056/// 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 +00001057/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001058unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1059 unsigned Size = 0;
1060 while (isWhitespace(Ptr[Size])) {
1061 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattner24f0e482009-04-18 22:05:41 +00001063 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1064 continue;
1065
1066 // If this is a \r\n or \n\r, skip the other half.
1067 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1068 Ptr[Size-1] != Ptr[Size])
1069 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Chris Lattner24f0e482009-04-18 22:05:41 +00001071 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001072 }
1073
Chris Lattner24f0e482009-04-18 22:05:41 +00001074 // Not an escaped newline, must be a \t or something else.
1075 return 0;
1076}
1077
Chris Lattner03374952009-04-18 22:27:02 +00001078/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1079/// them), skip over them and return the first non-escaped-newline found,
1080/// otherwise return P.
1081const char *Lexer::SkipEscapedNewLines(const char *P) {
1082 while (1) {
1083 const char *AfterEscape;
1084 if (*P == '\\') {
1085 AfterEscape = P+1;
1086 } else if (*P == '?') {
1087 // If not a trigraph for escape, bail out.
1088 if (P[1] != '?' || P[2] != '/')
1089 return P;
1090 AfterEscape = P+3;
1091 } else {
1092 return P;
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Chris Lattner03374952009-04-18 22:27:02 +00001095 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1096 if (NewLineSize == 0) return P;
1097 P = AfterEscape+NewLineSize;
1098 }
1099}
1100
Anna Zaksaca25bc2011-07-27 21:43:43 +00001101/// \brief Checks that the given token is the first token that occurs after the
1102/// given location (this excludes comments and whitespace). Returns the location
1103/// immediately after the specified token. If the token is not found or the
1104/// location is inside a macro, the returned source location will be invalid.
1105SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1106 tok::TokenKind TKind,
1107 const SourceManager &SM,
1108 const LangOptions &LangOpts,
1109 bool SkipTrailingWhitespaceAndNewLine) {
1110 if (Loc.isMacroID()) {
1111 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1112 return SourceLocation();
1113 Loc = SM.getExpansionRange(Loc).second;
1114 }
1115 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1116
1117 // Break down the source location.
1118 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1119
1120 // Try to load the file buffer.
1121 bool InvalidTemp = false;
1122 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1123 if (InvalidTemp)
1124 return SourceLocation();
1125
1126 const char *TokenBegin = File.data() + LocInfo.second;
1127
1128 // Lex from the start of the given location.
1129 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1130 TokenBegin, File.end());
1131 // Find the token.
1132 Token Tok;
1133 lexer.LexFromRawLexer(Tok);
1134 if (Tok.isNot(TKind))
1135 return SourceLocation();
1136 SourceLocation TokenLoc = Tok.getLocation();
1137
1138 // Calculate how much whitespace needs to be skipped if any.
1139 unsigned NumWhitespaceChars = 0;
1140 if (SkipTrailingWhitespaceAndNewLine) {
1141 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1142 Tok.getLength();
1143 unsigned char C = *TokenEnd;
1144 while (isHorizontalWhitespace(C)) {
1145 C = *(++TokenEnd);
1146 NumWhitespaceChars++;
1147 }
1148 if (isVerticalWhitespace(C))
1149 NumWhitespaceChars++;
1150 }
1151
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001152 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001153}
Chris Lattner24f0e482009-04-18 22:05:41 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1156/// get its size, and return it. This is tricky in several cases:
1157/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1158/// then either return the trigraph (skipping 3 chars) or the '?',
1159/// depending on whether trigraphs are enabled or not.
1160/// 2. If this is an escaped newline (potentially with whitespace between
1161/// the backslash and newline), implicitly skip the newline and return
1162/// the char after it.
1163/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1164///
1165/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1166/// know that we can accumulate into Size, and that we have already incremented
1167/// Ptr by Size bytes.
1168///
1169/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1170/// be updated to match.
1171///
1172char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001173 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 // If we have a slash, look for an escaped newline.
1175 if (Ptr[0] == '\\') {
1176 ++Size;
1177 ++Ptr;
1178Slash:
1179 // Common case, backslash-char where the char is not whitespace.
1180 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattner5636a3b2009-06-23 05:15:06 +00001182 // See if we have optional whitespace characters between the slash and
1183 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001184 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1185 // Remember that this token needs to be cleaned.
1186 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187
Chris Lattner24f0e482009-04-18 22:05:41 +00001188 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001189 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001190 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattner24f0e482009-04-18 22:05:41 +00001192 // Found backslash<whitespace><newline>. Parse the char after it.
1193 Size += EscapedNewLineSize;
1194 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001195
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001196 // If the char that we finally got was a \n, then we must have had
1197 // something like \<newline><newline>. We don't want to consume the
1198 // second newline.
1199 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1200 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001201
Chris Lattner24f0e482009-04-18 22:05:41 +00001202 // Use slow version to accumulate a correct size field.
1203 return getCharAndSizeSlow(Ptr, Size, Tok);
1204 }
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 // Otherwise, this is not an escaped newline, just return the slash.
1207 return '\\';
1208 }
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 // If this is a trigraph, process it.
1211 if (Ptr[0] == '?' && Ptr[1] == '?') {
1212 // If this is actually a legal trigraph (not something like "??x"), emit
1213 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1214 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1215 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001216 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217
1218 Ptr += 3;
1219 Size += 3;
1220 if (C == '\\') goto Slash;
1221 return C;
1222 }
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 // If this is neither, return a single character.
1226 ++Size;
1227 return *Ptr;
1228}
1229
1230
1231/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1232/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1233/// and that we have already incremented Ptr by Size bytes.
1234///
1235/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1236/// be updated to match.
1237char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1238 const LangOptions &Features) {
1239 // If we have a slash, look for an escaped newline.
1240 if (Ptr[0] == '\\') {
1241 ++Size;
1242 ++Ptr;
1243Slash:
1244 // Common case, backslash-char where the char is not whitespace.
1245 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001248 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1249 // Found backslash<whitespace><newline>. Parse the char after it.
1250 Size += EscapedNewLineSize;
1251 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001253 // If the char that we finally got was a \n, then we must have had
1254 // something like \<newline><newline>. We don't want to consume the
1255 // second newline.
1256 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1257 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001258
Chris Lattner24f0e482009-04-18 22:05:41 +00001259 // Use slow version to accumulate a correct size field.
1260 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1261 }
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 // Otherwise, this is not an escaped newline, just return the slash.
1264 return '\\';
1265 }
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // If this is a trigraph, process it.
1268 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1269 // If this is actually a legal trigraph (not something like "??x"), return
1270 // it.
1271 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1272 Ptr += 3;
1273 Size += 3;
1274 if (C == '\\') goto Slash;
1275 return C;
1276 }
1277 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 // If this is neither, return a single character.
1280 ++Size;
1281 return *Ptr;
1282}
1283
1284//===----------------------------------------------------------------------===//
1285// Helper methods for lexing.
1286//===----------------------------------------------------------------------===//
1287
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001288/// \brief Routine that indiscriminately skips bytes in the source file.
1289void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1290 BufferPtr += Bytes;
1291 if (BufferPtr > BufferEnd)
1292 BufferPtr = BufferEnd;
1293 IsAtStartOfLine = StartOfLine;
1294}
1295
Chris Lattnerd2177732007-07-20 16:59:19 +00001296void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1298 unsigned Size;
1299 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001300 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 --CurPtr; // Back up over the skipped character.
1304
1305 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1306 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1307 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001308 //
1309 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1310 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1312FinishIdentifier:
1313 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001314 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1315 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // If we are in raw mode, return this identifier raw. There is no need to
1318 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001319 if (LexingRawMode)
1320 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001322 // Fill in Result.IdentifierInfo and update the token kind,
1323 // looking up the identifier in the identifier table.
1324 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // Finally, now that we know we have an identifier, pass this off to the
1327 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001328 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001329 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001330
Chris Lattner6a170eb2009-01-21 07:43:11 +00001331 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 C = getCharAndSize(CurPtr, Size);
1337 while (1) {
1338 if (C == '$') {
1339 // If we hit a $ and they are not supported in identifiers, we are done.
1340 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001343 if (!isLexingRawMode())
1344 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 CurPtr = ConsumeChar(CurPtr, Size, Result);
1346 C = getCharAndSize(CurPtr, Size);
1347 continue;
1348 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1349 // Found end of identifier.
1350 goto FinishIdentifier;
1351 }
1352
1353 // Otherwise, this character is good, consume it.
1354 CurPtr = ConsumeChar(CurPtr, Size, Result);
1355
1356 C = getCharAndSize(CurPtr, Size);
1357 while (isIdentifierBody(C)) { // FIXME: UCNs.
1358 CurPtr = ConsumeChar(CurPtr, Size, Result);
1359 C = getCharAndSize(CurPtr, Size);
1360 }
1361 }
1362}
1363
Douglas Gregora75ec432010-08-30 14:50:47 +00001364/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001365/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001366static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1367 unsigned Size;
1368 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1369 if (C1 != '0')
1370 return false;
1371 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1372 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001373}
Reid Spencer5f016e22007-07-11 17:01:13 +00001374
Nate Begeman5253c7f2008-04-14 02:26:39 +00001375/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001376/// constant. From[-1] is the first character lexed. Return the end of the
1377/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001378void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 unsigned Size;
1380 char C = getCharAndSize(CurPtr, Size);
1381 char PrevCh = 0;
1382 while (isNumberBody(C)) { // FIXME: UCNs?
1383 CurPtr = ConsumeChar(CurPtr, Size, Result);
1384 PrevCh = C;
1385 C = getCharAndSize(CurPtr, Size);
1386 }
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001389 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1390 // If we are in Microsoft mode, don't continue if the constant is hex.
1391 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Francois Pichet62ec1f22011-09-17 17:15:52 +00001392 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001393 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1394 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001395
1396 // If we have a hex FP constant, continue.
Douglas Gregor46717302011-10-12 18:51:02 +00001397 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001401 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001402 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001403 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404}
1405
1406/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001407/// either " or L" or u8" or u" or U".
1408void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1409 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Richard Smith661a9962011-10-15 01:18:56 +00001412 if (!isLexingRawMode() &&
1413 (Kind == tok::utf8_string_literal ||
1414 Kind == tok::utf16_string_literal ||
1415 Kind == tok::utf32_string_literal))
1416 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 char C = getAndAdvanceChar(CurPtr, Result);
1419 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001420 // Skip escaped characters. Escaped newlines will already be processed by
1421 // getAndAdvanceChar.
1422 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001424
Chris Lattner571339c2010-05-30 23:27:38 +00001425 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001426 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001427 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001428 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001429 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 }
Chris Lattner571339c2010-05-30 23:27:38 +00001432
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001433 if (C == 0) {
1434 if (isCodeCompletionPoint(CurPtr-1)) {
1435 PP->CodeCompleteNaturalLanguage();
1436 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1437 return cutOffLexing();
1438 }
1439
Chris Lattner571339c2010-05-30 23:27:38 +00001440 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001441 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 C = getAndAdvanceChar(CurPtr, Result);
1443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001446 if (NulCharacter && !isLexingRawMode())
1447 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001450 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001451 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001452 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001453}
1454
Craig Topper2fa4e862011-08-11 04:06:15 +00001455/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1456/// having lexed R", LR", u8R", uR", or UR".
1457void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1458 tok::TokenKind Kind) {
1459 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1460 // Between the initial and final double quote characters of the raw string,
1461 // any transformations performed in phases 1 and 2 (trigraphs,
1462 // universal-character-names, and line splicing) are reverted.
1463
Richard Smith661a9962011-10-15 01:18:56 +00001464 if (!isLexingRawMode())
1465 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1466
Craig Topper2fa4e862011-08-11 04:06:15 +00001467 unsigned PrefixLen = 0;
1468
1469 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1470 ++PrefixLen;
1471
1472 // If the last character was not a '(', then we didn't lex a valid delimiter.
1473 if (CurPtr[PrefixLen] != '(') {
1474 if (!isLexingRawMode()) {
1475 const char *PrefixEnd = &CurPtr[PrefixLen];
1476 if (PrefixLen == 16) {
1477 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1478 } else {
1479 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1480 << StringRef(PrefixEnd, 1);
1481 }
1482 }
1483
1484 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1485 // it's possible the '"' was intended to be part of the raw string, but
1486 // there's not much we can do about that.
1487 while (1) {
1488 char C = *CurPtr++;
1489
1490 if (C == '"')
1491 break;
1492 if (C == 0 && CurPtr-1 == BufferEnd) {
1493 --CurPtr;
1494 break;
1495 }
1496 }
1497
1498 FormTokenWithChars(Result, CurPtr, tok::unknown);
1499 return;
1500 }
1501
1502 // Save prefix and move CurPtr past it
1503 const char *Prefix = CurPtr;
1504 CurPtr += PrefixLen + 1; // skip over prefix and '('
1505
1506 while (1) {
1507 char C = *CurPtr++;
1508
1509 if (C == ')') {
1510 // Check for prefix match and closing quote.
1511 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1512 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1513 break;
1514 }
1515 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1516 if (!isLexingRawMode())
1517 Diag(BufferPtr, diag::err_unterminated_raw_string)
1518 << StringRef(Prefix, PrefixLen);
1519 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1520 return;
1521 }
1522 }
1523
1524 // Update the location of token as well as BufferPtr.
1525 const char *TokStart = BufferPtr;
1526 FormTokenWithChars(Result, CurPtr, Kind);
1527 Result.setLiteralData(TokStart);
1528}
1529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1531/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001532void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001534 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 char C = getAndAdvanceChar(CurPtr, Result);
1536 while (C != '>') {
1537 // Skip escaped characters.
1538 if (C == '\\') {
1539 // Skip the escaped character.
1540 C = getAndAdvanceChar(CurPtr, Result);
1541 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001542 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1543 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001544 // If the filename is unterminated, then it must just be a lone <
1545 // character. Return this as such.
1546 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 return;
1548 } else if (C == 0) {
1549 NulCharacter = CurPtr-1;
1550 }
1551 C = getAndAdvanceChar(CurPtr, Result);
1552 }
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001555 if (NulCharacter && !isLexingRawMode())
1556 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001559 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001560 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001561 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001562}
1563
1564
1565/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001566/// lexed either ' or L' or u' or U'.
1567void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1568 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 const char *NulCharacter = 0; // Does this character contain the \0 character?
1570
Richard Smith661a9962011-10-15 01:18:56 +00001571 if (!isLexingRawMode() &&
1572 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1573 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 char C = getAndAdvanceChar(CurPtr, Result);
1576 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001577 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001578 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001579 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001581 }
1582
1583 while (C != '\'') {
1584 // Skip escaped characters.
1585 if (C == '\\') {
1586 // Skip the escaped character.
1587 // FIXME: UCN's
1588 C = getAndAdvanceChar(CurPtr, Result);
1589 } else if (C == '\n' || C == '\r' || // Newline.
1590 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001591 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001592 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001593 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1594 return;
1595 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001596 if (isCodeCompletionPoint(CurPtr-1)) {
1597 PP->CodeCompleteNaturalLanguage();
1598 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1599 return cutOffLexing();
1600 }
1601
Chris Lattnerd80f7862010-07-07 23:24:27 +00001602 NulCharacter = CurPtr-1;
1603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 C = getAndAdvanceChar(CurPtr, Result);
1605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Chris Lattnerd80f7862010-07-07 23:24:27 +00001607 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001608 if (NulCharacter && !isLexingRawMode())
1609 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001612 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001613 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001614 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615}
1616
1617/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1618/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001619///
1620/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1621///
1622bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 // Whitespace - Skip it, then return the token after the whitespace.
1624 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1625 while (1) {
1626 // Skip horizontal whitespace very aggressively.
1627 while (isHorizontalWhitespace(Char))
1628 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001630 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 if (Char != '\n' && Char != '\r')
1632 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 if (ParsingPreprocessorDirective) {
1635 // End of preprocessor directive line, let LexTokenInternal handle this.
1636 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001637 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 }
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 // ok, but handle newline.
1641 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001642 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001644 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 Char = *++CurPtr;
1646 }
1647
1648 // If this isn't immediately after a newline, there is leading space.
1649 char PrevChar = CurPtr[-1];
1650 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001651 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001652
Chris Lattnerd88dc482008-10-12 04:05:48 +00001653 // If the client wants us to return whitespace, return it now.
1654 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001655 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001656 return true;
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001660 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661}
1662
1663// SkipBCPLComment - We have just read the // characters from input. Skip until
1664// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001665/// BufferPtr and return.
1666///
1667/// If we're in KeepCommentMode or any CommentHandler has inserted
1668/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001669bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // If BCPL comments aren't explicitly enabled for this language, emit an
1671 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001672 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 // Mark them enabled so we only emit one warning for this translation
1676 // unit.
1677 Features.BCPLComment = true;
1678 }
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Scan over the body of the comment. The common case, when scanning, is that
1681 // the comment contains normal ascii characters with nothing interesting in
1682 // them. As such, optimize for this case with the inner loop.
1683 char C;
1684 do {
1685 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 // Skip over characters in the fast loop.
1687 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 C != '\n' && C != '\r') // Newline or DOS-style newline.
1689 C = *++CurPtr;
1690
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001691 const char *NextLine = CurPtr;
1692 if (C != 0) {
1693 // We found a newline, see if it's escaped.
1694 const char *EscapePtr = CurPtr-1;
1695 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1696 --EscapePtr;
1697
1698 if (*EscapePtr == '\\') // Escaped newline.
1699 CurPtr = EscapePtr;
1700 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1701 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1702 CurPtr = EscapePtr-2;
1703 else
1704 break; // This is a newline, we're done.
1705
1706 C = *CurPtr;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001710 // properly decode the character. Read it in raw mode to avoid emitting
1711 // diagnostics about things like trigraphs. If we see an escaped newline,
1712 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001714 bool OldRawMode = isLexingRawMode();
1715 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001717 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001718
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001719 // If we only read only one character, then no special handling is needed.
1720 // We're done and can skip forward to the newline.
1721 if (C != 0 && CurPtr == OldPtr+1) {
1722 CurPtr = NextLine;
1723 break;
1724 }
1725
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 // If we read multiple characters, and one of those characters was a \r or
1727 // \n, then we had an escaped newline within the comment. Emit diagnostic
1728 // unless the next line is also a // comment.
1729 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1730 for (; OldPtr != CurPtr; ++OldPtr)
1731 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1732 // Okay, we found a // comment that ends in a newline, if the next
1733 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001734 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001736 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 ++ForwardPtr;
1738 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1739 break;
1740 }
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Chris Lattner74d15df2008-11-22 02:02:22 +00001742 if (!isLexingRawMode())
1743 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 break;
1745 }
1746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Douglas Gregor55817af2010-08-25 17:04:25 +00001748 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001749 --CurPtr;
1750 break;
1751 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001752
1753 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1754 PP->CodeCompleteNaturalLanguage();
1755 cutOffLexing();
1756 return false;
1757 }
1758
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 } while (C != '\n' && C != '\r');
1760
Chris Lattner3d0ad582010-02-03 21:06:21 +00001761 // Found but did not consume the newline. Notify comment handlers about the
1762 // comment unless we're in a #if 0 block.
1763 if (PP && !isLexingRawMode() &&
1764 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1765 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001766 BufferPtr = CurPtr;
1767 return true; // A token has to be returned.
1768 }
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001771 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 return SaveBCPLComment(Result, CurPtr);
1773
1774 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001775 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1777 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001778 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 }
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001782 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001783 // contribute to another token), it isn't needed for correctness. Note that
1784 // this is ok even in KeepWhitespaceMode, because we would have returned the
1785 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001789 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001791 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001793 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001794}
1795
1796/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1797/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001798bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001799 // If we're not in a preprocessor directive, just return the // comment
1800 // directly.
1801 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Chris Lattner9e6293d2008-10-12 04:51:35 +00001803 if (!ParsingPreprocessorDirective)
1804 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Chris Lattner9e6293d2008-10-12 04:51:35 +00001806 // If this BCPL-style comment is in a macro definition, transmogrify it into
1807 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001808 bool Invalid = false;
1809 std::string Spelling = PP->getSpelling(Result, &Invalid);
1810 if (Invalid)
1811 return true;
1812
Chris Lattner9e6293d2008-10-12 04:51:35 +00001813 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1814 Spelling[1] = '*'; // Change prefix to "/*".
1815 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Chris Lattner9e6293d2008-10-12 04:51:35 +00001817 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001818 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001819 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001820 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001821}
1822
1823/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1824/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001825/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001826static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 Lexer *L) {
1828 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 // Back up off the newline.
1831 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 // If this is a two-character newline sequence, skip the other character.
1834 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1835 // \n\n or \r\r -> not escaped newline.
1836 if (CurPtr[0] == CurPtr[1])
1837 return false;
1838 // \n\r or \r\n -> skip the newline.
1839 --CurPtr;
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 // If we have horizontal whitespace, skip over it. We allow whitespace
1843 // between the slash and newline.
1844 bool HasSpace = false;
1845 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1846 --CurPtr;
1847 HasSpace = true;
1848 }
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // If we have a slash, we know this is an escaped newline.
1851 if (*CurPtr == '\\') {
1852 if (CurPtr[-1] != '*') return false;
1853 } else {
1854 // It isn't a slash, is it the ?? / trigraph?
1855 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1856 CurPtr[-3] != '*')
1857 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 // This is the trigraph ending the comment. Emit a stern warning!
1860 CurPtr -= 2;
1861
1862 // If no trigraphs are enabled, warn that we ignored this trigraph and
1863 // ignore this * character.
1864 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001865 if (!L->isLexingRawMode())
1866 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 return false;
1868 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001869 if (!L->isLexingRawMode())
1870 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001874 if (!L->isLexingRawMode())
1875 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001878 if (HasSpace && !L->isLexingRawMode())
1879 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 return true;
1882}
1883
1884#ifdef __SSE2__
1885#include <emmintrin.h>
1886#elif __ALTIVEC__
1887#include <altivec.h>
1888#undef bool
1889#endif
1890
1891/// SkipBlockComment - We have just read the /* characters from input. Read
1892/// until we find the */ characters that terminate the comment. Note that we
1893/// don't bother decoding trigraphs or escaped newlines in block comments,
1894/// because they cannot cause the comment to end. The only thing that can
1895/// happen is the comment could end with an escaped newline between the */ end
1896/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001897///
Chris Lattner046c2272010-01-18 22:35:47 +00001898/// If we're in KeepCommentMode or any CommentHandler has inserted
1899/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001900bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001902 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 // optimization helps people who like to put a lot of * characters in their
1904 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001905
1906 // The first character we get with newlines and trigraphs skipped to handle
1907 // the degenerate /*/ case below correctly if the * has an escaped newline
1908 // after it.
1909 unsigned CharSize;
1910 unsigned char C = getCharAndSize(CurPtr, CharSize);
1911 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001913 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001914 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001915 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattner31f0eca2008-10-12 04:19:49 +00001917 // KeepWhitespaceMode should return this broken comment as a token. Since
1918 // it isn't a well formed comment, just return it as an 'unknown' token.
1919 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001920 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001921 return true;
1922 }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Chris Lattner31f0eca2008-10-12 04:19:49 +00001924 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001925 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Chris Lattner8146b682007-07-21 23:43:37 +00001928 // Check to see if the first character after the '/*' is another /. If so,
1929 // then this slash does not end the block comment, it is part of it.
1930 if (C == '/')
1931 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 while (1) {
1934 // Skip over all non-interesting characters until we find end of buffer or a
1935 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001936 if (CurPtr + 24 < BufferEnd &&
1937 // If there is a code-completion point avoid the fast scan because it
1938 // doesn't check for '\0'.
1939 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 // While not aligned to a 16-byte boundary.
1941 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1942 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 if (C == '/') goto FoundSlash;
1945
1946#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001947 __m128i Slashes = _mm_set1_epi8('/');
1948 while (CurPtr+16 <= BufferEnd) {
1949 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
1950 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00001951 // Adjust the pointer to point directly after the first slash. It's
1952 // not necessary to set C here, it will be overwritten at the end of
1953 // the outer loop.
1954 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001955 goto FoundSlash;
1956 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001958 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001959#elif __ALTIVEC__
1960 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001961 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 '/', '/', '/', '/', '/', '/', '/', '/'
1963 };
1964 while (CurPtr+16 <= BufferEnd &&
1965 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1966 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001967#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 // Scan for '/' quickly. Many block comments are very large.
1969 while (CurPtr[0] != '/' &&
1970 CurPtr[1] != '/' &&
1971 CurPtr[2] != '/' &&
1972 CurPtr[3] != '/' &&
1973 CurPtr+4 < BufferEnd) {
1974 CurPtr += 4;
1975 }
1976#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // It has to be one of the bytes scanned, increment to it and read one.
1979 C = *CurPtr++;
1980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 // Loop to scan the remainder.
1983 while (C != '/' && C != '\0')
1984 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00001987 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 if (CurPtr[-2] == '*') // We found the final */. We're done!
1989 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1992 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1993 // We found the final */, though it had an escaped newline between the
1994 // * and /. We're done!
1995 break;
1996 }
1997 }
1998 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1999 // If this is a /* inside of the comment, emit a warning. Don't do this
2000 // if this is a /*/, which will end the comment. This misses cases with
2001 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002002 if (!isLexingRawMode())
2003 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 }
2005 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002006 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002007 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 // Note: the user probably forgot a */. We could continue immediately
2009 // after the /*, but this would involve lexing a lot of what really is the
2010 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002011 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Chris Lattner31f0eca2008-10-12 04:19:49 +00002013 // KeepWhitespaceMode should return this broken comment as a token. Since
2014 // it isn't a well formed comment, just return it as an 'unknown' token.
2015 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002016 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002017 return true;
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Chris Lattner31f0eca2008-10-12 04:19:49 +00002020 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002021 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002022 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2023 PP->CodeCompleteNaturalLanguage();
2024 cutOffLexing();
2025 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002027
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 C = *CurPtr++;
2029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Chris Lattner3d0ad582010-02-03 21:06:21 +00002031 // Notify comment handlers about the comment unless we're in a #if 0 block.
2032 if (PP && !isLexingRawMode() &&
2033 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2034 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002035 BufferPtr = CurPtr;
2036 return true; // A token has to be returned.
2037 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002038
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002040 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002041 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002042 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 }
2044
2045 // It is common for the tokens immediately after a /**/ comment to be
2046 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002047 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2048 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002050 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002052 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 }
2054
2055 // Otherwise, just return so that the next character will be lexed as a token.
2056 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002057 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002058 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002059}
2060
2061//===----------------------------------------------------------------------===//
2062// Primary Lexing Entry Points
2063//===----------------------------------------------------------------------===//
2064
Reid Spencer5f016e22007-07-11 17:01:13 +00002065/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2066/// uninterpreted string. This switches the lexer out of directive mode.
2067std::string Lexer::ReadToEndOfLine() {
2068 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2069 "Must be in a preprocessing directive!");
2070 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002071 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002072
2073 // CurPtr - Cache BufferPtr in an automatic variable.
2074 const char *CurPtr = BufferPtr;
2075 while (1) {
2076 char Char = getAndAdvanceChar(CurPtr, Tmp);
2077 switch (Char) {
2078 default:
2079 Result += Char;
2080 break;
2081 case 0: // Null.
2082 // Found end of file?
2083 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002084 if (isCodeCompletionPoint(CurPtr-1)) {
2085 PP->CodeCompleteNaturalLanguage();
2086 cutOffLexing();
2087 return Result;
2088 }
2089
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // Nope, normal character, continue.
2091 Result += Char;
2092 break;
2093 }
2094 // FALL THROUGH.
2095 case '\r':
2096 case '\n':
2097 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2098 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2099 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Peter Collingbourne84021552011-02-28 02:37:51 +00002101 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002103 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002104 if (PP)
2105 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002106 Lex(Tmp);
2107 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002108 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 // Finally, we're done, return the string we found.
2111 return Result;
2112 }
2113 }
2114}
2115
2116/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2117/// condition, reporting diagnostics and handling other edge cases as required.
2118/// This returns true if Result contains a token, false if PP.Lex should be
2119/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002120bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // If we hit the end of the file while parsing a preprocessor directive,
2122 // end the preprocessor directive first. The next token returned will
2123 // then be the end of file.
2124 if (ParsingPreprocessorDirective) {
2125 // Done parsing the "line".
2126 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002128 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002131 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002133 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002134
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 // If we are in raw mode, return this event as an EOF token. Let the caller
2136 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002137 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 Result.startToken();
2139 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002140 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 return true;
2142 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002143
Douglas Gregorf44e8542010-08-24 19:08:16 +00002144 // Issue diagnostics for unterminated #if and missing newline.
2145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // If we are in a #if directive, emit an error.
2147 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002148 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002149 PP->Diag(ConditionalStack.back().IfLoc,
2150 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 ConditionalStack.pop_back();
2152 }
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002154 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2155 // a pedwarn.
2156 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002157 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002158 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 BufferPtr = CurPtr;
2161
2162 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002163 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002164}
2165
2166/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2167/// the specified lexer will return a tok::l_paren token, 0 if it is something
2168/// else and 2 if there are no more tokens in the buffer controlled by the
2169/// lexer.
2170unsigned Lexer::isNextPPTokenLParen() {
2171 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 // Switch to 'skipping' mode. This will ensure that we can lex a token
2174 // without emitting diagnostics, disables macro expansion, and will cause EOF
2175 // to return an EOF token instead of popping the include stack.
2176 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 // Save state that can be changed while lexing so that we can restore it.
2179 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002180 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Chris Lattnerd2177732007-07-20 16:59:19 +00002182 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 Tok.startToken();
2184 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 // Restore state that may have changed.
2187 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002188 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 // Restore the lexer back to non-skipping mode.
2191 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002193 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002195 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002196}
2197
Chris Lattner34f349d2009-12-14 06:16:57 +00002198/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002199static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2200 ConflictMarkerKind CMK) {
2201 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2202 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2203 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2204 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002205 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002206 // Must occur at start of line.
2207 if (RestOfBuffer[Pos-1] != '\r' &&
2208 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002209 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2210 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002211 continue;
2212 }
2213 return RestOfBuffer.data()+Pos;
2214 }
2215 return 0;
2216}
2217
2218/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2219/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2220/// and recover nicely. This returns true if it is a conflict marker and false
2221/// if not.
2222bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2223 // Only a conflict marker if it starts at the beginning of a line.
2224 if (CurPtr != BufferStart &&
2225 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2226 return false;
2227
Richard Smithd5e1d602011-10-12 00:37:51 +00002228 // Check to see if we have <<<<<<< or >>>>.
2229 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2230 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002231 return false;
2232
2233 // If we have a situation where we don't care about conflict markers, ignore
2234 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002235 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002236 return false;
2237
Richard Smithd5e1d602011-10-12 00:37:51 +00002238 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2239
2240 // Check to see if there is an ending marker somewhere in the buffer at the
2241 // start of a line to terminate this conflict marker.
2242 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002243 // We found a match. We are really in a conflict marker.
2244 // Diagnose this, and ignore to the end of line.
2245 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002246 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002247
2248 // Skip ahead to the end of line. We know this exists because the
2249 // end-of-conflict marker starts with \r or \n.
2250 while (*CurPtr != '\r' && *CurPtr != '\n') {
2251 assert(CurPtr != BufferEnd && "Didn't find end of line");
2252 ++CurPtr;
2253 }
2254 BufferPtr = CurPtr;
2255 return true;
2256 }
2257
2258 // No end of conflict marker found.
2259 return false;
2260}
2261
2262
Richard Smithd5e1d602011-10-12 00:37:51 +00002263/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2264/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2265/// is the end of a conflict marker. Handle it by ignoring up until the end of
2266/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002267bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2268 // Only a conflict marker if it starts at the beginning of a line.
2269 if (CurPtr != BufferStart &&
2270 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2271 return false;
2272
2273 // If we have a situation where we don't care about conflict markers, ignore
2274 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002275 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002276 return false;
2277
Richard Smithd5e1d602011-10-12 00:37:51 +00002278 // Check to see if we have the marker (4 characters in a row).
2279 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002280 if (CurPtr[i] != CurPtr[0])
2281 return false;
2282
2283 // If we do have it, search for the end of the conflict marker. This could
2284 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2285 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002286 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2287 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002288 CurPtr = End;
2289
2290 // Skip ahead to the end of line.
2291 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2292 ++CurPtr;
2293
2294 BufferPtr = CurPtr;
2295
2296 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002297 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002298 return true;
2299 }
2300
2301 return false;
2302}
2303
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002304bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2305 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002306 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002307 return Loc == PP->getCodeCompletionLoc();
2308 }
2309
2310 return false;
2311}
2312
Reid Spencer5f016e22007-07-11 17:01:13 +00002313
2314/// LexTokenInternal - This implements a simple C family lexer. It is an
2315/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002316/// has a null character at the end of the file. This returns a preprocessing
2317/// token, not a normal token, as such, it is an internal interface. It assumes
2318/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002319void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002320LexNextToken:
2321 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002322 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 // CurPtr - Cache BufferPtr in an automatic variable.
2326 const char *CurPtr = BufferPtr;
2327
2328 // Small amounts of horizontal whitespace is very common between tokens.
2329 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2330 ++CurPtr;
2331 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2332 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Chris Lattnerd88dc482008-10-12 04:05:48 +00002334 // If we are keeping whitespace and other tokens, just return what we just
2335 // skipped. The next lexer invocation will return the token after the
2336 // whitespace.
2337 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002338 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002339 return;
2340 }
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002343 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 }
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 // Read a character, advancing over it.
2349 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002350 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 switch (Char) {
2353 case 0: // Null.
2354 // Found end of file?
2355 if (CurPtr-1 == BufferEnd) {
2356 // Read the PP instance variable into an automatic variable, because
2357 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002358 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2360 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002361 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2362 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 }
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002365 // Check if we are performing code completion.
2366 if (isCodeCompletionPoint(CurPtr-1)) {
2367 // Return the code-completion token.
2368 Result.startToken();
2369 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2370 return;
2371 }
2372
Chris Lattner74d15df2008-11-22 02:02:22 +00002373 if (!isLexingRawMode())
2374 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002375 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002376 if (SkipWhitespace(Result, CurPtr))
2377 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002380
2381 case 26: // DOS & CP/M EOF: "^Z".
2382 // If we're in Microsoft extensions mode, treat this as end of file.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002383 if (Features.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002384 // Read the PP instance variable into an automatic variable, because
2385 // LexEndOfFile will often delete 'this'.
2386 Preprocessor *PPCache = PP;
2387 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2388 return; // Got a token to return.
2389 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2390 return PPCache->Lex(Result);
2391 }
2392 // If Microsoft extensions are disabled, this is just random garbage.
2393 Kind = tok::unknown;
2394 break;
2395
Reid Spencer5f016e22007-07-11 17:01:13 +00002396 case '\n':
2397 case '\r':
2398 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002399 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 if (ParsingPreprocessorDirective) {
2401 // Done parsing the "line".
2402 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Reid Spencer5f016e22007-07-11 17:01:13 +00002404 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002405 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 // Since we consumed a newline, we are back at the start of a line.
2408 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Peter Collingbourne84021552011-02-28 02:37:51 +00002410 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 break;
2412 }
2413 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002414 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002416 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Chris Lattnerd88dc482008-10-12 04:05:48 +00002418 if (SkipWhitespace(Result, CurPtr))
2419 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 goto LexNextToken; // GCC isn't tail call eliminating.
2421 case ' ':
2422 case '\t':
2423 case '\f':
2424 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002425 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002426 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002427 if (SkipWhitespace(Result, CurPtr))
2428 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002429
2430 SkipIgnoredUnits:
2431 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Chris Lattner8133cfc2007-07-22 06:29:05 +00002433 // If the next token is obviously a // or /* */ comment, skip it efficiently
2434 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002435 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002436 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002437 if (SkipBCPLComment(Result, CurPtr+2))
2438 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002439 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002440 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002441 if (SkipBlockComment(Result, CurPtr+2))
2442 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002443 goto SkipIgnoredUnits;
2444 } else if (isHorizontalWhitespace(*CurPtr)) {
2445 goto SkipHorizontalWhitespace;
2446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002448
Chris Lattner3a570772008-01-03 17:58:54 +00002449 // C99 6.4.4.1: Integer Constants.
2450 // C99 6.4.4.2: Floating Constants.
2451 case '0': case '1': case '2': case '3': case '4':
2452 case '5': case '6': case '7': case '8': case '9':
2453 // Notify MIOpt that we read a non-whitespace/non-comment token.
2454 MIOpt.ReadToken();
2455 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Douglas Gregor5cee1192011-07-27 05:40:30 +00002457 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2458 // Notify MIOpt that we read a non-whitespace/non-comment token.
2459 MIOpt.ReadToken();
2460
2461 if (Features.CPlusPlus0x) {
2462 Char = getCharAndSize(CurPtr, SizeTmp);
2463
2464 // UTF-16 string literal
2465 if (Char == '"')
2466 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2467 tok::utf16_string_literal);
2468
2469 // UTF-16 character constant
2470 if (Char == '\'')
2471 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2472 tok::utf16_char_constant);
2473
Craig Topper2fa4e862011-08-11 04:06:15 +00002474 // UTF-16 raw string literal
2475 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2476 return LexRawStringLiteral(Result,
2477 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2478 SizeTmp2, Result),
2479 tok::utf16_string_literal);
2480
2481 if (Char == '8') {
2482 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2483
2484 // UTF-8 string literal
2485 if (Char2 == '"')
2486 return LexStringLiteral(Result,
2487 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2488 SizeTmp2, Result),
2489 tok::utf8_string_literal);
2490
2491 if (Char2 == 'R') {
2492 unsigned SizeTmp3;
2493 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2494 // UTF-8 raw string literal
2495 if (Char3 == '"') {
2496 return LexRawStringLiteral(Result,
2497 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2498 SizeTmp2, Result),
2499 SizeTmp3, Result),
2500 tok::utf8_string_literal);
2501 }
2502 }
2503 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002504 }
2505
2506 // treat u like the start of an identifier.
2507 return LexIdentifier(Result, CurPtr);
2508
2509 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2510 // Notify MIOpt that we read a non-whitespace/non-comment token.
2511 MIOpt.ReadToken();
2512
2513 if (Features.CPlusPlus0x) {
2514 Char = getCharAndSize(CurPtr, SizeTmp);
2515
2516 // UTF-32 string literal
2517 if (Char == '"')
2518 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2519 tok::utf32_string_literal);
2520
2521 // UTF-32 character constant
2522 if (Char == '\'')
2523 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2524 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002525
2526 // UTF-32 raw string literal
2527 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2528 return LexRawStringLiteral(Result,
2529 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2530 SizeTmp2, Result),
2531 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002532 }
2533
2534 // treat U like the start of an identifier.
2535 return LexIdentifier(Result, CurPtr);
2536
Craig Topper2fa4e862011-08-11 04:06:15 +00002537 case 'R': // Identifier or C++0x raw string literal
2538 // Notify MIOpt that we read a non-whitespace/non-comment token.
2539 MIOpt.ReadToken();
2540
2541 if (Features.CPlusPlus0x) {
2542 Char = getCharAndSize(CurPtr, SizeTmp);
2543
2544 if (Char == '"')
2545 return LexRawStringLiteral(Result,
2546 ConsumeChar(CurPtr, SizeTmp, Result),
2547 tok::string_literal);
2548 }
2549
2550 // treat R like the start of an identifier.
2551 return LexIdentifier(Result, CurPtr);
2552
Chris Lattner3a570772008-01-03 17:58:54 +00002553 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 // Notify MIOpt that we read a non-whitespace/non-comment token.
2555 MIOpt.ReadToken();
2556 Char = getCharAndSize(CurPtr, SizeTmp);
2557
2558 // Wide string literal.
2559 if (Char == '"')
2560 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002561 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002562
Craig Topper2fa4e862011-08-11 04:06:15 +00002563 // Wide raw string literal.
2564 if (Features.CPlusPlus0x && Char == 'R' &&
2565 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2566 return LexRawStringLiteral(Result,
2567 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2568 SizeTmp2, Result),
2569 tok::wide_string_literal);
2570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Wide character constant.
2572 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002573 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2574 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 // C99 6.4.2: Identifiers.
2578 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2579 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002580 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2582 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2583 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002584 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 case 'v': case 'w': case 'x': case 'y': case 'z':
2586 case '_':
2587 // Notify MIOpt that we read a non-whitespace/non-comment token.
2588 MIOpt.ReadToken();
2589 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002590
2591 case '$': // $ in identifiers.
2592 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002593 if (!isLexingRawMode())
2594 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002595 // Notify MIOpt that we read a non-whitespace/non-comment token.
2596 MIOpt.ReadToken();
2597 return LexIdentifier(Result, CurPtr);
2598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Chris Lattner9e6293d2008-10-12 04:51:35 +00002600 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002601 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 // C99 6.4.4: Character Constants.
2604 case '\'':
2605 // Notify MIOpt that we read a non-whitespace/non-comment token.
2606 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002607 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002608
2609 // C99 6.4.5: String Literals.
2610 case '"':
2611 // Notify MIOpt that we read a non-whitespace/non-comment token.
2612 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002613 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002614
2615 // C99 6.4.6: Punctuators.
2616 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002617 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 break;
2619 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002620 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 break;
2622 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002623 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 break;
2625 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002626 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 break;
2628 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002629 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 break;
2631 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002632 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 break;
2634 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002635 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 break;
2637 case '.':
2638 Char = getCharAndSize(CurPtr, SizeTmp);
2639 if (Char >= '0' && Char <= '9') {
2640 // Notify MIOpt that we read a non-whitespace/non-comment token.
2641 MIOpt.ReadToken();
2642
2643 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2644 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002645 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 CurPtr += SizeTmp;
2647 } else if (Char == '.' &&
2648 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002649 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2651 SizeTmp2, Result);
2652 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002653 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 }
2655 break;
2656 case '&':
2657 Char = getCharAndSize(CurPtr, SizeTmp);
2658 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002659 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2661 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002662 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2664 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002665 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 }
2667 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002668 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002670 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2672 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002673 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 }
2675 break;
2676 case '+':
2677 Char = getCharAndSize(CurPtr, SizeTmp);
2678 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002680 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002683 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002685 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 }
2687 break;
2688 case '-':
2689 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002690 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002691 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002692 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002693 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002694 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2696 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002697 Kind = tok::arrowstar;
2698 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002700 Kind = tok::arrow;
2701 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002703 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002705 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 }
2707 break;
2708 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002709 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 break;
2711 case '!':
2712 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002713 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2715 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002716 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 }
2718 break;
2719 case '/':
2720 // 6.4.9: Comments
2721 Char = getCharAndSize(CurPtr, SizeTmp);
2722 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002723 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2724 // want to lex this as a comment. There is one problem with this though,
2725 // that in one particular corner case, this can change the behavior of the
2726 // resultant program. For example, In "foo //**/ bar", C89 would lex
2727 // this as "foo / bar" and langauges with BCPL comments would lex it as
2728 // "foo". Check to see if the character after the second slash is a '*'.
2729 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002730 // However, we never do this in -traditional-cpp mode.
2731 if ((Features.BCPLComment ||
2732 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2733 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002734 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002735 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Chris Lattner8402c732009-01-16 22:39:25 +00002737 // It is common for the tokens immediately after a // comment to be
2738 // whitespace (indentation for the next line). Instead of going through
2739 // the big switch, handle it efficiently now.
2740 goto SkipIgnoredUnits;
2741 }
2742 }
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Chris Lattner8402c732009-01-16 22:39:25 +00002744 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002746 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002747 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002748 }
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Chris Lattner8402c732009-01-16 22:39:25 +00002750 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002752 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002754 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 }
2756 break;
2757 case '%':
2758 Char = getCharAndSize(CurPtr, SizeTmp);
2759 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002760 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2762 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002763 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2765 } else if (Features.Digraphs && Char == ':') {
2766 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2767 Char = getCharAndSize(CurPtr, SizeTmp);
2768 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002769 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2771 SizeTmp2, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002772 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002774 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002775 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002776 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002777 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 // We parsed a # character. If this occurs at the start of the line,
2779 // it's actually the start of a preprocessing directive. Callback to
2780 // the preprocessor to handle it.
2781 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002782 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002783 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002784 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // As an optimization, if the preprocessor didn't switch lexers, tail
2787 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002788 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 // Start a new token. If this is a #include or something, the PP may
2790 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002791 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002793 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002794 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 IsAtStartOfLine = false;
2796 }
2797 goto LexNextToken; // GCC isn't tail call eliminating.
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Chris Lattner168ae2d2007-10-17 20:41:00 +00002800 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Chris Lattnere91e9322009-03-18 20:58:27 +00002803 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 }
2805 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002806 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 }
2808 break;
2809 case '<':
2810 Char = getCharAndSize(CurPtr, SizeTmp);
2811 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002812 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002814 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2815 if (After == '=') {
2816 Kind = tok::lesslessequal;
2817 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2818 SizeTmp2, Result);
2819 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2820 // If this is actually a '<<<<<<<' version control conflict marker,
2821 // recognize it as such and recover nicely.
2822 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00002823 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
2824 // If this is '<<<<' and we're in a Perforce-style conflict marker,
2825 // ignore it.
2826 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002827 } else if (Features.CUDA && After == '<') {
2828 Kind = tok::lesslessless;
2829 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2830 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002831 } else {
2832 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2833 Kind = tok::lessless;
2834 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002837 Kind = tok::lessequal;
2838 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002839 if (Features.CPlusPlus0x &&
2840 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2841 // C++0x [lex.pptoken]p3:
2842 // Otherwise, if the next three characters are <:: and the subsequent
2843 // character is neither : nor >, the < is treated as a preprocessor
2844 // token by itself and not as the first character of the alternative
2845 // token <:.
2846 unsigned SizeTmp3;
2847 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2848 if (After != ':' && After != '>') {
2849 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00002850 if (!isLexingRawMode())
2851 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00002852 break;
2853 }
2854 }
2855
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002857 Kind = tok::l_square;
2858 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002860 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002861 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002862 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 }
2864 break;
2865 case '>':
2866 Char = getCharAndSize(CurPtr, SizeTmp);
2867 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002869 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002871 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2872 if (After == '=') {
2873 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2874 SizeTmp2, Result);
2875 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00002876 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
2877 // If this is actually a '>>>>' conflict marker, recognize it as such
2878 // and recover nicely.
2879 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00002880 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2881 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2882 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002883 } else if (Features.CUDA && After == '>') {
2884 Kind = tok::greatergreatergreater;
2885 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2886 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002887 } else {
2888 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2889 Kind = tok::greatergreater;
2890 }
2891
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002893 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 }
2895 break;
2896 case '^':
2897 Char = getCharAndSize(CurPtr, SizeTmp);
2898 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002900 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002901 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002902 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 }
2904 break;
2905 case '|':
2906 Char = getCharAndSize(CurPtr, SizeTmp);
2907 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002908 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2910 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002911 // If this is '|||||||' and we're in a conflict marker, ignore it.
2912 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2913 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002914 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2916 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002917 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 }
2919 break;
2920 case ':':
2921 Char = getCharAndSize(CurPtr, SizeTmp);
2922 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002923 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2925 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002926 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002928 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002929 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 }
2931 break;
2932 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002933 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 break;
2935 case '=':
2936 Char = getCharAndSize(CurPtr, SizeTmp);
2937 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002938 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00002939 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2940 goto LexNextToken;
2941
Chris Lattner9e6293d2008-10-12 04:51:35 +00002942 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002943 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002944 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002945 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 }
2947 break;
2948 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002949 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 break;
2951 case '#':
2952 Char = getCharAndSize(CurPtr, SizeTmp);
2953 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002954 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002955 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002956 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002957 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002958 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002959 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2961 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 // We parsed a # character. If this occurs at the start of the line,
2963 // it's actually the start of a preprocessing directive. Callback to
2964 // the preprocessor to handle it.
2965 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002966 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002967 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002968 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Reid Spencer5f016e22007-07-11 17:01:13 +00002970 // As an optimization, if the preprocessor didn't switch lexers, tail
2971 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002972 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002973 // Start a new token. If this is a #include or something, the PP may
2974 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002975 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002976 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002977 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002978 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 IsAtStartOfLine = false;
2980 }
2981 goto LexNextToken; // GCC isn't tail call eliminating.
2982 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002983 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 }
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Chris Lattnere91e9322009-03-18 20:58:27 +00002986 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 }
2988 break;
2989
Chris Lattner3a570772008-01-03 17:58:54 +00002990 case '@':
2991 // Objective C support.
2992 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002993 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002994 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002995 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002996 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 case '\\':
2999 // FIXME: UCN's.
3000 // FALL THROUGH.
3001 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003002 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 break;
3004 }
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 // Notify MIOpt that we read a non-whitespace/non-comment token.
3007 MIOpt.ReadToken();
3008
3009 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003010 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003011}