blob: 6cd18469e4cccc7101eb971c0fed713e830d201a [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
Richard Smith30cddae2012-11-28 07:29:00 +0000236/// \brief Slow case of getSpelling. Extract the characters comprising the
237/// spelling of this token from the provided input buffer.
238static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
241
242 size_t Length = 0;
243 const char *BufEnd = BufPtr + Tok.getLength();
244
245 if (Tok.is(tok::string_literal)) {
246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
248 unsigned Size;
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
250 BufPtr += Size;
251
252 if (Spelling[Length - 1] == '"')
253 break;
254 }
255
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
258 // r-char-sequence.
259 if (Length >= 2 &&
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
262 // quote.
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
266
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
269 Length += RawLength;
270 BufPtr += RawLength;
271
272 // The rest of the token is lexed normally.
273 }
274 }
275
276 while (BufPtr < BufEnd) {
277 unsigned Size;
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
279 BufPtr += Size;
280 }
281
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
284 return Length;
285}
286
Chris Lattnerb0607272010-11-17 07:26:20 +0000287/// getSpelling() - Return the 'spelling' of this token. The spelling of a
288/// token are the characters used to represent the token in the source file
289/// after trigraph expansion and escaped-newline folding. In particular, this
290/// wants to get the true, uncanonicalized, spelling of things like digraphs
291/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith30cddae2012-11-28 07:29:00 +0000293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
296 bool *invalid) {
John McCall834e3f62011-03-08 07:59:04 +0000297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000303 if (invalidTemp) {
304 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000305 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000306 }
307
308 const char *tokenBegin = file.data() + locInfo.second;
309
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
313 Token token;
314 lexer.LexFromRawLexer(token);
315
316 unsigned length = token.getLength();
317
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000320 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000321
Richard Smith30cddae2012-11-28 07:29:00 +0000322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner5f9e2722011-07-23 10:55:15 +0000325 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000326}
327
328/// getSpelling() - Return the 'spelling' of this token. The spelling of a
329/// token are the characters used to represent the token in the source file
330/// after trigraph expansion and escaped-newline folding. In particular, this
331/// wants to get the true, uncanonicalized, spelling of things like digraphs
332/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000333std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith30cddae2012-11-28 07:29:00 +0000336
Chris Lattnerb0607272010-11-17 07:26:20 +0000337 bool CharDataInvalid = false;
Richard Smith30cddae2012-11-28 07:29:00 +0000338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 &CharDataInvalid);
340 if (Invalid)
341 *Invalid = CharDataInvalid;
342 if (CharDataInvalid)
343 return std::string();
Richard Smith30cddae2012-11-28 07:29:00 +0000344
345 // If this token contains nothing interesting, return it directly.
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (!Tok.needsCleaning())
Richard Smith30cddae2012-11-28 07:29:00 +0000347 return std::string(TokStart, TokStart + Tok.getLength());
348
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 std::string Result;
Richard Smith30cddae2012-11-28 07:29:00 +0000350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattnerb0607272010-11-17 07:26:20 +0000352 return Result;
353}
354
355/// getSpelling - This method is used to get the spelling of a token into a
356/// preallocated buffer, instead of as an std::string. The caller is required
357/// to allocate enough space for the token, which is guaranteed to be at least
358/// Tok.getLength() bytes long. The actual length of the token is returned.
359///
360/// Note that this method may do two possible things: it may either fill in
361/// the buffer specified with characters, or it may *change the input pointer*
362/// to point to a constant buffer with the data already in it (avoiding a
363/// copy). The caller is not allowed to modify the returned buffer pointer
364/// if an internal buffer is returned.
365unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000367 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000369
370 const char *TokStart = 0;
371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
373 TokStart = Tok.getRawIdentifierData();
374 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
375 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000376 Buffer = II->getNameStart();
377 return II->getLength();
378 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000379
380 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000381 if (Tok.isLiteral())
382 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000383
Chris Lattnerb0607272010-11-17 07:26:20 +0000384 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000385 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000386 bool CharDataInvalid = false;
387 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
388 if (Invalid)
389 *Invalid = CharDataInvalid;
390 if (CharDataInvalid) {
391 Buffer = "";
392 return 0;
393 }
394 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000395
Chris Lattnerb0607272010-11-17 07:26:20 +0000396 // If this token contains nothing interesting, return it directly.
397 if (!Tok.needsCleaning()) {
398 Buffer = TokStart;
399 return Tok.getLength();
400 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000401
Chris Lattnerb0607272010-11-17 07:26:20 +0000402 // Otherwise, hard case, relex the characters into the string.
Richard Smith30cddae2012-11-28 07:29:00 +0000403 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattnerb0607272010-11-17 07:26:20 +0000404}
405
406
407
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000408static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000409
Chris Lattner9a611942007-10-17 21:18:47 +0000410/// MeasureTokenLength - Relex the token at the specified location and return
411/// its length in bytes in the input file. If the token needs cleaning (e.g.
412/// includes a trigraph or an escaped newline) then this count includes bytes
413/// that are part of that.
414unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000415 const SourceManager &SM,
416 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000417 // TODO: this could be special cased for common tokens like identifiers, ')',
418 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000419 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000420 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
421 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000422
423 // If this comes from a macro expansion, we really do want the macro name, not
424 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000425 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000426 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000427 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000428 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000429 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000430 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000431
432 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000433
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000434 if (isWhitespace(StrData[0]))
435 return 0;
436
Chris Lattner9a611942007-10-17 21:18:47 +0000437 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000438 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
439 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000440 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000441 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000442 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000443 return TheTok.getLength();
444}
445
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000446static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
447 const SourceManager &SM,
448 const LangOptions &LangOpts) {
449 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000450 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000451 if (LocInfo.first.isInvalid())
452 return Loc;
453
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000454 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000455 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000456 if (Invalid)
457 return Loc;
458
459 // Back up from the current location until we hit the beginning of a line
460 // (or the buffer). We'll relex from that point.
461 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000462 if (LocInfo.second >= Buffer.size())
463 return Loc;
464
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000465 const char *StrData = BufStart+LocInfo.second;
466 if (StrData[0] == '\n' || StrData[0] == '\r')
467 return Loc;
468
469 const char *LexStart = StrData;
470 while (LexStart != BufStart) {
471 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
472 ++LexStart;
473 break;
474 }
475
476 --LexStart;
477 }
478
479 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000480 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000481 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
482 TheLexer.SetCommentRetentionState(true);
483
484 // Lex tokens until we find the token that contains the source location.
485 Token TheTok;
486 do {
487 TheLexer.LexFromRawLexer(TheTok);
488
489 if (TheLexer.getBufferLocation() > StrData) {
490 // Lexing this token has taken the lexer past the source location we're
491 // looking for. If the current token encompasses our source location,
492 // return the beginning of that token.
493 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
494 return TheTok.getLocation();
495
496 // We ended up skipping over the source location entirely, which means
497 // that it points into whitespace. We're done here.
498 break;
499 }
500 } while (TheTok.getKind() != tok::eof);
501
502 // We've passed our source location; just return the original source location.
503 return Loc;
504}
505
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000506SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
507 const SourceManager &SM,
508 const LangOptions &LangOpts) {
509 if (Loc.isFileID())
510 return getBeginningOfFileToken(Loc, SM, LangOpts);
511
512 if (!SM.isMacroArgExpansion(Loc))
513 return Loc;
514
515 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
516 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
517 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000518 std::pair<FileID, unsigned> BeginFileLocInfo
519 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000520 assert(FileLocInfo.first == BeginFileLocInfo.first &&
521 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000522 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000523}
524
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000525namespace {
526 enum PreambleDirectiveKind {
527 PDK_Skipped,
528 PDK_StartIf,
529 PDK_EndIf,
530 PDK_Unknown
531 };
532}
533
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000534std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000535Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000536 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000537 // Create a lexer starting at the beginning of the file. Note that we use a
538 // "fake" file source location at offset 1 so that the lexer will track our
539 // position within the file.
540 const unsigned StartOffset = 1;
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000541 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
542 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000543 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000544
545 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
546 SourceLocation StartLoc = TheLexer.getSourceLocation();
547
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000548 bool InPreprocessorDirective = false;
549 Token TheTok;
550 Token IfStartTok;
551 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000552
553 unsigned MaxLineOffset = 0;
554 if (MaxLines) {
555 const char *CurPtr = Buffer->getBufferStart();
556 unsigned CurLine = 0;
557 while (CurPtr != Buffer->getBufferEnd()) {
558 char ch = *CurPtr++;
559 if (ch == '\n') {
560 ++CurLine;
561 if (CurLine == MaxLines)
562 break;
563 }
564 }
565 if (CurPtr != Buffer->getBufferEnd())
566 MaxLineOffset = CurPtr - Buffer->getBufferStart();
567 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000568
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000569 do {
570 TheLexer.LexFromRawLexer(TheTok);
571
572 if (InPreprocessorDirective) {
573 // If we've hit the end of the file, we're done.
574 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000575 break;
576 }
577
578 // If we haven't hit the end of the preprocessor directive, skip this
579 // token.
580 if (!TheTok.isAtStartOfLine())
581 continue;
582
583 // We've passed the end of the preprocessor directive, and will look
584 // at this token again below.
585 InPreprocessorDirective = false;
586 }
587
Douglas Gregordf95a132010-08-09 20:45:32 +0000588 // Keep track of the # of lines in the preamble.
589 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000590 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000591
592 // If we were asked to limit the number of lines in the preamble,
593 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000594 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000595 break;
596 }
597
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000598 // Comments are okay; skip over them.
599 if (TheTok.getKind() == tok::comment)
600 continue;
601
602 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
603 // This is the start of a preprocessor directive.
604 Token HashTok = TheTok;
605 InPreprocessorDirective = true;
606
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000607 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000608 // we don't have an identifier table available. Instead, just look at
609 // the raw identifier to recognize and categorize preprocessor directives.
610 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000611 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000612 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000613 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000614 PreambleDirectiveKind PDK
615 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
616 .Case("include", PDK_Skipped)
617 .Case("__include_macros", PDK_Skipped)
618 .Case("define", PDK_Skipped)
619 .Case("undef", PDK_Skipped)
620 .Case("line", PDK_Skipped)
621 .Case("error", PDK_Skipped)
622 .Case("pragma", PDK_Skipped)
623 .Case("import", PDK_Skipped)
624 .Case("include_next", PDK_Skipped)
625 .Case("warning", PDK_Skipped)
626 .Case("ident", PDK_Skipped)
627 .Case("sccs", PDK_Skipped)
628 .Case("assert", PDK_Skipped)
629 .Case("unassert", PDK_Skipped)
630 .Case("if", PDK_StartIf)
631 .Case("ifdef", PDK_StartIf)
632 .Case("ifndef", PDK_StartIf)
633 .Case("elif", PDK_Skipped)
634 .Case("else", PDK_Skipped)
635 .Case("endif", PDK_EndIf)
636 .Default(PDK_Unknown);
637
638 switch (PDK) {
639 case PDK_Skipped:
640 continue;
641
642 case PDK_StartIf:
643 if (IfCount == 0)
644 IfStartTok = HashTok;
645
646 ++IfCount;
647 continue;
648
649 case PDK_EndIf:
650 // Mismatched #endif. The preamble ends here.
651 if (IfCount == 0)
652 break;
653
654 --IfCount;
655 continue;
656
657 case PDK_Unknown:
658 // We don't know what this directive is; stop at the '#'.
659 break;
660 }
661 }
662
663 // We only end up here if we didn't recognize the preprocessor
664 // directive or it was one that can't occur in the preamble at this
665 // point. Roll back the current token to the location of the '#'.
666 InPreprocessorDirective = false;
667 TheTok = HashTok;
668 }
669
Douglas Gregordf95a132010-08-09 20:45:32 +0000670 // We hit a token that we don't recognize as being in the
671 // "preprocessing only" part of the file, so we're no longer in
672 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000673 break;
674 } while (true);
675
676 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000677 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
678 IfCount? IfStartTok.isAtStartOfLine()
679 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000680}
681
Chris Lattner7ef5c272010-11-17 07:05:50 +0000682
683/// AdvanceToTokenCharacter - Given a location that specifies the start of a
684/// token, return a new location that specifies a character within the token.
685SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
686 unsigned CharNo,
687 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000688 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000689 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000690 // character is. This needs to take into consideration newlines and
691 // trigraphs.
692 bool Invalid = false;
693 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
694
695 // If they request the first char of the token, we're trivially done.
696 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
697 return TokStart;
698
699 unsigned PhysOffset = 0;
700
701 // The usual case is that tokens don't contain anything interesting. Skip
702 // over the uninteresting characters. If a token only consists of simple
703 // chars, this method is extremely fast.
704 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
705 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000706 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000707 ++TokPtr, --CharNo, ++PhysOffset;
708 }
709
710 // If we have a character that may be a trigraph or escaped newline, use a
711 // lexer to parse it correctly.
712 for (; CharNo; --CharNo) {
713 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000714 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000715 TokPtr += Size;
716 PhysOffset += Size;
717 }
718
719 // Final detail: if we end up on an escaped newline, we want to return the
720 // location of the actual byte of the token. For example foo\<newline>bar
721 // advanced by 3 should return the location of b, not of \\. One compounding
722 // detail of this is that the escape may be made by a trigraph.
723 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
724 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
725
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000726 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000727}
728
729/// \brief Computes the source location just past the end of the
730/// token at this source location.
731///
732/// This routine can be used to produce a source location that
733/// points just past the end of the token referenced by \p Loc, and
734/// is generally used when a diagnostic needs to point just after a
735/// token where it expected something different that it received. If
736/// the returned source location would not be meaningful (e.g., if
737/// it points into a macro), this routine returns an invalid
738/// source location.
739///
740/// \param Offset an offset from the end of the token, where the source
741/// location should refer to. The default offset (0) produces a source
742/// location pointing just past the end of the token; an offset of 1 produces
743/// a source location pointing to the last character in the token, etc.
744SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
745 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000746 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000747 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000748 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000749
750 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000751 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000752 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000753 }
754
David Blaikie4e4d0842012-03-11 07:00:24 +0000755 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000756 if (Len > Offset)
757 Len = Len - Offset;
758 else
759 return Loc;
760
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000761 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000762}
763
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000764/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000765/// token of the macro expansion.
766bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000767 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000768 const LangOptions &LangOpts,
769 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000770 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
771
772 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
773 // FIXME: If the token comes from the macro token paste operator ('##')
774 // this function will always return false;
775 if (infoLoc.second > 0)
776 return false; // Does not point at the start of token.
777
Chandler Carruth433db062011-07-14 08:20:40 +0000778 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000779 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000780 if (expansionLoc.isFileID()) {
781 // No other macro expansions, this is the first.
782 if (MacroBegin)
783 *MacroBegin = expansionLoc;
784 return true;
785 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000786
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000787 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000788}
789
790/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000791/// token of the macro expansion.
792bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000793 const SourceManager &SM,
794 const LangOptions &LangOpts,
795 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000796 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
797
798 SourceLocation spellLoc = SM.getSpellingLoc(loc);
799 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
800 if (tokLen == 0)
801 return false;
802
803 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000804 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000805 if (SM.isInFileID(afterLoc, FID))
806 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000807
808 // FIXME: If the token comes from the macro token paste operator ('##')
809 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000810
Chandler Carruth433db062011-07-14 08:20:40 +0000811 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000812 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000813 if (expansionLoc.isFileID()) {
814 // No other macro expansions.
815 if (MacroEnd)
816 *MacroEnd = expansionLoc;
817 return true;
818 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000819
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000820 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000821}
822
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000823static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000824 const SourceManager &SM,
825 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000826 SourceLocation Begin = Range.getBegin();
827 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000828 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000829 if (Range.isTokenRange()) {
830 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
831 if (End.isInvalid())
832 return CharSourceRange();
833 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000834
835 // Break down the source locations.
836 FileID FID;
837 unsigned BeginOffs;
838 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
839 if (FID.isInvalid())
840 return CharSourceRange();
841
842 unsigned EndOffs;
843 if (!SM.isInFileID(End, FID, &EndOffs) ||
844 BeginOffs > EndOffs)
845 return CharSourceRange();
846
847 return CharSourceRange::getCharRange(Begin, End);
848}
849
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000850CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000851 const SourceManager &SM,
852 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000853 SourceLocation Begin = Range.getBegin();
854 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000855 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000856 return CharSourceRange();
857
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000858 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000859 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000860
861 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000862 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
863 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000864 Range.setBegin(Begin);
865 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000866 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000867
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000868 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000869 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
870 &End)) ||
871 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
872 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000873 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000874 Range.setEnd(End);
875 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000876 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000877
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000878 assert(Begin.isMacroID() && End.isMacroID());
879 SourceLocation MacroBegin, MacroEnd;
880 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000881 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
882 &MacroEnd)) ||
883 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
884 &MacroEnd)))) {
885 Range.setBegin(MacroBegin);
886 Range.setEnd(MacroEnd);
887 return makeRangeFromFileLocs(Range, SM, LangOpts);
888 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000889
890 FileID FID;
891 unsigned BeginOffs;
892 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
893 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000894 return CharSourceRange();
895
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000896 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000897 if (!SM.isInFileID(End, FID, &EndOffs) ||
898 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000899 return CharSourceRange();
900
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000901 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
902 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
903 if (Expansion.isMacroArgExpansion() &&
904 Expansion.getSpellingLoc().isFileID()) {
905 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000906 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
907 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
908 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000909 }
910
911 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000912}
913
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000914StringRef Lexer::getSourceText(CharSourceRange Range,
915 const SourceManager &SM,
916 const LangOptions &LangOpts,
917 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000918 Range = makeFileCharRange(Range, SM, LangOpts);
919 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000920 if (Invalid) *Invalid = true;
921 return StringRef();
922 }
923
924 // Break down the source location.
925 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
926 if (beginInfo.first.isInvalid()) {
927 if (Invalid) *Invalid = true;
928 return StringRef();
929 }
930
931 unsigned EndOffs;
932 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
933 beginInfo.second > EndOffs) {
934 if (Invalid) *Invalid = true;
935 return StringRef();
936 }
937
938 // Try to the load the file buffer.
939 bool invalidTemp = false;
940 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
941 if (invalidTemp) {
942 if (Invalid) *Invalid = true;
943 return StringRef();
944 }
945
946 if (Invalid) *Invalid = false;
947 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
948}
949
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000950StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
951 const SourceManager &SM,
952 const LangOptions &LangOpts) {
953 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000954
955 // Find the location of the immediate macro expansion.
956 while (1) {
957 FileID FID = SM.getFileID(Loc);
958 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
959 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
960 Loc = Expansion.getExpansionLocStart();
961 if (!Expansion.isMacroArgExpansion())
962 break;
963
964 // For macro arguments we need to check that the argument did not come
965 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
966
967 // Loc points to the argument id of the macro definition, move to the
968 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000969 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000970 SourceLocation SpellLoc = Expansion.getSpellingLoc();
971 if (SpellLoc.isFileID())
972 break; // No inner macro.
973
974 // If spelling location resides in the same FileID as macro expansion
975 // location, it means there is no inner macro.
976 FileID MacroFID = SM.getFileID(Loc);
977 if (SM.isInFileID(SpellLoc, MacroFID))
978 break;
979
980 // Argument came from inner macro.
981 Loc = SpellLoc;
982 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000983
984 // Find the spelling location of the start of the non-argument expansion
985 // range. This is where the macro name was spelled in order to begin
986 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000987 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000988
989 // Dig out the buffer where the macro name was spelled and the extents of the
990 // name so that we can render it into the expansion note.
991 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
992 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
993 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
994 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
995}
996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997//===----------------------------------------------------------------------===//
998// Character information.
999//===----------------------------------------------------------------------===//
1000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001enum {
1002 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
1003 CHAR_VERT_WS = 0x02, // '\r', '\n'
1004 CHAR_LETTER = 0x04, // a-z,A-Z
1005 CHAR_NUMBER = 0x08, // 0-9
1006 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +00001007 CHAR_PERIOD = 0x20, // .
1008 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +00001009};
1010
Chris Lattner03b98662009-07-07 17:09:54 +00001011// Statically initialize CharInfo table based on ASCII character set
1012// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +00001013static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +00001014{
1015// 0 NUL 1 SOH 2 STX 3 ETX
1016// 4 EOT 5 ENQ 6 ACK 7 BEL
1017 0 , 0 , 0 , 0 ,
1018 0 , 0 , 0 , 0 ,
1019// 8 BS 9 HT 10 NL 11 VT
1020//12 NP 13 CR 14 SO 15 SI
1021 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
1022 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
1023//16 DLE 17 DC1 18 DC2 19 DC3
1024//20 DC4 21 NAK 22 SYN 23 ETB
1025 0 , 0 , 0 , 0 ,
1026 0 , 0 , 0 , 0 ,
1027//24 CAN 25 EM 26 SUB 27 ESC
1028//28 FS 29 GS 30 RS 31 US
1029 0 , 0 , 0 , 0 ,
1030 0 , 0 , 0 , 0 ,
1031//32 SP 33 ! 34 " 35 #
1032//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001033 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1034 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001035//40 ( 41 ) 42 * 43 +
1036//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001037 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1038 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001039//48 0 49 1 50 2 51 3
1040//52 4 53 5 54 6 55 7
1041 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1042 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1043//56 8 57 9 58 : 59 ;
1044//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001045 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1046 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001047//64 @ 65 A 66 B 67 C
1048//68 D 69 E 70 F 71 G
1049 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1050 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1051//72 H 73 I 74 J 75 K
1052//76 L 77 M 78 N 79 O
1053 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1054 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1055//80 P 81 Q 82 R 83 S
1056//84 T 85 U 86 V 87 W
1057 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1058 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1059//88 X 89 Y 90 Z 91 [
1060//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001061 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1062 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001063//96 ` 97 a 98 b 99 c
1064//100 d 101 e 102 f 103 g
1065 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1066 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1067//104 h 105 i 106 j 107 k
1068//108 l 109 m 110 n 111 o
1069 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1070 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1071//112 p 113 q 114 r 115 s
1072//116 t 117 u 118 v 119 w
1073 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1074 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1075//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001076//124 | 125 } 126 ~ 127 DEL
1077 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1078 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001079};
1080
Chris Lattnera2bf1052009-12-17 05:29:40 +00001081static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 static bool isInited = false;
1083 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001084 // check the statically-initialized CharInfo table
1085 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1086 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1087 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1088 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1089 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1090 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1091 assert(CHAR_UNDER == CharInfo[(int)'_']);
1092 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1093 for (unsigned i = 'a'; i <= 'z'; ++i) {
1094 assert(CHAR_LETTER == CharInfo[i]);
1095 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1096 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001098 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001099
Chris Lattner03b98662009-07-07 17:09:54 +00001100 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101}
1102
Chris Lattner03b98662009-07-07 17:09:54 +00001103
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001104/// isIdentifierHead - Return true if this is the first character of an
1105/// identifier, which is [a-zA-Z_].
1106static inline bool isIdentifierHead(unsigned char c) {
1107 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1108}
1109
Reid Spencer5f016e22007-07-11 17:01:13 +00001110/// isIdentifierBody - Return true if this is the body character of an
1111/// identifier, which is [a-zA-Z0-9_].
1112static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001113 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114}
1115
1116/// isHorizontalWhitespace - Return true if this character is horizontal
James Dennetta05369f2012-06-15 21:36:54 +00001117/// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1118/// '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001119static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001120 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
1122
Anna Zaksaca25bc2011-07-27 21:43:43 +00001123/// isVerticalWhitespace - Return true if this character is vertical
James Dennetta05369f2012-06-15 21:36:54 +00001124/// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
Anna Zaksaca25bc2011-07-27 21:43:43 +00001125static inline bool isVerticalWhitespace(unsigned char c) {
1126 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1127}
1128
Reid Spencer5f016e22007-07-11 17:01:13 +00001129/// isWhitespace - Return true if this character is horizontal or vertical
James Dennetta05369f2012-06-15 21:36:54 +00001130/// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1131/// false for '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001132static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001133 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134}
1135
1136/// isNumberBody - Return true if this is the body character of an
1137/// preprocessing number, which is [a-zA-Z0-9_.].
1138static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001139 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001140 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141}
1142
Craig Topper2fa4e862011-08-11 04:06:15 +00001143/// isRawStringDelimBody - Return true if this is the body character of a
1144/// raw string delimiter.
1145static inline bool isRawStringDelimBody(unsigned char c) {
1146 return (CharInfo[c] &
1147 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1148 true : false;
1149}
1150
Jordan Rosed880b3a2012-06-07 01:10:31 +00001151// Allow external clients to make use of CharInfo.
1152bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1153 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1154}
1155
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157//===----------------------------------------------------------------------===//
1158// Diagnostics forwarding code.
1159//===----------------------------------------------------------------------===//
1160
Chris Lattner409a0362007-07-22 18:38:25 +00001161/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001162/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001163/// This is currently only used for _Pragma implementation, so it is the slow
1164/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001165static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1166 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001167static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1168 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001169 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001170 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner409a0362007-07-22 18:38:25 +00001172 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001173 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001174 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001175 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chandler Carruth433db062011-07-14 08:20:40 +00001177 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001178 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001179 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001180 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattnere7fb4842009-02-15 20:52:18 +00001182 // Figure out the expansion loc range, which is the range covered by the
1183 // original _Pragma(...) sequence.
1184 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001185 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chandler Carruthbf340e42011-07-26 03:03:05 +00001187 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001188}
1189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190/// getSourceLocation - Return a source location identifier for the specified
1191/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001192SourceLocation Lexer::getSourceLocation(const char *Loc,
1193 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001194 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001196
1197 // In the normal case, we're just lexing from a simple file buffer, return
1198 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001199 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001200 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001201 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattner2b2453a2009-01-17 06:22:33 +00001203 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1204 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001205 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001206 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001207}
1208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209/// Diag - Forwarding function for diagnostics. This translate a source
1210/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001211DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001212 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213}
Reid Spencer5f016e22007-07-11 17:01:13 +00001214
1215//===----------------------------------------------------------------------===//
1216// Trigraph and Escaped Newline Handling Code.
1217//===----------------------------------------------------------------------===//
1218
1219/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1220/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1221static char GetTrigraphCharForLetter(char Letter) {
1222 switch (Letter) {
1223 default: return 0;
1224 case '=': return '#';
1225 case ')': return ']';
1226 case '(': return '[';
1227 case '!': return '|';
1228 case '\'': return '^';
1229 case '>': return '}';
1230 case '/': return '\\';
1231 case '<': return '{';
1232 case '-': return '~';
1233 }
1234}
1235
1236/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1237/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1238/// return the result character. Finally, emit a warning about trigraph use
1239/// whether trigraphs are enabled or not.
1240static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1241 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001242 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001243
David Blaikie4e4d0842012-03-11 07:00:24 +00001244 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001245 if (!L->isLexingRawMode())
1246 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001247 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chris Lattner74d15df2008-11-22 02:02:22 +00001250 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001251 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 return Res;
1253}
1254
Chris Lattner24f0e482009-04-18 22:05:41 +00001255/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1256/// 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 +00001257/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001258unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1259 unsigned Size = 0;
1260 while (isWhitespace(Ptr[Size])) {
1261 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Chris Lattner24f0e482009-04-18 22:05:41 +00001263 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1264 continue;
1265
1266 // If this is a \r\n or \n\r, skip the other half.
1267 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1268 Ptr[Size-1] != Ptr[Size])
1269 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner24f0e482009-04-18 22:05:41 +00001271 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001272 }
1273
Chris Lattner24f0e482009-04-18 22:05:41 +00001274 // Not an escaped newline, must be a \t or something else.
1275 return 0;
1276}
1277
Chris Lattner03374952009-04-18 22:27:02 +00001278/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1279/// them), skip over them and return the first non-escaped-newline found,
1280/// otherwise return P.
1281const char *Lexer::SkipEscapedNewLines(const char *P) {
1282 while (1) {
1283 const char *AfterEscape;
1284 if (*P == '\\') {
1285 AfterEscape = P+1;
1286 } else if (*P == '?') {
1287 // If not a trigraph for escape, bail out.
1288 if (P[1] != '?' || P[2] != '/')
1289 return P;
1290 AfterEscape = P+3;
1291 } else {
1292 return P;
1293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Chris Lattner03374952009-04-18 22:27:02 +00001295 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1296 if (NewLineSize == 0) return P;
1297 P = AfterEscape+NewLineSize;
1298 }
1299}
1300
Anna Zaksaca25bc2011-07-27 21:43:43 +00001301/// \brief Checks that the given token is the first token that occurs after the
1302/// given location (this excludes comments and whitespace). Returns the location
1303/// immediately after the specified token. If the token is not found or the
1304/// location is inside a macro, the returned source location will be invalid.
1305SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1306 tok::TokenKind TKind,
1307 const SourceManager &SM,
1308 const LangOptions &LangOpts,
1309 bool SkipTrailingWhitespaceAndNewLine) {
1310 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001311 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001312 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001313 }
1314 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1315
1316 // Break down the source location.
1317 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1318
1319 // Try to load the file buffer.
1320 bool InvalidTemp = false;
1321 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1322 if (InvalidTemp)
1323 return SourceLocation();
1324
1325 const char *TokenBegin = File.data() + LocInfo.second;
1326
1327 // Lex from the start of the given location.
1328 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1329 TokenBegin, File.end());
1330 // Find the token.
1331 Token Tok;
1332 lexer.LexFromRawLexer(Tok);
1333 if (Tok.isNot(TKind))
1334 return SourceLocation();
1335 SourceLocation TokenLoc = Tok.getLocation();
1336
1337 // Calculate how much whitespace needs to be skipped if any.
1338 unsigned NumWhitespaceChars = 0;
1339 if (SkipTrailingWhitespaceAndNewLine) {
1340 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1341 Tok.getLength();
1342 unsigned char C = *TokenEnd;
1343 while (isHorizontalWhitespace(C)) {
1344 C = *(++TokenEnd);
1345 NumWhitespaceChars++;
1346 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001347
1348 // Skip \r, \n, \r\n, or \n\r
1349 if (C == '\n' || C == '\r') {
1350 char PrevC = C;
1351 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001352 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001353 if ((C == '\n' || C == '\r') && C != PrevC)
1354 NumWhitespaceChars++;
1355 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001356 }
1357
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001358 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001359}
Chris Lattner24f0e482009-04-18 22:05:41 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1362/// get its size, and return it. This is tricky in several cases:
1363/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1364/// then either return the trigraph (skipping 3 chars) or the '?',
1365/// depending on whether trigraphs are enabled or not.
1366/// 2. If this is an escaped newline (potentially with whitespace between
1367/// the backslash and newline), implicitly skip the newline and return
1368/// the char after it.
1369/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1370///
1371/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1372/// know that we can accumulate into Size, and that we have already incremented
1373/// Ptr by Size bytes.
1374///
1375/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1376/// be updated to match.
1377///
1378char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001379 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 // If we have a slash, look for an escaped newline.
1381 if (Ptr[0] == '\\') {
1382 ++Size;
1383 ++Ptr;
1384Slash:
1385 // Common case, backslash-char where the char is not whitespace.
1386 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Chris Lattner5636a3b2009-06-23 05:15:06 +00001388 // See if we have optional whitespace characters between the slash and
1389 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001390 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1391 // Remember that this token needs to be cleaned.
1392 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393
Chris Lattner24f0e482009-04-18 22:05:41 +00001394 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001395 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001396 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Chris Lattner24f0e482009-04-18 22:05:41 +00001398 // Found backslash<whitespace><newline>. Parse the char after it.
1399 Size += EscapedNewLineSize;
1400 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001401
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001402 // If the char that we finally got was a \n, then we must have had
1403 // something like \<newline><newline>. We don't want to consume the
1404 // second newline.
1405 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1406 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001407
Chris Lattner24f0e482009-04-18 22:05:41 +00001408 // Use slow version to accumulate a correct size field.
1409 return getCharAndSizeSlow(Ptr, Size, Tok);
1410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Otherwise, this is not an escaped newline, just return the slash.
1413 return '\\';
1414 }
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 // If this is a trigraph, process it.
1417 if (Ptr[0] == '?' && Ptr[1] == '?') {
1418 // If this is actually a legal trigraph (not something like "??x"), emit
1419 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1420 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1421 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001422 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001423
1424 Ptr += 3;
1425 Size += 3;
1426 if (C == '\\') goto Slash;
1427 return C;
1428 }
1429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 // If this is neither, return a single character.
1432 ++Size;
1433 return *Ptr;
1434}
1435
1436
1437/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1438/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1439/// and that we have already incremented Ptr by Size bytes.
1440///
1441/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1442/// be updated to match.
1443char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001444 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // If we have a slash, look for an escaped newline.
1446 if (Ptr[0] == '\\') {
1447 ++Size;
1448 ++Ptr;
1449Slash:
1450 // Common case, backslash-char where the char is not whitespace.
1451 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001454 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1455 // Found backslash<whitespace><newline>. Parse the char after it.
1456 Size += EscapedNewLineSize;
1457 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001459 // If the char that we finally got was a \n, then we must have had
1460 // something like \<newline><newline>. We don't want to consume the
1461 // second newline.
1462 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1463 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001464
Chris Lattner24f0e482009-04-18 22:05:41 +00001465 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001466 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 // Otherwise, this is not an escaped newline, just return the slash.
1470 return '\\';
1471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001474 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // If this is actually a legal trigraph (not something like "??x"), return
1476 // it.
1477 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1478 Ptr += 3;
1479 Size += 3;
1480 if (C == '\\') goto Slash;
1481 return C;
1482 }
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 // If this is neither, return a single character.
1486 ++Size;
1487 return *Ptr;
1488}
1489
1490//===----------------------------------------------------------------------===//
1491// Helper methods for lexing.
1492//===----------------------------------------------------------------------===//
1493
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001494/// \brief Routine that indiscriminately skips bytes in the source file.
1495void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1496 BufferPtr += Bytes;
1497 if (BufferPtr > BufferEnd)
1498 BufferPtr = BufferEnd;
1499 IsAtStartOfLine = StartOfLine;
1500}
1501
Chris Lattnerd2177732007-07-20 16:59:19 +00001502void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1504 unsigned Size;
1505 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001506 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 --CurPtr; // Back up over the skipped character.
1510
1511 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1512 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1513 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001514 //
1515 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1516 // cheaper
David Blaikie4e4d0842012-03-11 07:00:24 +00001517 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001518FinishIdentifier:
1519 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001520 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1521 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 // If we are in raw mode, return this identifier raw. There is no need to
1524 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001525 if (LexingRawMode)
1526 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001528 // Fill in Result.IdentifierInfo and update the token kind,
1529 // looking up the identifier in the identifier table.
1530 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Finally, now that we know we have an identifier, pass this off to the
1533 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001534 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001535 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001536
Chris Lattner6a170eb2009-01-21 07:43:11 +00001537 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 C = getCharAndSize(CurPtr, Size);
1543 while (1) {
1544 if (C == '$') {
1545 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001546 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001549 if (!isLexingRawMode())
1550 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 CurPtr = ConsumeChar(CurPtr, Size, Result);
1552 C = getCharAndSize(CurPtr, Size);
1553 continue;
1554 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1555 // Found end of identifier.
1556 goto FinishIdentifier;
1557 }
1558
1559 // Otherwise, this character is good, consume it.
1560 CurPtr = ConsumeChar(CurPtr, Size, Result);
1561
1562 C = getCharAndSize(CurPtr, Size);
1563 while (isIdentifierBody(C)) { // FIXME: UCNs.
1564 CurPtr = ConsumeChar(CurPtr, Size, Result);
1565 C = getCharAndSize(CurPtr, Size);
1566 }
1567 }
1568}
1569
Douglas Gregora75ec432010-08-30 14:50:47 +00001570/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001571/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001572bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001573 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001574 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001575 if (C1 != '0')
1576 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001577 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001578 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001579}
Reid Spencer5f016e22007-07-11 17:01:13 +00001580
Nate Begeman5253c7f2008-04-14 02:26:39 +00001581/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001582/// constant. From[-1] is the first character lexed. Return the end of the
1583/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001584void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 unsigned Size;
1586 char C = getCharAndSize(CurPtr, Size);
1587 char PrevCh = 0;
Nico Weberdd817312012-11-13 06:25:15 +00001588 while (isNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 CurPtr = ConsumeChar(CurPtr, Size, Result);
1590 PrevCh = C;
1591 C = getCharAndSize(CurPtr, Size);
1592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001595 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1596 // If we are in Microsoft mode, don't continue if the constant is hex.
1597 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001598 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001599 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601
1602 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001603 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1604 // Outside C99, we accept hexadecimal floating point numbers as a
1605 // not-quite-conforming extension. Only do so if this looks like it's
1606 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1607 bool IsHexFloat = true;
1608 if (!LangOpts.C99) {
1609 if (!isHexaLiteral(BufferPtr, LangOpts))
1610 IsHexFloat = false;
1611 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1612 IsHexFloat = false;
1613 }
1614 if (IsHexFloat)
1615 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001619 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001620 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001621 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001622}
1623
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001624/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001625/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001626const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001628
1629 // Maximally munch an identifier. FIXME: UCNs.
1630 unsigned Size;
1631 char C = getCharAndSize(CurPtr, Size);
1632 if (isIdentifierHead(C)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001633 if (!getLangOpts().CPlusPlus0x) {
Richard Smithe816c712012-03-07 03:13:00 +00001634 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001635 Diag(CurPtr,
1636 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1637 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1638 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1639 return CurPtr;
1640 }
1641
1642 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1643 // that does not start with an underscore is ill-formed. As a conforming
1644 // extension, we treat all such suffixes as if they had whitespace before
1645 // them.
1646 if (C != '_') {
1647 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001648 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1649 diag::ext_ms_reserved_user_defined_literal :
1650 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001651 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1652 return CurPtr;
1653 }
1654
Richard Smith99831e42012-03-06 03:21:47 +00001655 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001656 do {
1657 CurPtr = ConsumeChar(CurPtr, Size, Result);
1658 C = getCharAndSize(CurPtr, Size);
1659 } while (isIdentifierBody(C));
1660 }
1661 return CurPtr;
1662}
1663
Reid Spencer5f016e22007-07-11 17:01:13 +00001664/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001665/// either " or L" or u8" or u" or U".
1666void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1667 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Richard Smith661a9962011-10-15 01:18:56 +00001670 if (!isLexingRawMode() &&
1671 (Kind == tok::utf8_string_literal ||
1672 Kind == tok::utf16_string_literal ||
1673 Kind == tok::utf32_string_literal))
1674 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1675
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 char C = getAndAdvanceChar(CurPtr, Result);
1677 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001678 // Skip escaped characters. Escaped newlines will already be processed by
1679 // getAndAdvanceChar.
1680 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001682
Chris Lattner571339c2010-05-30 23:27:38 +00001683 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001684 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001685 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001686 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001687 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 }
Chris Lattner571339c2010-05-30 23:27:38 +00001690
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001691 if (C == 0) {
1692 if (isCodeCompletionPoint(CurPtr-1)) {
1693 PP->CodeCompleteNaturalLanguage();
1694 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1695 return cutOffLexing();
1696 }
1697
Chris Lattner571339c2010-05-30 23:27:38 +00001698 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001699 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 C = getAndAdvanceChar(CurPtr, Result);
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001703 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001704 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001705 CurPtr = LexUDSuffix(Result, CurPtr);
1706
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001708 if (NulCharacter && !isLexingRawMode())
1709 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001710
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001712 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001713 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001714 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715}
1716
Craig Topper2fa4e862011-08-11 04:06:15 +00001717/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1718/// having lexed R", LR", u8R", uR", or UR".
1719void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1720 tok::TokenKind Kind) {
1721 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1722 // Between the initial and final double quote characters of the raw string,
1723 // any transformations performed in phases 1 and 2 (trigraphs,
1724 // universal-character-names, and line splicing) are reverted.
1725
Richard Smith661a9962011-10-15 01:18:56 +00001726 if (!isLexingRawMode())
1727 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1728
Craig Topper2fa4e862011-08-11 04:06:15 +00001729 unsigned PrefixLen = 0;
1730
1731 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1732 ++PrefixLen;
1733
1734 // If the last character was not a '(', then we didn't lex a valid delimiter.
1735 if (CurPtr[PrefixLen] != '(') {
1736 if (!isLexingRawMode()) {
1737 const char *PrefixEnd = &CurPtr[PrefixLen];
1738 if (PrefixLen == 16) {
1739 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1740 } else {
1741 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1742 << StringRef(PrefixEnd, 1);
1743 }
1744 }
1745
1746 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1747 // it's possible the '"' was intended to be part of the raw string, but
1748 // there's not much we can do about that.
1749 while (1) {
1750 char C = *CurPtr++;
1751
1752 if (C == '"')
1753 break;
1754 if (C == 0 && CurPtr-1 == BufferEnd) {
1755 --CurPtr;
1756 break;
1757 }
1758 }
1759
1760 FormTokenWithChars(Result, CurPtr, tok::unknown);
1761 return;
1762 }
1763
1764 // Save prefix and move CurPtr past it
1765 const char *Prefix = CurPtr;
1766 CurPtr += PrefixLen + 1; // skip over prefix and '('
1767
1768 while (1) {
1769 char C = *CurPtr++;
1770
1771 if (C == ')') {
1772 // Check for prefix match and closing quote.
1773 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1774 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1775 break;
1776 }
1777 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1778 if (!isLexingRawMode())
1779 Diag(BufferPtr, diag::err_unterminated_raw_string)
1780 << StringRef(Prefix, PrefixLen);
1781 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1782 return;
1783 }
1784 }
1785
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001786 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001787 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001788 CurPtr = LexUDSuffix(Result, CurPtr);
1789
Craig Topper2fa4e862011-08-11 04:06:15 +00001790 // Update the location of token as well as BufferPtr.
1791 const char *TokStart = BufferPtr;
1792 FormTokenWithChars(Result, CurPtr, Kind);
1793 Result.setLiteralData(TokStart);
1794}
1795
Reid Spencer5f016e22007-07-11 17:01:13 +00001796/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1797/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001798void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001800 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 char C = getAndAdvanceChar(CurPtr, Result);
1802 while (C != '>') {
1803 // Skip escaped characters.
1804 if (C == '\\') {
1805 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001806 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001808 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1809 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001810 // If the filename is unterminated, then it must just be a lone <
1811 // character. Return this as such.
1812 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 return;
1814 } else if (C == 0) {
1815 NulCharacter = CurPtr-1;
1816 }
1817 C = getAndAdvanceChar(CurPtr, Result);
1818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001821 if (NulCharacter && !isLexingRawMode())
1822 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001825 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001826 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001827 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001828}
1829
1830
1831/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001832/// lexed either ' or L' or u' or U'.
1833void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1834 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 const char *NulCharacter = 0; // Does this character contain the \0 character?
1836
Richard Smith661a9962011-10-15 01:18:56 +00001837 if (!isLexingRawMode() &&
1838 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1839 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 char C = getAndAdvanceChar(CurPtr, Result);
1842 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001843 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001844 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001845 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001847 }
1848
1849 while (C != '\'') {
1850 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001851 if (C == '\\')
1852 C = getAndAdvanceChar(CurPtr, Result);
1853
1854 if (C == '\n' || C == '\r' || // Newline.
1855 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001856 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001857 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001858 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1859 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001860 }
1861
1862 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001863 if (isCodeCompletionPoint(CurPtr-1)) {
1864 PP->CodeCompleteNaturalLanguage();
1865 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1866 return cutOffLexing();
1867 }
1868
Chris Lattnerd80f7862010-07-07 23:24:27 +00001869 NulCharacter = CurPtr-1;
1870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 C = getAndAdvanceChar(CurPtr, Result);
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001874 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001875 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001876 CurPtr = LexUDSuffix(Result, CurPtr);
1877
Chris Lattnerd80f7862010-07-07 23:24:27 +00001878 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001879 if (NulCharacter && !isLexingRawMode())
1880 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001881
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001883 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001884 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001885 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001886}
1887
1888/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1889/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001890///
1891/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1892///
1893bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // Whitespace - Skip it, then return the token after the whitespace.
1895 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1896 while (1) {
1897 // Skip horizontal whitespace very aggressively.
1898 while (isHorizontalWhitespace(Char))
1899 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001901 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 if (Char != '\n' && Char != '\r')
1903 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 if (ParsingPreprocessorDirective) {
1906 // End of preprocessor directive line, let LexTokenInternal handle this.
1907 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001908 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 }
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 // ok, but handle newline.
1912 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001913 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001915 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 Char = *++CurPtr;
1917 }
1918
1919 // If this isn't immediately after a newline, there is leading space.
1920 char PrevChar = CurPtr[-1];
1921 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001922 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001923
Chris Lattnerd88dc482008-10-12 04:05:48 +00001924 // If the client wants us to return whitespace, return it now.
1925 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001926 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001927 return true;
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001931 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932}
1933
Nico Weberbb236282012-11-11 07:02:14 +00001934/// We have just read the // characters from input. Skip until we find the
1935/// newline character thats terminate the comment. Then update BufferPtr and
1936/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001937///
1938/// If we're in KeepCommentMode or any CommentHandler has inserted
1939/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001940bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1941 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001943 if (!LangOpts.LineComment && !isLexingRawMode()) {
1944 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 // Mark them enabled so we only emit one warning for this translation
1947 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001948 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // Scan over the body of the comment. The common case, when scanning, is that
1952 // the comment contains normal ascii characters with nothing interesting in
1953 // them. As such, optimize for this case with the inner loop.
1954 char C;
1955 do {
1956 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 // Skip over characters in the fast loop.
1958 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 C != '\n' && C != '\r') // Newline or DOS-style newline.
1960 C = *++CurPtr;
1961
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001962 const char *NextLine = CurPtr;
1963 if (C != 0) {
1964 // We found a newline, see if it's escaped.
1965 const char *EscapePtr = CurPtr-1;
1966 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1967 --EscapePtr;
1968
1969 if (*EscapePtr == '\\') // Escaped newline.
1970 CurPtr = EscapePtr;
1971 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1972 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1973 CurPtr = EscapePtr-2;
1974 else
1975 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001979 // properly decode the character. Read it in raw mode to avoid emitting
1980 // diagnostics about things like trigraphs. If we see an escaped newline,
1981 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001983 bool OldRawMode = isLexingRawMode();
1984 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001986 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001987
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001988 // If we only read only one character, then no special handling is needed.
1989 // We're done and can skip forward to the newline.
1990 if (C != 0 && CurPtr == OldPtr+1) {
1991 CurPtr = NextLine;
1992 break;
1993 }
1994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 // If we read multiple characters, and one of those characters was a \r or
1996 // \n, then we had an escaped newline within the comment. Emit diagnostic
1997 // unless the next line is also a // comment.
1998 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1999 for (; OldPtr != CurPtr; ++OldPtr)
2000 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2001 // Okay, we found a // comment that ends in a newline, if the next
2002 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002003 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002005 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 ++ForwardPtr;
2007 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2008 break;
2009 }
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Chris Lattner74d15df2008-11-22 02:02:22 +00002011 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00002012 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 break;
2014 }
2015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Douglas Gregor55817af2010-08-25 17:04:25 +00002017 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00002018 --CurPtr;
2019 break;
2020 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002021
2022 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2023 PP->CodeCompleteNaturalLanguage();
2024 cutOffLexing();
2025 return false;
2026 }
2027
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 } while (C != '\n' && C != '\r');
2029
Chris Lattner3d0ad582010-02-03 21:06:21 +00002030 // Found but did not consume the newline. Notify comment handlers about the
2031 // comment unless we're in a #if 0 block.
2032 if (PP && !isLexingRawMode() &&
2033 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2034 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002035 BufferPtr = CurPtr;
2036 return true; // A token has to be returned.
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002040 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002041 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002042
2043 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002044 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2046 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002047 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 }
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002051 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002052 // contribute to another token), it isn't needed for correctness. Note that
2053 // this is ok even in KeepWhitespaceMode, because we would have returned the
2054 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002058 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002060 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002062 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002063}
2064
Nico Weberbb236282012-11-11 07:02:14 +00002065/// If in save-comment mode, package up this Line comment in an appropriate
2066/// way and return it.
2067bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002068 // If we're not in a preprocessor directive, just return the // comment
2069 // directly.
2070 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
David Blaikie8c0b3782012-06-06 18:52:13 +00002072 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002073 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Nico Weberbb236282012-11-11 07:02:14 +00002075 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002076 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002077 bool Invalid = false;
2078 std::string Spelling = PP->getSpelling(Result, &Invalid);
2079 if (Invalid)
2080 return true;
2081
Nico Weberbb236282012-11-11 07:02:14 +00002082 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002083 Spelling[1] = '*'; // Change prefix to "/*".
2084 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Chris Lattner9e6293d2008-10-12 04:51:35 +00002086 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002087 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002088 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002089 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002090}
2091
2092/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002093/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2094/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002095static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 Lexer *L) {
2097 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 // Back up off the newline.
2100 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // If this is a two-character newline sequence, skip the other character.
2103 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2104 // \n\n or \r\r -> not escaped newline.
2105 if (CurPtr[0] == CurPtr[1])
2106 return false;
2107 // \n\r or \r\n -> skip the newline.
2108 --CurPtr;
2109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // If we have horizontal whitespace, skip over it. We allow whitespace
2112 // between the slash and newline.
2113 bool HasSpace = false;
2114 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2115 --CurPtr;
2116 HasSpace = true;
2117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // If we have a slash, we know this is an escaped newline.
2120 if (*CurPtr == '\\') {
2121 if (CurPtr[-1] != '*') return false;
2122 } else {
2123 // It isn't a slash, is it the ?? / trigraph?
2124 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2125 CurPtr[-3] != '*')
2126 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // This is the trigraph ending the comment. Emit a stern warning!
2129 CurPtr -= 2;
2130
2131 // If no trigraphs are enabled, warn that we ignored this trigraph and
2132 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002133 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002134 if (!L->isLexingRawMode())
2135 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 return false;
2137 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002138 if (!L->isLexingRawMode())
2139 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 }
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002143 if (!L->isLexingRawMode())
2144 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002147 if (HasSpace && !L->isLexingRawMode())
2148 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 return true;
2151}
2152
2153#ifdef __SSE2__
2154#include <emmintrin.h>
2155#elif __ALTIVEC__
2156#include <altivec.h>
2157#undef bool
2158#endif
2159
James Dennettec769932012-06-17 03:40:43 +00002160/// We have just read from input the / and * characters that started a comment.
2161/// Read until we find the * and / characters that terminate the comment.
2162/// Note that we don't bother decoding trigraphs or escaped newlines in block
2163/// comments, because they cannot cause the comment to end. The only thing
2164/// that can happen is the comment could end with an escaped newline between
2165/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002166///
Chris Lattner046c2272010-01-18 22:35:47 +00002167/// If we're in KeepCommentMode or any CommentHandler has inserted
2168/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002169bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002171 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002172 // optimization helps people who like to put a lot of * characters in their
2173 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002174
2175 // The first character we get with newlines and trigraphs skipped to handle
2176 // the degenerate /*/ case below correctly if the * has an escaped newline
2177 // after it.
2178 unsigned CharSize;
2179 unsigned char C = getCharAndSize(CurPtr, CharSize);
2180 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002182 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002183 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002184 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Chris Lattner31f0eca2008-10-12 04:19:49 +00002186 // KeepWhitespaceMode should return this broken comment as a token. Since
2187 // it isn't a well formed comment, just return it as an 'unknown' token.
2188 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002189 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002190 return true;
2191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Chris Lattner31f0eca2008-10-12 04:19:49 +00002193 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002194 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 }
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Chris Lattner8146b682007-07-21 23:43:37 +00002197 // Check to see if the first character after the '/*' is another /. If so,
2198 // then this slash does not end the block comment, it is part of it.
2199 if (C == '/')
2200 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 while (1) {
2203 // Skip over all non-interesting characters until we find end of buffer or a
2204 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002205 if (CurPtr + 24 < BufferEnd &&
2206 // If there is a code-completion point avoid the fast scan because it
2207 // doesn't check for '\0'.
2208 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 // While not aligned to a 16-byte boundary.
2210 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2211 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 if (C == '/') goto FoundSlash;
2214
2215#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002216 __m128i Slashes = _mm_set1_epi8('/');
2217 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002218 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2219 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002220 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002221 // Adjust the pointer to point directly after the first slash. It's
2222 // not necessary to set C here, it will be overwritten at the end of
2223 // the outer loop.
2224 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002225 goto FoundSlash;
2226 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002228 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002229#elif __ALTIVEC__
2230 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002231 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 '/', '/', '/', '/', '/', '/', '/', '/'
2233 };
2234 while (CurPtr+16 <= BufferEnd &&
2235 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2236 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002237#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 // Scan for '/' quickly. Many block comments are very large.
2239 while (CurPtr[0] != '/' &&
2240 CurPtr[1] != '/' &&
2241 CurPtr[2] != '/' &&
2242 CurPtr[3] != '/' &&
2243 CurPtr+4 < BufferEnd) {
2244 CurPtr += 4;
2245 }
2246#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // It has to be one of the bytes scanned, increment to it and read one.
2249 C = *CurPtr++;
2250 }
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 // Loop to scan the remainder.
2253 while (C != '/' && C != '\0')
2254 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002257 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 if (CurPtr[-2] == '*') // We found the final */. We're done!
2259 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2262 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2263 // We found the final */, though it had an escaped newline between the
2264 // * and /. We're done!
2265 break;
2266 }
2267 }
2268 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2269 // If this is a /* inside of the comment, emit a warning. Don't do this
2270 // if this is a /*/, which will end the comment. This misses cases with
2271 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002272 if (!isLexingRawMode())
2273 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 }
2275 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002276 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002277 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 // Note: the user probably forgot a */. We could continue immediately
2279 // after the /*, but this would involve lexing a lot of what really is the
2280 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002281 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Chris Lattner31f0eca2008-10-12 04:19:49 +00002283 // KeepWhitespaceMode should return this broken comment as a token. Since
2284 // it isn't a well formed comment, just return it as an 'unknown' token.
2285 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002286 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002287 return true;
2288 }
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Chris Lattner31f0eca2008-10-12 04:19:49 +00002290 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002291 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002292 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2293 PP->CodeCompleteNaturalLanguage();
2294 cutOffLexing();
2295 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002297
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 C = *CurPtr++;
2299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattner3d0ad582010-02-03 21:06:21 +00002301 // Notify comment handlers about the comment unless we're in a #if 0 block.
2302 if (PP && !isLexingRawMode() &&
2303 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2304 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002305 BufferPtr = CurPtr;
2306 return true; // A token has to be returned.
2307 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002308
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002310 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002311 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002312 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 }
2314
2315 // It is common for the tokens immediately after a /**/ comment to be
2316 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002317 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2318 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002320 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002322 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 }
2324
2325 // Otherwise, just return so that the next character will be lexed as a token.
2326 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002327 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002328 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002329}
2330
2331//===----------------------------------------------------------------------===//
2332// Primary Lexing Entry Points
2333//===----------------------------------------------------------------------===//
2334
Reid Spencer5f016e22007-07-11 17:01:13 +00002335/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2336/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002337void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2339 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002340 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002341
2342 // CurPtr - Cache BufferPtr in an automatic variable.
2343 const char *CurPtr = BufferPtr;
2344 while (1) {
2345 char Char = getAndAdvanceChar(CurPtr, Tmp);
2346 switch (Char) {
2347 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002348 if (Result)
2349 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 break;
2351 case 0: // Null.
2352 // Found end of file?
2353 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002354 if (isCodeCompletionPoint(CurPtr-1)) {
2355 PP->CodeCompleteNaturalLanguage();
2356 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002357 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002358 }
2359
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002361 if (Result)
2362 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002363 break;
2364 }
2365 // FALL THROUGH.
2366 case '\r':
2367 case '\n':
2368 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2369 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2370 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Peter Collingbourne84021552011-02-28 02:37:51 +00002372 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002374 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002375 if (PP)
2376 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002377 Lex(Tmp);
2378 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002379 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Benjamin Kramer3093b202012-05-18 19:32:16 +00002381 // Finally, we're done;
2382 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 }
2384 }
2385}
2386
2387/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2388/// condition, reporting diagnostics and handling other edge cases as required.
2389/// This returns true if Result contains a token, false if PP.Lex should be
2390/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002391bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 // If we hit the end of the file while parsing a preprocessor directive,
2393 // end the preprocessor directive first. The next token returned will
2394 // then be the end of file.
2395 if (ParsingPreprocessorDirective) {
2396 // Done parsing the "line".
2397 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002399 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002402 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002403 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002404 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002405
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 // If we are in raw mode, return this event as an EOF token. Let the caller
2407 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002408 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002409 Result.startToken();
2410 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002411 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 return true;
2413 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002414
Douglas Gregorf44e8542010-08-24 19:08:16 +00002415 // Issue diagnostics for unterminated #if and missing newline.
2416
Reid Spencer5f016e22007-07-11 17:01:13 +00002417 // If we are in a #if directive, emit an error.
2418 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002419 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002420 PP->Diag(ConditionalStack.back().IfLoc,
2421 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002422 ConditionalStack.pop_back();
2423 }
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002425 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2426 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002427 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2428 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2429 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2430 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 BufferPtr = CurPtr;
2433
2434 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002435 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002436}
2437
2438/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2439/// the specified lexer will return a tok::l_paren token, 0 if it is something
2440/// else and 2 if there are no more tokens in the buffer controlled by the
2441/// lexer.
2442unsigned Lexer::isNextPPTokenLParen() {
2443 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002444
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 // Switch to 'skipping' mode. This will ensure that we can lex a token
2446 // without emitting diagnostics, disables macro expansion, and will cause EOF
2447 // to return an EOF token instead of popping the include stack.
2448 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 // Save state that can be changed while lexing so that we can restore it.
2451 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002452 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Chris Lattnerd2177732007-07-20 16:59:19 +00002454 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002455 Tok.startToken();
2456 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Reid Spencer5f016e22007-07-11 17:01:13 +00002458 // Restore state that may have changed.
2459 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002460 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Reid Spencer5f016e22007-07-11 17:01:13 +00002462 // Restore the lexer back to non-skipping mode.
2463 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002465 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002467 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002468}
2469
James Dennettec769932012-06-17 03:40:43 +00002470/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002471static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2472 ConflictMarkerKind CMK) {
2473 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2474 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2475 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2476 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002477 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002478 // Must occur at start of line.
2479 if (RestOfBuffer[Pos-1] != '\r' &&
2480 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002481 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2482 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002483 continue;
2484 }
2485 return RestOfBuffer.data()+Pos;
2486 }
2487 return 0;
2488}
2489
2490/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2491/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2492/// and recover nicely. This returns true if it is a conflict marker and false
2493/// if not.
2494bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2495 // Only a conflict marker if it starts at the beginning of a line.
2496 if (CurPtr != BufferStart &&
2497 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2498 return false;
2499
Richard Smithd5e1d602011-10-12 00:37:51 +00002500 // Check to see if we have <<<<<<< or >>>>.
2501 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2502 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002503 return false;
2504
2505 // If we have a situation where we don't care about conflict markers, ignore
2506 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002507 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002508 return false;
2509
Richard Smithd5e1d602011-10-12 00:37:51 +00002510 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2511
2512 // Check to see if there is an ending marker somewhere in the buffer at the
2513 // start of a line to terminate this conflict marker.
2514 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002515 // We found a match. We are really in a conflict marker.
2516 // Diagnose this, and ignore to the end of line.
2517 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002518 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002519
2520 // Skip ahead to the end of line. We know this exists because the
2521 // end-of-conflict marker starts with \r or \n.
2522 while (*CurPtr != '\r' && *CurPtr != '\n') {
2523 assert(CurPtr != BufferEnd && "Didn't find end of line");
2524 ++CurPtr;
2525 }
2526 BufferPtr = CurPtr;
2527 return true;
2528 }
2529
2530 // No end of conflict marker found.
2531 return false;
2532}
2533
2534
Richard Smithd5e1d602011-10-12 00:37:51 +00002535/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2536/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2537/// is the end of a conflict marker. Handle it by ignoring up until the end of
2538/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002539bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2540 // Only a conflict marker if it starts at the beginning of a line.
2541 if (CurPtr != BufferStart &&
2542 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2543 return false;
2544
2545 // If we have a situation where we don't care about conflict markers, ignore
2546 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002547 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002548 return false;
2549
Richard Smithd5e1d602011-10-12 00:37:51 +00002550 // Check to see if we have the marker (4 characters in a row).
2551 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002552 if (CurPtr[i] != CurPtr[0])
2553 return false;
2554
2555 // If we do have it, search for the end of the conflict marker. This could
2556 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2557 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002558 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2559 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002560 CurPtr = End;
2561
2562 // Skip ahead to the end of line.
2563 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2564 ++CurPtr;
2565
2566 BufferPtr = CurPtr;
2567
2568 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002569 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002570 return true;
2571 }
2572
2573 return false;
2574}
2575
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002576bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2577 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002578 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002579 return Loc == PP->getCodeCompletionLoc();
2580 }
2581
2582 return false;
2583}
2584
Reid Spencer5f016e22007-07-11 17:01:13 +00002585
2586/// LexTokenInternal - This implements a simple C family lexer. It is an
2587/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002588/// has a null character at the end of the file. This returns a preprocessing
2589/// token, not a normal token, as such, it is an internal interface. It assumes
2590/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002591void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002592LexNextToken:
2593 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002594 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // CurPtr - Cache BufferPtr in an automatic variable.
2598 const char *CurPtr = BufferPtr;
2599
2600 // Small amounts of horizontal whitespace is very common between tokens.
2601 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2602 ++CurPtr;
2603 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2604 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Chris Lattnerd88dc482008-10-12 04:05:48 +00002606 // If we are keeping whitespace and other tokens, just return what we just
2607 // skipped. The next lexer invocation will return the token after the
2608 // whitespace.
2609 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002610 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002611 return;
2612 }
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002615 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002616 }
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 // Read a character, advancing over it.
2621 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002622 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002623
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 switch (Char) {
2625 case 0: // Null.
2626 // Found end of file?
2627 if (CurPtr-1 == BufferEnd) {
2628 // Read the PP instance variable into an automatic variable, because
2629 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002630 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2632 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002633 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2634 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 }
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002637 // Check if we are performing code completion.
2638 if (isCodeCompletionPoint(CurPtr-1)) {
2639 // Return the code-completion token.
2640 Result.startToken();
2641 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2642 return;
2643 }
2644
Chris Lattner74d15df2008-11-22 02:02:22 +00002645 if (!isLexingRawMode())
2646 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002647 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002648 if (SkipWhitespace(Result, CurPtr))
2649 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002652
2653 case 26: // DOS & CP/M EOF: "^Z".
2654 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002655 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002656 // Read the PP instance variable into an automatic variable, because
2657 // LexEndOfFile will often delete 'this'.
2658 Preprocessor *PPCache = PP;
2659 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2660 return; // Got a token to return.
2661 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2662 return PPCache->Lex(Result);
2663 }
2664 // If Microsoft extensions are disabled, this is just random garbage.
2665 Kind = tok::unknown;
2666 break;
2667
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 case '\n':
2669 case '\r':
2670 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002671 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002672 if (ParsingPreprocessorDirective) {
2673 // Done parsing the "line".
2674 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002677 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002678 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 // Since we consumed a newline, we are back at the start of a line.
2681 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Peter Collingbourne84021552011-02-28 02:37:51 +00002683 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 break;
2685 }
2686 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002687 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002689 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Chris Lattnerd88dc482008-10-12 04:05:48 +00002691 if (SkipWhitespace(Result, CurPtr))
2692 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 goto LexNextToken; // GCC isn't tail call eliminating.
2694 case ' ':
2695 case '\t':
2696 case '\f':
2697 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002698 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002699 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002700 if (SkipWhitespace(Result, CurPtr))
2701 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002702
2703 SkipIgnoredUnits:
2704 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Chris Lattner8133cfc2007-07-22 06:29:05 +00002706 // If the next token is obviously a // or /* */ comment, skip it efficiently
2707 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002708 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002709 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2710 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002711 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002712 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002713 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002714 if (SkipBlockComment(Result, CurPtr+2))
2715 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002716 goto SkipIgnoredUnits;
2717 } else if (isHorizontalWhitespace(*CurPtr)) {
2718 goto SkipHorizontalWhitespace;
2719 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002721
Chris Lattner3a570772008-01-03 17:58:54 +00002722 // C99 6.4.4.1: Integer Constants.
2723 // C99 6.4.4.2: Floating Constants.
2724 case '0': case '1': case '2': case '3': case '4':
2725 case '5': case '6': case '7': case '8': case '9':
2726 // Notify MIOpt that we read a non-whitespace/non-comment token.
2727 MIOpt.ReadToken();
2728 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregor5cee1192011-07-27 05:40:30 +00002730 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2731 // Notify MIOpt that we read a non-whitespace/non-comment token.
2732 MIOpt.ReadToken();
2733
David Blaikie4e4d0842012-03-11 07:00:24 +00002734 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002735 Char = getCharAndSize(CurPtr, SizeTmp);
2736
2737 // UTF-16 string literal
2738 if (Char == '"')
2739 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2740 tok::utf16_string_literal);
2741
2742 // UTF-16 character constant
2743 if (Char == '\'')
2744 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2745 tok::utf16_char_constant);
2746
Craig Topper2fa4e862011-08-11 04:06:15 +00002747 // UTF-16 raw string literal
2748 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2749 return LexRawStringLiteral(Result,
2750 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2751 SizeTmp2, Result),
2752 tok::utf16_string_literal);
2753
2754 if (Char == '8') {
2755 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2756
2757 // UTF-8 string literal
2758 if (Char2 == '"')
2759 return LexStringLiteral(Result,
2760 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2761 SizeTmp2, Result),
2762 tok::utf8_string_literal);
2763
2764 if (Char2 == 'R') {
2765 unsigned SizeTmp3;
2766 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2767 // UTF-8 raw string literal
2768 if (Char3 == '"') {
2769 return LexRawStringLiteral(Result,
2770 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2771 SizeTmp2, Result),
2772 SizeTmp3, Result),
2773 tok::utf8_string_literal);
2774 }
2775 }
2776 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002777 }
2778
2779 // treat u like the start of an identifier.
2780 return LexIdentifier(Result, CurPtr);
2781
2782 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2783 // Notify MIOpt that we read a non-whitespace/non-comment token.
2784 MIOpt.ReadToken();
2785
David Blaikie4e4d0842012-03-11 07:00:24 +00002786 if (LangOpts.CPlusPlus0x) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002787 Char = getCharAndSize(CurPtr, SizeTmp);
2788
2789 // UTF-32 string literal
2790 if (Char == '"')
2791 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2792 tok::utf32_string_literal);
2793
2794 // UTF-32 character constant
2795 if (Char == '\'')
2796 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2797 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002798
2799 // UTF-32 raw string literal
2800 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2801 return LexRawStringLiteral(Result,
2802 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2803 SizeTmp2, Result),
2804 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002805 }
2806
2807 // treat U like the start of an identifier.
2808 return LexIdentifier(Result, CurPtr);
2809
Craig Topper2fa4e862011-08-11 04:06:15 +00002810 case 'R': // Identifier or C++0x raw string literal
2811 // Notify MIOpt that we read a non-whitespace/non-comment token.
2812 MIOpt.ReadToken();
2813
David Blaikie4e4d0842012-03-11 07:00:24 +00002814 if (LangOpts.CPlusPlus0x) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002815 Char = getCharAndSize(CurPtr, SizeTmp);
2816
2817 if (Char == '"')
2818 return LexRawStringLiteral(Result,
2819 ConsumeChar(CurPtr, SizeTmp, Result),
2820 tok::string_literal);
2821 }
2822
2823 // treat R like the start of an identifier.
2824 return LexIdentifier(Result, CurPtr);
2825
Chris Lattner3a570772008-01-03 17:58:54 +00002826 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 // Notify MIOpt that we read a non-whitespace/non-comment token.
2828 MIOpt.ReadToken();
2829 Char = getCharAndSize(CurPtr, SizeTmp);
2830
2831 // Wide string literal.
2832 if (Char == '"')
2833 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002834 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002835
Craig Topper2fa4e862011-08-11 04:06:15 +00002836 // Wide raw string literal.
David Blaikie4e4d0842012-03-11 07:00:24 +00002837 if (LangOpts.CPlusPlus0x && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002838 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2839 return LexRawStringLiteral(Result,
2840 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2841 SizeTmp2, Result),
2842 tok::wide_string_literal);
2843
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 // Wide character constant.
2845 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002846 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2847 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 // C99 6.4.2: Identifiers.
2851 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2852 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002853 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2855 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2856 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002857 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 case 'v': case 'w': case 'x': case 'y': case 'z':
2859 case '_':
2860 // Notify MIOpt that we read a non-whitespace/non-comment token.
2861 MIOpt.ReadToken();
2862 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002863
2864 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002865 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002866 if (!isLexingRawMode())
2867 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002868 // Notify MIOpt that we read a non-whitespace/non-comment token.
2869 MIOpt.ReadToken();
2870 return LexIdentifier(Result, CurPtr);
2871 }
Mike Stump1eb44332009-09-09 15:08:12 +00002872
Chris Lattner9e6293d2008-10-12 04:51:35 +00002873 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002874 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 // C99 6.4.4: Character Constants.
2877 case '\'':
2878 // Notify MIOpt that we read a non-whitespace/non-comment token.
2879 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002880 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002881
2882 // C99 6.4.5: String Literals.
2883 case '"':
2884 // Notify MIOpt that we read a non-whitespace/non-comment token.
2885 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002886 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002887
2888 // C99 6.4.6: Punctuators.
2889 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002890 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 break;
2892 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002893 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 break;
2895 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002896 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002897 break;
2898 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002899 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 break;
2901 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002902 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 break;
2904 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002905 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002906 break;
2907 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002908 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 break;
2910 case '.':
2911 Char = getCharAndSize(CurPtr, SizeTmp);
2912 if (Char >= '0' && Char <= '9') {
2913 // Notify MIOpt that we read a non-whitespace/non-comment token.
2914 MIOpt.ReadToken();
2915
2916 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00002917 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002918 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 CurPtr += SizeTmp;
2920 } else if (Char == '.' &&
2921 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002922 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2924 SizeTmp2, Result);
2925 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002926 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002927 }
2928 break;
2929 case '&':
2930 Char = getCharAndSize(CurPtr, SizeTmp);
2931 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002932 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2934 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002935 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002936 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2937 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002938 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002939 }
2940 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002941 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002943 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002944 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2945 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002946 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002947 }
2948 break;
2949 case '+':
2950 Char = getCharAndSize(CurPtr, SizeTmp);
2951 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002952 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002953 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002955 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002956 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002958 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 }
2960 break;
2961 case '-':
2962 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002963 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002965 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00002966 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002967 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2969 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002970 Kind = tok::arrowstar;
2971 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002973 Kind = tok::arrow;
2974 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002976 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002978 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 }
2980 break;
2981 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002982 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 break;
2984 case '!':
2985 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002986 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2988 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002989 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 }
2991 break;
2992 case '/':
2993 // 6.4.9: Comments
2994 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00002995 if (Char == '/') { // Line comment.
2996 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00002997 // want to lex this as a comment. There is one problem with this though,
2998 // that in one particular corner case, this can change the behavior of the
2999 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003000 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003001 // "foo". Check to see if the character after the second slash is a '*'.
3002 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003003 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00003004 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003005 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003006 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00003007 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003008 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Chris Lattner8402c732009-01-16 22:39:25 +00003010 // It is common for the tokens immediately after a // comment to be
3011 // whitespace (indentation for the next line). Instead of going through
3012 // the big switch, handle it efficiently now.
3013 goto SkipIgnoredUnits;
3014 }
3015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Chris Lattner8402c732009-01-16 22:39:25 +00003017 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003019 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003020 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003021 }
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattner8402c732009-01-16 22:39:25 +00003023 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003025 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003027 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 }
3029 break;
3030 case '%':
3031 Char = getCharAndSize(CurPtr, SizeTmp);
3032 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003033 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003035 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003036 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003038 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3040 Char = getCharAndSize(CurPtr, SizeTmp);
3041 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003042 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3044 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003045 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003046 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003047 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003048 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003049 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003050 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 // We parsed a # character. If this occurs at the start of the line,
3052 // it's actually the start of a preprocessing directive. Callback to
3053 // the preprocessor to handle it.
3054 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003055 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3056 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Chris Lattnere91e9322009-03-18 20:58:27 +00003058 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003059 }
3060 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003061 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 }
3063 break;
3064 case '<':
3065 Char = getCharAndSize(CurPtr, SizeTmp);
3066 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003067 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003069 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3070 if (After == '=') {
3071 Kind = tok::lesslessequal;
3072 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3073 SizeTmp2, Result);
3074 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3075 // If this is actually a '<<<<<<<' version control conflict marker,
3076 // recognize it as such and recover nicely.
3077 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003078 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3079 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3080 // ignore it.
3081 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003082 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003083 Kind = tok::lesslessless;
3084 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3085 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003086 } else {
3087 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3088 Kind = tok::lessless;
3089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003090 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003091 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003092 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003093 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3094 if (LangOpts.CPlusPlus0x &&
Richard Smith87a1e192011-04-14 18:36:27 +00003095 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3096 // C++0x [lex.pptoken]p3:
3097 // Otherwise, if the next three characters are <:: and the subsequent
3098 // character is neither : nor >, the < is treated as a preprocessor
3099 // token by itself and not as the first character of the alternative
3100 // token <:.
3101 unsigned SizeTmp3;
3102 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3103 if (After != ':' && After != '>') {
3104 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003105 if (!isLexingRawMode())
3106 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003107 break;
3108 }
3109 }
3110
Reid Spencer5f016e22007-07-11 17:01:13 +00003111 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003112 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003113 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003114 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003115 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003116 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003117 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 }
3119 break;
3120 case '>':
3121 Char = getCharAndSize(CurPtr, SizeTmp);
3122 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003123 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003124 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003125 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003126 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3127 if (After == '=') {
3128 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3129 SizeTmp2, Result);
3130 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003131 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3132 // If this is actually a '>>>>' conflict marker, recognize it as such
3133 // and recover nicely.
3134 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003135 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3136 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3137 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003138 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003139 Kind = tok::greatergreatergreater;
3140 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3141 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003142 } else {
3143 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3144 Kind = tok::greatergreater;
3145 }
3146
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003148 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 }
3150 break;
3151 case '^':
3152 Char = getCharAndSize(CurPtr, SizeTmp);
3153 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003154 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003155 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003156 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003157 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 }
3159 break;
3160 case '|':
3161 Char = getCharAndSize(CurPtr, SizeTmp);
3162 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003163 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003164 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3165 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003166 // If this is '|||||||' and we're in a conflict marker, ignore it.
3167 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3168 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003169 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003170 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3171 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003172 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003173 }
3174 break;
3175 case ':':
3176 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003177 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003178 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003180 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003181 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003182 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003183 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003184 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 }
3186 break;
3187 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003188 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 break;
3190 case '=':
3191 Char = getCharAndSize(CurPtr, SizeTmp);
3192 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003193 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003194 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3195 goto LexNextToken;
3196
Chris Lattner9e6293d2008-10-12 04:51:35 +00003197 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003199 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003200 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003201 }
3202 break;
3203 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003204 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003205 break;
3206 case '#':
3207 Char = getCharAndSize(CurPtr, SizeTmp);
3208 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003209 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003211 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003212 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003213 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003214 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3216 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003217 // We parsed a # character. If this occurs at the start of the line,
3218 // it's actually the start of a preprocessing directive. Callback to
3219 // the preprocessor to handle it.
3220 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003221 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3222 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Chris Lattnere91e9322009-03-18 20:58:27 +00003224 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003225 }
3226 break;
3227
Chris Lattner3a570772008-01-03 17:58:54 +00003228 case '@':
3229 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003230 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003231 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003232 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003233 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003234 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Reid Spencer5f016e22007-07-11 17:01:13 +00003236 case '\\':
3237 // FIXME: UCN's.
3238 // FALL THROUGH.
3239 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003240 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003241 break;
3242 }
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Reid Spencer5f016e22007-07-11 17:01:13 +00003244 // Notify MIOpt that we read a non-whitespace/non-comment token.
3245 MIOpt.ReadToken();
3246
3247 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003248 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003249 return;
3250
3251HandleDirective:
3252 // We parsed a # character and it's the start of a preprocessing directive.
3253
3254 FormTokenWithChars(Result, CurPtr, tok::hash);
3255 PP->HandleDirective(Result);
3256
3257 // As an optimization, if the preprocessor didn't switch lexers, tail
3258 // recurse.
3259 if (PP->isCurrentLexer(this)) {
3260 // Start a new token. If this is a #include or something, the PP may
3261 // want us starting at the beginning of the line again. If so, set
3262 // the StartOfLine flag and clear LeadingSpace.
3263 if (IsAtStartOfLine) {
3264 Result.setFlag(Token::StartOfLine);
3265 Result.clearFlag(Token::LeadingSpace);
3266 IsAtStartOfLine = false;
3267 }
3268 goto LexNextToken; // GCC isn't tail call eliminating.
3269 }
3270 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003271}