blob: 354a44db84e7ee2175aa43e6a3f77f910bf32c65 [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;
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000516 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
517 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000518 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000519
520 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
521 SourceLocation StartLoc = TheLexer.getSourceLocation();
522
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000523 bool InPreprocessorDirective = false;
524 Token TheTok;
525 Token IfStartTok;
526 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000527
528 unsigned MaxLineOffset = 0;
529 if (MaxLines) {
530 const char *CurPtr = Buffer->getBufferStart();
531 unsigned CurLine = 0;
532 while (CurPtr != Buffer->getBufferEnd()) {
533 char ch = *CurPtr++;
534 if (ch == '\n') {
535 ++CurLine;
536 if (CurLine == MaxLines)
537 break;
538 }
539 }
540 if (CurPtr != Buffer->getBufferEnd())
541 MaxLineOffset = CurPtr - Buffer->getBufferStart();
542 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000543
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000544 do {
545 TheLexer.LexFromRawLexer(TheTok);
546
547 if (InPreprocessorDirective) {
548 // If we've hit the end of the file, we're done.
549 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000550 break;
551 }
552
553 // If we haven't hit the end of the preprocessor directive, skip this
554 // token.
555 if (!TheTok.isAtStartOfLine())
556 continue;
557
558 // We've passed the end of the preprocessor directive, and will look
559 // at this token again below.
560 InPreprocessorDirective = false;
561 }
562
Douglas Gregordf95a132010-08-09 20:45:32 +0000563 // Keep track of the # of lines in the preamble.
564 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000565 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000566
567 // If we were asked to limit the number of lines in the preamble,
568 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000569 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000570 break;
571 }
572
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000573 // Comments are okay; skip over them.
574 if (TheTok.getKind() == tok::comment)
575 continue;
576
577 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
578 // This is the start of a preprocessor directive.
579 Token HashTok = TheTok;
580 InPreprocessorDirective = true;
581
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000582 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000583 // we don't have an identifier table available. Instead, just look at
584 // the raw identifier to recognize and categorize preprocessor directives.
585 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000586 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000587 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000588 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000589 PreambleDirectiveKind PDK
590 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
591 .Case("include", PDK_Skipped)
592 .Case("__include_macros", PDK_Skipped)
593 .Case("define", PDK_Skipped)
594 .Case("undef", PDK_Skipped)
595 .Case("line", PDK_Skipped)
596 .Case("error", PDK_Skipped)
597 .Case("pragma", PDK_Skipped)
598 .Case("import", PDK_Skipped)
599 .Case("include_next", PDK_Skipped)
600 .Case("warning", PDK_Skipped)
601 .Case("ident", PDK_Skipped)
602 .Case("sccs", PDK_Skipped)
603 .Case("assert", PDK_Skipped)
604 .Case("unassert", PDK_Skipped)
605 .Case("if", PDK_StartIf)
606 .Case("ifdef", PDK_StartIf)
607 .Case("ifndef", PDK_StartIf)
608 .Case("elif", PDK_Skipped)
609 .Case("else", PDK_Skipped)
610 .Case("endif", PDK_EndIf)
611 .Default(PDK_Unknown);
612
613 switch (PDK) {
614 case PDK_Skipped:
615 continue;
616
617 case PDK_StartIf:
618 if (IfCount == 0)
619 IfStartTok = HashTok;
620
621 ++IfCount;
622 continue;
623
624 case PDK_EndIf:
625 // Mismatched #endif. The preamble ends here.
626 if (IfCount == 0)
627 break;
628
629 --IfCount;
630 continue;
631
632 case PDK_Unknown:
633 // We don't know what this directive is; stop at the '#'.
634 break;
635 }
636 }
637
638 // We only end up here if we didn't recognize the preprocessor
639 // directive or it was one that can't occur in the preamble at this
640 // point. Roll back the current token to the location of the '#'.
641 InPreprocessorDirective = false;
642 TheTok = HashTok;
643 }
644
Douglas Gregordf95a132010-08-09 20:45:32 +0000645 // We hit a token that we don't recognize as being in the
646 // "preprocessing only" part of the file, so we're no longer in
647 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000648 break;
649 } while (true);
650
651 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000652 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
653 IfCount? IfStartTok.isAtStartOfLine()
654 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000655}
656
Chris Lattner7ef5c272010-11-17 07:05:50 +0000657
658/// AdvanceToTokenCharacter - Given a location that specifies the start of a
659/// token, return a new location that specifies a character within the token.
660SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
661 unsigned CharNo,
662 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000663 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000664 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000665 // character is. This needs to take into consideration newlines and
666 // trigraphs.
667 bool Invalid = false;
668 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
669
670 // If they request the first char of the token, we're trivially done.
671 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
672 return TokStart;
673
674 unsigned PhysOffset = 0;
675
676 // The usual case is that tokens don't contain anything interesting. Skip
677 // over the uninteresting characters. If a token only consists of simple
678 // chars, this method is extremely fast.
679 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
680 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000681 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000682 ++TokPtr, --CharNo, ++PhysOffset;
683 }
684
685 // If we have a character that may be a trigraph or escaped newline, use a
686 // lexer to parse it correctly.
687 for (; CharNo; --CharNo) {
688 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000689 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000690 TokPtr += Size;
691 PhysOffset += Size;
692 }
693
694 // Final detail: if we end up on an escaped newline, we want to return the
695 // location of the actual byte of the token. For example foo\<newline>bar
696 // advanced by 3 should return the location of b, not of \\. One compounding
697 // detail of this is that the escape may be made by a trigraph.
698 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
699 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
700
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000701 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000702}
703
704/// \brief Computes the source location just past the end of the
705/// token at this source location.
706///
707/// This routine can be used to produce a source location that
708/// points just past the end of the token referenced by \p Loc, and
709/// is generally used when a diagnostic needs to point just after a
710/// token where it expected something different that it received. If
711/// the returned source location would not be meaningful (e.g., if
712/// it points into a macro), this routine returns an invalid
713/// source location.
714///
715/// \param Offset an offset from the end of the token, where the source
716/// location should refer to. The default offset (0) produces a source
717/// location pointing just past the end of the token; an offset of 1 produces
718/// a source location pointing to the last character in the token, etc.
719SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
720 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000721 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000722 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000723 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000724
725 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000726 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000727 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000728 }
729
David Blaikie4e4d0842012-03-11 07:00:24 +0000730 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000731 if (Len > Offset)
732 Len = Len - Offset;
733 else
734 return Loc;
735
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000736 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000737}
738
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000739/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000740/// token of the macro expansion.
741bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000742 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000743 const LangOptions &LangOpts,
744 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000745 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
746
747 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
748 // FIXME: If the token comes from the macro token paste operator ('##')
749 // this function will always return false;
750 if (infoLoc.second > 0)
751 return false; // Does not point at the start of token.
752
Chandler Carruth433db062011-07-14 08:20:40 +0000753 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000754 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000755 if (expansionLoc.isFileID()) {
756 // No other macro expansions, this is the first.
757 if (MacroBegin)
758 *MacroBegin = expansionLoc;
759 return true;
760 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000761
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000762 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000763}
764
765/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000766/// token of the macro expansion.
767bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000768 const SourceManager &SM,
769 const LangOptions &LangOpts,
770 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000771 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
772
773 SourceLocation spellLoc = SM.getSpellingLoc(loc);
774 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
775 if (tokLen == 0)
776 return false;
777
778 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000779 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000780 if (SM.isInFileID(afterLoc, FID))
781 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000782
783 // FIXME: If the token comes from the macro token paste operator ('##')
784 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000785
Chandler Carruth433db062011-07-14 08:20:40 +0000786 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000787 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000788 if (expansionLoc.isFileID()) {
789 // No other macro expansions.
790 if (MacroEnd)
791 *MacroEnd = expansionLoc;
792 return true;
793 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000794
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000795 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000796}
797
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000798static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000799 const SourceManager &SM,
800 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000801 SourceLocation Begin = Range.getBegin();
802 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000803 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000804 if (Range.isTokenRange()) {
805 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
806 if (End.isInvalid())
807 return CharSourceRange();
808 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000809
810 // Break down the source locations.
811 FileID FID;
812 unsigned BeginOffs;
813 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
814 if (FID.isInvalid())
815 return CharSourceRange();
816
817 unsigned EndOffs;
818 if (!SM.isInFileID(End, FID, &EndOffs) ||
819 BeginOffs > EndOffs)
820 return CharSourceRange();
821
822 return CharSourceRange::getCharRange(Begin, End);
823}
824
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000825CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000826 const SourceManager &SM,
827 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000828 SourceLocation Begin = Range.getBegin();
829 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000830 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000831 return CharSourceRange();
832
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000833 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000834 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000835
836 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000837 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
838 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000839 Range.setBegin(Begin);
840 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000841 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000842
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000843 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000844 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
845 &End)) ||
846 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
847 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000848 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000849 Range.setEnd(End);
850 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000851 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000852
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000853 assert(Begin.isMacroID() && End.isMacroID());
854 SourceLocation MacroBegin, MacroEnd;
855 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000856 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
857 &MacroEnd)) ||
858 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
859 &MacroEnd)))) {
860 Range.setBegin(MacroBegin);
861 Range.setEnd(MacroEnd);
862 return makeRangeFromFileLocs(Range, SM, LangOpts);
863 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000864
865 FileID FID;
866 unsigned BeginOffs;
867 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
868 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000869 return CharSourceRange();
870
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000871 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000872 if (!SM.isInFileID(End, FID, &EndOffs) ||
873 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000874 return CharSourceRange();
875
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000876 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
877 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
878 if (Expansion.isMacroArgExpansion() &&
879 Expansion.getSpellingLoc().isFileID()) {
880 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000881 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
882 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000884 }
885
886 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000887}
888
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000889StringRef Lexer::getSourceText(CharSourceRange Range,
890 const SourceManager &SM,
891 const LangOptions &LangOpts,
892 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000893 Range = makeFileCharRange(Range, SM, LangOpts);
894 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000895 if (Invalid) *Invalid = true;
896 return StringRef();
897 }
898
899 // Break down the source location.
900 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
901 if (beginInfo.first.isInvalid()) {
902 if (Invalid) *Invalid = true;
903 return StringRef();
904 }
905
906 unsigned EndOffs;
907 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
908 beginInfo.second > EndOffs) {
909 if (Invalid) *Invalid = true;
910 return StringRef();
911 }
912
913 // Try to the load the file buffer.
914 bool invalidTemp = false;
915 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
916 if (invalidTemp) {
917 if (Invalid) *Invalid = true;
918 return StringRef();
919 }
920
921 if (Invalid) *Invalid = false;
922 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
923}
924
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000925StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
926 const SourceManager &SM,
927 const LangOptions &LangOpts) {
928 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000929
930 // Find the location of the immediate macro expansion.
931 while (1) {
932 FileID FID = SM.getFileID(Loc);
933 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
934 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
935 Loc = Expansion.getExpansionLocStart();
936 if (!Expansion.isMacroArgExpansion())
937 break;
938
939 // For macro arguments we need to check that the argument did not come
940 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
941
942 // Loc points to the argument id of the macro definition, move to the
943 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000944 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000945 SourceLocation SpellLoc = Expansion.getSpellingLoc();
946 if (SpellLoc.isFileID())
947 break; // No inner macro.
948
949 // If spelling location resides in the same FileID as macro expansion
950 // location, it means there is no inner macro.
951 FileID MacroFID = SM.getFileID(Loc);
952 if (SM.isInFileID(SpellLoc, MacroFID))
953 break;
954
955 // Argument came from inner macro.
956 Loc = SpellLoc;
957 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000958
959 // Find the spelling location of the start of the non-argument expansion
960 // range. This is where the macro name was spelled in order to begin
961 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000962 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000963
964 // Dig out the buffer where the macro name was spelled and the extents of the
965 // name so that we can render it into the expansion note.
966 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
967 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
968 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
969 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
970}
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972//===----------------------------------------------------------------------===//
973// Character information.
974//===----------------------------------------------------------------------===//
975
Reid Spencer5f016e22007-07-11 17:01:13 +0000976enum {
977 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
978 CHAR_VERT_WS = 0x02, // '\r', '\n'
979 CHAR_LETTER = 0x04, // a-z,A-Z
980 CHAR_NUMBER = 0x08, // 0-9
981 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000982 CHAR_PERIOD = 0x20, // .
983 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000984};
985
Chris Lattner03b98662009-07-07 17:09:54 +0000986// Statically initialize CharInfo table based on ASCII character set
987// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000988static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000989{
990// 0 NUL 1 SOH 2 STX 3 ETX
991// 4 EOT 5 ENQ 6 ACK 7 BEL
992 0 , 0 , 0 , 0 ,
993 0 , 0 , 0 , 0 ,
994// 8 BS 9 HT 10 NL 11 VT
995//12 NP 13 CR 14 SO 15 SI
996 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
997 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
998//16 DLE 17 DC1 18 DC2 19 DC3
999//20 DC4 21 NAK 22 SYN 23 ETB
1000 0 , 0 , 0 , 0 ,
1001 0 , 0 , 0 , 0 ,
1002//24 CAN 25 EM 26 SUB 27 ESC
1003//28 FS 29 GS 30 RS 31 US
1004 0 , 0 , 0 , 0 ,
1005 0 , 0 , 0 , 0 ,
1006//32 SP 33 ! 34 " 35 #
1007//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001008 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1009 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001010//40 ( 41 ) 42 * 43 +
1011//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001012 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1013 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001014//48 0 49 1 50 2 51 3
1015//52 4 53 5 54 6 55 7
1016 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1017 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1018//56 8 57 9 58 : 59 ;
1019//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001020 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1021 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001022//64 @ 65 A 66 B 67 C
1023//68 D 69 E 70 F 71 G
1024 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1025 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1026//72 H 73 I 74 J 75 K
1027//76 L 77 M 78 N 79 O
1028 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1029 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1030//80 P 81 Q 82 R 83 S
1031//84 T 85 U 86 V 87 W
1032 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1033 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1034//88 X 89 Y 90 Z 91 [
1035//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001036 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1037 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001038//96 ` 97 a 98 b 99 c
1039//100 d 101 e 102 f 103 g
1040 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1041 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1042//104 h 105 i 106 j 107 k
1043//108 l 109 m 110 n 111 o
1044 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1045 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1046//112 p 113 q 114 r 115 s
1047//116 t 117 u 118 v 119 w
1048 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1049 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1050//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001051//124 | 125 } 126 ~ 127 DEL
1052 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1053 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001054};
1055
Chris Lattnera2bf1052009-12-17 05:29:40 +00001056static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 static bool isInited = false;
1058 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001059 // check the statically-initialized CharInfo table
1060 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1061 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1062 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1063 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1064 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1065 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1066 assert(CHAR_UNDER == CharInfo[(int)'_']);
1067 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1068 for (unsigned i = 'a'; i <= 'z'; ++i) {
1069 assert(CHAR_LETTER == CharInfo[i]);
1070 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1071 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001073 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001074
Chris Lattner03b98662009-07-07 17:09:54 +00001075 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001076}
1077
Chris Lattner03b98662009-07-07 17:09:54 +00001078
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001079/// isIdentifierHead - Return true if this is the first character of an
1080/// identifier, which is [a-zA-Z_].
1081static inline bool isIdentifierHead(unsigned char c) {
1082 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1083}
1084
Reid Spencer5f016e22007-07-11 17:01:13 +00001085/// isIdentifierBody - Return true if this is the body character of an
1086/// identifier, which is [a-zA-Z0-9_].
1087static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001088 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089}
1090
1091/// isHorizontalWhitespace - Return true if this character is horizontal
James Dennetta05369f2012-06-15 21:36:54 +00001092/// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1093/// '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001094static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001095 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001096}
1097
Anna Zaksaca25bc2011-07-27 21:43:43 +00001098/// isVerticalWhitespace - Return true if this character is vertical
James Dennetta05369f2012-06-15 21:36:54 +00001099/// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
Anna Zaksaca25bc2011-07-27 21:43:43 +00001100static inline bool isVerticalWhitespace(unsigned char c) {
1101 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1102}
1103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104/// isWhitespace - Return true if this character is horizontal or vertical
James Dennetta05369f2012-06-15 21:36:54 +00001105/// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1106/// false for '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001107static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001108 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001109}
1110
1111/// isNumberBody - Return true if this is the body character of an
1112/// preprocessing number, which is [a-zA-Z0-9_.].
1113static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001114 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001115 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001116}
1117
Craig Topper2fa4e862011-08-11 04:06:15 +00001118/// isRawStringDelimBody - Return true if this is the body character of a
1119/// raw string delimiter.
1120static inline bool isRawStringDelimBody(unsigned char c) {
1121 return (CharInfo[c] &
1122 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1123 true : false;
1124}
1125
Jordan Rosed880b3a2012-06-07 01:10:31 +00001126// Allow external clients to make use of CharInfo.
1127bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1128 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1129}
1130
Reid Spencer5f016e22007-07-11 17:01:13 +00001131
1132//===----------------------------------------------------------------------===//
1133// Diagnostics forwarding code.
1134//===----------------------------------------------------------------------===//
1135
Chris Lattner409a0362007-07-22 18:38:25 +00001136/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001137/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001138/// This is currently only used for _Pragma implementation, so it is the slow
1139/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001140static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1141 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001142static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1143 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001144 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001145 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner409a0362007-07-22 18:38:25 +00001147 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001148 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001149 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001150 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Chandler Carruth433db062011-07-14 08:20:40 +00001152 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001153 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001154 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001155 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Chris Lattnere7fb4842009-02-15 20:52:18 +00001157 // Figure out the expansion loc range, which is the range covered by the
1158 // original _Pragma(...) sequence.
1159 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001160 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Chandler Carruthbf340e42011-07-26 03:03:05 +00001162 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001163}
1164
Reid Spencer5f016e22007-07-11 17:01:13 +00001165/// getSourceLocation - Return a source location identifier for the specified
1166/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001167SourceLocation Lexer::getSourceLocation(const char *Loc,
1168 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001169 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001171
1172 // In the normal case, we're just lexing from a simple file buffer, return
1173 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001174 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001175 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001176 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Chris Lattner2b2453a2009-01-17 06:22:33 +00001178 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1179 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001180 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001181 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001182}
1183
Reid Spencer5f016e22007-07-11 17:01:13 +00001184/// Diag - Forwarding function for diagnostics. This translate a source
1185/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001186DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001187 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188}
Reid Spencer5f016e22007-07-11 17:01:13 +00001189
1190//===----------------------------------------------------------------------===//
1191// Trigraph and Escaped Newline Handling Code.
1192//===----------------------------------------------------------------------===//
1193
1194/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1195/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1196static char GetTrigraphCharForLetter(char Letter) {
1197 switch (Letter) {
1198 default: return 0;
1199 case '=': return '#';
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 }
1209}
1210
1211/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1212/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1213/// return the result character. Finally, emit a warning about trigraph use
1214/// whether trigraphs are enabled or not.
1215static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1216 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001217 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
David Blaikie4e4d0842012-03-11 07:00:24 +00001219 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001220 if (!L->isLexingRawMode())
1221 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001222 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattner74d15df2008-11-22 02:02:22 +00001225 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001226 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 return Res;
1228}
1229
Chris Lattner24f0e482009-04-18 22:05:41 +00001230/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1231/// 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 +00001232/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001233unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1234 unsigned Size = 0;
1235 while (isWhitespace(Ptr[Size])) {
1236 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Chris Lattner24f0e482009-04-18 22:05:41 +00001238 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1239 continue;
1240
1241 // If this is a \r\n or \n\r, skip the other half.
1242 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1243 Ptr[Size-1] != Ptr[Size])
1244 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Chris Lattner24f0e482009-04-18 22:05:41 +00001246 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001247 }
1248
Chris Lattner24f0e482009-04-18 22:05:41 +00001249 // Not an escaped newline, must be a \t or something else.
1250 return 0;
1251}
1252
Chris Lattner03374952009-04-18 22:27:02 +00001253/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1254/// them), skip over them and return the first non-escaped-newline found,
1255/// otherwise return P.
1256const char *Lexer::SkipEscapedNewLines(const char *P) {
1257 while (1) {
1258 const char *AfterEscape;
1259 if (*P == '\\') {
1260 AfterEscape = P+1;
1261 } else if (*P == '?') {
1262 // If not a trigraph for escape, bail out.
1263 if (P[1] != '?' || P[2] != '/')
1264 return P;
1265 AfterEscape = P+3;
1266 } else {
1267 return P;
1268 }
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattner03374952009-04-18 22:27:02 +00001270 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1271 if (NewLineSize == 0) return P;
1272 P = AfterEscape+NewLineSize;
1273 }
1274}
1275
Anna Zaksaca25bc2011-07-27 21:43:43 +00001276/// \brief Checks that the given token is the first token that occurs after the
1277/// given location (this excludes comments and whitespace). Returns the location
1278/// immediately after the specified token. If the token is not found or the
1279/// location is inside a macro, the returned source location will be invalid.
1280SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1281 tok::TokenKind TKind,
1282 const SourceManager &SM,
1283 const LangOptions &LangOpts,
1284 bool SkipTrailingWhitespaceAndNewLine) {
1285 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001286 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001287 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001288 }
1289 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1290
1291 // Break down the source location.
1292 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1293
1294 // Try to load the file buffer.
1295 bool InvalidTemp = false;
1296 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1297 if (InvalidTemp)
1298 return SourceLocation();
1299
1300 const char *TokenBegin = File.data() + LocInfo.second;
1301
1302 // Lex from the start of the given location.
1303 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1304 TokenBegin, File.end());
1305 // Find the token.
1306 Token Tok;
1307 lexer.LexFromRawLexer(Tok);
1308 if (Tok.isNot(TKind))
1309 return SourceLocation();
1310 SourceLocation TokenLoc = Tok.getLocation();
1311
1312 // Calculate how much whitespace needs to be skipped if any.
1313 unsigned NumWhitespaceChars = 0;
1314 if (SkipTrailingWhitespaceAndNewLine) {
1315 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1316 Tok.getLength();
1317 unsigned char C = *TokenEnd;
1318 while (isHorizontalWhitespace(C)) {
1319 C = *(++TokenEnd);
1320 NumWhitespaceChars++;
1321 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001322
1323 // Skip \r, \n, \r\n, or \n\r
1324 if (C == '\n' || C == '\r') {
1325 char PrevC = C;
1326 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001327 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001328 if ((C == '\n' || C == '\r') && C != PrevC)
1329 NumWhitespaceChars++;
1330 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001331 }
1332
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001333 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001334}
Chris Lattner24f0e482009-04-18 22:05:41 +00001335
Reid Spencer5f016e22007-07-11 17:01:13 +00001336/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1337/// get its size, and return it. This is tricky in several cases:
1338/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1339/// then either return the trigraph (skipping 3 chars) or the '?',
1340/// depending on whether trigraphs are enabled or not.
1341/// 2. If this is an escaped newline (potentially with whitespace between
1342/// the backslash and newline), implicitly skip the newline and return
1343/// the char after it.
1344/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1345///
1346/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1347/// know that we can accumulate into Size, and that we have already incremented
1348/// Ptr by Size bytes.
1349///
1350/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1351/// be updated to match.
1352///
1353char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001354 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 // If we have a slash, look for an escaped newline.
1356 if (Ptr[0] == '\\') {
1357 ++Size;
1358 ++Ptr;
1359Slash:
1360 // Common case, backslash-char where the char is not whitespace.
1361 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattner5636a3b2009-06-23 05:15:06 +00001363 // See if we have optional whitespace characters between the slash and
1364 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001365 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1366 // Remember that this token needs to be cleaned.
1367 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
Chris Lattner24f0e482009-04-18 22:05:41 +00001369 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001370 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001371 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattner24f0e482009-04-18 22:05:41 +00001373 // Found backslash<whitespace><newline>. Parse the char after it.
1374 Size += EscapedNewLineSize;
1375 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001376
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001377 // If the char that we finally got was a \n, then we must have had
1378 // something like \<newline><newline>. We don't want to consume the
1379 // second newline.
1380 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1381 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001382
Chris Lattner24f0e482009-04-18 22:05:41 +00001383 // Use slow version to accumulate a correct size field.
1384 return getCharAndSizeSlow(Ptr, Size, Tok);
1385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // Otherwise, this is not an escaped newline, just return the slash.
1388 return '\\';
1389 }
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 // If this is a trigraph, process it.
1392 if (Ptr[0] == '?' && Ptr[1] == '?') {
1393 // If this is actually a legal trigraph (not something like "??x"), emit
1394 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1395 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1396 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001397 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001398
1399 Ptr += 3;
1400 Size += 3;
1401 if (C == '\\') goto Slash;
1402 return C;
1403 }
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 // If this is neither, return a single character.
1407 ++Size;
1408 return *Ptr;
1409}
1410
1411
1412/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1413/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1414/// and that we have already incremented Ptr by Size bytes.
1415///
1416/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1417/// be updated to match.
1418char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001419 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 // If we have a slash, look for an escaped newline.
1421 if (Ptr[0] == '\\') {
1422 ++Size;
1423 ++Ptr;
1424Slash:
1425 // Common case, backslash-char where the char is not whitespace.
1426 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001429 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1430 // Found backslash<whitespace><newline>. Parse the char after it.
1431 Size += EscapedNewLineSize;
1432 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001434 // If the char that we finally got was a \n, then we must have had
1435 // something like \<newline><newline>. We don't want to consume the
1436 // second newline.
1437 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1438 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001439
Chris Lattner24f0e482009-04-18 22:05:41 +00001440 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001441 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // Otherwise, this is not an escaped newline, just return the slash.
1445 return '\\';
1446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001449 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // If this is actually a legal trigraph (not something like "??x"), return
1451 // it.
1452 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1453 Ptr += 3;
1454 Size += 3;
1455 if (C == '\\') goto Slash;
1456 return C;
1457 }
1458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 // If this is neither, return a single character.
1461 ++Size;
1462 return *Ptr;
1463}
1464
1465//===----------------------------------------------------------------------===//
1466// Helper methods for lexing.
1467//===----------------------------------------------------------------------===//
1468
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001469/// \brief Routine that indiscriminately skips bytes in the source file.
1470void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1471 BufferPtr += Bytes;
1472 if (BufferPtr > BufferEnd)
1473 BufferPtr = BufferEnd;
1474 IsAtStartOfLine = StartOfLine;
1475}
1476
Chris Lattnerd2177732007-07-20 16:59:19 +00001477void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1479 unsigned Size;
1480 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001481 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 --CurPtr; // Back up over the skipped character.
1485
1486 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1487 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1488 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001489 //
1490 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1491 // cheaper
David Blaikie4e4d0842012-03-11 07:00:24 +00001492 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001493FinishIdentifier:
1494 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001495 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1496 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // If we are in raw mode, return this identifier raw. There is no need to
1499 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001500 if (LexingRawMode)
1501 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001503 // Fill in Result.IdentifierInfo and update the token kind,
1504 // looking up the identifier in the identifier table.
1505 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 // Finally, now that we know we have an identifier, pass this off to the
1508 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001509 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001510 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001511
Chris Lattner6a170eb2009-01-21 07:43:11 +00001512 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 C = getCharAndSize(CurPtr, Size);
1518 while (1) {
1519 if (C == '$') {
1520 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001524 if (!isLexingRawMode())
1525 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 CurPtr = ConsumeChar(CurPtr, Size, Result);
1527 C = getCharAndSize(CurPtr, Size);
1528 continue;
1529 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1530 // Found end of identifier.
1531 goto FinishIdentifier;
1532 }
1533
1534 // Otherwise, this character is good, consume it.
1535 CurPtr = ConsumeChar(CurPtr, Size, Result);
1536
1537 C = getCharAndSize(CurPtr, Size);
1538 while (isIdentifierBody(C)) { // FIXME: UCNs.
1539 CurPtr = ConsumeChar(CurPtr, Size, Result);
1540 C = getCharAndSize(CurPtr, Size);
1541 }
1542 }
1543}
1544
Douglas Gregora75ec432010-08-30 14:50:47 +00001545/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001546/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001547bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001548 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001549 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001550 if (C1 != '0')
1551 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001552 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001553 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001554}
Reid Spencer5f016e22007-07-11 17:01:13 +00001555
Nate Begeman5253c7f2008-04-14 02:26:39 +00001556/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001557/// constant. From[-1] is the first character lexed. Return the end of the
1558/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001559void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 unsigned Size;
1561 char C = getCharAndSize(CurPtr, Size);
1562 char PrevCh = 0;
Nico Weberdd817312012-11-13 06:25:15 +00001563 while (isNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 CurPtr = ConsumeChar(CurPtr, Size, Result);
1565 PrevCh = C;
1566 C = getCharAndSize(CurPtr, Size);
1567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001570 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1571 // If we are in Microsoft mode, don't continue if the constant is hex.
1572 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001573 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001574 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001576
1577 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001578 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1579 // Outside C99, we accept hexadecimal floating point numbers as a
1580 // not-quite-conforming extension. Only do so if this looks like it's
1581 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1582 bool IsHexFloat = true;
1583 if (!LangOpts.C99) {
1584 if (!isHexaLiteral(BufferPtr, LangOpts))
1585 IsHexFloat = false;
1586 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1587 IsHexFloat = false;
1588 }
1589 if (IsHexFloat)
1590 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001594 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001595 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001596 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597}
1598
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001599/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001600/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001601const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001602 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001603
1604 // Maximally munch an identifier. FIXME: UCNs.
1605 unsigned Size;
1606 char C = getCharAndSize(CurPtr, Size);
1607 if (isIdentifierHead(C)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001608 if (!getLangOpts().CPlusPlus0x) {
Richard Smithe816c712012-03-07 03:13:00 +00001609 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001610 Diag(CurPtr,
1611 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1612 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1613 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1614 return CurPtr;
1615 }
1616
1617 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1618 // that does not start with an underscore is ill-formed. As a conforming
1619 // extension, we treat all such suffixes as if they had whitespace before
1620 // them.
1621 if (C != '_') {
1622 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001623 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1624 diag::ext_ms_reserved_user_defined_literal :
1625 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001626 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1627 return CurPtr;
1628 }
1629
Richard Smith99831e42012-03-06 03:21:47 +00001630 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001631 do {
1632 CurPtr = ConsumeChar(CurPtr, Size, Result);
1633 C = getCharAndSize(CurPtr, Size);
1634 } while (isIdentifierBody(C));
1635 }
1636 return CurPtr;
1637}
1638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001640/// either " or L" or u8" or u" or U".
1641void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1642 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Richard Smith661a9962011-10-15 01:18:56 +00001645 if (!isLexingRawMode() &&
1646 (Kind == tok::utf8_string_literal ||
1647 Kind == tok::utf16_string_literal ||
1648 Kind == tok::utf32_string_literal))
1649 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1650
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 char C = getAndAdvanceChar(CurPtr, Result);
1652 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001653 // Skip escaped characters. Escaped newlines will already be processed by
1654 // getAndAdvanceChar.
1655 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001657
Chris Lattner571339c2010-05-30 23:27:38 +00001658 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001659 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001660 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001661 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001662 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 }
Chris Lattner571339c2010-05-30 23:27:38 +00001665
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001666 if (C == 0) {
1667 if (isCodeCompletionPoint(CurPtr-1)) {
1668 PP->CodeCompleteNaturalLanguage();
1669 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1670 return cutOffLexing();
1671 }
1672
Chris Lattner571339c2010-05-30 23:27:38 +00001673 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001674 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 C = getAndAdvanceChar(CurPtr, Result);
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001678 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001679 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001680 CurPtr = LexUDSuffix(Result, CurPtr);
1681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001683 if (NulCharacter && !isLexingRawMode())
1684 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001687 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001688 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001689 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001690}
1691
Craig Topper2fa4e862011-08-11 04:06:15 +00001692/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1693/// having lexed R", LR", u8R", uR", or UR".
1694void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1695 tok::TokenKind Kind) {
1696 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1697 // Between the initial and final double quote characters of the raw string,
1698 // any transformations performed in phases 1 and 2 (trigraphs,
1699 // universal-character-names, and line splicing) are reverted.
1700
Richard Smith661a9962011-10-15 01:18:56 +00001701 if (!isLexingRawMode())
1702 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1703
Craig Topper2fa4e862011-08-11 04:06:15 +00001704 unsigned PrefixLen = 0;
1705
1706 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1707 ++PrefixLen;
1708
1709 // If the last character was not a '(', then we didn't lex a valid delimiter.
1710 if (CurPtr[PrefixLen] != '(') {
1711 if (!isLexingRawMode()) {
1712 const char *PrefixEnd = &CurPtr[PrefixLen];
1713 if (PrefixLen == 16) {
1714 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1715 } else {
1716 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1717 << StringRef(PrefixEnd, 1);
1718 }
1719 }
1720
1721 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1722 // it's possible the '"' was intended to be part of the raw string, but
1723 // there's not much we can do about that.
1724 while (1) {
1725 char C = *CurPtr++;
1726
1727 if (C == '"')
1728 break;
1729 if (C == 0 && CurPtr-1 == BufferEnd) {
1730 --CurPtr;
1731 break;
1732 }
1733 }
1734
1735 FormTokenWithChars(Result, CurPtr, tok::unknown);
1736 return;
1737 }
1738
1739 // Save prefix and move CurPtr past it
1740 const char *Prefix = CurPtr;
1741 CurPtr += PrefixLen + 1; // skip over prefix and '('
1742
1743 while (1) {
1744 char C = *CurPtr++;
1745
1746 if (C == ')') {
1747 // Check for prefix match and closing quote.
1748 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1749 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1750 break;
1751 }
1752 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1753 if (!isLexingRawMode())
1754 Diag(BufferPtr, diag::err_unterminated_raw_string)
1755 << StringRef(Prefix, PrefixLen);
1756 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1757 return;
1758 }
1759 }
1760
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001761 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001762 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001763 CurPtr = LexUDSuffix(Result, CurPtr);
1764
Craig Topper2fa4e862011-08-11 04:06:15 +00001765 // Update the location of token as well as BufferPtr.
1766 const char *TokStart = BufferPtr;
1767 FormTokenWithChars(Result, CurPtr, Kind);
1768 Result.setLiteralData(TokStart);
1769}
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1772/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001773void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001775 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 char C = getAndAdvanceChar(CurPtr, Result);
1777 while (C != '>') {
1778 // Skip escaped characters.
1779 if (C == '\\') {
1780 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001781 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001783 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1784 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001785 // If the filename is unterminated, then it must just be a lone <
1786 // character. Return this as such.
1787 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 return;
1789 } else if (C == 0) {
1790 NulCharacter = CurPtr-1;
1791 }
1792 C = getAndAdvanceChar(CurPtr, Result);
1793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001796 if (NulCharacter && !isLexingRawMode())
1797 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001800 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001801 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001802 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001803}
1804
1805
1806/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001807/// lexed either ' or L' or u' or U'.
1808void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1809 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 const char *NulCharacter = 0; // Does this character contain the \0 character?
1811
Richard Smith661a9962011-10-15 01:18:56 +00001812 if (!isLexingRawMode() &&
1813 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1814 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 char C = getAndAdvanceChar(CurPtr, Result);
1817 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001818 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001819 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001820 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001822 }
1823
1824 while (C != '\'') {
1825 // Skip escaped characters.
1826 if (C == '\\') {
1827 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001828 getAndAdvanceChar(CurPtr, Result);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001829 } else if (C == '\n' || C == '\r' || // Newline.
1830 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001831 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001832 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001833 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1834 return;
1835 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001836 if (isCodeCompletionPoint(CurPtr-1)) {
1837 PP->CodeCompleteNaturalLanguage();
1838 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1839 return cutOffLexing();
1840 }
1841
Chris Lattnerd80f7862010-07-07 23:24:27 +00001842 NulCharacter = CurPtr-1;
1843 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 C = getAndAdvanceChar(CurPtr, Result);
1845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001847 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001848 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001849 CurPtr = LexUDSuffix(Result, CurPtr);
1850
Chris Lattnerd80f7862010-07-07 23:24:27 +00001851 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001852 if (NulCharacter && !isLexingRawMode())
1853 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001856 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001857 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001858 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001859}
1860
1861/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1862/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001863///
1864/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1865///
1866bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 // Whitespace - Skip it, then return the token after the whitespace.
1868 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1869 while (1) {
1870 // Skip horizontal whitespace very aggressively.
1871 while (isHorizontalWhitespace(Char))
1872 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001874 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 if (Char != '\n' && Char != '\r')
1876 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 if (ParsingPreprocessorDirective) {
1879 // End of preprocessor directive line, let LexTokenInternal handle this.
1880 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001881 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 }
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 // ok, but handle newline.
1885 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001886 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001888 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 Char = *++CurPtr;
1890 }
1891
1892 // If this isn't immediately after a newline, there is leading space.
1893 char PrevChar = CurPtr[-1];
1894 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001895 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896
Chris Lattnerd88dc482008-10-12 04:05:48 +00001897 // If the client wants us to return whitespace, return it now.
1898 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001899 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001900 return true;
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001904 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001905}
1906
Nico Weberbb236282012-11-11 07:02:14 +00001907/// We have just read the // characters from input. Skip until we find the
1908/// newline character thats terminate the comment. Then update BufferPtr and
1909/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001910///
1911/// If we're in KeepCommentMode or any CommentHandler has inserted
1912/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001913bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1914 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001916 if (!LangOpts.LineComment && !isLexingRawMode()) {
1917 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 // Mark them enabled so we only emit one warning for this translation
1920 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001921 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 // Scan over the body of the comment. The common case, when scanning, is that
1925 // the comment contains normal ascii characters with nothing interesting in
1926 // them. As such, optimize for this case with the inner loop.
1927 char C;
1928 do {
1929 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // Skip over characters in the fast loop.
1931 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 C != '\n' && C != '\r') // Newline or DOS-style newline.
1933 C = *++CurPtr;
1934
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001935 const char *NextLine = CurPtr;
1936 if (C != 0) {
1937 // We found a newline, see if it's escaped.
1938 const char *EscapePtr = CurPtr-1;
1939 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1940 --EscapePtr;
1941
1942 if (*EscapePtr == '\\') // Escaped newline.
1943 CurPtr = EscapePtr;
1944 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1945 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1946 CurPtr = EscapePtr-2;
1947 else
1948 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001952 // properly decode the character. Read it in raw mode to avoid emitting
1953 // diagnostics about things like trigraphs. If we see an escaped newline,
1954 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001956 bool OldRawMode = isLexingRawMode();
1957 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001959 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001960
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001961 // If we only read only one character, then no special handling is needed.
1962 // We're done and can skip forward to the newline.
1963 if (C != 0 && CurPtr == OldPtr+1) {
1964 CurPtr = NextLine;
1965 break;
1966 }
1967
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 // If we read multiple characters, and one of those characters was a \r or
1969 // \n, then we had an escaped newline within the comment. Emit diagnostic
1970 // unless the next line is also a // comment.
1971 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1972 for (; OldPtr != CurPtr; ++OldPtr)
1973 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1974 // Okay, we found a // comment that ends in a newline, if the next
1975 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001976 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001978 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 ++ForwardPtr;
1980 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1981 break;
1982 }
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Chris Lattner74d15df2008-11-22 02:02:22 +00001984 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00001985 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 break;
1987 }
1988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Douglas Gregor55817af2010-08-25 17:04:25 +00001990 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001991 --CurPtr;
1992 break;
1993 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001994
1995 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1996 PP->CodeCompleteNaturalLanguage();
1997 cutOffLexing();
1998 return false;
1999 }
2000
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 } while (C != '\n' && C != '\r');
2002
Chris Lattner3d0ad582010-02-03 21:06:21 +00002003 // Found but did not consume the newline. Notify comment handlers about the
2004 // comment unless we're in a #if 0 block.
2005 if (PP && !isLexingRawMode() &&
2006 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2007 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002008 BufferPtr = CurPtr;
2009 return true; // A token has to be returned.
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002013 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002014 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002015
2016 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002017 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2019 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002020 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002024 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002025 // contribute to another token), it isn't needed for correctness. Note that
2026 // this is ok even in KeepWhitespaceMode, because we would have returned the
2027 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002031 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002033 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002035 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002036}
2037
Nico Weberbb236282012-11-11 07:02:14 +00002038/// If in save-comment mode, package up this Line comment in an appropriate
2039/// way and return it.
2040bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002041 // If we're not in a preprocessor directive, just return the // comment
2042 // directly.
2043 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002044
David Blaikie8c0b3782012-06-06 18:52:13 +00002045 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002046 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Nico Weberbb236282012-11-11 07:02:14 +00002048 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002049 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002050 bool Invalid = false;
2051 std::string Spelling = PP->getSpelling(Result, &Invalid);
2052 if (Invalid)
2053 return true;
2054
Nico Weberbb236282012-11-11 07:02:14 +00002055 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002056 Spelling[1] = '*'; // Change prefix to "/*".
2057 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Chris Lattner9e6293d2008-10-12 04:51:35 +00002059 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002060 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002061 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002062 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002063}
2064
2065/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002066/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2067/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002068static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 Lexer *L) {
2070 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Reid Spencer5f016e22007-07-11 17:01:13 +00002072 // Back up off the newline.
2073 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 // If this is a two-character newline sequence, skip the other character.
2076 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2077 // \n\n or \r\r -> not escaped newline.
2078 if (CurPtr[0] == CurPtr[1])
2079 return false;
2080 // \n\r or \r\n -> skip the newline.
2081 --CurPtr;
2082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 // If we have horizontal whitespace, skip over it. We allow whitespace
2085 // between the slash and newline.
2086 bool HasSpace = false;
2087 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2088 --CurPtr;
2089 HasSpace = true;
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // If we have a slash, we know this is an escaped newline.
2093 if (*CurPtr == '\\') {
2094 if (CurPtr[-1] != '*') return false;
2095 } else {
2096 // It isn't a slash, is it the ?? / trigraph?
2097 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2098 CurPtr[-3] != '*')
2099 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 // This is the trigraph ending the comment. Emit a stern warning!
2102 CurPtr -= 2;
2103
2104 // If no trigraphs are enabled, warn that we ignored this trigraph and
2105 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002106 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002107 if (!L->isLexingRawMode())
2108 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 return false;
2110 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002111 if (!L->isLexingRawMode())
2112 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002116 if (!L->isLexingRawMode())
2117 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002120 if (HasSpace && !L->isLexingRawMode())
2121 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 return true;
2124}
2125
2126#ifdef __SSE2__
2127#include <emmintrin.h>
2128#elif __ALTIVEC__
2129#include <altivec.h>
2130#undef bool
2131#endif
2132
James Dennettec769932012-06-17 03:40:43 +00002133/// We have just read from input the / and * characters that started a comment.
2134/// Read until we find the * and / characters that terminate the comment.
2135/// Note that we don't bother decoding trigraphs or escaped newlines in block
2136/// comments, because they cannot cause the comment to end. The only thing
2137/// that can happen is the comment could end with an escaped newline between
2138/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002139///
Chris Lattner046c2272010-01-18 22:35:47 +00002140/// If we're in KeepCommentMode or any CommentHandler has inserted
2141/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002142bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002144 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 // optimization helps people who like to put a lot of * characters in their
2146 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002147
2148 // The first character we get with newlines and trigraphs skipped to handle
2149 // the degenerate /*/ case below correctly if the * has an escaped newline
2150 // after it.
2151 unsigned CharSize;
2152 unsigned char C = getCharAndSize(CurPtr, CharSize);
2153 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002155 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002156 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002157 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Chris Lattner31f0eca2008-10-12 04:19:49 +00002159 // KeepWhitespaceMode should return this broken comment as a token. Since
2160 // it isn't a well formed comment, just return it as an 'unknown' token.
2161 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002162 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002163 return true;
2164 }
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Chris Lattner31f0eca2008-10-12 04:19:49 +00002166 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002167 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Chris Lattner8146b682007-07-21 23:43:37 +00002170 // Check to see if the first character after the '/*' is another /. If so,
2171 // then this slash does not end the block comment, it is part of it.
2172 if (C == '/')
2173 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 while (1) {
2176 // Skip over all non-interesting characters until we find end of buffer or a
2177 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002178 if (CurPtr + 24 < BufferEnd &&
2179 // If there is a code-completion point avoid the fast scan because it
2180 // doesn't check for '\0'.
2181 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 // While not aligned to a 16-byte boundary.
2183 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2184 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 if (C == '/') goto FoundSlash;
2187
2188#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002189 __m128i Slashes = _mm_set1_epi8('/');
2190 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002191 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2192 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002193 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002194 // Adjust the pointer to point directly after the first slash. It's
2195 // not necessary to set C here, it will be overwritten at the end of
2196 // the outer loop.
2197 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002198 goto FoundSlash;
2199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002201 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002202#elif __ALTIVEC__
2203 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002204 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 '/', '/', '/', '/', '/', '/', '/', '/'
2206 };
2207 while (CurPtr+16 <= BufferEnd &&
2208 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2209 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002210#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 // Scan for '/' quickly. Many block comments are very large.
2212 while (CurPtr[0] != '/' &&
2213 CurPtr[1] != '/' &&
2214 CurPtr[2] != '/' &&
2215 CurPtr[3] != '/' &&
2216 CurPtr+4 < BufferEnd) {
2217 CurPtr += 4;
2218 }
2219#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 // It has to be one of the bytes scanned, increment to it and read one.
2222 C = *CurPtr++;
2223 }
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // Loop to scan the remainder.
2226 while (C != '/' && C != '\0')
2227 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002230 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002231 if (CurPtr[-2] == '*') // We found the final */. We're done!
2232 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2235 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2236 // We found the final */, though it had an escaped newline between the
2237 // * and /. We're done!
2238 break;
2239 }
2240 }
2241 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2242 // If this is a /* inside of the comment, emit a warning. Don't do this
2243 // if this is a /*/, which will end the comment. This misses cases with
2244 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002245 if (!isLexingRawMode())
2246 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 }
2248 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002249 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002250 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 // Note: the user probably forgot a */. We could continue immediately
2252 // after the /*, but this would involve lexing a lot of what really is the
2253 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002254 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Chris Lattner31f0eca2008-10-12 04:19:49 +00002256 // KeepWhitespaceMode should return this broken comment as a token. Since
2257 // it isn't a well formed comment, just return it as an 'unknown' token.
2258 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002259 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002260 return true;
2261 }
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Chris Lattner31f0eca2008-10-12 04:19:49 +00002263 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002264 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002265 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2266 PP->CodeCompleteNaturalLanguage();
2267 cutOffLexing();
2268 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002270
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 C = *CurPtr++;
2272 }
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Chris Lattner3d0ad582010-02-03 21:06:21 +00002274 // Notify comment handlers about the comment unless we're in a #if 0 block.
2275 if (PP && !isLexingRawMode() &&
2276 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2277 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002278 BufferPtr = CurPtr;
2279 return true; // A token has to be returned.
2280 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002281
Reid Spencer5f016e22007-07-11 17:01:13 +00002282 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002283 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002284 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002285 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 }
2287
2288 // It is common for the tokens immediately after a /**/ comment to be
2289 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002290 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2291 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002293 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002295 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 }
2297
2298 // Otherwise, just return so that the next character will be lexed as a token.
2299 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002300 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002301 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002302}
2303
2304//===----------------------------------------------------------------------===//
2305// Primary Lexing Entry Points
2306//===----------------------------------------------------------------------===//
2307
Reid Spencer5f016e22007-07-11 17:01:13 +00002308/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2309/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002310void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2312 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002313 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002314
2315 // CurPtr - Cache BufferPtr in an automatic variable.
2316 const char *CurPtr = BufferPtr;
2317 while (1) {
2318 char Char = getAndAdvanceChar(CurPtr, Tmp);
2319 switch (Char) {
2320 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002321 if (Result)
2322 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 break;
2324 case 0: // Null.
2325 // Found end of file?
2326 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002327 if (isCodeCompletionPoint(CurPtr-1)) {
2328 PP->CodeCompleteNaturalLanguage();
2329 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002330 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002331 }
2332
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002334 if (Result)
2335 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002336 break;
2337 }
2338 // FALL THROUGH.
2339 case '\r':
2340 case '\n':
2341 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2342 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2343 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Peter Collingbourne84021552011-02-28 02:37:51 +00002345 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002347 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002348 if (PP)
2349 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002350 Lex(Tmp);
2351 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002352 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Benjamin Kramer3093b202012-05-18 19:32:16 +00002354 // Finally, we're done;
2355 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 }
2357 }
2358}
2359
2360/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2361/// condition, reporting diagnostics and handling other edge cases as required.
2362/// This returns true if Result contains a token, false if PP.Lex should be
2363/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002364bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002365 // If we hit the end of the file while parsing a preprocessor directive,
2366 // end the preprocessor directive first. The next token returned will
2367 // then be the end of file.
2368 if (ParsingPreprocessorDirective) {
2369 // Done parsing the "line".
2370 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002371 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002372 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002373
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002375 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002377 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002378
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 // If we are in raw mode, return this event as an EOF token. Let the caller
2380 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002381 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 Result.startToken();
2383 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002384 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 return true;
2386 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002387
Douglas Gregorf44e8542010-08-24 19:08:16 +00002388 // Issue diagnostics for unterminated #if and missing newline.
2389
Reid Spencer5f016e22007-07-11 17:01:13 +00002390 // If we are in a #if directive, emit an error.
2391 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002392 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002393 PP->Diag(ConditionalStack.back().IfLoc,
2394 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 ConditionalStack.pop_back();
2396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002398 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2399 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002400 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2401 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2402 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2403 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Reid Spencer5f016e22007-07-11 17:01:13 +00002405 BufferPtr = CurPtr;
2406
2407 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002408 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002409}
2410
2411/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2412/// the specified lexer will return a tok::l_paren token, 0 if it is something
2413/// else and 2 if there are no more tokens in the buffer controlled by the
2414/// lexer.
2415unsigned Lexer::isNextPPTokenLParen() {
2416 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Reid Spencer5f016e22007-07-11 17:01:13 +00002418 // Switch to 'skipping' mode. This will ensure that we can lex a token
2419 // without emitting diagnostics, disables macro expansion, and will cause EOF
2420 // to return an EOF token instead of popping the include stack.
2421 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 // Save state that can be changed while lexing so that we can restore it.
2424 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002425 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Chris Lattnerd2177732007-07-20 16:59:19 +00002427 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 Tok.startToken();
2429 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 // Restore state that may have changed.
2432 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002433 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 // Restore the lexer back to non-skipping mode.
2436 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002437
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002438 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002439 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002440 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002441}
2442
James Dennettec769932012-06-17 03:40:43 +00002443/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002444static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2445 ConflictMarkerKind CMK) {
2446 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2447 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2448 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2449 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002450 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002451 // Must occur at start of line.
2452 if (RestOfBuffer[Pos-1] != '\r' &&
2453 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002454 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2455 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002456 continue;
2457 }
2458 return RestOfBuffer.data()+Pos;
2459 }
2460 return 0;
2461}
2462
2463/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2464/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2465/// and recover nicely. This returns true if it is a conflict marker and false
2466/// if not.
2467bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2468 // Only a conflict marker if it starts at the beginning of a line.
2469 if (CurPtr != BufferStart &&
2470 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2471 return false;
2472
Richard Smithd5e1d602011-10-12 00:37:51 +00002473 // Check to see if we have <<<<<<< or >>>>.
2474 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2475 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002476 return false;
2477
2478 // If we have a situation where we don't care about conflict markers, ignore
2479 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002480 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002481 return false;
2482
Richard Smithd5e1d602011-10-12 00:37:51 +00002483 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2484
2485 // Check to see if there is an ending marker somewhere in the buffer at the
2486 // start of a line to terminate this conflict marker.
2487 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002488 // We found a match. We are really in a conflict marker.
2489 // Diagnose this, and ignore to the end of line.
2490 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002491 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002492
2493 // Skip ahead to the end of line. We know this exists because the
2494 // end-of-conflict marker starts with \r or \n.
2495 while (*CurPtr != '\r' && *CurPtr != '\n') {
2496 assert(CurPtr != BufferEnd && "Didn't find end of line");
2497 ++CurPtr;
2498 }
2499 BufferPtr = CurPtr;
2500 return true;
2501 }
2502
2503 // No end of conflict marker found.
2504 return false;
2505}
2506
2507
Richard Smithd5e1d602011-10-12 00:37:51 +00002508/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2509/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2510/// is the end of a conflict marker. Handle it by ignoring up until the end of
2511/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002512bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2513 // Only a conflict marker if it starts at the beginning of a line.
2514 if (CurPtr != BufferStart &&
2515 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2516 return false;
2517
2518 // If we have a situation where we don't care about conflict markers, ignore
2519 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002520 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002521 return false;
2522
Richard Smithd5e1d602011-10-12 00:37:51 +00002523 // Check to see if we have the marker (4 characters in a row).
2524 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002525 if (CurPtr[i] != CurPtr[0])
2526 return false;
2527
2528 // If we do have it, search for the end of the conflict marker. This could
2529 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2530 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002531 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2532 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002533 CurPtr = End;
2534
2535 // Skip ahead to the end of line.
2536 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2537 ++CurPtr;
2538
2539 BufferPtr = CurPtr;
2540
2541 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002542 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002543 return true;
2544 }
2545
2546 return false;
2547}
2548
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002549bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2550 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002551 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002552 return Loc == PP->getCodeCompletionLoc();
2553 }
2554
2555 return false;
2556}
2557
Reid Spencer5f016e22007-07-11 17:01:13 +00002558
2559/// LexTokenInternal - This implements a simple C family lexer. It is an
2560/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002561/// has a null character at the end of the file. This returns a preprocessing
2562/// token, not a normal token, as such, it is an internal interface. It assumes
2563/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002564void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002565LexNextToken:
2566 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002567 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 // CurPtr - Cache BufferPtr in an automatic variable.
2571 const char *CurPtr = BufferPtr;
2572
2573 // Small amounts of horizontal whitespace is very common between tokens.
2574 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2575 ++CurPtr;
2576 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2577 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Chris Lattnerd88dc482008-10-12 04:05:48 +00002579 // If we are keeping whitespace and other tokens, just return what we just
2580 // skipped. The next lexer invocation will return the token after the
2581 // whitespace.
2582 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002583 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002584 return;
2585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002588 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 }
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 // Read a character, advancing over it.
2594 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002595 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 switch (Char) {
2598 case 0: // Null.
2599 // Found end of file?
2600 if (CurPtr-1 == BufferEnd) {
2601 // Read the PP instance variable into an automatic variable, because
2602 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002603 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2605 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002606 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2607 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 }
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002610 // Check if we are performing code completion.
2611 if (isCodeCompletionPoint(CurPtr-1)) {
2612 // Return the code-completion token.
2613 Result.startToken();
2614 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2615 return;
2616 }
2617
Chris Lattner74d15df2008-11-22 02:02:22 +00002618 if (!isLexingRawMode())
2619 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002620 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002621 if (SkipWhitespace(Result, CurPtr))
2622 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002623
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002625
2626 case 26: // DOS & CP/M EOF: "^Z".
2627 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002628 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002629 // Read the PP instance variable into an automatic variable, because
2630 // LexEndOfFile will often delete 'this'.
2631 Preprocessor *PPCache = PP;
2632 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2633 return; // Got a token to return.
2634 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2635 return PPCache->Lex(Result);
2636 }
2637 // If Microsoft extensions are disabled, this is just random garbage.
2638 Kind = tok::unknown;
2639 break;
2640
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 case '\n':
2642 case '\r':
2643 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002644 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 if (ParsingPreprocessorDirective) {
2646 // Done parsing the "line".
2647 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002650 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002651 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 // Since we consumed a newline, we are back at the start of a line.
2654 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Peter Collingbourne84021552011-02-28 02:37:51 +00002656 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 break;
2658 }
2659 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002660 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002662 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Chris Lattnerd88dc482008-10-12 04:05:48 +00002664 if (SkipWhitespace(Result, CurPtr))
2665 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 goto LexNextToken; // GCC isn't tail call eliminating.
2667 case ' ':
2668 case '\t':
2669 case '\f':
2670 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002671 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002672 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002673 if (SkipWhitespace(Result, CurPtr))
2674 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002675
2676 SkipIgnoredUnits:
2677 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Chris Lattner8133cfc2007-07-22 06:29:05 +00002679 // If the next token is obviously a // or /* */ comment, skip it efficiently
2680 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002681 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002682 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2683 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002684 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002685 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002686 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002687 if (SkipBlockComment(Result, CurPtr+2))
2688 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002689 goto SkipIgnoredUnits;
2690 } else if (isHorizontalWhitespace(*CurPtr)) {
2691 goto SkipHorizontalWhitespace;
2692 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002694
Chris Lattner3a570772008-01-03 17:58:54 +00002695 // C99 6.4.4.1: Integer Constants.
2696 // C99 6.4.4.2: Floating Constants.
2697 case '0': case '1': case '2': case '3': case '4':
2698 case '5': case '6': case '7': case '8': case '9':
2699 // Notify MIOpt that we read a non-whitespace/non-comment token.
2700 MIOpt.ReadToken();
2701 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Douglas Gregor5cee1192011-07-27 05:40:30 +00002703 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2704 // Notify MIOpt that we read a non-whitespace/non-comment token.
2705 MIOpt.ReadToken();
2706
David Blaikie4e4d0842012-03-11 07:00:24 +00002707 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002708 Char = getCharAndSize(CurPtr, SizeTmp);
2709
2710 // UTF-16 string literal
2711 if (Char == '"')
2712 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2713 tok::utf16_string_literal);
2714
2715 // UTF-16 character constant
2716 if (Char == '\'')
2717 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2718 tok::utf16_char_constant);
2719
Craig Topper2fa4e862011-08-11 04:06:15 +00002720 // UTF-16 raw string literal
2721 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2722 return LexRawStringLiteral(Result,
2723 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2724 SizeTmp2, Result),
2725 tok::utf16_string_literal);
2726
2727 if (Char == '8') {
2728 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2729
2730 // UTF-8 string literal
2731 if (Char2 == '"')
2732 return LexStringLiteral(Result,
2733 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2734 SizeTmp2, Result),
2735 tok::utf8_string_literal);
2736
2737 if (Char2 == 'R') {
2738 unsigned SizeTmp3;
2739 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2740 // UTF-8 raw string literal
2741 if (Char3 == '"') {
2742 return LexRawStringLiteral(Result,
2743 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2744 SizeTmp2, Result),
2745 SizeTmp3, Result),
2746 tok::utf8_string_literal);
2747 }
2748 }
2749 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002750 }
2751
2752 // treat u like the start of an identifier.
2753 return LexIdentifier(Result, CurPtr);
2754
2755 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2756 // Notify MIOpt that we read a non-whitespace/non-comment token.
2757 MIOpt.ReadToken();
2758
David Blaikie4e4d0842012-03-11 07:00:24 +00002759 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002760 Char = getCharAndSize(CurPtr, SizeTmp);
2761
2762 // UTF-32 string literal
2763 if (Char == '"')
2764 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2765 tok::utf32_string_literal);
2766
2767 // UTF-32 character constant
2768 if (Char == '\'')
2769 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2770 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002771
2772 // UTF-32 raw string literal
2773 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2774 return LexRawStringLiteral(Result,
2775 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2776 SizeTmp2, Result),
2777 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002778 }
2779
2780 // treat U like the start of an identifier.
2781 return LexIdentifier(Result, CurPtr);
2782
Craig Topper2fa4e862011-08-11 04:06:15 +00002783 case 'R': // Identifier or C++0x raw string literal
2784 // Notify MIOpt that we read a non-whitespace/non-comment token.
2785 MIOpt.ReadToken();
2786
David Blaikie4e4d0842012-03-11 07:00:24 +00002787 if (LangOpts.CPlusPlus0x) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002788 Char = getCharAndSize(CurPtr, SizeTmp);
2789
2790 if (Char == '"')
2791 return LexRawStringLiteral(Result,
2792 ConsumeChar(CurPtr, SizeTmp, Result),
2793 tok::string_literal);
2794 }
2795
2796 // treat R like the start of an identifier.
2797 return LexIdentifier(Result, CurPtr);
2798
Chris Lattner3a570772008-01-03 17:58:54 +00002799 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 // Notify MIOpt that we read a non-whitespace/non-comment token.
2801 MIOpt.ReadToken();
2802 Char = getCharAndSize(CurPtr, SizeTmp);
2803
2804 // Wide string literal.
2805 if (Char == '"')
2806 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002807 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002808
Craig Topper2fa4e862011-08-11 04:06:15 +00002809 // Wide raw string literal.
David Blaikie4e4d0842012-03-11 07:00:24 +00002810 if (LangOpts.CPlusPlus0x && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002811 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2812 return LexRawStringLiteral(Result,
2813 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2814 SizeTmp2, Result),
2815 tok::wide_string_literal);
2816
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 // Wide character constant.
2818 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002819 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2820 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Reid Spencer5f016e22007-07-11 17:01:13 +00002823 // C99 6.4.2: Identifiers.
2824 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2825 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002826 case 'O': case 'P': case 'Q': /*'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 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2829 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002830 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 case 'v': case 'w': case 'x': case 'y': case 'z':
2832 case '_':
2833 // Notify MIOpt that we read a non-whitespace/non-comment token.
2834 MIOpt.ReadToken();
2835 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002836
2837 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002838 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002839 if (!isLexingRawMode())
2840 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002841 // Notify MIOpt that we read a non-whitespace/non-comment token.
2842 MIOpt.ReadToken();
2843 return LexIdentifier(Result, CurPtr);
2844 }
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Chris Lattner9e6293d2008-10-12 04:51:35 +00002846 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002847 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 // C99 6.4.4: Character Constants.
2850 case '\'':
2851 // Notify MIOpt that we read a non-whitespace/non-comment token.
2852 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002853 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002854
2855 // C99 6.4.5: String Literals.
2856 case '"':
2857 // Notify MIOpt that we read a non-whitespace/non-comment token.
2858 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002859 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860
2861 // C99 6.4.6: Punctuators.
2862 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002863 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 break;
2865 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002866 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 break;
2868 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002869 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 break;
2871 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002872 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 break;
2874 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002875 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 break;
2877 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002878 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002879 break;
2880 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002881 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 break;
2883 case '.':
2884 Char = getCharAndSize(CurPtr, SizeTmp);
2885 if (Char >= '0' && Char <= '9') {
2886 // Notify MIOpt that we read a non-whitespace/non-comment token.
2887 MIOpt.ReadToken();
2888
2889 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00002890 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002891 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 CurPtr += SizeTmp;
2893 } else if (Char == '.' &&
2894 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002895 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2897 SizeTmp2, Result);
2898 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002899 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 }
2901 break;
2902 case '&':
2903 Char = getCharAndSize(CurPtr, SizeTmp);
2904 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002905 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002906 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2907 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002908 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2910 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002911 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 }
2913 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002914 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002916 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002917 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2918 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002919 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 }
2921 break;
2922 case '+':
2923 Char = getCharAndSize(CurPtr, SizeTmp);
2924 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002926 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002929 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002930 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002931 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002932 }
2933 break;
2934 case '-':
2935 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002936 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002938 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00002939 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002940 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002941 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2942 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002943 Kind = tok::arrowstar;
2944 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002946 Kind = tok::arrow;
2947 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002949 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002951 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 }
2953 break;
2954 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002955 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 break;
2957 case '!':
2958 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002959 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2961 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002962 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002963 }
2964 break;
2965 case '/':
2966 // 6.4.9: Comments
2967 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00002968 if (Char == '/') { // Line comment.
2969 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00002970 // want to lex this as a comment. There is one problem with this though,
2971 // that in one particular corner case, this can change the behavior of the
2972 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00002973 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00002974 // "foo". Check to see if the character after the second slash is a '*'.
2975 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002976 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00002977 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002978 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002979 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00002980 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002981 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002982
Chris Lattner8402c732009-01-16 22:39:25 +00002983 // It is common for the tokens immediately after a // comment to be
2984 // whitespace (indentation for the next line). Instead of going through
2985 // the big switch, handle it efficiently now.
2986 goto SkipIgnoredUnits;
2987 }
2988 }
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Chris Lattner8402c732009-01-16 22:39:25 +00002990 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002992 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002993 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Chris Lattner8402c732009-01-16 22:39:25 +00002996 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002998 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003000 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 }
3002 break;
3003 case '%':
3004 Char = getCharAndSize(CurPtr, SizeTmp);
3005 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003006 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003008 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003009 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003011 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3013 Char = getCharAndSize(CurPtr, SizeTmp);
3014 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003015 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3017 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003018 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003020 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003021 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003022 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003023 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 // We parsed a # character. If this occurs at the start of the line,
3025 // it's actually the start of a preprocessing directive. Callback to
3026 // the preprocessor to handle it.
3027 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003028 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3029 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Chris Lattnere91e9322009-03-18 20:58:27 +00003031 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 }
3033 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003034 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 }
3036 break;
3037 case '<':
3038 Char = getCharAndSize(CurPtr, SizeTmp);
3039 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003040 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003042 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3043 if (After == '=') {
3044 Kind = tok::lesslessequal;
3045 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3046 SizeTmp2, Result);
3047 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3048 // If this is actually a '<<<<<<<' version control conflict marker,
3049 // recognize it as such and recover nicely.
3050 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003051 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3052 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3053 // ignore it.
3054 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003055 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003056 Kind = tok::lesslessless;
3057 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3058 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003059 } else {
3060 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3061 Kind = tok::lessless;
3062 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003064 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003065 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003066 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3067 if (LangOpts.CPlusPlus0x &&
Richard Smith87a1e192011-04-14 18:36:27 +00003068 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3069 // C++0x [lex.pptoken]p3:
3070 // Otherwise, if the next three characters are <:: and the subsequent
3071 // character is neither : nor >, the < is treated as a preprocessor
3072 // token by itself and not as the first character of the alternative
3073 // token <:.
3074 unsigned SizeTmp3;
3075 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3076 if (After != ':' && After != '>') {
3077 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003078 if (!isLexingRawMode())
3079 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003080 break;
3081 }
3082 }
3083
Reid Spencer5f016e22007-07-11 17:01:13 +00003084 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003085 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003086 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003087 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003088 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003090 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003091 }
3092 break;
3093 case '>':
3094 Char = getCharAndSize(CurPtr, SizeTmp);
3095 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003097 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003099 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3100 if (After == '=') {
3101 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3102 SizeTmp2, Result);
3103 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003104 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3105 // If this is actually a '>>>>' conflict marker, recognize it as such
3106 // and recover nicely.
3107 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003108 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3109 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3110 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003111 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003112 Kind = tok::greatergreatergreater;
3113 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3114 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003115 } else {
3116 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3117 Kind = tok::greatergreater;
3118 }
3119
Reid Spencer5f016e22007-07-11 17:01:13 +00003120 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003121 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003122 }
3123 break;
3124 case '^':
3125 Char = getCharAndSize(CurPtr, SizeTmp);
3126 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003127 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003128 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003129 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003130 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003131 }
3132 break;
3133 case '|':
3134 Char = getCharAndSize(CurPtr, SizeTmp);
3135 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003136 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003137 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3138 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003139 // If this is '|||||||' and we're in a conflict marker, ignore it.
3140 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3141 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003142 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3144 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003145 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003146 }
3147 break;
3148 case ':':
3149 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003150 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003151 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003152 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003153 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003154 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003155 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003156 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003157 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 }
3159 break;
3160 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003161 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003162 break;
3163 case '=':
3164 Char = getCharAndSize(CurPtr, SizeTmp);
3165 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003166 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003167 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3168 goto LexNextToken;
3169
Chris Lattner9e6293d2008-10-12 04:51:35 +00003170 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003171 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003172 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003173 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003174 }
3175 break;
3176 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003177 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003178 break;
3179 case '#':
3180 Char = getCharAndSize(CurPtr, SizeTmp);
3181 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003182 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003183 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003184 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003185 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003186 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003187 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3189 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003190 // We parsed a # character. If this occurs at the start of the line,
3191 // it's actually the start of a preprocessing directive. Callback to
3192 // the preprocessor to handle it.
3193 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003194 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3195 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003196
Chris Lattnere91e9322009-03-18 20:58:27 +00003197 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 }
3199 break;
3200
Chris Lattner3a570772008-01-03 17:58:54 +00003201 case '@':
3202 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003203 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003204 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003205 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003206 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003207 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Reid Spencer5f016e22007-07-11 17:01:13 +00003209 case '\\':
3210 // FIXME: UCN's.
3211 // FALL THROUGH.
3212 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003213 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003214 break;
3215 }
Mike Stump1eb44332009-09-09 15:08:12 +00003216
Reid Spencer5f016e22007-07-11 17:01:13 +00003217 // Notify MIOpt that we read a non-whitespace/non-comment token.
3218 MIOpt.ReadToken();
3219
3220 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003221 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003222 return;
3223
3224HandleDirective:
3225 // We parsed a # character and it's the start of a preprocessing directive.
3226
3227 FormTokenWithChars(Result, CurPtr, tok::hash);
3228 PP->HandleDirective(Result);
3229
3230 // As an optimization, if the preprocessor didn't switch lexers, tail
3231 // recurse.
3232 if (PP->isCurrentLexer(this)) {
3233 // Start a new token. If this is a #include or something, the PP may
3234 // want us starting at the beginning of the line again. If so, set
3235 // the StartOfLine flag and clear LeadingSpace.
3236 if (IsAtStartOfLine) {
3237 Result.setFlag(Token::StartOfLine);
3238 Result.clearFlag(Token::LeadingSpace);
3239 IsAtStartOfLine = false;
3240 }
3241 goto LexNextToken; // GCC isn't tail call eliminating.
3242 }
3243 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003244}