blob: 78d58d3a8c03b8ccaf762a64c8bf86b6cafa63c0 [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) {
547 InPreprocessorDirective = false;
548 break;
549 }
550
551 // If we haven't hit the end of the preprocessor directive, skip this
552 // token.
553 if (!TheTok.isAtStartOfLine())
554 continue;
555
556 // We've passed the end of the preprocessor directive, and will look
557 // at this token again below.
558 InPreprocessorDirective = false;
559 }
560
Douglas Gregordf95a132010-08-09 20:45:32 +0000561 // Keep track of the # of lines in the preamble.
562 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000563 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000564
565 // If we were asked to limit the number of lines in the preamble,
566 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000567 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000568 break;
569 }
570
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000571 // Comments are okay; skip over them.
572 if (TheTok.getKind() == tok::comment)
573 continue;
574
575 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
576 // This is the start of a preprocessor directive.
577 Token HashTok = TheTok;
578 InPreprocessorDirective = true;
579
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000580 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000581 // we don't have an identifier table available. Instead, just look at
582 // the raw identifier to recognize and categorize preprocessor directives.
583 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000584 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000586 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000587 PreambleDirectiveKind PDK
588 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
589 .Case("include", PDK_Skipped)
590 .Case("__include_macros", PDK_Skipped)
591 .Case("define", PDK_Skipped)
592 .Case("undef", PDK_Skipped)
593 .Case("line", PDK_Skipped)
594 .Case("error", PDK_Skipped)
595 .Case("pragma", PDK_Skipped)
596 .Case("import", PDK_Skipped)
597 .Case("include_next", PDK_Skipped)
598 .Case("warning", PDK_Skipped)
599 .Case("ident", PDK_Skipped)
600 .Case("sccs", PDK_Skipped)
601 .Case("assert", PDK_Skipped)
602 .Case("unassert", PDK_Skipped)
603 .Case("if", PDK_StartIf)
604 .Case("ifdef", PDK_StartIf)
605 .Case("ifndef", PDK_StartIf)
606 .Case("elif", PDK_Skipped)
607 .Case("else", PDK_Skipped)
608 .Case("endif", PDK_EndIf)
609 .Default(PDK_Unknown);
610
611 switch (PDK) {
612 case PDK_Skipped:
613 continue;
614
615 case PDK_StartIf:
616 if (IfCount == 0)
617 IfStartTok = HashTok;
618
619 ++IfCount;
620 continue;
621
622 case PDK_EndIf:
623 // Mismatched #endif. The preamble ends here.
624 if (IfCount == 0)
625 break;
626
627 --IfCount;
628 continue;
629
630 case PDK_Unknown:
631 // We don't know what this directive is; stop at the '#'.
632 break;
633 }
634 }
635
636 // We only end up here if we didn't recognize the preprocessor
637 // directive or it was one that can't occur in the preamble at this
638 // point. Roll back the current token to the location of the '#'.
639 InPreprocessorDirective = false;
640 TheTok = HashTok;
641 }
642
Douglas Gregordf95a132010-08-09 20:45:32 +0000643 // We hit a token that we don't recognize as being in the
644 // "preprocessing only" part of the file, so we're no longer in
645 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000646 break;
647 } while (true);
648
649 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000650 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
651 IfCount? IfStartTok.isAtStartOfLine()
652 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000653}
654
Chris Lattner7ef5c272010-11-17 07:05:50 +0000655
656/// AdvanceToTokenCharacter - Given a location that specifies the start of a
657/// token, return a new location that specifies a character within the token.
658SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
659 unsigned CharNo,
660 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000661 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000662 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000663 // character is. This needs to take into consideration newlines and
664 // trigraphs.
665 bool Invalid = false;
666 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
667
668 // If they request the first char of the token, we're trivially done.
669 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
670 return TokStart;
671
672 unsigned PhysOffset = 0;
673
674 // The usual case is that tokens don't contain anything interesting. Skip
675 // over the uninteresting characters. If a token only consists of simple
676 // chars, this method is extremely fast.
677 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
678 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000679 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000680 ++TokPtr, --CharNo, ++PhysOffset;
681 }
682
683 // If we have a character that may be a trigraph or escaped newline, use a
684 // lexer to parse it correctly.
685 for (; CharNo; --CharNo) {
686 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000687 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000688 TokPtr += Size;
689 PhysOffset += Size;
690 }
691
692 // Final detail: if we end up on an escaped newline, we want to return the
693 // location of the actual byte of the token. For example foo\<newline>bar
694 // advanced by 3 should return the location of b, not of \\. One compounding
695 // detail of this is that the escape may be made by a trigraph.
696 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
697 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
698
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000699 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000700}
701
702/// \brief Computes the source location just past the end of the
703/// token at this source location.
704///
705/// This routine can be used to produce a source location that
706/// points just past the end of the token referenced by \p Loc, and
707/// is generally used when a diagnostic needs to point just after a
708/// token where it expected something different that it received. If
709/// the returned source location would not be meaningful (e.g., if
710/// it points into a macro), this routine returns an invalid
711/// source location.
712///
713/// \param Offset an offset from the end of the token, where the source
714/// location should refer to. The default offset (0) produces a source
715/// location pointing just past the end of the token; an offset of 1 produces
716/// a source location pointing to the last character in the token, etc.
717SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
718 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000719 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000720 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000721 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000722
723 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000724 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000725 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000726 }
727
David Blaikie4e4d0842012-03-11 07:00:24 +0000728 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000729 if (Len > Offset)
730 Len = Len - Offset;
731 else
732 return Loc;
733
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000734 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000735}
736
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000737/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000738/// token of the macro expansion.
739bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000740 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000741 const LangOptions &LangOpts,
742 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000743 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
744
745 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
746 // FIXME: If the token comes from the macro token paste operator ('##')
747 // this function will always return false;
748 if (infoLoc.second > 0)
749 return false; // Does not point at the start of token.
750
Chandler Carruth433db062011-07-14 08:20:40 +0000751 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000752 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000753 if (expansionLoc.isFileID()) {
754 // No other macro expansions, this is the first.
755 if (MacroBegin)
756 *MacroBegin = expansionLoc;
757 return true;
758 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000759
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000760 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000761}
762
763/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000764/// token of the macro expansion.
765bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000766 const SourceManager &SM,
767 const LangOptions &LangOpts,
768 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000769 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
770
771 SourceLocation spellLoc = SM.getSpellingLoc(loc);
772 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
773 if (tokLen == 0)
774 return false;
775
776 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000777 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000778 if (SM.isInFileID(afterLoc, FID))
779 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000780
781 // FIXME: If the token comes from the macro token paste operator ('##')
782 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000783
Chandler Carruth433db062011-07-14 08:20:40 +0000784 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000785 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000786 if (expansionLoc.isFileID()) {
787 // No other macro expansions.
788 if (MacroEnd)
789 *MacroEnd = expansionLoc;
790 return true;
791 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000792
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000793 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000794}
795
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000796static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000797 const SourceManager &SM,
798 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000799 SourceLocation Begin = Range.getBegin();
800 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000801 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000802 if (Range.isTokenRange()) {
803 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
804 if (End.isInvalid())
805 return CharSourceRange();
806 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000807
808 // Break down the source locations.
809 FileID FID;
810 unsigned BeginOffs;
811 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
812 if (FID.isInvalid())
813 return CharSourceRange();
814
815 unsigned EndOffs;
816 if (!SM.isInFileID(End, FID, &EndOffs) ||
817 BeginOffs > EndOffs)
818 return CharSourceRange();
819
820 return CharSourceRange::getCharRange(Begin, End);
821}
822
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000823/// \brief Accepts a range and returns a character range with file locations.
824///
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000825/// Returns a null range if a part of the range resides inside a macro
826/// expansion or the range does not reside on the same FileID.
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000827CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000828 const SourceManager &SM,
829 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000830 SourceLocation Begin = Range.getBegin();
831 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000832 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000833 return CharSourceRange();
834
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000835 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000836 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000837
838 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000839 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
840 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000841 Range.setBegin(Begin);
842 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000843 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000844
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000845 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000846 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
847 &End)) ||
848 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
849 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000850 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000851 Range.setEnd(End);
852 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000853 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000854
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000855 assert(Begin.isMacroID() && End.isMacroID());
856 SourceLocation MacroBegin, MacroEnd;
857 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000858 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
859 &MacroEnd)) ||
860 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
861 &MacroEnd)))) {
862 Range.setBegin(MacroBegin);
863 Range.setEnd(MacroEnd);
864 return makeRangeFromFileLocs(Range, SM, LangOpts);
865 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000866
867 FileID FID;
868 unsigned BeginOffs;
869 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
870 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000871 return CharSourceRange();
872
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000873 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000874 if (!SM.isInFileID(End, FID, &EndOffs) ||
875 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000876 return CharSourceRange();
877
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000878 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
879 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
880 if (Expansion.isMacroArgExpansion() &&
881 Expansion.getSpellingLoc().isFileID()) {
882 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000883 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
884 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000886 }
887
888 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000889}
890
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000891StringRef Lexer::getSourceText(CharSourceRange Range,
892 const SourceManager &SM,
893 const LangOptions &LangOpts,
894 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000895 Range = makeFileCharRange(Range, SM, LangOpts);
896 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000897 if (Invalid) *Invalid = true;
898 return StringRef();
899 }
900
901 // Break down the source location.
902 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
903 if (beginInfo.first.isInvalid()) {
904 if (Invalid) *Invalid = true;
905 return StringRef();
906 }
907
908 unsigned EndOffs;
909 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
910 beginInfo.second > EndOffs) {
911 if (Invalid) *Invalid = true;
912 return StringRef();
913 }
914
915 // Try to the load the file buffer.
916 bool invalidTemp = false;
917 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
918 if (invalidTemp) {
919 if (Invalid) *Invalid = true;
920 return StringRef();
921 }
922
923 if (Invalid) *Invalid = false;
924 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
925}
926
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000927StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
928 const SourceManager &SM,
929 const LangOptions &LangOpts) {
930 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000931
932 // Find the location of the immediate macro expansion.
933 while (1) {
934 FileID FID = SM.getFileID(Loc);
935 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
936 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
937 Loc = Expansion.getExpansionLocStart();
938 if (!Expansion.isMacroArgExpansion())
939 break;
940
941 // For macro arguments we need to check that the argument did not come
942 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
943
944 // Loc points to the argument id of the macro definition, move to the
945 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000946 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000947 SourceLocation SpellLoc = Expansion.getSpellingLoc();
948 if (SpellLoc.isFileID())
949 break; // No inner macro.
950
951 // If spelling location resides in the same FileID as macro expansion
952 // location, it means there is no inner macro.
953 FileID MacroFID = SM.getFileID(Loc);
954 if (SM.isInFileID(SpellLoc, MacroFID))
955 break;
956
957 // Argument came from inner macro.
958 Loc = SpellLoc;
959 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000960
961 // Find the spelling location of the start of the non-argument expansion
962 // range. This is where the macro name was spelled in order to begin
963 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000964 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000965
966 // Dig out the buffer where the macro name was spelled and the extents of the
967 // name so that we can render it into the expansion note.
968 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
969 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
970 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
971 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
972}
973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974//===----------------------------------------------------------------------===//
975// Character information.
976//===----------------------------------------------------------------------===//
977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978enum {
979 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
980 CHAR_VERT_WS = 0x02, // '\r', '\n'
981 CHAR_LETTER = 0x04, // a-z,A-Z
982 CHAR_NUMBER = 0x08, // 0-9
983 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000984 CHAR_PERIOD = 0x20, // .
985 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000986};
987
Chris Lattner03b98662009-07-07 17:09:54 +0000988// Statically initialize CharInfo table based on ASCII character set
989// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000990static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000991{
992// 0 NUL 1 SOH 2 STX 3 ETX
993// 4 EOT 5 ENQ 6 ACK 7 BEL
994 0 , 0 , 0 , 0 ,
995 0 , 0 , 0 , 0 ,
996// 8 BS 9 HT 10 NL 11 VT
997//12 NP 13 CR 14 SO 15 SI
998 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
999 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
1000//16 DLE 17 DC1 18 DC2 19 DC3
1001//20 DC4 21 NAK 22 SYN 23 ETB
1002 0 , 0 , 0 , 0 ,
1003 0 , 0 , 0 , 0 ,
1004//24 CAN 25 EM 26 SUB 27 ESC
1005//28 FS 29 GS 30 RS 31 US
1006 0 , 0 , 0 , 0 ,
1007 0 , 0 , 0 , 0 ,
1008//32 SP 33 ! 34 " 35 #
1009//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001010 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1011 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001012//40 ( 41 ) 42 * 43 +
1013//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001014 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1015 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001016//48 0 49 1 50 2 51 3
1017//52 4 53 5 54 6 55 7
1018 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1019 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1020//56 8 57 9 58 : 59 ;
1021//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001022 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1023 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001024//64 @ 65 A 66 B 67 C
1025//68 D 69 E 70 F 71 G
1026 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1027 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1028//72 H 73 I 74 J 75 K
1029//76 L 77 M 78 N 79 O
1030 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1031 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1032//80 P 81 Q 82 R 83 S
1033//84 T 85 U 86 V 87 W
1034 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1035 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1036//88 X 89 Y 90 Z 91 [
1037//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001038 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1039 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001040//96 ` 97 a 98 b 99 c
1041//100 d 101 e 102 f 103 g
1042 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1043 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1044//104 h 105 i 106 j 107 k
1045//108 l 109 m 110 n 111 o
1046 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1047 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1048//112 p 113 q 114 r 115 s
1049//116 t 117 u 118 v 119 w
1050 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1051 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1052//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001053//124 | 125 } 126 ~ 127 DEL
1054 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1055 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001056};
1057
Chris Lattnera2bf1052009-12-17 05:29:40 +00001058static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 static bool isInited = false;
1060 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001061 // check the statically-initialized CharInfo table
1062 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1063 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1064 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1065 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1066 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1067 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1068 assert(CHAR_UNDER == CharInfo[(int)'_']);
1069 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1070 for (unsigned i = 'a'; i <= 'z'; ++i) {
1071 assert(CHAR_LETTER == CharInfo[i]);
1072 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1073 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001075 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001076
Chris Lattner03b98662009-07-07 17:09:54 +00001077 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001078}
1079
Chris Lattner03b98662009-07-07 17:09:54 +00001080
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001081/// isIdentifierHead - Return true if this is the first character of an
1082/// identifier, which is [a-zA-Z_].
1083static inline bool isIdentifierHead(unsigned char c) {
1084 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1085}
1086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087/// isIdentifierBody - Return true if this is the body character of an
1088/// identifier, which is [a-zA-Z0-9_].
1089static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001090 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001091}
1092
1093/// isHorizontalWhitespace - Return true if this character is horizontal
1094/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
1095static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001096 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001097}
1098
Anna Zaksaca25bc2011-07-27 21:43:43 +00001099/// isVerticalWhitespace - Return true if this character is vertical
1100/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
1101static inline bool isVerticalWhitespace(unsigned char c) {
1102 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1103}
1104
Reid Spencer5f016e22007-07-11 17:01:13 +00001105/// isWhitespace - Return true if this character is horizontal or vertical
1106/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
1107/// for '\0'.
1108static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001109 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001110}
1111
1112/// isNumberBody - Return true if this is the body character of an
1113/// preprocessing number, which is [a-zA-Z0-9_.].
1114static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001115 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001116 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001117}
1118
Craig Topper2fa4e862011-08-11 04:06:15 +00001119/// isRawStringDelimBody - Return true if this is the body character of a
1120/// raw string delimiter.
1121static inline bool isRawStringDelimBody(unsigned char c) {
1122 return (CharInfo[c] &
1123 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1124 true : false;
1125}
1126
Jordan Rosed880b3a2012-06-07 01:10:31 +00001127// Allow external clients to make use of CharInfo.
1128bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1129 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1130}
1131
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
1133//===----------------------------------------------------------------------===//
1134// Diagnostics forwarding code.
1135//===----------------------------------------------------------------------===//
1136
Chris Lattner409a0362007-07-22 18:38:25 +00001137/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001138/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001139/// This is currently only used for _Pragma implementation, so it is the slow
1140/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001141static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1142 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001143static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1144 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001145 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001146 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chris Lattner409a0362007-07-22 18:38:25 +00001148 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001149 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001150 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001151 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Chandler Carruth433db062011-07-14 08:20:40 +00001153 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001154 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001155 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001156 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Chris Lattnere7fb4842009-02-15 20:52:18 +00001158 // Figure out the expansion loc range, which is the range covered by the
1159 // original _Pragma(...) sequence.
1160 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001161 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Chandler Carruthbf340e42011-07-26 03:03:05 +00001163 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001164}
1165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166/// getSourceLocation - Return a source location identifier for the specified
1167/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001168SourceLocation Lexer::getSourceLocation(const char *Loc,
1169 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001170 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001172
1173 // In the normal case, we're just lexing from a simple file buffer, return
1174 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001175 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001176 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001177 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Chris Lattner2b2453a2009-01-17 06:22:33 +00001179 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1180 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001181 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001182 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001183}
1184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185/// Diag - Forwarding function for diagnostics. This translate a source
1186/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001187DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001188 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001189}
Reid Spencer5f016e22007-07-11 17:01:13 +00001190
1191//===----------------------------------------------------------------------===//
1192// Trigraph and Escaped Newline Handling Code.
1193//===----------------------------------------------------------------------===//
1194
1195/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1196/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1197static char GetTrigraphCharForLetter(char Letter) {
1198 switch (Letter) {
1199 default: return 0;
1200 case '=': return '#';
1201 case ')': return ']';
1202 case '(': return '[';
1203 case '!': return '|';
1204 case '\'': return '^';
1205 case '>': return '}';
1206 case '/': return '\\';
1207 case '<': return '{';
1208 case '-': return '~';
1209 }
1210}
1211
1212/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1213/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1214/// return the result character. Finally, emit a warning about trigraph use
1215/// whether trigraphs are enabled or not.
1216static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1217 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001218 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
David Blaikie4e4d0842012-03-11 07:00:24 +00001220 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001221 if (!L->isLexingRawMode())
1222 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001223 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattner74d15df2008-11-22 02:02:22 +00001226 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001227 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 return Res;
1229}
1230
Chris Lattner24f0e482009-04-18 22:05:41 +00001231/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1232/// 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 +00001233/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001234unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1235 unsigned Size = 0;
1236 while (isWhitespace(Ptr[Size])) {
1237 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Chris Lattner24f0e482009-04-18 22:05:41 +00001239 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1240 continue;
1241
1242 // If this is a \r\n or \n\r, skip the other half.
1243 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1244 Ptr[Size-1] != Ptr[Size])
1245 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Chris Lattner24f0e482009-04-18 22:05:41 +00001247 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001248 }
1249
Chris Lattner24f0e482009-04-18 22:05:41 +00001250 // Not an escaped newline, must be a \t or something else.
1251 return 0;
1252}
1253
Chris Lattner03374952009-04-18 22:27:02 +00001254/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1255/// them), skip over them and return the first non-escaped-newline found,
1256/// otherwise return P.
1257const char *Lexer::SkipEscapedNewLines(const char *P) {
1258 while (1) {
1259 const char *AfterEscape;
1260 if (*P == '\\') {
1261 AfterEscape = P+1;
1262 } else if (*P == '?') {
1263 // If not a trigraph for escape, bail out.
1264 if (P[1] != '?' || P[2] != '/')
1265 return P;
1266 AfterEscape = P+3;
1267 } else {
1268 return P;
1269 }
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner03374952009-04-18 22:27:02 +00001271 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1272 if (NewLineSize == 0) return P;
1273 P = AfterEscape+NewLineSize;
1274 }
1275}
1276
Anna Zaksaca25bc2011-07-27 21:43:43 +00001277/// \brief Checks that the given token is the first token that occurs after the
1278/// given location (this excludes comments and whitespace). Returns the location
1279/// immediately after the specified token. If the token is not found or the
1280/// location is inside a macro, the returned source location will be invalid.
1281SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1282 tok::TokenKind TKind,
1283 const SourceManager &SM,
1284 const LangOptions &LangOpts,
1285 bool SkipTrailingWhitespaceAndNewLine) {
1286 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001287 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001288 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001289 }
1290 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1291
1292 // Break down the source location.
1293 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1294
1295 // Try to load the file buffer.
1296 bool InvalidTemp = false;
1297 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1298 if (InvalidTemp)
1299 return SourceLocation();
1300
1301 const char *TokenBegin = File.data() + LocInfo.second;
1302
1303 // Lex from the start of the given location.
1304 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1305 TokenBegin, File.end());
1306 // Find the token.
1307 Token Tok;
1308 lexer.LexFromRawLexer(Tok);
1309 if (Tok.isNot(TKind))
1310 return SourceLocation();
1311 SourceLocation TokenLoc = Tok.getLocation();
1312
1313 // Calculate how much whitespace needs to be skipped if any.
1314 unsigned NumWhitespaceChars = 0;
1315 if (SkipTrailingWhitespaceAndNewLine) {
1316 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1317 Tok.getLength();
1318 unsigned char C = *TokenEnd;
1319 while (isHorizontalWhitespace(C)) {
1320 C = *(++TokenEnd);
1321 NumWhitespaceChars++;
1322 }
1323 if (isVerticalWhitespace(C))
1324 NumWhitespaceChars++;
1325 }
1326
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001327 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001328}
Chris Lattner24f0e482009-04-18 22:05:41 +00001329
Reid Spencer5f016e22007-07-11 17:01:13 +00001330/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1331/// get its size, and return it. This is tricky in several cases:
1332/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1333/// then either return the trigraph (skipping 3 chars) or the '?',
1334/// depending on whether trigraphs are enabled or not.
1335/// 2. If this is an escaped newline (potentially with whitespace between
1336/// the backslash and newline), implicitly skip the newline and return
1337/// the char after it.
1338/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1339///
1340/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1341/// know that we can accumulate into Size, and that we have already incremented
1342/// Ptr by Size bytes.
1343///
1344/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1345/// be updated to match.
1346///
1347char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001348 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // If we have a slash, look for an escaped newline.
1350 if (Ptr[0] == '\\') {
1351 ++Size;
1352 ++Ptr;
1353Slash:
1354 // Common case, backslash-char where the char is not whitespace.
1355 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Chris Lattner5636a3b2009-06-23 05:15:06 +00001357 // See if we have optional whitespace characters between the slash and
1358 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001359 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1360 // Remember that this token needs to be cleaned.
1361 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001362
Chris Lattner24f0e482009-04-18 22:05:41 +00001363 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001364 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001365 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner24f0e482009-04-18 22:05:41 +00001367 // Found backslash<whitespace><newline>. Parse the char after it.
1368 Size += EscapedNewLineSize;
1369 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001370
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001371 // If the char that we finally got was a \n, then we must have had
1372 // something like \<newline><newline>. We don't want to consume the
1373 // second newline.
1374 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1375 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001376
Chris Lattner24f0e482009-04-18 22:05:41 +00001377 // Use slow version to accumulate a correct size field.
1378 return getCharAndSizeSlow(Ptr, Size, Tok);
1379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 // Otherwise, this is not an escaped newline, just return the slash.
1382 return '\\';
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 // If this is a trigraph, process it.
1386 if (Ptr[0] == '?' && Ptr[1] == '?') {
1387 // If this is actually a legal trigraph (not something like "??x"), emit
1388 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1389 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1390 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001391 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392
1393 Ptr += 3;
1394 Size += 3;
1395 if (C == '\\') goto Slash;
1396 return C;
1397 }
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // If this is neither, return a single character.
1401 ++Size;
1402 return *Ptr;
1403}
1404
1405
1406/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1407/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1408/// and that we have already incremented Ptr by Size bytes.
1409///
1410/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1411/// be updated to match.
1412char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001413 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 // If we have a slash, look for an escaped newline.
1415 if (Ptr[0] == '\\') {
1416 ++Size;
1417 ++Ptr;
1418Slash:
1419 // Common case, backslash-char where the char is not whitespace.
1420 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001423 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1424 // Found backslash<whitespace><newline>. Parse the char after it.
1425 Size += EscapedNewLineSize;
1426 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001428 // If the char that we finally got was a \n, then we must have had
1429 // something like \<newline><newline>. We don't want to consume the
1430 // second newline.
1431 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1432 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001433
Chris Lattner24f0e482009-04-18 22:05:41 +00001434 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001435 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001436 }
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 // Otherwise, this is not an escaped newline, just return the slash.
1439 return '\\';
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001443 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // If this is actually a legal trigraph (not something like "??x"), return
1445 // it.
1446 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1447 Ptr += 3;
1448 Size += 3;
1449 if (C == '\\') goto Slash;
1450 return C;
1451 }
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 // If this is neither, return a single character.
1455 ++Size;
1456 return *Ptr;
1457}
1458
1459//===----------------------------------------------------------------------===//
1460// Helper methods for lexing.
1461//===----------------------------------------------------------------------===//
1462
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001463/// \brief Routine that indiscriminately skips bytes in the source file.
1464void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1465 BufferPtr += Bytes;
1466 if (BufferPtr > BufferEnd)
1467 BufferPtr = BufferEnd;
1468 IsAtStartOfLine = StartOfLine;
1469}
1470
Chris Lattnerd2177732007-07-20 16:59:19 +00001471void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1473 unsigned Size;
1474 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001475 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001477
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 --CurPtr; // Back up over the skipped character.
1479
1480 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1481 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1482 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001483 //
1484 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1485 // cheaper
David Blaikie4e4d0842012-03-11 07:00:24 +00001486 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001487FinishIdentifier:
1488 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001489 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1490 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 // If we are in raw mode, return this identifier raw. There is no need to
1493 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001494 if (LexingRawMode)
1495 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001497 // Fill in Result.IdentifierInfo and update the token kind,
1498 // looking up the identifier in the identifier table.
1499 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 // Finally, now that we know we have an identifier, pass this off to the
1502 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001503 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001504 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001505
Chris Lattner6a170eb2009-01-21 07:43:11 +00001506 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 }
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 C = getCharAndSize(CurPtr, Size);
1512 while (1) {
1513 if (C == '$') {
1514 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001515 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001518 if (!isLexingRawMode())
1519 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 CurPtr = ConsumeChar(CurPtr, Size, Result);
1521 C = getCharAndSize(CurPtr, Size);
1522 continue;
1523 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1524 // Found end of identifier.
1525 goto FinishIdentifier;
1526 }
1527
1528 // Otherwise, this character is good, consume it.
1529 CurPtr = ConsumeChar(CurPtr, Size, Result);
1530
1531 C = getCharAndSize(CurPtr, Size);
1532 while (isIdentifierBody(C)) { // FIXME: UCNs.
1533 CurPtr = ConsumeChar(CurPtr, Size, Result);
1534 C = getCharAndSize(CurPtr, Size);
1535 }
1536 }
1537}
1538
Douglas Gregora75ec432010-08-30 14:50:47 +00001539/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001540/// in microsoft mode (where this is supposed to be several different tokens).
David Blaikie4e4d0842012-03-11 07:00:24 +00001541static bool isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001542 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001543 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001544 if (C1 != '0')
1545 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001546 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001547 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001548}
Reid Spencer5f016e22007-07-11 17:01:13 +00001549
Nate Begeman5253c7f2008-04-14 02:26:39 +00001550/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001551/// constant. From[-1] is the first character lexed. Return the end of the
1552/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001553void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 unsigned Size;
1555 char C = getCharAndSize(CurPtr, Size);
1556 char PrevCh = 0;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001557 while (isNumberBody(C)) { // FIXME: UCNs.
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 CurPtr = ConsumeChar(CurPtr, Size, Result);
1559 PrevCh = C;
1560 C = getCharAndSize(CurPtr, Size);
1561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001564 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1565 // If we are in Microsoft mode, don't continue if the constant is hex.
1566 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001567 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001568 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1569 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001570
1571 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001572 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1573 // Outside C99, we accept hexadecimal floating point numbers as a
1574 // not-quite-conforming extension. Only do so if this looks like it's
1575 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1576 bool IsHexFloat = true;
1577 if (!LangOpts.C99) {
1578 if (!isHexaLiteral(BufferPtr, LangOpts))
1579 IsHexFloat = false;
1580 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1581 IsHexFloat = false;
1582 }
1583 if (IsHexFloat)
1584 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001588 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001589 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001590 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001591}
1592
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001593/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001594/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001595const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001596 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001597
1598 // Maximally munch an identifier. FIXME: UCNs.
1599 unsigned Size;
1600 char C = getCharAndSize(CurPtr, Size);
1601 if (isIdentifierHead(C)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001602 if (!getLangOpts().CPlusPlus0x) {
Richard Smithe816c712012-03-07 03:13:00 +00001603 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001604 Diag(CurPtr,
1605 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1606 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1607 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1608 return CurPtr;
1609 }
1610
1611 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1612 // that does not start with an underscore is ill-formed. As a conforming
1613 // extension, we treat all such suffixes as if they had whitespace before
1614 // them.
1615 if (C != '_') {
1616 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001617 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1618 diag::ext_ms_reserved_user_defined_literal :
1619 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001620 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1621 return CurPtr;
1622 }
1623
Richard Smith99831e42012-03-06 03:21:47 +00001624 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001625 do {
1626 CurPtr = ConsumeChar(CurPtr, Size, Result);
1627 C = getCharAndSize(CurPtr, Size);
1628 } while (isIdentifierBody(C));
1629 }
1630 return CurPtr;
1631}
1632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001634/// either " or L" or u8" or u" or U".
1635void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1636 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Richard Smith661a9962011-10-15 01:18:56 +00001639 if (!isLexingRawMode() &&
1640 (Kind == tok::utf8_string_literal ||
1641 Kind == tok::utf16_string_literal ||
1642 Kind == tok::utf32_string_literal))
1643 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1644
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 char C = getAndAdvanceChar(CurPtr, Result);
1646 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001647 // Skip escaped characters. Escaped newlines will already be processed by
1648 // getAndAdvanceChar.
1649 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001651
Chris Lattner571339c2010-05-30 23:27:38 +00001652 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001653 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001654 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001655 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001656 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 }
Chris Lattner571339c2010-05-30 23:27:38 +00001659
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001660 if (C == 0) {
1661 if (isCodeCompletionPoint(CurPtr-1)) {
1662 PP->CodeCompleteNaturalLanguage();
1663 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1664 return cutOffLexing();
1665 }
1666
Chris Lattner571339c2010-05-30 23:27:38 +00001667 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001668 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 C = getAndAdvanceChar(CurPtr, Result);
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001672 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001673 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001674 CurPtr = LexUDSuffix(Result, CurPtr);
1675
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001677 if (NulCharacter && !isLexingRawMode())
1678 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001681 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001682 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001683 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001684}
1685
Craig Topper2fa4e862011-08-11 04:06:15 +00001686/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1687/// having lexed R", LR", u8R", uR", or UR".
1688void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1689 tok::TokenKind Kind) {
1690 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1691 // Between the initial and final double quote characters of the raw string,
1692 // any transformations performed in phases 1 and 2 (trigraphs,
1693 // universal-character-names, and line splicing) are reverted.
1694
Richard Smith661a9962011-10-15 01:18:56 +00001695 if (!isLexingRawMode())
1696 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1697
Craig Topper2fa4e862011-08-11 04:06:15 +00001698 unsigned PrefixLen = 0;
1699
1700 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1701 ++PrefixLen;
1702
1703 // If the last character was not a '(', then we didn't lex a valid delimiter.
1704 if (CurPtr[PrefixLen] != '(') {
1705 if (!isLexingRawMode()) {
1706 const char *PrefixEnd = &CurPtr[PrefixLen];
1707 if (PrefixLen == 16) {
1708 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1709 } else {
1710 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1711 << StringRef(PrefixEnd, 1);
1712 }
1713 }
1714
1715 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1716 // it's possible the '"' was intended to be part of the raw string, but
1717 // there's not much we can do about that.
1718 while (1) {
1719 char C = *CurPtr++;
1720
1721 if (C == '"')
1722 break;
1723 if (C == 0 && CurPtr-1 == BufferEnd) {
1724 --CurPtr;
1725 break;
1726 }
1727 }
1728
1729 FormTokenWithChars(Result, CurPtr, tok::unknown);
1730 return;
1731 }
1732
1733 // Save prefix and move CurPtr past it
1734 const char *Prefix = CurPtr;
1735 CurPtr += PrefixLen + 1; // skip over prefix and '('
1736
1737 while (1) {
1738 char C = *CurPtr++;
1739
1740 if (C == ')') {
1741 // Check for prefix match and closing quote.
1742 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1743 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1744 break;
1745 }
1746 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1747 if (!isLexingRawMode())
1748 Diag(BufferPtr, diag::err_unterminated_raw_string)
1749 << StringRef(Prefix, PrefixLen);
1750 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1751 return;
1752 }
1753 }
1754
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001755 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001756 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001757 CurPtr = LexUDSuffix(Result, CurPtr);
1758
Craig Topper2fa4e862011-08-11 04:06:15 +00001759 // Update the location of token as well as BufferPtr.
1760 const char *TokStart = BufferPtr;
1761 FormTokenWithChars(Result, CurPtr, Kind);
1762 Result.setLiteralData(TokStart);
1763}
1764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1766/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001767void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001769 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 char C = getAndAdvanceChar(CurPtr, Result);
1771 while (C != '>') {
1772 // Skip escaped characters.
1773 if (C == '\\') {
1774 // Skip the escaped character.
1775 C = getAndAdvanceChar(CurPtr, Result);
1776 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001777 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1778 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001779 // If the filename is unterminated, then it must just be a lone <
1780 // character. Return this as such.
1781 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 return;
1783 } else if (C == 0) {
1784 NulCharacter = CurPtr-1;
1785 }
1786 C = getAndAdvanceChar(CurPtr, Result);
1787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001790 if (NulCharacter && !isLexingRawMode())
1791 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001794 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001795 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001796 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001797}
1798
1799
1800/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001801/// lexed either ' or L' or u' or U'.
1802void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1803 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 const char *NulCharacter = 0; // Does this character contain the \0 character?
1805
Richard Smith661a9962011-10-15 01:18:56 +00001806 if (!isLexingRawMode() &&
1807 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1808 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1809
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 char C = getAndAdvanceChar(CurPtr, Result);
1811 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001812 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001813 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001814 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001816 }
1817
1818 while (C != '\'') {
1819 // Skip escaped characters.
1820 if (C == '\\') {
1821 // Skip the escaped character.
1822 // FIXME: UCN's
1823 C = getAndAdvanceChar(CurPtr, Result);
1824 } else if (C == '\n' || C == '\r' || // Newline.
1825 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001826 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001827 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001828 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1829 return;
1830 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001831 if (isCodeCompletionPoint(CurPtr-1)) {
1832 PP->CodeCompleteNaturalLanguage();
1833 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1834 return cutOffLexing();
1835 }
1836
Chris Lattnerd80f7862010-07-07 23:24:27 +00001837 NulCharacter = CurPtr-1;
1838 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 C = getAndAdvanceChar(CurPtr, Result);
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001842 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001843 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001844 CurPtr = LexUDSuffix(Result, CurPtr);
1845
Chris Lattnerd80f7862010-07-07 23:24:27 +00001846 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001847 if (NulCharacter && !isLexingRawMode())
1848 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001849
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001851 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001852 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001853 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854}
1855
1856/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1857/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001858///
1859/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1860///
1861bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 // Whitespace - Skip it, then return the token after the whitespace.
1863 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1864 while (1) {
1865 // Skip horizontal whitespace very aggressively.
1866 while (isHorizontalWhitespace(Char))
1867 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001869 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 if (Char != '\n' && Char != '\r')
1871 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 if (ParsingPreprocessorDirective) {
1874 // End of preprocessor directive line, let LexTokenInternal handle this.
1875 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001876 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 // ok, but handle newline.
1880 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001881 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001883 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 Char = *++CurPtr;
1885 }
1886
1887 // If this isn't immediately after a newline, there is leading space.
1888 char PrevChar = CurPtr[-1];
1889 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001890 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001891
Chris Lattnerd88dc482008-10-12 04:05:48 +00001892 // If the client wants us to return whitespace, return it now.
1893 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001894 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001895 return true;
1896 }
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001899 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001900}
1901
1902// SkipBCPLComment - We have just read the // characters from input. Skip until
1903// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001904/// BufferPtr and return.
1905///
1906/// If we're in KeepCommentMode or any CommentHandler has inserted
1907/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001908bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 // If BCPL comments aren't explicitly enabled for this language, emit an
1910 // extension warning.
David Blaikie4e4d0842012-03-11 07:00:24 +00001911 if (!LangOpts.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 // Mark them enabled so we only emit one warning for this translation
1915 // unit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001916 LangOpts.BCPLComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 // Scan over the body of the comment. The common case, when scanning, is that
1920 // the comment contains normal ascii characters with nothing interesting in
1921 // them. As such, optimize for this case with the inner loop.
1922 char C;
1923 do {
1924 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // Skip over characters in the fast loop.
1926 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 C != '\n' && C != '\r') // Newline or DOS-style newline.
1928 C = *++CurPtr;
1929
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001930 const char *NextLine = CurPtr;
1931 if (C != 0) {
1932 // We found a newline, see if it's escaped.
1933 const char *EscapePtr = CurPtr-1;
1934 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1935 --EscapePtr;
1936
1937 if (*EscapePtr == '\\') // Escaped newline.
1938 CurPtr = EscapePtr;
1939 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1940 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1941 CurPtr = EscapePtr-2;
1942 else
1943 break; // This is a newline, we're done.
1944
1945 C = *CurPtr;
1946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001949 // properly decode the character. Read it in raw mode to avoid emitting
1950 // diagnostics about things like trigraphs. If we see an escaped newline,
1951 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001953 bool OldRawMode = isLexingRawMode();
1954 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001956 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001957
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001958 // If we only read only one character, then no special handling is needed.
1959 // We're done and can skip forward to the newline.
1960 if (C != 0 && CurPtr == OldPtr+1) {
1961 CurPtr = NextLine;
1962 break;
1963 }
1964
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 // If we read multiple characters, and one of those characters was a \r or
1966 // \n, then we had an escaped newline within the comment. Emit diagnostic
1967 // unless the next line is also a // comment.
1968 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1969 for (; OldPtr != CurPtr; ++OldPtr)
1970 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1971 // Okay, we found a // comment that ends in a newline, if the next
1972 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001973 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001975 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 ++ForwardPtr;
1977 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1978 break;
1979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Chris Lattner74d15df2008-11-22 02:02:22 +00001981 if (!isLexingRawMode())
1982 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 break;
1984 }
1985 }
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Douglas Gregor55817af2010-08-25 17:04:25 +00001987 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001988 --CurPtr;
1989 break;
1990 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001991
1992 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1993 PP->CodeCompleteNaturalLanguage();
1994 cutOffLexing();
1995 return false;
1996 }
1997
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 } while (C != '\n' && C != '\r');
1999
Chris Lattner3d0ad582010-02-03 21:06:21 +00002000 // Found but did not consume the newline. Notify comment handlers about the
2001 // comment unless we're in a #if 0 block.
2002 if (PP && !isLexingRawMode() &&
2003 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2004 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002005 BufferPtr = CurPtr;
2006 return true; // A token has to be returned.
2007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002010 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 return SaveBCPLComment(Result, CurPtr);
2012
2013 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002014 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2016 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002017 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002021 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002022 // contribute to another token), it isn't needed for correctness. Note that
2023 // this is ok even in KeepWhitespaceMode, because we would have returned the
2024 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002028 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002030 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002032 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002033}
2034
2035/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
2036/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00002037bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002038 // If we're not in a preprocessor directive, just return the // comment
2039 // directly.
2040 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
David Blaikie8c0b3782012-06-06 18:52:13 +00002042 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002043 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Chris Lattner9e6293d2008-10-12 04:51:35 +00002045 // If this BCPL-style comment is in a macro definition, transmogrify it into
2046 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002047 bool Invalid = false;
2048 std::string Spelling = PP->getSpelling(Result, &Invalid);
2049 if (Invalid)
2050 return true;
2051
Chris Lattner9e6293d2008-10-12 04:51:35 +00002052 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
2053 Spelling[1] = '*'; // Change prefix to "/*".
2054 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Chris Lattner9e6293d2008-10-12 04:51:35 +00002056 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00002057 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002058 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002059 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002060}
2061
2062/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002063/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2064/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002065static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 Lexer *L) {
2067 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // Back up off the newline.
2070 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Reid Spencer5f016e22007-07-11 17:01:13 +00002072 // If this is a two-character newline sequence, skip the other character.
2073 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2074 // \n\n or \r\r -> not escaped newline.
2075 if (CurPtr[0] == CurPtr[1])
2076 return false;
2077 // \n\r or \r\n -> skip the newline.
2078 --CurPtr;
2079 }
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 // If we have horizontal whitespace, skip over it. We allow whitespace
2082 // between the slash and newline.
2083 bool HasSpace = false;
2084 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2085 --CurPtr;
2086 HasSpace = true;
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 // If we have a slash, we know this is an escaped newline.
2090 if (*CurPtr == '\\') {
2091 if (CurPtr[-1] != '*') return false;
2092 } else {
2093 // It isn't a slash, is it the ?? / trigraph?
2094 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2095 CurPtr[-3] != '*')
2096 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // This is the trigraph ending the comment. Emit a stern warning!
2099 CurPtr -= 2;
2100
2101 // If no trigraphs are enabled, warn that we ignored this trigraph and
2102 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002103 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002104 if (!L->isLexingRawMode())
2105 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 return false;
2107 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002108 if (!L->isLexingRawMode())
2109 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002113 if (!L->isLexingRawMode())
2114 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002117 if (HasSpace && !L->isLexingRawMode())
2118 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 return true;
2121}
2122
2123#ifdef __SSE2__
2124#include <emmintrin.h>
2125#elif __ALTIVEC__
2126#include <altivec.h>
2127#undef bool
2128#endif
2129
2130/// SkipBlockComment - We have just read the /* characters from input. Read
2131/// until we find the */ characters that terminate the comment. Note that we
2132/// don't bother decoding trigraphs or escaped newlines in block comments,
2133/// because they cannot cause the comment to end. The only thing that can
2134/// happen is the comment could end with an escaped newline between the */ end
2135/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00002136///
Chris Lattner046c2272010-01-18 22:35:47 +00002137/// If we're in KeepCommentMode or any CommentHandler has inserted
2138/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002139bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002141 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // optimization helps people who like to put a lot of * characters in their
2143 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002144
2145 // The first character we get with newlines and trigraphs skipped to handle
2146 // the degenerate /*/ case below correctly if the * has an escaped newline
2147 // after it.
2148 unsigned CharSize;
2149 unsigned char C = getCharAndSize(CurPtr, CharSize);
2150 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002152 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002153 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002154 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattner31f0eca2008-10-12 04:19:49 +00002156 // KeepWhitespaceMode should return this broken comment as a token. Since
2157 // it isn't a well formed comment, just return it as an 'unknown' token.
2158 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002159 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002160 return true;
2161 }
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Chris Lattner31f0eca2008-10-12 04:19:49 +00002163 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002164 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Chris Lattner8146b682007-07-21 23:43:37 +00002167 // Check to see if the first character after the '/*' is another /. If so,
2168 // then this slash does not end the block comment, it is part of it.
2169 if (C == '/')
2170 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Reid Spencer5f016e22007-07-11 17:01:13 +00002172 while (1) {
2173 // Skip over all non-interesting characters until we find end of buffer or a
2174 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002175 if (CurPtr + 24 < BufferEnd &&
2176 // If there is a code-completion point avoid the fast scan because it
2177 // doesn't check for '\0'.
2178 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 // While not aligned to a 16-byte boundary.
2180 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2181 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 if (C == '/') goto FoundSlash;
2184
2185#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002186 __m128i Slashes = _mm_set1_epi8('/');
2187 while (CurPtr+16 <= BufferEnd) {
2188 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
2189 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002190 // Adjust the pointer to point directly after the first slash. It's
2191 // not necessary to set C here, it will be overwritten at the end of
2192 // the outer loop.
2193 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002194 goto FoundSlash;
2195 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002197 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002198#elif __ALTIVEC__
2199 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002200 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 '/', '/', '/', '/', '/', '/', '/', '/'
2202 };
2203 while (CurPtr+16 <= BufferEnd &&
2204 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2205 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002206#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // Scan for '/' quickly. Many block comments are very large.
2208 while (CurPtr[0] != '/' &&
2209 CurPtr[1] != '/' &&
2210 CurPtr[2] != '/' &&
2211 CurPtr[3] != '/' &&
2212 CurPtr+4 < BufferEnd) {
2213 CurPtr += 4;
2214 }
2215#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 // It has to be one of the bytes scanned, increment to it and read one.
2218 C = *CurPtr++;
2219 }
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 // Loop to scan the remainder.
2222 while (C != '/' && C != '\0')
2223 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002226 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 if (CurPtr[-2] == '*') // We found the final */. We're done!
2228 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2231 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2232 // We found the final */, though it had an escaped newline between the
2233 // * and /. We're done!
2234 break;
2235 }
2236 }
2237 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2238 // If this is a /* inside of the comment, emit a warning. Don't do this
2239 // if this is a /*/, which will end the comment. This misses cases with
2240 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002241 if (!isLexingRawMode())
2242 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 }
2244 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002245 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002246 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 // Note: the user probably forgot a */. We could continue immediately
2248 // after the /*, but this would involve lexing a lot of what really is the
2249 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002250 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Chris Lattner31f0eca2008-10-12 04:19:49 +00002252 // KeepWhitespaceMode should return this broken comment as a token. Since
2253 // it isn't a well formed comment, just return it as an 'unknown' token.
2254 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002255 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002256 return true;
2257 }
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Chris Lattner31f0eca2008-10-12 04:19:49 +00002259 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002260 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002261 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2262 PP->CodeCompleteNaturalLanguage();
2263 cutOffLexing();
2264 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002266
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 C = *CurPtr++;
2268 }
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Chris Lattner3d0ad582010-02-03 21:06:21 +00002270 // Notify comment handlers about the comment unless we're in a #if 0 block.
2271 if (PP && !isLexingRawMode() &&
2272 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2273 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002274 BufferPtr = CurPtr;
2275 return true; // A token has to be returned.
2276 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002279 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002280 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002281 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 }
2283
2284 // It is common for the tokens immediately after a /**/ comment to be
2285 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002286 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2287 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002289 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002291 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 }
2293
2294 // Otherwise, just return so that the next character will be lexed as a token.
2295 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002296 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002297 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002298}
2299
2300//===----------------------------------------------------------------------===//
2301// Primary Lexing Entry Points
2302//===----------------------------------------------------------------------===//
2303
Reid Spencer5f016e22007-07-11 17:01:13 +00002304/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2305/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002306void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2308 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002309 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002310
2311 // CurPtr - Cache BufferPtr in an automatic variable.
2312 const char *CurPtr = BufferPtr;
2313 while (1) {
2314 char Char = getAndAdvanceChar(CurPtr, Tmp);
2315 switch (Char) {
2316 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002317 if (Result)
2318 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 break;
2320 case 0: // Null.
2321 // Found end of file?
2322 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002323 if (isCodeCompletionPoint(CurPtr-1)) {
2324 PP->CodeCompleteNaturalLanguage();
2325 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002326 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002327 }
2328
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002330 if (Result)
2331 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002332 break;
2333 }
2334 // FALL THROUGH.
2335 case '\r':
2336 case '\n':
2337 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2338 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2339 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Peter Collingbourne84021552011-02-28 02:37:51 +00002341 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002343 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002344 if (PP)
2345 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002346 Lex(Tmp);
2347 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002348 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Benjamin Kramer3093b202012-05-18 19:32:16 +00002350 // Finally, we're done;
2351 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 }
2353 }
2354}
2355
2356/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2357/// condition, reporting diagnostics and handling other edge cases as required.
2358/// This returns true if Result contains a token, false if PP.Lex should be
2359/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002360bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 // If we hit the end of the file while parsing a preprocessor directive,
2362 // end the preprocessor directive first. The next token returned will
2363 // then be the end of file.
2364 if (ParsingPreprocessorDirective) {
2365 // Done parsing the "line".
2366 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002368 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002371 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002373 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002374
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 // If we are in raw mode, return this event as an EOF token. Let the caller
2376 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002377 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 Result.startToken();
2379 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002380 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002381 return true;
2382 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002383
Douglas Gregorf44e8542010-08-24 19:08:16 +00002384 // Issue diagnostics for unterminated #if and missing newline.
2385
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 // If we are in a #if directive, emit an error.
2387 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002388 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002389 PP->Diag(ConditionalStack.back().IfLoc,
2390 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 ConditionalStack.pop_back();
2392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002394 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2395 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002396 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2397 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2398 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2399 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 BufferPtr = CurPtr;
2402
2403 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002404 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002405}
2406
2407/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2408/// the specified lexer will return a tok::l_paren token, 0 if it is something
2409/// else and 2 if there are no more tokens in the buffer controlled by the
2410/// lexer.
2411unsigned Lexer::isNextPPTokenLParen() {
2412 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 // Switch to 'skipping' mode. This will ensure that we can lex a token
2415 // without emitting diagnostics, disables macro expansion, and will cause EOF
2416 // to return an EOF token instead of popping the include stack.
2417 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Reid Spencer5f016e22007-07-11 17:01:13 +00002419 // Save state that can be changed while lexing so that we can restore it.
2420 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002421 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Chris Lattnerd2177732007-07-20 16:59:19 +00002423 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 Tok.startToken();
2425 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // Restore state that may have changed.
2428 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002429 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 // Restore the lexer back to non-skipping mode.
2432 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002434 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002436 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002437}
2438
Chris Lattner34f349d2009-12-14 06:16:57 +00002439/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002440static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2441 ConflictMarkerKind CMK) {
2442 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2443 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2444 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2445 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002446 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002447 // Must occur at start of line.
2448 if (RestOfBuffer[Pos-1] != '\r' &&
2449 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002450 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2451 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002452 continue;
2453 }
2454 return RestOfBuffer.data()+Pos;
2455 }
2456 return 0;
2457}
2458
2459/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2460/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2461/// and recover nicely. This returns true if it is a conflict marker and false
2462/// if not.
2463bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2464 // Only a conflict marker if it starts at the beginning of a line.
2465 if (CurPtr != BufferStart &&
2466 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2467 return false;
2468
Richard Smithd5e1d602011-10-12 00:37:51 +00002469 // Check to see if we have <<<<<<< or >>>>.
2470 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2471 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002472 return false;
2473
2474 // If we have a situation where we don't care about conflict markers, ignore
2475 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002476 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002477 return false;
2478
Richard Smithd5e1d602011-10-12 00:37:51 +00002479 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2480
2481 // Check to see if there is an ending marker somewhere in the buffer at the
2482 // start of a line to terminate this conflict marker.
2483 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002484 // We found a match. We are really in a conflict marker.
2485 // Diagnose this, and ignore to the end of line.
2486 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002487 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002488
2489 // Skip ahead to the end of line. We know this exists because the
2490 // end-of-conflict marker starts with \r or \n.
2491 while (*CurPtr != '\r' && *CurPtr != '\n') {
2492 assert(CurPtr != BufferEnd && "Didn't find end of line");
2493 ++CurPtr;
2494 }
2495 BufferPtr = CurPtr;
2496 return true;
2497 }
2498
2499 // No end of conflict marker found.
2500 return false;
2501}
2502
2503
Richard Smithd5e1d602011-10-12 00:37:51 +00002504/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2505/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2506/// is the end of a conflict marker. Handle it by ignoring up until the end of
2507/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002508bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2509 // Only a conflict marker if it starts at the beginning of a line.
2510 if (CurPtr != BufferStart &&
2511 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2512 return false;
2513
2514 // If we have a situation where we don't care about conflict markers, ignore
2515 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002516 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002517 return false;
2518
Richard Smithd5e1d602011-10-12 00:37:51 +00002519 // Check to see if we have the marker (4 characters in a row).
2520 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002521 if (CurPtr[i] != CurPtr[0])
2522 return false;
2523
2524 // If we do have it, search for the end of the conflict marker. This could
2525 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2526 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002527 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2528 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002529 CurPtr = End;
2530
2531 // Skip ahead to the end of line.
2532 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2533 ++CurPtr;
2534
2535 BufferPtr = CurPtr;
2536
2537 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002538 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002539 return true;
2540 }
2541
2542 return false;
2543}
2544
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002545bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2546 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002547 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002548 return Loc == PP->getCodeCompletionLoc();
2549 }
2550
2551 return false;
2552}
2553
Reid Spencer5f016e22007-07-11 17:01:13 +00002554
2555/// LexTokenInternal - This implements a simple C family lexer. It is an
2556/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002557/// has a null character at the end of the file. This returns a preprocessing
2558/// token, not a normal token, as such, it is an internal interface. It assumes
2559/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002560void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002561LexNextToken:
2562 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002563 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 // CurPtr - Cache BufferPtr in an automatic variable.
2567 const char *CurPtr = BufferPtr;
2568
2569 // Small amounts of horizontal whitespace is very common between tokens.
2570 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2571 ++CurPtr;
2572 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2573 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Chris Lattnerd88dc482008-10-12 04:05:48 +00002575 // If we are keeping whitespace and other tokens, just return what we just
2576 // skipped. The next lexer invocation will return the token after the
2577 // whitespace.
2578 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002579 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002580 return;
2581 }
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002584 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 // Read a character, advancing over it.
2590 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002591 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 switch (Char) {
2594 case 0: // Null.
2595 // Found end of file?
2596 if (CurPtr-1 == BufferEnd) {
2597 // Read the PP instance variable into an automatic variable, because
2598 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002599 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2601 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002602 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2603 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 }
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002606 // Check if we are performing code completion.
2607 if (isCodeCompletionPoint(CurPtr-1)) {
2608 // Return the code-completion token.
2609 Result.startToken();
2610 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2611 return;
2612 }
2613
Chris Lattner74d15df2008-11-22 02:02:22 +00002614 if (!isLexingRawMode())
2615 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002616 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002617 if (SkipWhitespace(Result, CurPtr))
2618 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002621
2622 case 26: // DOS & CP/M EOF: "^Z".
2623 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002624 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002625 // Read the PP instance variable into an automatic variable, because
2626 // LexEndOfFile will often delete 'this'.
2627 Preprocessor *PPCache = PP;
2628 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2629 return; // Got a token to return.
2630 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2631 return PPCache->Lex(Result);
2632 }
2633 // If Microsoft extensions are disabled, this is just random garbage.
2634 Kind = tok::unknown;
2635 break;
2636
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 case '\n':
2638 case '\r':
2639 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002640 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 if (ParsingPreprocessorDirective) {
2642 // Done parsing the "line".
2643 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002646 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002647 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 // Since we consumed a newline, we are back at the start of a line.
2650 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Peter Collingbourne84021552011-02-28 02:37:51 +00002652 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 break;
2654 }
2655 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002656 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002658 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Chris Lattnerd88dc482008-10-12 04:05:48 +00002660 if (SkipWhitespace(Result, CurPtr))
2661 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 goto LexNextToken; // GCC isn't tail call eliminating.
2663 case ' ':
2664 case '\t':
2665 case '\f':
2666 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002667 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002668 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002669 if (SkipWhitespace(Result, CurPtr))
2670 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002671
2672 SkipIgnoredUnits:
2673 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Chris Lattner8133cfc2007-07-22 06:29:05 +00002675 // If the next token is obviously a // or /* */ comment, skip it efficiently
2676 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002677 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002678 LangOpts.BCPLComment && !LangOpts.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002679 if (SkipBCPLComment(Result, CurPtr+2))
2680 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002681 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002682 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002683 if (SkipBlockComment(Result, CurPtr+2))
2684 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002685 goto SkipIgnoredUnits;
2686 } else if (isHorizontalWhitespace(*CurPtr)) {
2687 goto SkipHorizontalWhitespace;
2688 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002690
Chris Lattner3a570772008-01-03 17:58:54 +00002691 // C99 6.4.4.1: Integer Constants.
2692 // C99 6.4.4.2: Floating Constants.
2693 case '0': case '1': case '2': case '3': case '4':
2694 case '5': case '6': case '7': case '8': case '9':
2695 // Notify MIOpt that we read a non-whitespace/non-comment token.
2696 MIOpt.ReadToken();
2697 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor5cee1192011-07-27 05:40:30 +00002699 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2700 // Notify MIOpt that we read a non-whitespace/non-comment token.
2701 MIOpt.ReadToken();
2702
David Blaikie4e4d0842012-03-11 07:00:24 +00002703 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002704 Char = getCharAndSize(CurPtr, SizeTmp);
2705
2706 // UTF-16 string literal
2707 if (Char == '"')
2708 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2709 tok::utf16_string_literal);
2710
2711 // UTF-16 character constant
2712 if (Char == '\'')
2713 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2714 tok::utf16_char_constant);
2715
Craig Topper2fa4e862011-08-11 04:06:15 +00002716 // UTF-16 raw string literal
2717 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2718 return LexRawStringLiteral(Result,
2719 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2720 SizeTmp2, Result),
2721 tok::utf16_string_literal);
2722
2723 if (Char == '8') {
2724 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2725
2726 // UTF-8 string literal
2727 if (Char2 == '"')
2728 return LexStringLiteral(Result,
2729 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2730 SizeTmp2, Result),
2731 tok::utf8_string_literal);
2732
2733 if (Char2 == 'R') {
2734 unsigned SizeTmp3;
2735 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2736 // UTF-8 raw string literal
2737 if (Char3 == '"') {
2738 return LexRawStringLiteral(Result,
2739 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2740 SizeTmp2, Result),
2741 SizeTmp3, Result),
2742 tok::utf8_string_literal);
2743 }
2744 }
2745 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002746 }
2747
2748 // treat u like the start of an identifier.
2749 return LexIdentifier(Result, CurPtr);
2750
2751 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2752 // Notify MIOpt that we read a non-whitespace/non-comment token.
2753 MIOpt.ReadToken();
2754
David Blaikie4e4d0842012-03-11 07:00:24 +00002755 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002756 Char = getCharAndSize(CurPtr, SizeTmp);
2757
2758 // UTF-32 string literal
2759 if (Char == '"')
2760 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2761 tok::utf32_string_literal);
2762
2763 // UTF-32 character constant
2764 if (Char == '\'')
2765 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2766 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002767
2768 // UTF-32 raw string literal
2769 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2770 return LexRawStringLiteral(Result,
2771 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2772 SizeTmp2, Result),
2773 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002774 }
2775
2776 // treat U like the start of an identifier.
2777 return LexIdentifier(Result, CurPtr);
2778
Craig Topper2fa4e862011-08-11 04:06:15 +00002779 case 'R': // Identifier or C++0x raw string literal
2780 // Notify MIOpt that we read a non-whitespace/non-comment token.
2781 MIOpt.ReadToken();
2782
David Blaikie4e4d0842012-03-11 07:00:24 +00002783 if (LangOpts.CPlusPlus0x) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002784 Char = getCharAndSize(CurPtr, SizeTmp);
2785
2786 if (Char == '"')
2787 return LexRawStringLiteral(Result,
2788 ConsumeChar(CurPtr, SizeTmp, Result),
2789 tok::string_literal);
2790 }
2791
2792 // treat R like the start of an identifier.
2793 return LexIdentifier(Result, CurPtr);
2794
Chris Lattner3a570772008-01-03 17:58:54 +00002795 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 // Notify MIOpt that we read a non-whitespace/non-comment token.
2797 MIOpt.ReadToken();
2798 Char = getCharAndSize(CurPtr, SizeTmp);
2799
2800 // Wide string literal.
2801 if (Char == '"')
2802 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002803 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002804
Craig Topper2fa4e862011-08-11 04:06:15 +00002805 // Wide raw string literal.
David Blaikie4e4d0842012-03-11 07:00:24 +00002806 if (LangOpts.CPlusPlus0x && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002807 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2808 return LexRawStringLiteral(Result,
2809 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2810 SizeTmp2, Result),
2811 tok::wide_string_literal);
2812
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Wide character constant.
2814 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002815 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2816 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Reid Spencer5f016e22007-07-11 17:01:13 +00002819 // C99 6.4.2: Identifiers.
2820 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2821 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002822 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002823 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2824 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2825 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002826 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 case 'v': case 'w': case 'x': case 'y': case 'z':
2828 case '_':
2829 // Notify MIOpt that we read a non-whitespace/non-comment token.
2830 MIOpt.ReadToken();
2831 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002832
2833 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002834 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002835 if (!isLexingRawMode())
2836 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002837 // Notify MIOpt that we read a non-whitespace/non-comment token.
2838 MIOpt.ReadToken();
2839 return LexIdentifier(Result, CurPtr);
2840 }
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Chris Lattner9e6293d2008-10-12 04:51:35 +00002842 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002843 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 // C99 6.4.4: Character Constants.
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 LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002850
2851 // C99 6.4.5: String Literals.
2852 case '"':
2853 // Notify MIOpt that we read a non-whitespace/non-comment token.
2854 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002855 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002856
2857 // C99 6.4.6: Punctuators.
2858 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002859 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 break;
2861 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002862 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863 break;
2864 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002865 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 break;
2867 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002868 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 break;
2870 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002871 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002872 break;
2873 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002874 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002875 break;
2876 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002877 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 break;
2879 case '.':
2880 Char = getCharAndSize(CurPtr, SizeTmp);
2881 if (Char >= '0' && Char <= '9') {
2882 // Notify MIOpt that we read a non-whitespace/non-comment token.
2883 MIOpt.ReadToken();
2884
2885 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00002886 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002887 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 CurPtr += SizeTmp;
2889 } else if (Char == '.' &&
2890 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002891 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2893 SizeTmp2, Result);
2894 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002895 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 }
2897 break;
2898 case '&':
2899 Char = getCharAndSize(CurPtr, SizeTmp);
2900 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002901 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002902 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2903 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002904 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2906 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002907 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002908 }
2909 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002910 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002911 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002912 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2914 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002915 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 }
2917 break;
2918 case '+':
2919 Char = getCharAndSize(CurPtr, SizeTmp);
2920 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002921 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002922 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002925 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002926 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002927 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 }
2929 break;
2930 case '-':
2931 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002932 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002934 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00002935 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002936 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2938 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002939 Kind = tok::arrowstar;
2940 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002941 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002942 Kind = tok::arrow;
2943 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002944 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002945 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002947 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 }
2949 break;
2950 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002951 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 break;
2953 case '!':
2954 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002955 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2957 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002958 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 }
2960 break;
2961 case '/':
2962 // 6.4.9: Comments
2963 Char = getCharAndSize(CurPtr, SizeTmp);
2964 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002965 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2966 // want to lex this as a comment. There is one problem with this though,
2967 // that in one particular corner case, this can change the behavior of the
2968 // resultant program. For example, In "foo //**/ bar", C89 would lex
2969 // this as "foo / bar" and langauges with BCPL comments would lex it as
2970 // "foo". Check to see if the character after the second slash is a '*'.
2971 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002972 // However, we never do this in -traditional-cpp mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002973 if ((LangOpts.BCPLComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002974 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002975 !LangOpts.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002976 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002977 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Chris Lattner8402c732009-01-16 22:39:25 +00002979 // It is common for the tokens immediately after a // comment to be
2980 // whitespace (indentation for the next line). Instead of going through
2981 // the big switch, handle it efficiently now.
2982 goto SkipIgnoredUnits;
2983 }
2984 }
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Chris Lattner8402c732009-01-16 22:39:25 +00002986 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002988 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002989 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002990 }
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Chris Lattner8402c732009-01-16 22:39:25 +00002992 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002994 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002996 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 }
2998 break;
2999 case '%':
3000 Char = getCharAndSize(CurPtr, SizeTmp);
3001 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003002 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003003 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003004 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003005 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003007 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003008 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3009 Char = getCharAndSize(CurPtr, SizeTmp);
3010 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003011 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3013 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003014 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003016 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003017 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003018 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003019 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003020 // We parsed a # character. If this occurs at the start of the line,
3021 // it's actually the start of a preprocessing directive. Callback to
3022 // the preprocessor to handle it.
3023 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003024 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003025 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003026 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 // As an optimization, if the preprocessor didn't switch lexers, tail
3029 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003030 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 // Start a new token. If this is a #include or something, the PP may
3032 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003033 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003035 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003036 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 IsAtStartOfLine = false;
3038 }
3039 goto LexNextToken; // GCC isn't tail call eliminating.
3040 }
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Chris Lattner168ae2d2007-10-17 20:41:00 +00003042 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 }
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Chris Lattnere91e9322009-03-18 20:58:27 +00003045 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003046 }
3047 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003048 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003049 }
3050 break;
3051 case '<':
3052 Char = getCharAndSize(CurPtr, SizeTmp);
3053 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003054 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003055 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003056 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3057 if (After == '=') {
3058 Kind = tok::lesslessequal;
3059 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3060 SizeTmp2, Result);
3061 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3062 // If this is actually a '<<<<<<<' version control conflict marker,
3063 // recognize it as such and recover nicely.
3064 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003065 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3066 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3067 // ignore it.
3068 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003069 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003070 Kind = tok::lesslessless;
3071 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3072 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003073 } else {
3074 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3075 Kind = tok::lessless;
3076 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003077 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003079 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003080 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3081 if (LangOpts.CPlusPlus0x &&
Richard Smith87a1e192011-04-14 18:36:27 +00003082 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3083 // C++0x [lex.pptoken]p3:
3084 // Otherwise, if the next three characters are <:: and the subsequent
3085 // character is neither : nor >, the < is treated as a preprocessor
3086 // token by itself and not as the first character of the alternative
3087 // token <:.
3088 unsigned SizeTmp3;
3089 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3090 if (After != ':' && After != '>') {
3091 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003092 if (!isLexingRawMode())
3093 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003094 break;
3095 }
3096 }
3097
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003099 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003100 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003102 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003103 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003104 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003105 }
3106 break;
3107 case '>':
3108 Char = getCharAndSize(CurPtr, SizeTmp);
3109 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003110 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003111 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003112 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003113 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3114 if (After == '=') {
3115 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3116 SizeTmp2, Result);
3117 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003118 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3119 // If this is actually a '>>>>' conflict marker, recognize it as such
3120 // and recover nicely.
3121 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003122 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3123 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3124 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003125 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003126 Kind = tok::greatergreatergreater;
3127 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3128 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003129 } else {
3130 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3131 Kind = tok::greatergreater;
3132 }
3133
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003135 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003136 }
3137 break;
3138 case '^':
3139 Char = getCharAndSize(CurPtr, SizeTmp);
3140 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003141 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003142 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003144 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 }
3146 break;
3147 case '|':
3148 Char = getCharAndSize(CurPtr, SizeTmp);
3149 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003150 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003151 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3152 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003153 // If this is '|||||||' and we're in a conflict marker, ignore it.
3154 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3155 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003156 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3158 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003159 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003160 }
3161 break;
3162 case ':':
3163 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003164 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003165 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003167 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003168 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003169 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003170 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003171 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 }
3173 break;
3174 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003175 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003176 break;
3177 case '=':
3178 Char = getCharAndSize(CurPtr, SizeTmp);
3179 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003180 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003181 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3182 goto LexNextToken;
3183
Chris Lattner9e6293d2008-10-12 04:51:35 +00003184 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003186 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003187 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 }
3189 break;
3190 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003191 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003192 break;
3193 case '#':
3194 Char = getCharAndSize(CurPtr, SizeTmp);
3195 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003196 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003197 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003198 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003199 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003200 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003201 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003202 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3203 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 // We parsed a # character. If this occurs at the start of the line,
3205 // it's actually the start of a preprocessing directive. Callback to
3206 // the preprocessor to handle it.
3207 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003208 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003209 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003210 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 // As an optimization, if the preprocessor didn't switch lexers, tail
3213 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003214 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 // Start a new token. If this is a #include or something, the PP may
3216 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003217 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003219 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003220 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 IsAtStartOfLine = false;
3222 }
3223 goto LexNextToken; // GCC isn't tail call eliminating.
3224 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00003225 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003226 }
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Chris Lattnere91e9322009-03-18 20:58:27 +00003228 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003229 }
3230 break;
3231
Chris Lattner3a570772008-01-03 17:58:54 +00003232 case '@':
3233 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003234 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003235 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003236 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003237 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003238 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Reid Spencer5f016e22007-07-11 17:01:13 +00003240 case '\\':
3241 // FIXME: UCN's.
3242 // FALL THROUGH.
3243 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003244 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 break;
3246 }
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Reid Spencer5f016e22007-07-11 17:01:13 +00003248 // Notify MIOpt that we read a non-whitespace/non-comment token.
3249 MIOpt.ReadToken();
3250
3251 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003252 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003253}