blob: e214ece281b165c68a27258d1b03e63ac6424a98 [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"
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Chris Lattner409a0362007-07-22 18:38:25 +000034#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "llvm/Support/MemoryBuffer.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000036#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Chris Lattnera2bf1052009-12-17 05:29:40 +000039static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000040
Chris Lattnerdbf388b2007-10-07 08:47:24 +000041//===----------------------------------------------------------------------===//
42// Token Class Implementation
43//===----------------------------------------------------------------------===//
44
Mike Stump1eb44332009-09-09 15:08:12 +000045/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000046bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000047 if (IdentifierInfo *II = getIdentifierInfo())
48 return II->getObjCKeywordID() == objcKey;
49 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000050}
51
52/// getObjCKeywordID - Return the ObjC keyword kind.
53tok::ObjCKeywordKind Token::getObjCKeywordID() const {
54 IdentifierInfo *specId = getIdentifierInfo();
55 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
56}
57
Chris Lattner53702cd2007-12-13 01:59:49 +000058
Chris Lattnerdbf388b2007-10-07 08:47:24 +000059//===----------------------------------------------------------------------===//
60// Lexer Class Implementation
61//===----------------------------------------------------------------------===//
62
David Blaikie99ba9e32011-12-20 02:48:34 +000063void Lexer::anchor() { }
64
Mike Stump1eb44332009-09-09 15:08:12 +000065void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000066 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000067 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner22d91ca2009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner22d91ca2009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000076
Eric Christopher156119d2011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattner22d91ca2009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000093
Chris Lattner22d91ca2009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Chris Lattner22d91ca2009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner22d91ca2009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner22d91ca2009-01-17 06:55:17 +0000103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner22d91ca2009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner0770dab2009-01-17 07:56:59 +0000113/// Lexer constructor - Create a new lexer object for the specified buffer
114/// with the specified preprocessor managing the lexing process. This lexer
115/// assumes that the associated file buffer and Preprocessor objects will
116/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikie4e4d0842012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner0770dab2009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Chris Lattner0770dab2009-01-17 07:56:59 +0000125 // Default to keeping comments if the preprocessor wants them.
126 SetCommentRetentionState(PP.getCommentRetentionState());
127}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000128
Chris Lattner168ae2d2007-10-17 20:41:00 +0000129/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000130/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner590f0cc2008-10-12 01:15:46 +0000131/// range will outlive it, so it doesn't take ownership of it.
David Blaikie4e4d0842012-03-11 07:00:24 +0000132Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000133 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikie4e4d0842012-03-11 07:00:24 +0000134 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000135
Chris Lattner22d91ca2009-01-17 06:55:17 +0000136 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner168ae2d2007-10-17 20:41:00 +0000138 // We *are* in raw mode.
139 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000140}
141
Chris Lattner025c3a62009-01-17 07:35:14 +0000142/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000143/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner025c3a62009-01-17 07:35:14 +0000144/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000145Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikie4e4d0842012-03-11 07:00:24 +0000146 const SourceManager &SM, const LangOptions &langOpts)
147 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000148
Mike Stump1eb44332009-09-09 15:08:12 +0000149 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner025c3a62009-01-17 07:35:14 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
154}
155
Chris Lattner42e00d12009-01-17 08:27:52 +0000156/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
157/// _Pragma expansion. This has a variety of magic semantics that this method
158/// sets up. It returns a new'd Lexer that must be delete'd when done.
159///
160/// On entrance to this routine, TokStartLoc is a macro location which has a
161/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000162/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000163/// "expanded from".
164///
165/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
166/// normal lexer that remaps tokens as they fly by. This would require making
167/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
168/// interface that could handle this stuff. This would pull GetMappedTokenLoc
169/// out of the critical path of the lexer!
170///
Mike Stump1eb44332009-09-09 15:08:12 +0000171Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000172 SourceLocation ExpansionLocStart,
173 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000174 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000175 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000176
177 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000178 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000179 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
180 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner42e00d12009-01-17 08:27:52 +0000182 // Now that the lexer is created, change the start/end locations so that we
183 // just lex the subsection of the file that we want. This is lexing from a
184 // scratch buffer.
185 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner42e00d12009-01-17 08:27:52 +0000187 L->BufferPtr = StrData;
188 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000189 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000190
191 // Set the SourceLocation with the remapping information. This ensures that
192 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000193 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
194 ExpansionLocStart,
195 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000198 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner42e00d12009-01-17 08:27:52 +0000201 // This lexer really is for _Pragma.
202 L->Is_PragmaLexer = true;
203 return L;
204}
205
Chris Lattner168ae2d2007-10-17 20:41:00 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207/// Stringify - Convert the specified string into a C string, with surrounding
208/// ""'s, and with escaped \ and " characters.
209std::string Lexer::Stringify(const std::string &Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
215 ++i; ++e;
216 }
217 }
218 return Result;
219}
220
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221/// Stringify - Convert the specified string into a C string by escaping '\'
222/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000223void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
230}
231
Chris Lattnerb0607272010-11-17 07:26:20 +0000232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
236/// getSpelling() - Return the 'spelling' of this token. The spelling of a
237/// token are the characters used to represent the token in the source file
238/// after trigraph expansion and escaped-newline folding. In particular, this
239/// wants to get the true, uncanonicalized, spelling of things like digraphs
240/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000241StringRef Lexer::getSpelling(SourceLocation loc,
242 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000243 const SourceManager &SM,
244 const LangOptions &options,
245 bool *invalid) {
246 // Break down the source location.
247 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
248
249 // Try to the load the file buffer.
250 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000252 if (invalidTemp) {
253 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000254 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000255 }
256
257 const char *tokenBegin = file.data() + locInfo.second;
258
259 // Lex from the start of the given location.
260 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
261 file.begin(), tokenBegin, file.end());
262 Token token;
263 lexer.LexFromRawLexer(token);
264
265 unsigned length = token.getLength();
266
267 // Common case: no need for cleaning.
268 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000269 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000270
271 // Hard case, we need to relex the characters into the string.
272 buffer.clear();
273 buffer.reserve(length);
274
275 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
276 unsigned charSize;
277 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
278 ti += charSize;
279 }
280
Chris Lattner5f9e2722011-07-23 10:55:15 +0000281 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000282}
283
284/// getSpelling() - Return the 'spelling' of this token. The spelling of a
285/// token are the characters used to represent the token in the source file
286/// after trigraph expansion and escaped-newline folding. In particular, this
287/// wants to get the true, uncanonicalized, spelling of things like digraphs
288/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000289std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000290 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000291 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
292
293 // If this token contains nothing interesting, return it directly.
294 bool CharDataInvalid = false;
295 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
296 &CharDataInvalid);
297 if (Invalid)
298 *Invalid = CharDataInvalid;
299 if (CharDataInvalid)
300 return std::string();
301
302 if (!Tok.needsCleaning())
303 return std::string(TokStart, TokStart+Tok.getLength());
304
305 std::string Result;
306 Result.reserve(Tok.getLength());
307
308 // Otherwise, hard case, relex the characters into the string.
309 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
310 Ptr != End; ) {
311 unsigned CharSize;
David Blaikie4e4d0842012-03-11 07:00:24 +0000312 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts));
Chris Lattnerb0607272010-11-17 07:26:20 +0000313 Ptr += CharSize;
314 }
315 assert(Result.size() != unsigned(Tok.getLength()) &&
316 "NeedsCleaning flag set on something that didn't need cleaning!");
317 return Result;
318}
319
320/// getSpelling - This method is used to get the spelling of a token into a
321/// preallocated buffer, instead of as an std::string. The caller is required
322/// to allocate enough space for the token, which is guaranteed to be at least
323/// Tok.getLength() bytes long. The actual length of the token is returned.
324///
325/// Note that this method may do two possible things: it may either fill in
326/// the buffer specified with characters, or it may *change the input pointer*
327/// to point to a constant buffer with the data already in it (avoiding a
328/// copy). The caller is not allowed to modify the returned buffer pointer
329/// if an internal buffer is returned.
330unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
331 const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000332 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000333 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000334
335 const char *TokStart = 0;
336 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
337 if (Tok.is(tok::raw_identifier))
338 TokStart = Tok.getRawIdentifierData();
339 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
340 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000341 Buffer = II->getNameStart();
342 return II->getLength();
343 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000344
345 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (Tok.isLiteral())
347 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000348
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000350 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000351 bool CharDataInvalid = false;
352 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
353 if (Invalid)
354 *Invalid = CharDataInvalid;
355 if (CharDataInvalid) {
356 Buffer = "";
357 return 0;
358 }
359 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000360
Chris Lattnerb0607272010-11-17 07:26:20 +0000361 // If this token contains nothing interesting, return it directly.
362 if (!Tok.needsCleaning()) {
363 Buffer = TokStart;
364 return Tok.getLength();
365 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000366
Chris Lattnerb0607272010-11-17 07:26:20 +0000367 // Otherwise, hard case, relex the characters into the string.
368 char *OutBuf = const_cast<char*>(Buffer);
369 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
370 Ptr != End; ) {
371 unsigned CharSize;
David Blaikie4e4d0842012-03-11 07:00:24 +0000372 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts);
Chris Lattnerb0607272010-11-17 07:26:20 +0000373 Ptr += CharSize;
374 }
375 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
376 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000377
Chris Lattnerb0607272010-11-17 07:26:20 +0000378 return OutBuf-Buffer;
379}
380
381
382
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
Chris Lattner9a611942007-10-17 21:18:47 +0000385/// MeasureTokenLength - Relex the token at the specified location and return
386/// its length in bytes in the input file. If the token needs cleaning (e.g.
387/// includes a trigraph or an escaped newline) then this count includes bytes
388/// that are part of that.
389unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000390 const SourceManager &SM,
391 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000392 // TODO: this could be special cased for common tokens like identifiers, ')',
393 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000394 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000395 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
396 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000397
398 // If this comes from a macro expansion, we really do want the macro name, not
399 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000400 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000401 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000402 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000403 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000404 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000405 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000406
407 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000408
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409 if (isWhitespace(StrData[0]))
410 return 0;
411
Chris Lattner9a611942007-10-17 21:18:47 +0000412 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000413 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
414 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000415 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000416 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000417 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000418 return TheTok.getLength();
419}
420
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000421static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
422 const SourceManager &SM,
423 const LangOptions &LangOpts) {
424 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000425 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000426 if (LocInfo.first.isInvalid())
427 return Loc;
428
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000429 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000431 if (Invalid)
432 return Loc;
433
434 // Back up from the current location until we hit the beginning of a line
435 // (or the buffer). We'll relex from that point.
436 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000437 if (LocInfo.second >= Buffer.size())
438 return Loc;
439
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000440 const char *StrData = BufStart+LocInfo.second;
441 if (StrData[0] == '\n' || StrData[0] == '\r')
442 return Loc;
443
444 const char *LexStart = StrData;
445 while (LexStart != BufStart) {
446 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
447 ++LexStart;
448 break;
449 }
450
451 --LexStart;
452 }
453
454 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000455 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000456 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
457 TheLexer.SetCommentRetentionState(true);
458
459 // Lex tokens until we find the token that contains the source location.
460 Token TheTok;
461 do {
462 TheLexer.LexFromRawLexer(TheTok);
463
464 if (TheLexer.getBufferLocation() > StrData) {
465 // Lexing this token has taken the lexer past the source location we're
466 // looking for. If the current token encompasses our source location,
467 // return the beginning of that token.
468 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
469 return TheTok.getLocation();
470
471 // We ended up skipping over the source location entirely, which means
472 // that it points into whitespace. We're done here.
473 break;
474 }
475 } while (TheTok.getKind() != tok::eof);
476
477 // We've passed our source location; just return the original source location.
478 return Loc;
479}
480
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000481SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
482 const SourceManager &SM,
483 const LangOptions &LangOpts) {
484 if (Loc.isFileID())
485 return getBeginningOfFileToken(Loc, SM, LangOpts);
486
487 if (!SM.isMacroArgExpansion(Loc))
488 return Loc;
489
490 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
491 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
492 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000493 std::pair<FileID, unsigned> BeginFileLocInfo
494 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000495 assert(FileLocInfo.first == BeginFileLocInfo.first &&
496 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000497 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000498}
499
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000500namespace {
501 enum PreambleDirectiveKind {
502 PDK_Skipped,
503 PDK_StartIf,
504 PDK_EndIf,
505 PDK_Unknown
506 };
507}
508
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000509std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000510Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000511 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000512 // Create a lexer starting at the beginning of the file. Note that we use a
513 // "fake" file source location at offset 1 so that the lexer will track our
514 // position within the file.
515 const unsigned StartOffset = 1;
516 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
David Blaikie4e4d0842012-03-11 07:00:24 +0000517 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000518 Buffer->getBufferStart(), Buffer->getBufferEnd());
519
520 bool InPreprocessorDirective = false;
521 Token TheTok;
522 Token IfStartTok;
523 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000524
525 unsigned MaxLineOffset = 0;
526 if (MaxLines) {
527 const char *CurPtr = Buffer->getBufferStart();
528 unsigned CurLine = 0;
529 while (CurPtr != Buffer->getBufferEnd()) {
530 char ch = *CurPtr++;
531 if (ch == '\n') {
532 ++CurLine;
533 if (CurLine == MaxLines)
534 break;
535 }
536 }
537 if (CurPtr != Buffer->getBufferEnd())
538 MaxLineOffset = CurPtr - Buffer->getBufferStart();
539 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000540
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000541 do {
542 TheLexer.LexFromRawLexer(TheTok);
543
544 if (InPreprocessorDirective) {
545 // If we've hit the end of the file, we're done.
546 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000547 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,
David Blaikie4e4d0842012-03-11 07:00:24 +0000660 const LangOptions &LangOpts) {
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;
David Blaikie4e4d0842012-03-11 07:00:24 +0000686 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000687 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,
David Blaikie4e4d0842012-03-11 07:00:24 +0000718 const LangOptions &LangOpts) {
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()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000723 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000724 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000725 }
726
David Blaikie4e4d0842012-03-11 07:00:24 +0000727 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000728 if (Len > Offset)
729 Len = Len - Offset;
730 else
731 return Loc;
732
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000733 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000734}
735
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000736/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000737/// token of the macro expansion.
738bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000739 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000740 const LangOptions &LangOpts,
741 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000742 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
743
744 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
745 // FIXME: If the token comes from the macro token paste operator ('##')
746 // this function will always return false;
747 if (infoLoc.second > 0)
748 return false; // Does not point at the start of token.
749
Chandler Carruth433db062011-07-14 08:20:40 +0000750 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000751 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000752 if (expansionLoc.isFileID()) {
753 // No other macro expansions, this is the first.
754 if (MacroBegin)
755 *MacroBegin = expansionLoc;
756 return true;
757 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000758
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000759 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000760}
761
762/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000763/// token of the macro expansion.
764bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000765 const SourceManager &SM,
766 const LangOptions &LangOpts,
767 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000768 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
769
770 SourceLocation spellLoc = SM.getSpellingLoc(loc);
771 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
772 if (tokLen == 0)
773 return false;
774
775 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000776 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000777 if (SM.isInFileID(afterLoc, FID))
778 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000779
780 // FIXME: If the token comes from the macro token paste operator ('##')
781 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000782
Chandler Carruth433db062011-07-14 08:20:40 +0000783 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000784 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000785 if (expansionLoc.isFileID()) {
786 // No other macro expansions.
787 if (MacroEnd)
788 *MacroEnd = expansionLoc;
789 return true;
790 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000791
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000792 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000793}
794
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000795static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000796 const SourceManager &SM,
797 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000798 SourceLocation Begin = Range.getBegin();
799 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000800 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000801 if (Range.isTokenRange()) {
802 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
803 if (End.isInvalid())
804 return CharSourceRange();
805 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000806
807 // Break down the source locations.
808 FileID FID;
809 unsigned BeginOffs;
810 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
811 if (FID.isInvalid())
812 return CharSourceRange();
813
814 unsigned EndOffs;
815 if (!SM.isInFileID(End, FID, &EndOffs) ||
816 BeginOffs > EndOffs)
817 return CharSourceRange();
818
819 return CharSourceRange::getCharRange(Begin, End);
820}
821
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000822CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000823 const SourceManager &SM,
824 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000825 SourceLocation Begin = Range.getBegin();
826 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000827 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000828 return CharSourceRange();
829
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000830 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000831 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000832
833 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000834 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
835 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000836 Range.setBegin(Begin);
837 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000838 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000839
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000840 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000841 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
842 &End)) ||
843 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
844 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000845 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000846 Range.setEnd(End);
847 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000848 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000849
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000850 assert(Begin.isMacroID() && End.isMacroID());
851 SourceLocation MacroBegin, MacroEnd;
852 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000853 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
854 &MacroEnd)) ||
855 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
856 &MacroEnd)))) {
857 Range.setBegin(MacroBegin);
858 Range.setEnd(MacroEnd);
859 return makeRangeFromFileLocs(Range, SM, LangOpts);
860 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000861
862 FileID FID;
863 unsigned BeginOffs;
864 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
865 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000866 return CharSourceRange();
867
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000868 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000869 if (!SM.isInFileID(End, FID, &EndOffs) ||
870 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000871 return CharSourceRange();
872
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000873 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
874 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
875 if (Expansion.isMacroArgExpansion() &&
876 Expansion.getSpellingLoc().isFileID()) {
877 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000878 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
879 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
880 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000881 }
882
883 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000884}
885
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000886StringRef Lexer::getSourceText(CharSourceRange Range,
887 const SourceManager &SM,
888 const LangOptions &LangOpts,
889 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000890 Range = makeFileCharRange(Range, SM, LangOpts);
891 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000892 if (Invalid) *Invalid = true;
893 return StringRef();
894 }
895
896 // Break down the source location.
897 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
898 if (beginInfo.first.isInvalid()) {
899 if (Invalid) *Invalid = true;
900 return StringRef();
901 }
902
903 unsigned EndOffs;
904 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
905 beginInfo.second > EndOffs) {
906 if (Invalid) *Invalid = true;
907 return StringRef();
908 }
909
910 // Try to the load the file buffer.
911 bool invalidTemp = false;
912 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
913 if (invalidTemp) {
914 if (Invalid) *Invalid = true;
915 return StringRef();
916 }
917
918 if (Invalid) *Invalid = false;
919 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
920}
921
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000922StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
923 const SourceManager &SM,
924 const LangOptions &LangOpts) {
925 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000926
927 // Find the location of the immediate macro expansion.
928 while (1) {
929 FileID FID = SM.getFileID(Loc);
930 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
931 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
932 Loc = Expansion.getExpansionLocStart();
933 if (!Expansion.isMacroArgExpansion())
934 break;
935
936 // For macro arguments we need to check that the argument did not come
937 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
938
939 // Loc points to the argument id of the macro definition, move to the
940 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000941 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000942 SourceLocation SpellLoc = Expansion.getSpellingLoc();
943 if (SpellLoc.isFileID())
944 break; // No inner macro.
945
946 // If spelling location resides in the same FileID as macro expansion
947 // location, it means there is no inner macro.
948 FileID MacroFID = SM.getFileID(Loc);
949 if (SM.isInFileID(SpellLoc, MacroFID))
950 break;
951
952 // Argument came from inner macro.
953 Loc = SpellLoc;
954 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000955
956 // Find the spelling location of the start of the non-argument expansion
957 // range. This is where the macro name was spelled in order to begin
958 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000959 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000960
961 // Dig out the buffer where the macro name was spelled and the extents of the
962 // name so that we can render it into the expansion note.
963 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
964 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
965 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
966 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
967}
968
Reid Spencer5f016e22007-07-11 17:01:13 +0000969//===----------------------------------------------------------------------===//
970// Character information.
971//===----------------------------------------------------------------------===//
972
Reid Spencer5f016e22007-07-11 17:01:13 +0000973enum {
974 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
975 CHAR_VERT_WS = 0x02, // '\r', '\n'
976 CHAR_LETTER = 0x04, // a-z,A-Z
977 CHAR_NUMBER = 0x08, // 0-9
978 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000979 CHAR_PERIOD = 0x20, // .
980 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000981};
982
Chris Lattner03b98662009-07-07 17:09:54 +0000983// Statically initialize CharInfo table based on ASCII character set
984// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000985static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000986{
987// 0 NUL 1 SOH 2 STX 3 ETX
988// 4 EOT 5 ENQ 6 ACK 7 BEL
989 0 , 0 , 0 , 0 ,
990 0 , 0 , 0 , 0 ,
991// 8 BS 9 HT 10 NL 11 VT
992//12 NP 13 CR 14 SO 15 SI
993 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
994 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
995//16 DLE 17 DC1 18 DC2 19 DC3
996//20 DC4 21 NAK 22 SYN 23 ETB
997 0 , 0 , 0 , 0 ,
998 0 , 0 , 0 , 0 ,
999//24 CAN 25 EM 26 SUB 27 ESC
1000//28 FS 29 GS 30 RS 31 US
1001 0 , 0 , 0 , 0 ,
1002 0 , 0 , 0 , 0 ,
1003//32 SP 33 ! 34 " 35 #
1004//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001005 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1006 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001007//40 ( 41 ) 42 * 43 +
1008//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001009 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1010 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001011//48 0 49 1 50 2 51 3
1012//52 4 53 5 54 6 55 7
1013 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1014 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1015//56 8 57 9 58 : 59 ;
1016//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001017 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1018 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001019//64 @ 65 A 66 B 67 C
1020//68 D 69 E 70 F 71 G
1021 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1022 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1023//72 H 73 I 74 J 75 K
1024//76 L 77 M 78 N 79 O
1025 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1026 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1027//80 P 81 Q 82 R 83 S
1028//84 T 85 U 86 V 87 W
1029 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1030 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1031//88 X 89 Y 90 Z 91 [
1032//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001033 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1034 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001035//96 ` 97 a 98 b 99 c
1036//100 d 101 e 102 f 103 g
1037 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1038 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1039//104 h 105 i 106 j 107 k
1040//108 l 109 m 110 n 111 o
1041 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1042 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1043//112 p 113 q 114 r 115 s
1044//116 t 117 u 118 v 119 w
1045 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1046 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1047//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001048//124 | 125 } 126 ~ 127 DEL
1049 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1050 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001051};
1052
Chris Lattnera2bf1052009-12-17 05:29:40 +00001053static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 static bool isInited = false;
1055 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001056 // check the statically-initialized CharInfo table
1057 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1058 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1059 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1060 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1061 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1062 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1063 assert(CHAR_UNDER == CharInfo[(int)'_']);
1064 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1065 for (unsigned i = 'a'; i <= 'z'; ++i) {
1066 assert(CHAR_LETTER == CharInfo[i]);
1067 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1068 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001070 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001071
Chris Lattner03b98662009-07-07 17:09:54 +00001072 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001073}
1074
Chris Lattner03b98662009-07-07 17:09:54 +00001075
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001076/// isIdentifierHead - Return true if this is the first character of an
1077/// identifier, which is [a-zA-Z_].
1078static inline bool isIdentifierHead(unsigned char c) {
1079 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1080}
1081
Reid Spencer5f016e22007-07-11 17:01:13 +00001082/// isIdentifierBody - Return true if this is the body character of an
1083/// identifier, which is [a-zA-Z0-9_].
1084static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001085 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001086}
1087
1088/// isHorizontalWhitespace - Return true if this character is horizontal
James Dennetta05369f2012-06-15 21:36:54 +00001089/// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1090/// '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001091static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001092 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001093}
1094
Anna Zaksaca25bc2011-07-27 21:43:43 +00001095/// isVerticalWhitespace - Return true if this character is vertical
James Dennetta05369f2012-06-15 21:36:54 +00001096/// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
Anna Zaksaca25bc2011-07-27 21:43:43 +00001097static inline bool isVerticalWhitespace(unsigned char c) {
1098 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1099}
1100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101/// isWhitespace - Return true if this character is horizontal or vertical
James Dennetta05369f2012-06-15 21:36:54 +00001102/// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1103/// false for '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001104static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001105 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106}
1107
1108/// isNumberBody - Return true if this is the body character of an
1109/// preprocessing number, which is [a-zA-Z0-9_.].
1110static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001111 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001112 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001113}
1114
Craig Topper2fa4e862011-08-11 04:06:15 +00001115/// isRawStringDelimBody - Return true if this is the body character of a
1116/// raw string delimiter.
1117static inline bool isRawStringDelimBody(unsigned char c) {
1118 return (CharInfo[c] &
1119 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1120 true : false;
1121}
1122
Jordan Rosed880b3a2012-06-07 01:10:31 +00001123// Allow external clients to make use of CharInfo.
1124bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1125 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1126}
1127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128
1129//===----------------------------------------------------------------------===//
1130// Diagnostics forwarding code.
1131//===----------------------------------------------------------------------===//
1132
Chris Lattner409a0362007-07-22 18:38:25 +00001133/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001134/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001135/// This is currently only used for _Pragma implementation, so it is the slow
1136/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001137static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1138 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001139static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1140 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001141 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001142 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattner409a0362007-07-22 18:38:25 +00001144 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001145 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001146 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001147 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chandler Carruth433db062011-07-14 08:20:40 +00001149 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001150 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001151 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001152 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Chris Lattnere7fb4842009-02-15 20:52:18 +00001154 // Figure out the expansion loc range, which is the range covered by the
1155 // original _Pragma(...) sequence.
1156 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001157 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Chandler Carruthbf340e42011-07-26 03:03:05 +00001159 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001160}
1161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162/// getSourceLocation - Return a source location identifier for the specified
1163/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001164SourceLocation Lexer::getSourceLocation(const char *Loc,
1165 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001166 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001168
1169 // In the normal case, we're just lexing from a simple file buffer, return
1170 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001171 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001172 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001173 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Chris Lattner2b2453a2009-01-17 06:22:33 +00001175 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1176 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001177 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001178 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001179}
1180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181/// Diag - Forwarding function for diagnostics. This translate a source
1182/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001183DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001184 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001185}
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
1187//===----------------------------------------------------------------------===//
1188// Trigraph and Escaped Newline Handling Code.
1189//===----------------------------------------------------------------------===//
1190
1191/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1192/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1193static char GetTrigraphCharForLetter(char Letter) {
1194 switch (Letter) {
1195 default: return 0;
1196 case '=': return '#';
1197 case ')': return ']';
1198 case '(': return '[';
1199 case '!': return '|';
1200 case '\'': return '^';
1201 case '>': return '}';
1202 case '/': return '\\';
1203 case '<': return '{';
1204 case '-': return '~';
1205 }
1206}
1207
1208/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1209/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1210/// return the result character. Finally, emit a warning about trigraph use
1211/// whether trigraphs are enabled or not.
1212static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1213 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001214 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
David Blaikie4e4d0842012-03-11 07:00:24 +00001216 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001217 if (!L->isLexingRawMode())
1218 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001219 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 }
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner74d15df2008-11-22 02:02:22 +00001222 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001223 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 return Res;
1225}
1226
Chris Lattner24f0e482009-04-18 22:05:41 +00001227/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1228/// 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 +00001229/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001230unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1231 unsigned Size = 0;
1232 while (isWhitespace(Ptr[Size])) {
1233 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Chris Lattner24f0e482009-04-18 22:05:41 +00001235 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1236 continue;
1237
1238 // If this is a \r\n or \n\r, skip the other half.
1239 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1240 Ptr[Size-1] != Ptr[Size])
1241 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Chris Lattner24f0e482009-04-18 22:05:41 +00001243 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001244 }
1245
Chris Lattner24f0e482009-04-18 22:05:41 +00001246 // Not an escaped newline, must be a \t or something else.
1247 return 0;
1248}
1249
Chris Lattner03374952009-04-18 22:27:02 +00001250/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1251/// them), skip over them and return the first non-escaped-newline found,
1252/// otherwise return P.
1253const char *Lexer::SkipEscapedNewLines(const char *P) {
1254 while (1) {
1255 const char *AfterEscape;
1256 if (*P == '\\') {
1257 AfterEscape = P+1;
1258 } else if (*P == '?') {
1259 // If not a trigraph for escape, bail out.
1260 if (P[1] != '?' || P[2] != '/')
1261 return P;
1262 AfterEscape = P+3;
1263 } else {
1264 return P;
1265 }
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Chris Lattner03374952009-04-18 22:27:02 +00001267 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1268 if (NewLineSize == 0) return P;
1269 P = AfterEscape+NewLineSize;
1270 }
1271}
1272
Anna Zaksaca25bc2011-07-27 21:43:43 +00001273/// \brief Checks that the given token is the first token that occurs after the
1274/// given location (this excludes comments and whitespace). Returns the location
1275/// immediately after the specified token. If the token is not found or the
1276/// location is inside a macro, the returned source location will be invalid.
1277SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1278 tok::TokenKind TKind,
1279 const SourceManager &SM,
1280 const LangOptions &LangOpts,
1281 bool SkipTrailingWhitespaceAndNewLine) {
1282 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001283 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001284 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001285 }
1286 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1287
1288 // Break down the source location.
1289 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1290
1291 // Try to load the file buffer.
1292 bool InvalidTemp = false;
1293 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1294 if (InvalidTemp)
1295 return SourceLocation();
1296
1297 const char *TokenBegin = File.data() + LocInfo.second;
1298
1299 // Lex from the start of the given location.
1300 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1301 TokenBegin, File.end());
1302 // Find the token.
1303 Token Tok;
1304 lexer.LexFromRawLexer(Tok);
1305 if (Tok.isNot(TKind))
1306 return SourceLocation();
1307 SourceLocation TokenLoc = Tok.getLocation();
1308
1309 // Calculate how much whitespace needs to be skipped if any.
1310 unsigned NumWhitespaceChars = 0;
1311 if (SkipTrailingWhitespaceAndNewLine) {
1312 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1313 Tok.getLength();
1314 unsigned char C = *TokenEnd;
1315 while (isHorizontalWhitespace(C)) {
1316 C = *(++TokenEnd);
1317 NumWhitespaceChars++;
1318 }
1319 if (isVerticalWhitespace(C))
1320 NumWhitespaceChars++;
1321 }
1322
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001323 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001324}
Chris Lattner24f0e482009-04-18 22:05:41 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1327/// get its size, and return it. This is tricky in several cases:
1328/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1329/// then either return the trigraph (skipping 3 chars) or the '?',
1330/// depending on whether trigraphs are enabled or not.
1331/// 2. If this is an escaped newline (potentially with whitespace between
1332/// the backslash and newline), implicitly skip the newline and return
1333/// the char after it.
1334/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1335///
1336/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1337/// know that we can accumulate into Size, and that we have already incremented
1338/// Ptr by Size bytes.
1339///
1340/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1341/// be updated to match.
1342///
1343char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001344 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // If we have a slash, look for an escaped newline.
1346 if (Ptr[0] == '\\') {
1347 ++Size;
1348 ++Ptr;
1349Slash:
1350 // Common case, backslash-char where the char is not whitespace.
1351 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Chris Lattner5636a3b2009-06-23 05:15:06 +00001353 // See if we have optional whitespace characters between the slash and
1354 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001355 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1356 // Remember that this token needs to be cleaned.
1357 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Chris Lattner24f0e482009-04-18 22:05:41 +00001359 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001360 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001361 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner24f0e482009-04-18 22:05:41 +00001363 // Found backslash<whitespace><newline>. Parse the char after it.
1364 Size += EscapedNewLineSize;
1365 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001366
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001367 // If the char that we finally got was a \n, then we must have had
1368 // something like \<newline><newline>. We don't want to consume the
1369 // second newline.
1370 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1371 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001372
Chris Lattner24f0e482009-04-18 22:05:41 +00001373 // Use slow version to accumulate a correct size field.
1374 return getCharAndSizeSlow(Ptr, Size, Tok);
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // Otherwise, this is not an escaped newline, just return the slash.
1378 return '\\';
1379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 // If this is a trigraph, process it.
1382 if (Ptr[0] == '?' && Ptr[1] == '?') {
1383 // If this is actually a legal trigraph (not something like "??x"), emit
1384 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1385 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1386 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001387 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388
1389 Ptr += 3;
1390 Size += 3;
1391 if (C == '\\') goto Slash;
1392 return C;
1393 }
1394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 // If this is neither, return a single character.
1397 ++Size;
1398 return *Ptr;
1399}
1400
1401
1402/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1403/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1404/// and that we have already incremented Ptr by Size bytes.
1405///
1406/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1407/// be updated to match.
1408char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001409 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 // If we have a slash, look for an escaped newline.
1411 if (Ptr[0] == '\\') {
1412 ++Size;
1413 ++Ptr;
1414Slash:
1415 // Common case, backslash-char where the char is not whitespace.
1416 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001419 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1420 // Found backslash<whitespace><newline>. Parse the char after it.
1421 Size += EscapedNewLineSize;
1422 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001424 // If the char that we finally got was a \n, then we must have had
1425 // something like \<newline><newline>. We don't want to consume the
1426 // second newline.
1427 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1428 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001429
Chris Lattner24f0e482009-04-18 22:05:41 +00001430 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001431 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 // Otherwise, this is not an escaped newline, just return the slash.
1435 return '\\';
1436 }
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001439 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 // If this is actually a legal trigraph (not something like "??x"), return
1441 // it.
1442 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1443 Ptr += 3;
1444 Size += 3;
1445 if (C == '\\') goto Slash;
1446 return C;
1447 }
1448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // If this is neither, return a single character.
1451 ++Size;
1452 return *Ptr;
1453}
1454
1455//===----------------------------------------------------------------------===//
1456// Helper methods for lexing.
1457//===----------------------------------------------------------------------===//
1458
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001459/// \brief Routine that indiscriminately skips bytes in the source file.
1460void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1461 BufferPtr += Bytes;
1462 if (BufferPtr > BufferEnd)
1463 BufferPtr = BufferEnd;
1464 IsAtStartOfLine = StartOfLine;
1465}
1466
Chris Lattnerd2177732007-07-20 16:59:19 +00001467void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1469 unsigned Size;
1470 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001471 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001473
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 --CurPtr; // Back up over the skipped character.
1475
1476 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1477 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1478 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001479 //
1480 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1481 // cheaper
David Blaikie4e4d0842012-03-11 07:00:24 +00001482 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001483FinishIdentifier:
1484 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001485 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1486 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 // If we are in raw mode, return this identifier raw. There is no need to
1489 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001490 if (LexingRawMode)
1491 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001493 // Fill in Result.IdentifierInfo and update the token kind,
1494 // looking up the identifier in the identifier table.
1495 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // Finally, now that we know we have an identifier, pass this off to the
1498 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001499 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001500 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001501
Chris Lattner6a170eb2009-01-21 07:43:11 +00001502 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 C = getCharAndSize(CurPtr, Size);
1508 while (1) {
1509 if (C == '$') {
1510 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001511 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001514 if (!isLexingRawMode())
1515 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 CurPtr = ConsumeChar(CurPtr, Size, Result);
1517 C = getCharAndSize(CurPtr, Size);
1518 continue;
1519 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1520 // Found end of identifier.
1521 goto FinishIdentifier;
1522 }
1523
1524 // Otherwise, this character is good, consume it.
1525 CurPtr = ConsumeChar(CurPtr, Size, Result);
1526
1527 C = getCharAndSize(CurPtr, Size);
1528 while (isIdentifierBody(C)) { // FIXME: UCNs.
1529 CurPtr = ConsumeChar(CurPtr, Size, Result);
1530 C = getCharAndSize(CurPtr, Size);
1531 }
1532 }
1533}
1534
Douglas Gregora75ec432010-08-30 14:50:47 +00001535/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001536/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001537bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001538 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001539 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001540 if (C1 != '0')
1541 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001542 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001543 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001544}
Reid Spencer5f016e22007-07-11 17:01:13 +00001545
Nate Begeman5253c7f2008-04-14 02:26:39 +00001546/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001547/// constant. From[-1] is the first character lexed. Return the end of the
1548/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001549void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 unsigned Size;
1551 char C = getCharAndSize(CurPtr, Size);
1552 char PrevCh = 0;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001553 while (isNumberBody(C)) { // FIXME: UCNs.
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 CurPtr = ConsumeChar(CurPtr, Size, Result);
1555 PrevCh = C;
1556 C = getCharAndSize(CurPtr, Size);
1557 }
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001560 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1561 // If we are in Microsoft mode, don't continue if the constant is hex.
1562 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001563 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001564 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1565 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001566
1567 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001568 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1569 // Outside C99, we accept hexadecimal floating point numbers as a
1570 // not-quite-conforming extension. Only do so if this looks like it's
1571 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1572 bool IsHexFloat = true;
1573 if (!LangOpts.C99) {
1574 if (!isHexaLiteral(BufferPtr, LangOpts))
1575 IsHexFloat = false;
1576 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1577 IsHexFloat = false;
1578 }
1579 if (IsHexFloat)
1580 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001584 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001585 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001586 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001587}
1588
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001589/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001590/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001591const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001592 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001593
1594 // Maximally munch an identifier. FIXME: UCNs.
1595 unsigned Size;
1596 char C = getCharAndSize(CurPtr, Size);
1597 if (isIdentifierHead(C)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001598 if (!getLangOpts().CPlusPlus0x) {
Richard Smithe816c712012-03-07 03:13:00 +00001599 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001600 Diag(CurPtr,
1601 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1602 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1603 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1604 return CurPtr;
1605 }
1606
1607 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1608 // that does not start with an underscore is ill-formed. As a conforming
1609 // extension, we treat all such suffixes as if they had whitespace before
1610 // them.
1611 if (C != '_') {
1612 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001613 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1614 diag::ext_ms_reserved_user_defined_literal :
1615 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001616 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1617 return CurPtr;
1618 }
1619
Richard Smith99831e42012-03-06 03:21:47 +00001620 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001621 do {
1622 CurPtr = ConsumeChar(CurPtr, Size, Result);
1623 C = getCharAndSize(CurPtr, Size);
1624 } while (isIdentifierBody(C));
1625 }
1626 return CurPtr;
1627}
1628
Reid Spencer5f016e22007-07-11 17:01:13 +00001629/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001630/// either " or L" or u8" or u" or U".
1631void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1632 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Richard Smith661a9962011-10-15 01:18:56 +00001635 if (!isLexingRawMode() &&
1636 (Kind == tok::utf8_string_literal ||
1637 Kind == tok::utf16_string_literal ||
1638 Kind == tok::utf32_string_literal))
1639 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 char C = getAndAdvanceChar(CurPtr, Result);
1642 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001643 // Skip escaped characters. Escaped newlines will already be processed by
1644 // getAndAdvanceChar.
1645 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001647
Chris Lattner571339c2010-05-30 23:27:38 +00001648 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001649 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001650 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001651 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001652 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 }
Chris Lattner571339c2010-05-30 23:27:38 +00001655
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001656 if (C == 0) {
1657 if (isCodeCompletionPoint(CurPtr-1)) {
1658 PP->CodeCompleteNaturalLanguage();
1659 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1660 return cutOffLexing();
1661 }
1662
Chris Lattner571339c2010-05-30 23:27:38 +00001663 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001664 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 C = getAndAdvanceChar(CurPtr, Result);
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001668 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001669 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001670 CurPtr = LexUDSuffix(Result, CurPtr);
1671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001673 if (NulCharacter && !isLexingRawMode())
1674 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001675
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001677 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001678 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001679 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680}
1681
Craig Topper2fa4e862011-08-11 04:06:15 +00001682/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1683/// having lexed R", LR", u8R", uR", or UR".
1684void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1685 tok::TokenKind Kind) {
1686 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1687 // Between the initial and final double quote characters of the raw string,
1688 // any transformations performed in phases 1 and 2 (trigraphs,
1689 // universal-character-names, and line splicing) are reverted.
1690
Richard Smith661a9962011-10-15 01:18:56 +00001691 if (!isLexingRawMode())
1692 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1693
Craig Topper2fa4e862011-08-11 04:06:15 +00001694 unsigned PrefixLen = 0;
1695
1696 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1697 ++PrefixLen;
1698
1699 // If the last character was not a '(', then we didn't lex a valid delimiter.
1700 if (CurPtr[PrefixLen] != '(') {
1701 if (!isLexingRawMode()) {
1702 const char *PrefixEnd = &CurPtr[PrefixLen];
1703 if (PrefixLen == 16) {
1704 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1705 } else {
1706 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1707 << StringRef(PrefixEnd, 1);
1708 }
1709 }
1710
1711 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1712 // it's possible the '"' was intended to be part of the raw string, but
1713 // there's not much we can do about that.
1714 while (1) {
1715 char C = *CurPtr++;
1716
1717 if (C == '"')
1718 break;
1719 if (C == 0 && CurPtr-1 == BufferEnd) {
1720 --CurPtr;
1721 break;
1722 }
1723 }
1724
1725 FormTokenWithChars(Result, CurPtr, tok::unknown);
1726 return;
1727 }
1728
1729 // Save prefix and move CurPtr past it
1730 const char *Prefix = CurPtr;
1731 CurPtr += PrefixLen + 1; // skip over prefix and '('
1732
1733 while (1) {
1734 char C = *CurPtr++;
1735
1736 if (C == ')') {
1737 // Check for prefix match and closing quote.
1738 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1739 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1740 break;
1741 }
1742 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1743 if (!isLexingRawMode())
1744 Diag(BufferPtr, diag::err_unterminated_raw_string)
1745 << StringRef(Prefix, PrefixLen);
1746 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1747 return;
1748 }
1749 }
1750
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001751 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001752 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001753 CurPtr = LexUDSuffix(Result, CurPtr);
1754
Craig Topper2fa4e862011-08-11 04:06:15 +00001755 // Update the location of token as well as BufferPtr.
1756 const char *TokStart = BufferPtr;
1757 FormTokenWithChars(Result, CurPtr, Kind);
1758 Result.setLiteralData(TokStart);
1759}
1760
Reid Spencer5f016e22007-07-11 17:01:13 +00001761/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1762/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001763void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001765 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 char C = getAndAdvanceChar(CurPtr, Result);
1767 while (C != '>') {
1768 // Skip escaped characters.
1769 if (C == '\\') {
1770 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001771 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001773 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1774 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001775 // If the filename is unterminated, then it must just be a lone <
1776 // character. Return this as such.
1777 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 return;
1779 } else if (C == 0) {
1780 NulCharacter = CurPtr-1;
1781 }
1782 C = getAndAdvanceChar(CurPtr, Result);
1783 }
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001786 if (NulCharacter && !isLexingRawMode())
1787 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001790 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001791 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001792 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001793}
1794
1795
1796/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001797/// lexed either ' or L' or u' or U'.
1798void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1799 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 const char *NulCharacter = 0; // Does this character contain the \0 character?
1801
Richard Smith661a9962011-10-15 01:18:56 +00001802 if (!isLexingRawMode() &&
1803 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1804 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1805
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 char C = getAndAdvanceChar(CurPtr, Result);
1807 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001808 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001809 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001810 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001811 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001812 }
1813
1814 while (C != '\'') {
1815 // Skip escaped characters.
1816 if (C == '\\') {
1817 // Skip the escaped character.
1818 // FIXME: UCN's
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001819 getAndAdvanceChar(CurPtr, Result);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001820 } else if (C == '\n' || C == '\r' || // Newline.
1821 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001822 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001823 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001824 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1825 return;
1826 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001827 if (isCodeCompletionPoint(CurPtr-1)) {
1828 PP->CodeCompleteNaturalLanguage();
1829 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1830 return cutOffLexing();
1831 }
1832
Chris Lattnerd80f7862010-07-07 23:24:27 +00001833 NulCharacter = CurPtr-1;
1834 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 C = getAndAdvanceChar(CurPtr, Result);
1836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001838 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001839 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001840 CurPtr = LexUDSuffix(Result, CurPtr);
1841
Chris Lattnerd80f7862010-07-07 23:24:27 +00001842 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001843 if (NulCharacter && !isLexingRawMode())
1844 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001845
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001847 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001848 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001849 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001850}
1851
1852/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1853/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001854///
1855/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1856///
1857bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 // Whitespace - Skip it, then return the token after the whitespace.
1859 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1860 while (1) {
1861 // Skip horizontal whitespace very aggressively.
1862 while (isHorizontalWhitespace(Char))
1863 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001865 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 if (Char != '\n' && Char != '\r')
1867 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 if (ParsingPreprocessorDirective) {
1870 // End of preprocessor directive line, let LexTokenInternal handle this.
1871 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001872 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 }
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 // ok, but handle newline.
1876 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001877 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001879 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 Char = *++CurPtr;
1881 }
1882
1883 // If this isn't immediately after a newline, there is leading space.
1884 char PrevChar = CurPtr[-1];
1885 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001886 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001887
Chris Lattnerd88dc482008-10-12 04:05:48 +00001888 // If the client wants us to return whitespace, return it now.
1889 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001890 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001891 return true;
1892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001895 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001896}
1897
1898// SkipBCPLComment - We have just read the // characters from input. Skip until
1899// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001900/// BufferPtr and return.
1901///
1902/// If we're in KeepCommentMode or any CommentHandler has inserted
1903/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001904bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 // If BCPL comments aren't explicitly enabled for this language, emit an
1906 // extension warning.
David Blaikie4e4d0842012-03-11 07:00:24 +00001907 if (!LangOpts.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // Mark them enabled so we only emit one warning for this translation
1911 // unit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001912 LangOpts.BCPLComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 }
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // Scan over the body of the comment. The common case, when scanning, is that
1916 // the comment contains normal ascii characters with nothing interesting in
1917 // them. As such, optimize for this case with the inner loop.
1918 char C;
1919 do {
1920 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // Skip over characters in the fast loop.
1922 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 C != '\n' && C != '\r') // Newline or DOS-style newline.
1924 C = *++CurPtr;
1925
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001926 const char *NextLine = CurPtr;
1927 if (C != 0) {
1928 // We found a newline, see if it's escaped.
1929 const char *EscapePtr = CurPtr-1;
1930 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1931 --EscapePtr;
1932
1933 if (*EscapePtr == '\\') // Escaped newline.
1934 CurPtr = EscapePtr;
1935 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1936 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1937 CurPtr = EscapePtr-2;
1938 else
1939 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001943 // properly decode the character. Read it in raw mode to avoid emitting
1944 // diagnostics about things like trigraphs. If we see an escaped newline,
1945 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001947 bool OldRawMode = isLexingRawMode();
1948 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001950 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001951
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001952 // If we only read only one character, then no special handling is needed.
1953 // We're done and can skip forward to the newline.
1954 if (C != 0 && CurPtr == OldPtr+1) {
1955 CurPtr = NextLine;
1956 break;
1957 }
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // If we read multiple characters, and one of those characters was a \r or
1960 // \n, then we had an escaped newline within the comment. Emit diagnostic
1961 // unless the next line is also a // comment.
1962 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1963 for (; OldPtr != CurPtr; ++OldPtr)
1964 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1965 // Okay, we found a // comment that ends in a newline, if the next
1966 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001967 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001969 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 ++ForwardPtr;
1971 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1972 break;
1973 }
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Chris Lattner74d15df2008-11-22 02:02:22 +00001975 if (!isLexingRawMode())
1976 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 break;
1978 }
1979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor55817af2010-08-25 17:04:25 +00001981 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001982 --CurPtr;
1983 break;
1984 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001985
1986 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1987 PP->CodeCompleteNaturalLanguage();
1988 cutOffLexing();
1989 return false;
1990 }
1991
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 } while (C != '\n' && C != '\r');
1993
Chris Lattner3d0ad582010-02-03 21:06:21 +00001994 // Found but did not consume the newline. Notify comment handlers about the
1995 // comment unless we're in a #if 0 block.
1996 if (PP && !isLexingRawMode() &&
1997 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1998 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001999 BufferPtr = CurPtr;
2000 return true; // A token has to be returned.
2001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002004 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 return SaveBCPLComment(Result, CurPtr);
2006
2007 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002008 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2010 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002011 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002015 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002016 // contribute to another token), it isn't needed for correctness. Note that
2017 // this is ok even in KeepWhitespaceMode, because we would have returned the
2018 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002022 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002024 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002026 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002027}
2028
2029/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
2030/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00002031bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002032 // If we're not in a preprocessor directive, just return the // comment
2033 // directly.
2034 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
David Blaikie8c0b3782012-06-06 18:52:13 +00002036 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002037 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Chris Lattner9e6293d2008-10-12 04:51:35 +00002039 // If this BCPL-style comment is in a macro definition, transmogrify it into
2040 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002041 bool Invalid = false;
2042 std::string Spelling = PP->getSpelling(Result, &Invalid);
2043 if (Invalid)
2044 return true;
2045
Chris Lattner9e6293d2008-10-12 04:51:35 +00002046 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
2047 Spelling[1] = '*'; // Change prefix to "/*".
2048 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattner9e6293d2008-10-12 04:51:35 +00002050 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00002051 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002052 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002053 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002054}
2055
2056/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002057/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2058/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002059static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 Lexer *L) {
2061 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 // Back up off the newline.
2064 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // If this is a two-character newline sequence, skip the other character.
2067 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2068 // \n\n or \r\r -> not escaped newline.
2069 if (CurPtr[0] == CurPtr[1])
2070 return false;
2071 // \n\r or \r\n -> skip the newline.
2072 --CurPtr;
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 // If we have horizontal whitespace, skip over it. We allow whitespace
2076 // between the slash and newline.
2077 bool HasSpace = false;
2078 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2079 --CurPtr;
2080 HasSpace = true;
2081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 // If we have a slash, we know this is an escaped newline.
2084 if (*CurPtr == '\\') {
2085 if (CurPtr[-1] != '*') return false;
2086 } else {
2087 // It isn't a slash, is it the ?? / trigraph?
2088 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2089 CurPtr[-3] != '*')
2090 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // This is the trigraph ending the comment. Emit a stern warning!
2093 CurPtr -= 2;
2094
2095 // If no trigraphs are enabled, warn that we ignored this trigraph and
2096 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002097 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002098 if (!L->isLexingRawMode())
2099 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 return false;
2101 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002102 if (!L->isLexingRawMode())
2103 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002107 if (!L->isLexingRawMode())
2108 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002111 if (HasSpace && !L->isLexingRawMode())
2112 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 return true;
2115}
2116
2117#ifdef __SSE2__
2118#include <emmintrin.h>
2119#elif __ALTIVEC__
2120#include <altivec.h>
2121#undef bool
2122#endif
2123
James Dennettec769932012-06-17 03:40:43 +00002124/// We have just read from input the / and * characters that started a comment.
2125/// Read until we find the * and / characters that terminate the comment.
2126/// Note that we don't bother decoding trigraphs or escaped newlines in block
2127/// comments, because they cannot cause the comment to end. The only thing
2128/// that can happen is the comment could end with an escaped newline between
2129/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002130///
Chris Lattner046c2272010-01-18 22:35:47 +00002131/// If we're in KeepCommentMode or any CommentHandler has inserted
2132/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002133bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002135 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 // optimization helps people who like to put a lot of * characters in their
2137 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002138
2139 // The first character we get with newlines and trigraphs skipped to handle
2140 // the degenerate /*/ case below correctly if the * has an escaped newline
2141 // after it.
2142 unsigned CharSize;
2143 unsigned char C = getCharAndSize(CurPtr, CharSize);
2144 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002146 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002147 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002148 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Chris Lattner31f0eca2008-10-12 04:19:49 +00002150 // KeepWhitespaceMode should return this broken comment as a token. Since
2151 // it isn't a well formed comment, just return it as an 'unknown' token.
2152 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002153 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002154 return true;
2155 }
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Chris Lattner31f0eca2008-10-12 04:19:49 +00002157 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002158 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Chris Lattner8146b682007-07-21 23:43:37 +00002161 // Check to see if the first character after the '/*' is another /. If so,
2162 // then this slash does not end the block comment, it is part of it.
2163 if (C == '/')
2164 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 while (1) {
2167 // Skip over all non-interesting characters until we find end of buffer or a
2168 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002169 if (CurPtr + 24 < BufferEnd &&
2170 // If there is a code-completion point avoid the fast scan because it
2171 // doesn't check for '\0'.
2172 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 // While not aligned to a 16-byte boundary.
2174 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2175 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 if (C == '/') goto FoundSlash;
2178
2179#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002180 __m128i Slashes = _mm_set1_epi8('/');
2181 while (CurPtr+16 <= BufferEnd) {
2182 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
2183 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002184 // Adjust the pointer to point directly after the first slash. It's
2185 // not necessary to set C here, it will be overwritten at the end of
2186 // the outer loop.
2187 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002188 goto FoundSlash;
2189 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002191 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002192#elif __ALTIVEC__
2193 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002194 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 '/', '/', '/', '/', '/', '/', '/', '/'
2196 };
2197 while (CurPtr+16 <= BufferEnd &&
2198 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2199 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002200#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 // Scan for '/' quickly. Many block comments are very large.
2202 while (CurPtr[0] != '/' &&
2203 CurPtr[1] != '/' &&
2204 CurPtr[2] != '/' &&
2205 CurPtr[3] != '/' &&
2206 CurPtr+4 < BufferEnd) {
2207 CurPtr += 4;
2208 }
2209#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 // It has to be one of the bytes scanned, increment to it and read one.
2212 C = *CurPtr++;
2213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // Loop to scan the remainder.
2216 while (C != '/' && C != '\0')
2217 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002220 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 if (CurPtr[-2] == '*') // We found the final */. We're done!
2222 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Reid Spencer5f016e22007-07-11 17:01:13 +00002224 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2225 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2226 // We found the final */, though it had an escaped newline between the
2227 // * and /. We're done!
2228 break;
2229 }
2230 }
2231 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2232 // If this is a /* inside of the comment, emit a warning. Don't do this
2233 // if this is a /*/, which will end the comment. This misses cases with
2234 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002235 if (!isLexingRawMode())
2236 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 }
2238 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002239 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002240 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // Note: the user probably forgot a */. We could continue immediately
2242 // after the /*, but this would involve lexing a lot of what really is the
2243 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002244 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Chris Lattner31f0eca2008-10-12 04:19:49 +00002246 // KeepWhitespaceMode should return this broken comment as a token. Since
2247 // it isn't a well formed comment, just return it as an 'unknown' token.
2248 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002249 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002250 return true;
2251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Chris Lattner31f0eca2008-10-12 04:19:49 +00002253 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002254 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002255 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2256 PP->CodeCompleteNaturalLanguage();
2257 cutOffLexing();
2258 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002260
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 C = *CurPtr++;
2262 }
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chris Lattner3d0ad582010-02-03 21:06:21 +00002264 // Notify comment handlers about the comment unless we're in a #if 0 block.
2265 if (PP && !isLexingRawMode() &&
2266 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2267 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002268 BufferPtr = CurPtr;
2269 return true; // A token has to be returned.
2270 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002271
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002273 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002274 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002275 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002276 }
2277
2278 // It is common for the tokens immediately after a /**/ comment to be
2279 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002280 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2281 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002283 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002285 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 }
2287
2288 // Otherwise, just return so that the next character will be lexed as a token.
2289 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002290 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002291 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292}
2293
2294//===----------------------------------------------------------------------===//
2295// Primary Lexing Entry Points
2296//===----------------------------------------------------------------------===//
2297
Reid Spencer5f016e22007-07-11 17:01:13 +00002298/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2299/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002300void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2302 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002303 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002304
2305 // CurPtr - Cache BufferPtr in an automatic variable.
2306 const char *CurPtr = BufferPtr;
2307 while (1) {
2308 char Char = getAndAdvanceChar(CurPtr, Tmp);
2309 switch (Char) {
2310 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002311 if (Result)
2312 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 break;
2314 case 0: // Null.
2315 // Found end of file?
2316 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002317 if (isCodeCompletionPoint(CurPtr-1)) {
2318 PP->CodeCompleteNaturalLanguage();
2319 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002320 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002321 }
2322
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002324 if (Result)
2325 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 break;
2327 }
2328 // FALL THROUGH.
2329 case '\r':
2330 case '\n':
2331 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2332 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2333 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Peter Collingbourne84021552011-02-28 02:37:51 +00002335 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002337 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002338 if (PP)
2339 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002340 Lex(Tmp);
2341 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002342 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Benjamin Kramer3093b202012-05-18 19:32:16 +00002344 // Finally, we're done;
2345 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
2347 }
2348}
2349
2350/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2351/// condition, reporting diagnostics and handling other edge cases as required.
2352/// This returns true if Result contains a token, false if PP.Lex should be
2353/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002354bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 // If we hit the end of the file while parsing a preprocessor directive,
2356 // end the preprocessor directive first. The next token returned will
2357 // then be the end of file.
2358 if (ParsingPreprocessorDirective) {
2359 // Done parsing the "line".
2360 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002362 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002365 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002367 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 // If we are in raw mode, return this event as an EOF token. Let the caller
2370 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002371 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 Result.startToken();
2373 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002374 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 return true;
2376 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002377
Douglas Gregorf44e8542010-08-24 19:08:16 +00002378 // Issue diagnostics for unterminated #if and missing newline.
2379
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 // If we are in a #if directive, emit an error.
2381 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002382 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002383 PP->Diag(ConditionalStack.back().IfLoc,
2384 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 ConditionalStack.pop_back();
2386 }
Mike Stump1eb44332009-09-09 15:08:12 +00002387
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002388 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2389 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002390 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2391 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2392 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2393 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 BufferPtr = CurPtr;
2396
2397 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002398 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002399}
2400
2401/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2402/// the specified lexer will return a tok::l_paren token, 0 if it is something
2403/// else and 2 if there are no more tokens in the buffer controlled by the
2404/// lexer.
2405unsigned Lexer::isNextPPTokenLParen() {
2406 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002407
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 // Switch to 'skipping' mode. This will ensure that we can lex a token
2409 // without emitting diagnostics, disables macro expansion, and will cause EOF
2410 // to return an EOF token instead of popping the include stack.
2411 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 // Save state that can be changed while lexing so that we can restore it.
2414 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002415 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Chris Lattnerd2177732007-07-20 16:59:19 +00002417 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002418 Tok.startToken();
2419 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Reid Spencer5f016e22007-07-11 17:01:13 +00002421 // Restore state that may have changed.
2422 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002423 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Reid Spencer5f016e22007-07-11 17:01:13 +00002425 // Restore the lexer back to non-skipping mode.
2426 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002428 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002429 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002430 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002431}
2432
James Dennettec769932012-06-17 03:40:43 +00002433/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002434static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2435 ConflictMarkerKind CMK) {
2436 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2437 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2438 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2439 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002441 // Must occur at start of line.
2442 if (RestOfBuffer[Pos-1] != '\r' &&
2443 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002444 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2445 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002446 continue;
2447 }
2448 return RestOfBuffer.data()+Pos;
2449 }
2450 return 0;
2451}
2452
2453/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2454/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2455/// and recover nicely. This returns true if it is a conflict marker and false
2456/// if not.
2457bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2458 // Only a conflict marker if it starts at the beginning of a line.
2459 if (CurPtr != BufferStart &&
2460 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2461 return false;
2462
Richard Smithd5e1d602011-10-12 00:37:51 +00002463 // Check to see if we have <<<<<<< or >>>>.
2464 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2465 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002466 return false;
2467
2468 // If we have a situation where we don't care about conflict markers, ignore
2469 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002470 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002471 return false;
2472
Richard Smithd5e1d602011-10-12 00:37:51 +00002473 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2474
2475 // Check to see if there is an ending marker somewhere in the buffer at the
2476 // start of a line to terminate this conflict marker.
2477 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002478 // We found a match. We are really in a conflict marker.
2479 // Diagnose this, and ignore to the end of line.
2480 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002481 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002482
2483 // Skip ahead to the end of line. We know this exists because the
2484 // end-of-conflict marker starts with \r or \n.
2485 while (*CurPtr != '\r' && *CurPtr != '\n') {
2486 assert(CurPtr != BufferEnd && "Didn't find end of line");
2487 ++CurPtr;
2488 }
2489 BufferPtr = CurPtr;
2490 return true;
2491 }
2492
2493 // No end of conflict marker found.
2494 return false;
2495}
2496
2497
Richard Smithd5e1d602011-10-12 00:37:51 +00002498/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2499/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2500/// is the end of a conflict marker. Handle it by ignoring up until the end of
2501/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002502bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2503 // Only a conflict marker if it starts at the beginning of a line.
2504 if (CurPtr != BufferStart &&
2505 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2506 return false;
2507
2508 // If we have a situation where we don't care about conflict markers, ignore
2509 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002510 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002511 return false;
2512
Richard Smithd5e1d602011-10-12 00:37:51 +00002513 // Check to see if we have the marker (4 characters in a row).
2514 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002515 if (CurPtr[i] != CurPtr[0])
2516 return false;
2517
2518 // If we do have it, search for the end of the conflict marker. This could
2519 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2520 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002521 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2522 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002523 CurPtr = End;
2524
2525 // Skip ahead to the end of line.
2526 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2527 ++CurPtr;
2528
2529 BufferPtr = CurPtr;
2530
2531 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002532 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002533 return true;
2534 }
2535
2536 return false;
2537}
2538
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002539bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2540 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002541 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002542 return Loc == PP->getCodeCompletionLoc();
2543 }
2544
2545 return false;
2546}
2547
Reid Spencer5f016e22007-07-11 17:01:13 +00002548
2549/// LexTokenInternal - This implements a simple C family lexer. It is an
2550/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002551/// has a null character at the end of the file. This returns a preprocessing
2552/// token, not a normal token, as such, it is an internal interface. It assumes
2553/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002554void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002555LexNextToken:
2556 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002557 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 // CurPtr - Cache BufferPtr in an automatic variable.
2561 const char *CurPtr = BufferPtr;
2562
2563 // Small amounts of horizontal whitespace is very common between tokens.
2564 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2565 ++CurPtr;
2566 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2567 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Chris Lattnerd88dc482008-10-12 04:05:48 +00002569 // If we are keeping whitespace and other tokens, just return what we just
2570 // skipped. The next lexer invocation will return the token after the
2571 // whitespace.
2572 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002573 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002574 return;
2575 }
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002578 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 // Read a character, advancing over it.
2584 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002585 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 switch (Char) {
2588 case 0: // Null.
2589 // Found end of file?
2590 if (CurPtr-1 == BufferEnd) {
2591 // Read the PP instance variable into an automatic variable, because
2592 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002593 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2595 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002596 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2597 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002600 // Check if we are performing code completion.
2601 if (isCodeCompletionPoint(CurPtr-1)) {
2602 // Return the code-completion token.
2603 Result.startToken();
2604 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2605 return;
2606 }
2607
Chris Lattner74d15df2008-11-22 02:02:22 +00002608 if (!isLexingRawMode())
2609 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002610 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002611 if (SkipWhitespace(Result, CurPtr))
2612 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002615
2616 case 26: // DOS & CP/M EOF: "^Z".
2617 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002618 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002619 // Read the PP instance variable into an automatic variable, because
2620 // LexEndOfFile will often delete 'this'.
2621 Preprocessor *PPCache = PP;
2622 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2623 return; // Got a token to return.
2624 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2625 return PPCache->Lex(Result);
2626 }
2627 // If Microsoft extensions are disabled, this is just random garbage.
2628 Kind = tok::unknown;
2629 break;
2630
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 case '\n':
2632 case '\r':
2633 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002634 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 if (ParsingPreprocessorDirective) {
2636 // Done parsing the "line".
2637 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002640 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002641 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 // Since we consumed a newline, we are back at the start of a line.
2644 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Peter Collingbourne84021552011-02-28 02:37:51 +00002646 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 break;
2648 }
2649 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002650 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002652 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Chris Lattnerd88dc482008-10-12 04:05:48 +00002654 if (SkipWhitespace(Result, CurPtr))
2655 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 goto LexNextToken; // GCC isn't tail call eliminating.
2657 case ' ':
2658 case '\t':
2659 case '\f':
2660 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002661 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002662 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002663 if (SkipWhitespace(Result, CurPtr))
2664 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002665
2666 SkipIgnoredUnits:
2667 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002668
Chris Lattner8133cfc2007-07-22 06:29:05 +00002669 // If the next token is obviously a // or /* */ comment, skip it efficiently
2670 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002671 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002672 LangOpts.BCPLComment && !LangOpts.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002673 if (SkipBCPLComment(Result, CurPtr+2))
2674 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002675 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002676 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002677 if (SkipBlockComment(Result, CurPtr+2))
2678 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002679 goto SkipIgnoredUnits;
2680 } else if (isHorizontalWhitespace(*CurPtr)) {
2681 goto SkipHorizontalWhitespace;
2682 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002684
Chris Lattner3a570772008-01-03 17:58:54 +00002685 // C99 6.4.4.1: Integer Constants.
2686 // C99 6.4.4.2: Floating Constants.
2687 case '0': case '1': case '2': case '3': case '4':
2688 case '5': case '6': case '7': case '8': case '9':
2689 // Notify MIOpt that we read a non-whitespace/non-comment token.
2690 MIOpt.ReadToken();
2691 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Douglas Gregor5cee1192011-07-27 05:40:30 +00002693 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2694 // Notify MIOpt that we read a non-whitespace/non-comment token.
2695 MIOpt.ReadToken();
2696
David Blaikie4e4d0842012-03-11 07:00:24 +00002697 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002698 Char = getCharAndSize(CurPtr, SizeTmp);
2699
2700 // UTF-16 string literal
2701 if (Char == '"')
2702 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2703 tok::utf16_string_literal);
2704
2705 // UTF-16 character constant
2706 if (Char == '\'')
2707 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2708 tok::utf16_char_constant);
2709
Craig Topper2fa4e862011-08-11 04:06:15 +00002710 // UTF-16 raw string literal
2711 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2712 return LexRawStringLiteral(Result,
2713 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2714 SizeTmp2, Result),
2715 tok::utf16_string_literal);
2716
2717 if (Char == '8') {
2718 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2719
2720 // UTF-8 string literal
2721 if (Char2 == '"')
2722 return LexStringLiteral(Result,
2723 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2724 SizeTmp2, Result),
2725 tok::utf8_string_literal);
2726
2727 if (Char2 == 'R') {
2728 unsigned SizeTmp3;
2729 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2730 // UTF-8 raw string literal
2731 if (Char3 == '"') {
2732 return LexRawStringLiteral(Result,
2733 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2734 SizeTmp2, Result),
2735 SizeTmp3, Result),
2736 tok::utf8_string_literal);
2737 }
2738 }
2739 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002740 }
2741
2742 // treat u like the start of an identifier.
2743 return LexIdentifier(Result, CurPtr);
2744
2745 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2746 // Notify MIOpt that we read a non-whitespace/non-comment token.
2747 MIOpt.ReadToken();
2748
David Blaikie4e4d0842012-03-11 07:00:24 +00002749 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002750 Char = getCharAndSize(CurPtr, SizeTmp);
2751
2752 // UTF-32 string literal
2753 if (Char == '"')
2754 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2755 tok::utf32_string_literal);
2756
2757 // UTF-32 character constant
2758 if (Char == '\'')
2759 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2760 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002761
2762 // UTF-32 raw string literal
2763 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2764 return LexRawStringLiteral(Result,
2765 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2766 SizeTmp2, Result),
2767 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002768 }
2769
2770 // treat U like the start of an identifier.
2771 return LexIdentifier(Result, CurPtr);
2772
Craig Topper2fa4e862011-08-11 04:06:15 +00002773 case 'R': // Identifier or C++0x raw string literal
2774 // Notify MIOpt that we read a non-whitespace/non-comment token.
2775 MIOpt.ReadToken();
2776
David Blaikie4e4d0842012-03-11 07:00:24 +00002777 if (LangOpts.CPlusPlus0x) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002778 Char = getCharAndSize(CurPtr, SizeTmp);
2779
2780 if (Char == '"')
2781 return LexRawStringLiteral(Result,
2782 ConsumeChar(CurPtr, SizeTmp, Result),
2783 tok::string_literal);
2784 }
2785
2786 // treat R like the start of an identifier.
2787 return LexIdentifier(Result, CurPtr);
2788
Chris Lattner3a570772008-01-03 17:58:54 +00002789 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 // Notify MIOpt that we read a non-whitespace/non-comment token.
2791 MIOpt.ReadToken();
2792 Char = getCharAndSize(CurPtr, SizeTmp);
2793
2794 // Wide string literal.
2795 if (Char == '"')
2796 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002797 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002798
Craig Topper2fa4e862011-08-11 04:06:15 +00002799 // Wide raw string literal.
David Blaikie4e4d0842012-03-11 07:00:24 +00002800 if (LangOpts.CPlusPlus0x && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002801 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2802 return LexRawStringLiteral(Result,
2803 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2804 SizeTmp2, Result),
2805 tok::wide_string_literal);
2806
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 // Wide character constant.
2808 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002809 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2810 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // C99 6.4.2: Identifiers.
2814 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2815 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002816 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2818 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2819 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002820 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 case 'v': case 'w': case 'x': case 'y': case 'z':
2822 case '_':
2823 // Notify MIOpt that we read a non-whitespace/non-comment token.
2824 MIOpt.ReadToken();
2825 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002826
2827 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002828 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002829 if (!isLexingRawMode())
2830 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002831 // Notify MIOpt that we read a non-whitespace/non-comment token.
2832 MIOpt.ReadToken();
2833 return LexIdentifier(Result, CurPtr);
2834 }
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Chris Lattner9e6293d2008-10-12 04:51:35 +00002836 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002837 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 // C99 6.4.4: Character Constants.
2840 case '\'':
2841 // Notify MIOpt that we read a non-whitespace/non-comment token.
2842 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002843 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002844
2845 // C99 6.4.5: String Literals.
2846 case '"':
2847 // Notify MIOpt that we read a non-whitespace/non-comment token.
2848 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002849 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002850
2851 // C99 6.4.6: Punctuators.
2852 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002853 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 break;
2855 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002856 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 break;
2858 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002859 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 break;
2861 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002862 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 break;
2864 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002865 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 break;
2867 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002868 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 break;
2870 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002871 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002872 break;
2873 case '.':
2874 Char = getCharAndSize(CurPtr, SizeTmp);
2875 if (Char >= '0' && Char <= '9') {
2876 // Notify MIOpt that we read a non-whitespace/non-comment token.
2877 MIOpt.ReadToken();
2878
2879 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00002880 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002881 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 CurPtr += SizeTmp;
2883 } else if (Char == '.' &&
2884 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002885 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2887 SizeTmp2, Result);
2888 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002889 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 }
2891 break;
2892 case '&':
2893 Char = getCharAndSize(CurPtr, SizeTmp);
2894 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002895 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2897 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002898 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2900 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002901 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002902 }
2903 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002904 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002906 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002907 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2908 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002909 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 }
2911 break;
2912 case '+':
2913 Char = getCharAndSize(CurPtr, SizeTmp);
2914 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002916 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002917 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002919 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002921 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 }
2923 break;
2924 case '-':
2925 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002926 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002928 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00002929 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002930 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2932 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002933 Kind = tok::arrowstar;
2934 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002935 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002936 Kind = tok::arrow;
2937 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002938 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002939 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002941 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 }
2943 break;
2944 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002945 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 break;
2947 case '!':
2948 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002949 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2951 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002952 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 }
2954 break;
2955 case '/':
2956 // 6.4.9: Comments
2957 Char = getCharAndSize(CurPtr, SizeTmp);
2958 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002959 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2960 // want to lex this as a comment. There is one problem with this though,
2961 // that in one particular corner case, this can change the behavior of the
2962 // resultant program. For example, In "foo //**/ bar", C89 would lex
2963 // this as "foo / bar" and langauges with BCPL comments would lex it as
2964 // "foo". Check to see if the character after the second slash is a '*'.
2965 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002966 // However, we never do this in -traditional-cpp mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002967 if ((LangOpts.BCPLComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002968 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002969 !LangOpts.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002970 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002971 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Chris Lattner8402c732009-01-16 22:39:25 +00002973 // It is common for the tokens immediately after a // comment to be
2974 // whitespace (indentation for the next line). Instead of going through
2975 // the big switch, handle it efficiently now.
2976 goto SkipIgnoredUnits;
2977 }
2978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Chris Lattner8402c732009-01-16 22:39:25 +00002980 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002982 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002983 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002984 }
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Chris Lattner8402c732009-01-16 22:39:25 +00002986 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002988 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002990 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 }
2992 break;
2993 case '%':
2994 Char = getCharAndSize(CurPtr, SizeTmp);
2995 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002996 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00002998 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002999 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003001 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003002 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3003 Char = getCharAndSize(CurPtr, SizeTmp);
3004 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003005 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3007 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003008 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003010 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003011 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003012 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003013 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003014 // We parsed a # character. If this occurs at the start of the line,
3015 // it's actually the start of a preprocessing directive. Callback to
3016 // the preprocessor to handle it.
3017 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003018 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003019 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003020 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 // As an optimization, if the preprocessor didn't switch lexers, tail
3023 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003024 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 // Start a new token. If this is a #include or something, the PP may
3026 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003027 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003029 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003030 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 IsAtStartOfLine = false;
3032 }
3033 goto LexNextToken; // GCC isn't tail call eliminating.
3034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Chris Lattner168ae2d2007-10-17 20:41:00 +00003036 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 }
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Chris Lattnere91e9322009-03-18 20:58:27 +00003039 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003040 }
3041 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003042 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 }
3044 break;
3045 case '<':
3046 Char = getCharAndSize(CurPtr, SizeTmp);
3047 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003048 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003049 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003050 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3051 if (After == '=') {
3052 Kind = tok::lesslessequal;
3053 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3054 SizeTmp2, Result);
3055 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3056 // If this is actually a '<<<<<<<' version control conflict marker,
3057 // recognize it as such and recover nicely.
3058 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003059 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3060 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3061 // ignore it.
3062 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003063 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003064 Kind = tok::lesslessless;
3065 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3066 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003067 } else {
3068 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3069 Kind = tok::lessless;
3070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003071 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003073 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003074 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3075 if (LangOpts.CPlusPlus0x &&
Richard Smith87a1e192011-04-14 18:36:27 +00003076 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3077 // C++0x [lex.pptoken]p3:
3078 // Otherwise, if the next three characters are <:: and the subsequent
3079 // character is neither : nor >, the < is treated as a preprocessor
3080 // token by itself and not as the first character of the alternative
3081 // token <:.
3082 unsigned SizeTmp3;
3083 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3084 if (After != ':' && After != '>') {
3085 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003086 if (!isLexingRawMode())
3087 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003088 break;
3089 }
3090 }
3091
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003093 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003094 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003095 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003096 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003098 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003099 }
3100 break;
3101 case '>':
3102 Char = getCharAndSize(CurPtr, SizeTmp);
3103 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003104 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003105 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003106 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003107 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3108 if (After == '=') {
3109 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3110 SizeTmp2, Result);
3111 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003112 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3113 // If this is actually a '>>>>' conflict marker, recognize it as such
3114 // and recover nicely.
3115 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003116 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3117 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3118 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003119 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003120 Kind = tok::greatergreatergreater;
3121 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3122 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003123 } else {
3124 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3125 Kind = tok::greatergreater;
3126 }
3127
Reid Spencer5f016e22007-07-11 17:01:13 +00003128 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003129 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003130 }
3131 break;
3132 case '^':
3133 Char = getCharAndSize(CurPtr, SizeTmp);
3134 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003135 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003136 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003137 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003138 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003139 }
3140 break;
3141 case '|':
3142 Char = getCharAndSize(CurPtr, SizeTmp);
3143 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003144 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3146 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003147 // If this is '|||||||' and we're in a conflict marker, ignore it.
3148 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3149 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003150 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003151 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3152 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003153 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003154 }
3155 break;
3156 case ':':
3157 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003158 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003159 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003160 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003161 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003162 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003163 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003164 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003165 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 }
3167 break;
3168 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003169 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003170 break;
3171 case '=':
3172 Char = getCharAndSize(CurPtr, SizeTmp);
3173 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003174 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003175 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3176 goto LexNextToken;
3177
Chris Lattner9e6293d2008-10-12 04:51:35 +00003178 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003180 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003181 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003182 }
3183 break;
3184 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003185 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003186 break;
3187 case '#':
3188 Char = getCharAndSize(CurPtr, SizeTmp);
3189 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003190 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003192 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003193 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003194 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003195 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003196 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3197 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 // We parsed a # character. If this occurs at the start of the line,
3199 // it's actually the start of a preprocessing directive. Callback to
3200 // the preprocessor to handle it.
3201 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003202 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003203 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003204 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Reid Spencer5f016e22007-07-11 17:01:13 +00003206 // As an optimization, if the preprocessor didn't switch lexers, tail
3207 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003208 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003209 // Start a new token. If this is a #include or something, the PP may
3210 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003211 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003213 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003214 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 IsAtStartOfLine = false;
3216 }
3217 goto LexNextToken; // GCC isn't tail call eliminating.
3218 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00003219 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 }
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Chris Lattnere91e9322009-03-18 20:58:27 +00003222 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003223 }
3224 break;
3225
Chris Lattner3a570772008-01-03 17:58:54 +00003226 case '@':
3227 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003228 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003229 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003230 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003231 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003232 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 case '\\':
3235 // FIXME: UCN's.
3236 // FALL THROUGH.
3237 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003238 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003239 break;
3240 }
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Reid Spencer5f016e22007-07-11 17:01:13 +00003242 // Notify MIOpt that we read a non-whitespace/non-comment token.
3243 MIOpt.ReadToken();
3244
3245 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003246 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003247}