blob: 967359f2616af679f5f3026874c86acacc683af9 [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)),
120 Features(PP.getLangOptions()) {
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
Chris Lattner590f0cc2008-10-12 01:15:46 +0000130/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
131/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000132Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000133 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000134 : FileLoc(fileloc), Features(features) {
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
143/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
144/// 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,
146 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000147 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000148
Mike Stump1eb44332009-09-09 15:08:12 +0000149 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner025c3a62009-01-17 07:35:14 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
154}
155
Chris Lattner42e00d12009-01-17 08:27:52 +0000156/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
157/// _Pragma expansion. This has a variety of magic semantics that this method
158/// sets up. It returns a new'd Lexer that must be delete'd when done.
159///
160/// On entrance to this routine, TokStartLoc is a macro location which has a
161/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000162/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000163/// "expanded from".
164///
165/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
166/// normal lexer that remaps tokens as they fly by. This would require making
167/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
168/// interface that could handle this stuff. This would pull GetMappedTokenLoc
169/// out of the critical path of the lexer!
170///
Mike Stump1eb44332009-09-09 15:08:12 +0000171Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000172 SourceLocation ExpansionLocStart,
173 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000174 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000175 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000176
177 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000178 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000179 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
180 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner42e00d12009-01-17 08:27:52 +0000182 // Now that the lexer is created, change the start/end locations so that we
183 // just lex the subsection of the file that we want. This is lexing from a
184 // scratch buffer.
185 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner42e00d12009-01-17 08:27:52 +0000187 L->BufferPtr = StrData;
188 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000189 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000190
191 // Set the SourceLocation with the remapping information. This ensures that
192 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000193 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
194 ExpansionLocStart,
195 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000198 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner42e00d12009-01-17 08:27:52 +0000201 // This lexer really is for _Pragma.
202 L->Is_PragmaLexer = true;
203 return L;
204}
205
Chris Lattner168ae2d2007-10-17 20:41:00 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207/// Stringify - Convert the specified string into a C string, with surrounding
208/// ""'s, and with escaped \ and " characters.
209std::string Lexer::Stringify(const std::string &Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
215 ++i; ++e;
216 }
217 }
218 return Result;
219}
220
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221/// Stringify - Convert the specified string into a C string by escaping '\'
222/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000223void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
230}
231
Chris Lattnerb0607272010-11-17 07:26:20 +0000232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
236/// getSpelling() - Return the 'spelling' of this token. The spelling of a
237/// token are the characters used to represent the token in the source file
238/// after trigraph expansion and escaped-newline folding. In particular, this
239/// wants to get the true, uncanonicalized, spelling of things like digraphs
240/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000241StringRef Lexer::getSpelling(SourceLocation loc,
242 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000243 const SourceManager &SM,
244 const LangOptions &options,
245 bool *invalid) {
246 // Break down the source location.
247 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
248
249 // Try to the load the file buffer.
250 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000251 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000252 if (invalidTemp) {
253 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000254 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000255 }
256
257 const char *tokenBegin = file.data() + locInfo.second;
258
259 // Lex from the start of the given location.
260 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
261 file.begin(), tokenBegin, file.end());
262 Token token;
263 lexer.LexFromRawLexer(token);
264
265 unsigned length = token.getLength();
266
267 // Common case: no need for cleaning.
268 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000269 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000270
271 // Hard case, we need to relex the characters into the string.
272 buffer.clear();
273 buffer.reserve(length);
274
275 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
276 unsigned charSize;
277 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
278 ti += charSize;
279 }
280
Chris Lattner5f9e2722011-07-23 10:55:15 +0000281 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000282}
283
284/// getSpelling() - Return the 'spelling' of this token. The spelling of a
285/// token are the characters used to represent the token in the source file
286/// after trigraph expansion and escaped-newline folding. In particular, this
287/// wants to get the true, uncanonicalized, spelling of things like digraphs
288/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000289std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
290 const LangOptions &Features, bool *Invalid) {
291 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
292
293 // If this token contains nothing interesting, return it directly.
294 bool CharDataInvalid = false;
295 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
296 &CharDataInvalid);
297 if (Invalid)
298 *Invalid = CharDataInvalid;
299 if (CharDataInvalid)
300 return std::string();
301
302 if (!Tok.needsCleaning())
303 return std::string(TokStart, TokStart+Tok.getLength());
304
305 std::string Result;
306 Result.reserve(Tok.getLength());
307
308 // Otherwise, hard case, relex the characters into the string.
309 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
310 Ptr != End; ) {
311 unsigned CharSize;
312 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
313 Ptr += CharSize;
314 }
315 assert(Result.size() != unsigned(Tok.getLength()) &&
316 "NeedsCleaning flag set on something that didn't need cleaning!");
317 return Result;
318}
319
320/// getSpelling - This method is used to get the spelling of a token into a
321/// preallocated buffer, instead of as an std::string. The caller is required
322/// to allocate enough space for the token, which is guaranteed to be at least
323/// Tok.getLength() bytes long. The actual length of the token is returned.
324///
325/// Note that this method may do two possible things: it may either fill in
326/// the buffer specified with characters, or it may *change the input pointer*
327/// to point to a constant buffer with the data already in it (avoiding a
328/// copy). The caller is not allowed to modify the returned buffer pointer
329/// if an internal buffer is returned.
330unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
331 const SourceManager &SourceMgr,
332 const LangOptions &Features, bool *Invalid) {
333 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000334
335 const char *TokStart = 0;
336 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
337 if (Tok.is(tok::raw_identifier))
338 TokStart = Tok.getRawIdentifierData();
339 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
340 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000341 Buffer = II->getNameStart();
342 return II->getLength();
343 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000344
345 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (Tok.isLiteral())
347 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000348
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000350 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000351 bool CharDataInvalid = false;
352 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
353 if (Invalid)
354 *Invalid = CharDataInvalid;
355 if (CharDataInvalid) {
356 Buffer = "";
357 return 0;
358 }
359 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000360
Chris Lattnerb0607272010-11-17 07:26:20 +0000361 // If this token contains nothing interesting, return it directly.
362 if (!Tok.needsCleaning()) {
363 Buffer = TokStart;
364 return Tok.getLength();
365 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000366
Chris Lattnerb0607272010-11-17 07:26:20 +0000367 // Otherwise, hard case, relex the characters into the string.
368 char *OutBuf = const_cast<char*>(Buffer);
369 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
370 Ptr != End; ) {
371 unsigned CharSize;
372 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
373 Ptr += CharSize;
374 }
375 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
376 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000377
Chris Lattnerb0607272010-11-17 07:26:20 +0000378 return OutBuf-Buffer;
379}
380
381
382
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000383static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
Chris Lattner9a611942007-10-17 21:18:47 +0000385/// MeasureTokenLength - Relex the token at the specified location and return
386/// its length in bytes in the input file. If the token needs cleaning (e.g.
387/// includes a trigraph or an escaped newline) then this count includes bytes
388/// that are part of that.
389unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000390 const SourceManager &SM,
391 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000392 // TODO: this could be special cased for common tokens like identifiers, ')',
393 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000394 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000395 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
396 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000397
398 // If this comes from a macro expansion, we really do want the macro name, not
399 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000400 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000401 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000402 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000403 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000404 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000405 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000406
407 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000408
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000409 if (isWhitespace(StrData[0]))
410 return 0;
411
Chris Lattner9a611942007-10-17 21:18:47 +0000412 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000413 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
414 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000415 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000416 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000417 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000418 return TheTok.getLength();
419}
420
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000421static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
422 const SourceManager &SM,
423 const LangOptions &LangOpts) {
424 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000425 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000426 if (LocInfo.first.isInvalid())
427 return Loc;
428
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000429 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000431 if (Invalid)
432 return Loc;
433
434 // Back up from the current location until we hit the beginning of a line
435 // (or the buffer). We'll relex from that point.
436 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000437 if (LocInfo.second >= Buffer.size())
438 return Loc;
439
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000440 const char *StrData = BufStart+LocInfo.second;
441 if (StrData[0] == '\n' || StrData[0] == '\r')
442 return Loc;
443
444 const char *LexStart = StrData;
445 while (LexStart != BufStart) {
446 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
447 ++LexStart;
448 break;
449 }
450
451 --LexStart;
452 }
453
454 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000455 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000456 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
457 TheLexer.SetCommentRetentionState(true);
458
459 // Lex tokens until we find the token that contains the source location.
460 Token TheTok;
461 do {
462 TheLexer.LexFromRawLexer(TheTok);
463
464 if (TheLexer.getBufferLocation() > StrData) {
465 // Lexing this token has taken the lexer past the source location we're
466 // looking for. If the current token encompasses our source location,
467 // return the beginning of that token.
468 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
469 return TheTok.getLocation();
470
471 // We ended up skipping over the source location entirely, which means
472 // that it points into whitespace. We're done here.
473 break;
474 }
475 } while (TheTok.getKind() != tok::eof);
476
477 // We've passed our source location; just return the original source location.
478 return Loc;
479}
480
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000481SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
482 const SourceManager &SM,
483 const LangOptions &LangOpts) {
484 if (Loc.isFileID())
485 return getBeginningOfFileToken(Loc, SM, LangOpts);
486
487 if (!SM.isMacroArgExpansion(Loc))
488 return Loc;
489
490 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
491 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
492 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000493 std::pair<FileID, unsigned> BeginFileLocInfo
494 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000495 assert(FileLocInfo.first == BeginFileLocInfo.first &&
496 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000497 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000498}
499
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000500namespace {
501 enum PreambleDirectiveKind {
502 PDK_Skipped,
503 PDK_StartIf,
504 PDK_EndIf,
505 PDK_Unknown
506 };
507}
508
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000509std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000510Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
511 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000512 // Create a lexer starting at the beginning of the file. Note that we use a
513 // "fake" file source location at offset 1 so that the lexer will track our
514 // position within the file.
515 const unsigned StartOffset = 1;
516 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000517 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000518 Buffer->getBufferStart(), Buffer->getBufferEnd());
519
520 bool InPreprocessorDirective = false;
521 Token TheTok;
522 Token IfStartTok;
523 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000524
525 unsigned MaxLineOffset = 0;
526 if (MaxLines) {
527 const char *CurPtr = Buffer->getBufferStart();
528 unsigned CurLine = 0;
529 while (CurPtr != Buffer->getBufferEnd()) {
530 char ch = *CurPtr++;
531 if (ch == '\n') {
532 ++CurLine;
533 if (CurLine == MaxLines)
534 break;
535 }
536 }
537 if (CurPtr != Buffer->getBufferEnd())
538 MaxLineOffset = CurPtr - Buffer->getBufferStart();
539 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000540
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000541 do {
542 TheLexer.LexFromRawLexer(TheTok);
543
544 if (InPreprocessorDirective) {
545 // If we've hit the end of the file, we're done.
546 if (TheTok.getKind() == tok::eof) {
547 InPreprocessorDirective = false;
548 break;
549 }
550
551 // If we haven't hit the end of the preprocessor directive, skip this
552 // token.
553 if (!TheTok.isAtStartOfLine())
554 continue;
555
556 // We've passed the end of the preprocessor directive, and will look
557 // at this token again below.
558 InPreprocessorDirective = false;
559 }
560
Douglas Gregordf95a132010-08-09 20:45:32 +0000561 // Keep track of the # of lines in the preamble.
562 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000563 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000564
565 // If we were asked to limit the number of lines in the preamble,
566 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000567 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000568 break;
569 }
570
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000571 // Comments are okay; skip over them.
572 if (TheTok.getKind() == tok::comment)
573 continue;
574
575 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
576 // This is the start of a preprocessor directive.
577 Token HashTok = TheTok;
578 InPreprocessorDirective = true;
579
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000580 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000581 // we don't have an identifier table available. Instead, just look at
582 // the raw identifier to recognize and categorize preprocessor directives.
583 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000584 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000586 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000587 PreambleDirectiveKind PDK
588 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
589 .Case("include", PDK_Skipped)
590 .Case("__include_macros", PDK_Skipped)
591 .Case("define", PDK_Skipped)
592 .Case("undef", PDK_Skipped)
593 .Case("line", PDK_Skipped)
594 .Case("error", PDK_Skipped)
595 .Case("pragma", PDK_Skipped)
596 .Case("import", PDK_Skipped)
597 .Case("include_next", PDK_Skipped)
598 .Case("warning", PDK_Skipped)
599 .Case("ident", PDK_Skipped)
600 .Case("sccs", PDK_Skipped)
601 .Case("assert", PDK_Skipped)
602 .Case("unassert", PDK_Skipped)
603 .Case("if", PDK_StartIf)
604 .Case("ifdef", PDK_StartIf)
605 .Case("ifndef", PDK_StartIf)
606 .Case("elif", PDK_Skipped)
607 .Case("else", PDK_Skipped)
608 .Case("endif", PDK_EndIf)
609 .Default(PDK_Unknown);
610
611 switch (PDK) {
612 case PDK_Skipped:
613 continue;
614
615 case PDK_StartIf:
616 if (IfCount == 0)
617 IfStartTok = HashTok;
618
619 ++IfCount;
620 continue;
621
622 case PDK_EndIf:
623 // Mismatched #endif. The preamble ends here.
624 if (IfCount == 0)
625 break;
626
627 --IfCount;
628 continue;
629
630 case PDK_Unknown:
631 // We don't know what this directive is; stop at the '#'.
632 break;
633 }
634 }
635
636 // We only end up here if we didn't recognize the preprocessor
637 // directive or it was one that can't occur in the preamble at this
638 // point. Roll back the current token to the location of the '#'.
639 InPreprocessorDirective = false;
640 TheTok = HashTok;
641 }
642
Douglas Gregordf95a132010-08-09 20:45:32 +0000643 // We hit a token that we don't recognize as being in the
644 // "preprocessing only" part of the file, so we're no longer in
645 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000646 break;
647 } while (true);
648
649 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000650 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
651 IfCount? IfStartTok.isAtStartOfLine()
652 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000653}
654
Chris Lattner7ef5c272010-11-17 07:05:50 +0000655
656/// AdvanceToTokenCharacter - Given a location that specifies the start of a
657/// token, return a new location that specifies a character within the token.
658SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
659 unsigned CharNo,
660 const SourceManager &SM,
661 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000662 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000663 // character is. This needs to take into consideration newlines and
664 // trigraphs.
665 bool Invalid = false;
666 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
667
668 // If they request the first char of the token, we're trivially done.
669 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
670 return TokStart;
671
672 unsigned PhysOffset = 0;
673
674 // The usual case is that tokens don't contain anything interesting. Skip
675 // over the uninteresting characters. If a token only consists of simple
676 // chars, this method is extremely fast.
677 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
678 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000679 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000680 ++TokPtr, --CharNo, ++PhysOffset;
681 }
682
683 // If we have a character that may be a trigraph or escaped newline, use a
684 // lexer to parse it correctly.
685 for (; CharNo; --CharNo) {
686 unsigned Size;
687 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
688 TokPtr += Size;
689 PhysOffset += Size;
690 }
691
692 // Final detail: if we end up on an escaped newline, we want to return the
693 // location of the actual byte of the token. For example foo\<newline>bar
694 // advanced by 3 should return the location of b, not of \\. One compounding
695 // detail of this is that the escape may be made by a trigraph.
696 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
697 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
698
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000699 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000700}
701
702/// \brief Computes the source location just past the end of the
703/// token at this source location.
704///
705/// This routine can be used to produce a source location that
706/// points just past the end of the token referenced by \p Loc, and
707/// is generally used when a diagnostic needs to point just after a
708/// token where it expected something different that it received. If
709/// the returned source location would not be meaningful (e.g., if
710/// it points into a macro), this routine returns an invalid
711/// source location.
712///
713/// \param Offset an offset from the end of the token, where the source
714/// location should refer to. The default offset (0) produces a source
715/// location pointing just past the end of the token; an offset of 1 produces
716/// a source location pointing to the last character in the token, etc.
717SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
718 const SourceManager &SM,
719 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000720 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000721 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000722
723 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000724 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000725 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000726 }
727
Chris Lattner7ef5c272010-11-17 07:05:50 +0000728 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
729 if (Len > Offset)
730 Len = Len - Offset;
731 else
732 return Loc;
733
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000734 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000735}
736
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000737/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000738/// token of the macro expansion.
739bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000740 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000741 const LangOptions &LangOpts,
742 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000743 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
744
745 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
746 // FIXME: If the token comes from the macro token paste operator ('##')
747 // this function will always return false;
748 if (infoLoc.second > 0)
749 return false; // Does not point at the start of token.
750
Chandler Carruth433db062011-07-14 08:20:40 +0000751 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000752 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000753 if (expansionLoc.isFileID()) {
754 // No other macro expansions, this is the first.
755 if (MacroBegin)
756 *MacroBegin = expansionLoc;
757 return true;
758 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000759
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000760 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000761}
762
763/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000764/// token of the macro expansion.
765bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000766 const SourceManager &SM,
767 const LangOptions &LangOpts,
768 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000769 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
770
771 SourceLocation spellLoc = SM.getSpellingLoc(loc);
772 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
773 if (tokLen == 0)
774 return false;
775
776 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000777 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000778 if (SM.isInFileID(afterLoc, FID))
779 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000780
781 // FIXME: If the token comes from the macro token paste operator ('##')
782 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000783
Chandler Carruth433db062011-07-14 08:20:40 +0000784 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000785 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000786 if (expansionLoc.isFileID()) {
787 // No other macro expansions.
788 if (MacroEnd)
789 *MacroEnd = expansionLoc;
790 return true;
791 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000792
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000793 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000794}
795
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000796static CharSourceRange makeRangeFromFileLocs(SourceLocation Begin,
797 SourceLocation End,
798 const SourceManager &SM,
799 const LangOptions &LangOpts) {
800 assert(Begin.isFileID() && End.isFileID());
801 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
802 if (End.isInvalid())
803 return CharSourceRange();
804
805 // Break down the source locations.
806 FileID FID;
807 unsigned BeginOffs;
808 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
809 if (FID.isInvalid())
810 return CharSourceRange();
811
812 unsigned EndOffs;
813 if (!SM.isInFileID(End, FID, &EndOffs) ||
814 BeginOffs > EndOffs)
815 return CharSourceRange();
816
817 return CharSourceRange::getCharRange(Begin, End);
818}
819
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000820/// \brief Accepts a token source range and returns a character range with
821/// file locations.
822/// Returns a null range if a part of the range resides inside a macro
823/// expansion or the range does not reside on the same FileID.
824CharSourceRange Lexer::makeFileCharRange(SourceRange TokenRange,
825 const SourceManager &SM,
826 const LangOptions &LangOpts) {
827 SourceLocation Begin = TokenRange.getBegin();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000828 SourceLocation End = TokenRange.getEnd();
829 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000830 return CharSourceRange();
831
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000832 if (Begin.isFileID() && End.isFileID())
833 return makeRangeFromFileLocs(Begin, End, SM, LangOpts);
834
835 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000836 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
837 return CharSourceRange();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000838 return makeRangeFromFileLocs(Begin, End, SM, LangOpts);
839 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000840
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000841 if (Begin.isFileID() && End.isMacroID()) {
842 if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
843 return CharSourceRange();
844 return makeRangeFromFileLocs(Begin, End, SM, LangOpts);
845 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000846
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000847 assert(Begin.isMacroID() && End.isMacroID());
848 SourceLocation MacroBegin, MacroEnd;
849 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
850 isAtEndOfMacroExpansion(End, SM, LangOpts, &MacroEnd))
851 return makeRangeFromFileLocs(MacroBegin, MacroEnd, SM, LangOpts);
852
853 FileID FID;
854 unsigned BeginOffs;
855 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
856 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000857 return CharSourceRange();
858
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000859 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000860 if (!SM.isInFileID(End, FID, &EndOffs) ||
861 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000862 return CharSourceRange();
863
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000864 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
865 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
866 if (Expansion.isMacroArgExpansion() &&
867 Expansion.getSpellingLoc().isFileID()) {
868 SourceLocation SpellLoc = Expansion.getSpellingLoc();
869 return makeRangeFromFileLocs(SpellLoc.getLocWithOffset(BeginOffs),
870 SpellLoc.getLocWithOffset(EndOffs),
871 SM, LangOpts);
872 }
873
874 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000875}
876
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000877StringRef Lexer::getSourceText(CharSourceRange Range,
878 const SourceManager &SM,
879 const LangOptions &LangOpts,
880 bool *Invalid) {
881 if (Range.isTokenRange())
882 Range = makeFileCharRange(Range.getAsRange(), SM, LangOpts);
883
884 if (Range.isInvalid() ||
885 Range.getBegin().isMacroID() || Range.getEnd().isMacroID()) {
886 if (Invalid) *Invalid = true;
887 return StringRef();
888 }
889
890 // Break down the source location.
891 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
892 if (beginInfo.first.isInvalid()) {
893 if (Invalid) *Invalid = true;
894 return StringRef();
895 }
896
897 unsigned EndOffs;
898 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
899 beginInfo.second > EndOffs) {
900 if (Invalid) *Invalid = true;
901 return StringRef();
902 }
903
904 // Try to the load the file buffer.
905 bool invalidTemp = false;
906 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
907 if (invalidTemp) {
908 if (Invalid) *Invalid = true;
909 return StringRef();
910 }
911
912 if (Invalid) *Invalid = false;
913 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
914}
915
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000916StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
917 const SourceManager &SM,
918 const LangOptions &LangOpts) {
919 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
920 // Walk past macro argument expanions.
921 while (SM.isMacroArgExpansion(Loc))
922 Loc = SM.getImmediateExpansionRange(Loc).first;
923
924 // Find the spelling location of the start of the non-argument expansion
925 // range. This is where the macro name was spelled in order to begin
926 // expanding this macro.
927 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
928
929 // Dig out the buffer where the macro name was spelled and the extents of the
930 // name so that we can render it into the expansion note.
931 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
932 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
933 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
934 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
935}
936
Reid Spencer5f016e22007-07-11 17:01:13 +0000937//===----------------------------------------------------------------------===//
938// Character information.
939//===----------------------------------------------------------------------===//
940
Reid Spencer5f016e22007-07-11 17:01:13 +0000941enum {
942 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
943 CHAR_VERT_WS = 0x02, // '\r', '\n'
944 CHAR_LETTER = 0x04, // a-z,A-Z
945 CHAR_NUMBER = 0x08, // 0-9
946 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000947 CHAR_PERIOD = 0x20, // .
948 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000949};
950
Chris Lattner03b98662009-07-07 17:09:54 +0000951// Statically initialize CharInfo table based on ASCII character set
952// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000953static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000954{
955// 0 NUL 1 SOH 2 STX 3 ETX
956// 4 EOT 5 ENQ 6 ACK 7 BEL
957 0 , 0 , 0 , 0 ,
958 0 , 0 , 0 , 0 ,
959// 8 BS 9 HT 10 NL 11 VT
960//12 NP 13 CR 14 SO 15 SI
961 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
962 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
963//16 DLE 17 DC1 18 DC2 19 DC3
964//20 DC4 21 NAK 22 SYN 23 ETB
965 0 , 0 , 0 , 0 ,
966 0 , 0 , 0 , 0 ,
967//24 CAN 25 EM 26 SUB 27 ESC
968//28 FS 29 GS 30 RS 31 US
969 0 , 0 , 0 , 0 ,
970 0 , 0 , 0 , 0 ,
971//32 SP 33 ! 34 " 35 #
972//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000973 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
974 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000975//40 ( 41 ) 42 * 43 +
976//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000977 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
978 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000979//48 0 49 1 50 2 51 3
980//52 4 53 5 54 6 55 7
981 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
982 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
983//56 8 57 9 58 : 59 ;
984//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000985 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
986 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000987//64 @ 65 A 66 B 67 C
988//68 D 69 E 70 F 71 G
989 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
990 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
991//72 H 73 I 74 J 75 K
992//76 L 77 M 78 N 79 O
993 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
994 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
995//80 P 81 Q 82 R 83 S
996//84 T 85 U 86 V 87 W
997 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
998 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
999//88 X 89 Y 90 Z 91 [
1000//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001001 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1002 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001003//96 ` 97 a 98 b 99 c
1004//100 d 101 e 102 f 103 g
1005 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1006 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1007//104 h 105 i 106 j 107 k
1008//108 l 109 m 110 n 111 o
1009 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1010 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1011//112 p 113 q 114 r 115 s
1012//116 t 117 u 118 v 119 w
1013 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1014 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1015//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001016//124 | 125 } 126 ~ 127 DEL
1017 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1018 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001019};
1020
Chris Lattnera2bf1052009-12-17 05:29:40 +00001021static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 static bool isInited = false;
1023 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001024 // check the statically-initialized CharInfo table
1025 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1026 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1027 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1028 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1029 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1030 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1031 assert(CHAR_UNDER == CharInfo[(int)'_']);
1032 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1033 for (unsigned i = 'a'; i <= 'z'; ++i) {
1034 assert(CHAR_LETTER == CharInfo[i]);
1035 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1036 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001038 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001039
Chris Lattner03b98662009-07-07 17:09:54 +00001040 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001041}
1042
Chris Lattner03b98662009-07-07 17:09:54 +00001043
Reid Spencer5f016e22007-07-11 17:01:13 +00001044/// isIdentifierBody - Return true if this is the body character of an
1045/// identifier, which is [a-zA-Z0-9_].
1046static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001047 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001048}
1049
1050/// isHorizontalWhitespace - Return true if this character is horizontal
1051/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
1052static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001053 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001054}
1055
Anna Zaksaca25bc2011-07-27 21:43:43 +00001056/// isVerticalWhitespace - Return true if this character is vertical
1057/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
1058static inline bool isVerticalWhitespace(unsigned char c) {
1059 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1060}
1061
Reid Spencer5f016e22007-07-11 17:01:13 +00001062/// isWhitespace - Return true if this character is horizontal or vertical
1063/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
1064/// for '\0'.
1065static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001066 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001067}
1068
1069/// isNumberBody - Return true if this is the body character of an
1070/// preprocessing number, which is [a-zA-Z0-9_.].
1071static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001072 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001073 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001074}
1075
Craig Topper2fa4e862011-08-11 04:06:15 +00001076/// isRawStringDelimBody - Return true if this is the body character of a
1077/// raw string delimiter.
1078static inline bool isRawStringDelimBody(unsigned char c) {
1079 return (CharInfo[c] &
1080 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1081 true : false;
1082}
1083
Reid Spencer5f016e22007-07-11 17:01:13 +00001084
1085//===----------------------------------------------------------------------===//
1086// Diagnostics forwarding code.
1087//===----------------------------------------------------------------------===//
1088
Chris Lattner409a0362007-07-22 18:38:25 +00001089/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001090/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001091/// This is currently only used for _Pragma implementation, so it is the slow
1092/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001093static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1094 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001095static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1096 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001097 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001098 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Chris Lattner409a0362007-07-22 18:38:25 +00001100 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001101 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001102 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001103 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chandler Carruth433db062011-07-14 08:20:40 +00001105 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001106 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001107 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001108 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Chris Lattnere7fb4842009-02-15 20:52:18 +00001110 // Figure out the expansion loc range, which is the range covered by the
1111 // original _Pragma(...) sequence.
1112 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001113 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Chandler Carruthbf340e42011-07-26 03:03:05 +00001115 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001116}
1117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118/// getSourceLocation - Return a source location identifier for the specified
1119/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001120SourceLocation Lexer::getSourceLocation(const char *Loc,
1121 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001122 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001124
1125 // In the normal case, we're just lexing from a simple file buffer, return
1126 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001127 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001128 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001129 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattner2b2453a2009-01-17 06:22:33 +00001131 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1132 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001133 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001134 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001135}
1136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137/// Diag - Forwarding function for diagnostics. This translate a source
1138/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001139DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001140 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001141}
Reid Spencer5f016e22007-07-11 17:01:13 +00001142
1143//===----------------------------------------------------------------------===//
1144// Trigraph and Escaped Newline Handling Code.
1145//===----------------------------------------------------------------------===//
1146
1147/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1148/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1149static char GetTrigraphCharForLetter(char Letter) {
1150 switch (Letter) {
1151 default: return 0;
1152 case '=': return '#';
1153 case ')': return ']';
1154 case '(': return '[';
1155 case '!': return '|';
1156 case '\'': return '^';
1157 case '>': return '}';
1158 case '/': return '\\';
1159 case '<': return '{';
1160 case '-': return '~';
1161 }
1162}
1163
1164/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1165/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1166/// return the result character. Finally, emit a warning about trigraph use
1167/// whether trigraphs are enabled or not.
1168static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1169 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001170 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Chris Lattner3692b092008-11-18 07:59:24 +00001172 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001173 if (!L->isLexingRawMode())
1174 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001175 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 }
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Chris Lattner74d15df2008-11-22 02:02:22 +00001178 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001179 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 return Res;
1181}
1182
Chris Lattner24f0e482009-04-18 22:05:41 +00001183/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1184/// 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 +00001185/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001186unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1187 unsigned Size = 0;
1188 while (isWhitespace(Ptr[Size])) {
1189 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattner24f0e482009-04-18 22:05:41 +00001191 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1192 continue;
1193
1194 // If this is a \r\n or \n\r, skip the other half.
1195 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1196 Ptr[Size-1] != Ptr[Size])
1197 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Chris Lattner24f0e482009-04-18 22:05:41 +00001199 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001200 }
1201
Chris Lattner24f0e482009-04-18 22:05:41 +00001202 // Not an escaped newline, must be a \t or something else.
1203 return 0;
1204}
1205
Chris Lattner03374952009-04-18 22:27:02 +00001206/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1207/// them), skip over them and return the first non-escaped-newline found,
1208/// otherwise return P.
1209const char *Lexer::SkipEscapedNewLines(const char *P) {
1210 while (1) {
1211 const char *AfterEscape;
1212 if (*P == '\\') {
1213 AfterEscape = P+1;
1214 } else if (*P == '?') {
1215 // If not a trigraph for escape, bail out.
1216 if (P[1] != '?' || P[2] != '/')
1217 return P;
1218 AfterEscape = P+3;
1219 } else {
1220 return P;
1221 }
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Chris Lattner03374952009-04-18 22:27:02 +00001223 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1224 if (NewLineSize == 0) return P;
1225 P = AfterEscape+NewLineSize;
1226 }
1227}
1228
Anna Zaksaca25bc2011-07-27 21:43:43 +00001229/// \brief Checks that the given token is the first token that occurs after the
1230/// given location (this excludes comments and whitespace). Returns the location
1231/// immediately after the specified token. If the token is not found or the
1232/// location is inside a macro, the returned source location will be invalid.
1233SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1234 tok::TokenKind TKind,
1235 const SourceManager &SM,
1236 const LangOptions &LangOpts,
1237 bool SkipTrailingWhitespaceAndNewLine) {
1238 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001239 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001240 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001241 }
1242 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1243
1244 // Break down the source location.
1245 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1246
1247 // Try to load the file buffer.
1248 bool InvalidTemp = false;
1249 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1250 if (InvalidTemp)
1251 return SourceLocation();
1252
1253 const char *TokenBegin = File.data() + LocInfo.second;
1254
1255 // Lex from the start of the given location.
1256 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1257 TokenBegin, File.end());
1258 // Find the token.
1259 Token Tok;
1260 lexer.LexFromRawLexer(Tok);
1261 if (Tok.isNot(TKind))
1262 return SourceLocation();
1263 SourceLocation TokenLoc = Tok.getLocation();
1264
1265 // Calculate how much whitespace needs to be skipped if any.
1266 unsigned NumWhitespaceChars = 0;
1267 if (SkipTrailingWhitespaceAndNewLine) {
1268 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1269 Tok.getLength();
1270 unsigned char C = *TokenEnd;
1271 while (isHorizontalWhitespace(C)) {
1272 C = *(++TokenEnd);
1273 NumWhitespaceChars++;
1274 }
1275 if (isVerticalWhitespace(C))
1276 NumWhitespaceChars++;
1277 }
1278
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001279 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001280}
Chris Lattner24f0e482009-04-18 22:05:41 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1283/// get its size, and return it. This is tricky in several cases:
1284/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1285/// then either return the trigraph (skipping 3 chars) or the '?',
1286/// depending on whether trigraphs are enabled or not.
1287/// 2. If this is an escaped newline (potentially with whitespace between
1288/// the backslash and newline), implicitly skip the newline and return
1289/// the char after it.
1290/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1291///
1292/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1293/// know that we can accumulate into Size, and that we have already incremented
1294/// Ptr by Size bytes.
1295///
1296/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1297/// be updated to match.
1298///
1299char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001300 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 // If we have a slash, look for an escaped newline.
1302 if (Ptr[0] == '\\') {
1303 ++Size;
1304 ++Ptr;
1305Slash:
1306 // Common case, backslash-char where the char is not whitespace.
1307 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Chris Lattner5636a3b2009-06-23 05:15:06 +00001309 // See if we have optional whitespace characters between the slash and
1310 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001311 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1312 // Remember that this token needs to be cleaned.
1313 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314
Chris Lattner24f0e482009-04-18 22:05:41 +00001315 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001316 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001317 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Chris Lattner24f0e482009-04-18 22:05:41 +00001319 // Found backslash<whitespace><newline>. Parse the char after it.
1320 Size += EscapedNewLineSize;
1321 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001322
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001323 // If the char that we finally got was a \n, then we must have had
1324 // something like \<newline><newline>. We don't want to consume the
1325 // second newline.
1326 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1327 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001328
Chris Lattner24f0e482009-04-18 22:05:41 +00001329 // Use slow version to accumulate a correct size field.
1330 return getCharAndSizeSlow(Ptr, Size, Tok);
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Reid Spencer5f016e22007-07-11 17:01:13 +00001333 // Otherwise, this is not an escaped newline, just return the slash.
1334 return '\\';
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // If this is a trigraph, process it.
1338 if (Ptr[0] == '?' && Ptr[1] == '?') {
1339 // If this is actually a legal trigraph (not something like "??x"), emit
1340 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1341 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1342 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001343 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
1345 Ptr += 3;
1346 Size += 3;
1347 if (C == '\\') goto Slash;
1348 return C;
1349 }
1350 }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // If this is neither, return a single character.
1353 ++Size;
1354 return *Ptr;
1355}
1356
1357
1358/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1359/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1360/// and that we have already incremented Ptr by Size bytes.
1361///
1362/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1363/// be updated to match.
1364char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1365 const LangOptions &Features) {
1366 // If we have a slash, look for an escaped newline.
1367 if (Ptr[0] == '\\') {
1368 ++Size;
1369 ++Ptr;
1370Slash:
1371 // Common case, backslash-char where the char is not whitespace.
1372 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001375 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1376 // Found backslash<whitespace><newline>. Parse the char after it.
1377 Size += EscapedNewLineSize;
1378 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001380 // If the char that we finally got was a \n, then we must have had
1381 // something like \<newline><newline>. We don't want to consume the
1382 // second newline.
1383 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1384 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001385
Chris Lattner24f0e482009-04-18 22:05:41 +00001386 // Use slow version to accumulate a correct size field.
1387 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 // Otherwise, this is not an escaped newline, just return the slash.
1391 return '\\';
1392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // If this is a trigraph, process it.
1395 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1396 // If this is actually a legal trigraph (not something like "??x"), return
1397 // it.
1398 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1399 Ptr += 3;
1400 Size += 3;
1401 if (C == '\\') goto Slash;
1402 return C;
1403 }
1404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 // If this is neither, return a single character.
1407 ++Size;
1408 return *Ptr;
1409}
1410
1411//===----------------------------------------------------------------------===//
1412// Helper methods for lexing.
1413//===----------------------------------------------------------------------===//
1414
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001415/// \brief Routine that indiscriminately skips bytes in the source file.
1416void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1417 BufferPtr += Bytes;
1418 if (BufferPtr > BufferEnd)
1419 BufferPtr = BufferEnd;
1420 IsAtStartOfLine = StartOfLine;
1421}
1422
Chris Lattnerd2177732007-07-20 16:59:19 +00001423void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1425 unsigned Size;
1426 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001427 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001429
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 --CurPtr; // Back up over the skipped character.
1431
1432 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1433 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1434 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001435 //
1436 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1437 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1439FinishIdentifier:
1440 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001441 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1442 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // If we are in raw mode, return this identifier raw. There is no need to
1445 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001446 if (LexingRawMode)
1447 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001449 // Fill in Result.IdentifierInfo and update the token kind,
1450 // looking up the identifier in the identifier table.
1451 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 // Finally, now that we know we have an identifier, pass this off to the
1454 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001455 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001456 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001457
Chris Lattner6a170eb2009-01-21 07:43:11 +00001458 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 }
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 C = getCharAndSize(CurPtr, Size);
1464 while (1) {
1465 if (C == '$') {
1466 // If we hit a $ and they are not supported in identifiers, we are done.
1467 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001470 if (!isLexingRawMode())
1471 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 CurPtr = ConsumeChar(CurPtr, Size, Result);
1473 C = getCharAndSize(CurPtr, Size);
1474 continue;
1475 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1476 // Found end of identifier.
1477 goto FinishIdentifier;
1478 }
1479
1480 // Otherwise, this character is good, consume it.
1481 CurPtr = ConsumeChar(CurPtr, Size, Result);
1482
1483 C = getCharAndSize(CurPtr, Size);
1484 while (isIdentifierBody(C)) { // FIXME: UCNs.
1485 CurPtr = ConsumeChar(CurPtr, Size, Result);
1486 C = getCharAndSize(CurPtr, Size);
1487 }
1488 }
1489}
1490
Douglas Gregora75ec432010-08-30 14:50:47 +00001491/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001492/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001493static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1494 unsigned Size;
1495 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1496 if (C1 != '0')
1497 return false;
1498 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1499 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001500}
Reid Spencer5f016e22007-07-11 17:01:13 +00001501
Nate Begeman5253c7f2008-04-14 02:26:39 +00001502/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001503/// constant. From[-1] is the first character lexed. Return the end of the
1504/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001505void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 unsigned Size;
1507 char C = getCharAndSize(CurPtr, Size);
1508 char PrevCh = 0;
1509 while (isNumberBody(C)) { // FIXME: UCNs?
1510 CurPtr = ConsumeChar(CurPtr, Size, Result);
1511 PrevCh = C;
1512 C = getCharAndSize(CurPtr, Size);
1513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001516 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1517 // If we are in Microsoft mode, don't continue if the constant is hex.
1518 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Francois Pichet62ec1f22011-09-17 17:15:52 +00001519 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001520 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001522
1523 // If we have a hex FP constant, continue.
Douglas Gregor46717302011-10-12 18:51:02 +00001524 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001528 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001529 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001530 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001531}
1532
1533/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001534/// either " or L" or u8" or u" or U".
1535void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1536 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Richard Smith661a9962011-10-15 01:18:56 +00001539 if (!isLexingRawMode() &&
1540 (Kind == tok::utf8_string_literal ||
1541 Kind == tok::utf16_string_literal ||
1542 Kind == tok::utf32_string_literal))
1543 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 char C = getAndAdvanceChar(CurPtr, Result);
1546 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001547 // Skip escaped characters. Escaped newlines will already be processed by
1548 // getAndAdvanceChar.
1549 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001551
Chris Lattner571339c2010-05-30 23:27:38 +00001552 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001553 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001554 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001555 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001556 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 }
Chris Lattner571339c2010-05-30 23:27:38 +00001559
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001560 if (C == 0) {
1561 if (isCodeCompletionPoint(CurPtr-1)) {
1562 PP->CodeCompleteNaturalLanguage();
1563 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1564 return cutOffLexing();
1565 }
1566
Chris Lattner571339c2010-05-30 23:27:38 +00001567 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001568 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 C = getAndAdvanceChar(CurPtr, Result);
1570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001573 if (NulCharacter && !isLexingRawMode())
1574 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001577 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001578 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001579 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580}
1581
Craig Topper2fa4e862011-08-11 04:06:15 +00001582/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1583/// having lexed R", LR", u8R", uR", or UR".
1584void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1585 tok::TokenKind Kind) {
1586 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1587 // Between the initial and final double quote characters of the raw string,
1588 // any transformations performed in phases 1 and 2 (trigraphs,
1589 // universal-character-names, and line splicing) are reverted.
1590
Richard Smith661a9962011-10-15 01:18:56 +00001591 if (!isLexingRawMode())
1592 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1593
Craig Topper2fa4e862011-08-11 04:06:15 +00001594 unsigned PrefixLen = 0;
1595
1596 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1597 ++PrefixLen;
1598
1599 // If the last character was not a '(', then we didn't lex a valid delimiter.
1600 if (CurPtr[PrefixLen] != '(') {
1601 if (!isLexingRawMode()) {
1602 const char *PrefixEnd = &CurPtr[PrefixLen];
1603 if (PrefixLen == 16) {
1604 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1605 } else {
1606 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1607 << StringRef(PrefixEnd, 1);
1608 }
1609 }
1610
1611 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1612 // it's possible the '"' was intended to be part of the raw string, but
1613 // there's not much we can do about that.
1614 while (1) {
1615 char C = *CurPtr++;
1616
1617 if (C == '"')
1618 break;
1619 if (C == 0 && CurPtr-1 == BufferEnd) {
1620 --CurPtr;
1621 break;
1622 }
1623 }
1624
1625 FormTokenWithChars(Result, CurPtr, tok::unknown);
1626 return;
1627 }
1628
1629 // Save prefix and move CurPtr past it
1630 const char *Prefix = CurPtr;
1631 CurPtr += PrefixLen + 1; // skip over prefix and '('
1632
1633 while (1) {
1634 char C = *CurPtr++;
1635
1636 if (C == ')') {
1637 // Check for prefix match and closing quote.
1638 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1639 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1640 break;
1641 }
1642 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1643 if (!isLexingRawMode())
1644 Diag(BufferPtr, diag::err_unterminated_raw_string)
1645 << StringRef(Prefix, PrefixLen);
1646 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1647 return;
1648 }
1649 }
1650
1651 // Update the location of token as well as BufferPtr.
1652 const char *TokStart = BufferPtr;
1653 FormTokenWithChars(Result, CurPtr, Kind);
1654 Result.setLiteralData(TokStart);
1655}
1656
Reid Spencer5f016e22007-07-11 17:01:13 +00001657/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1658/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001659void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001661 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 char C = getAndAdvanceChar(CurPtr, Result);
1663 while (C != '>') {
1664 // Skip escaped characters.
1665 if (C == '\\') {
1666 // Skip the escaped character.
1667 C = getAndAdvanceChar(CurPtr, Result);
1668 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001669 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1670 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001671 // If the filename is unterminated, then it must just be a lone <
1672 // character. Return this as such.
1673 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 return;
1675 } else if (C == 0) {
1676 NulCharacter = CurPtr-1;
1677 }
1678 C = getAndAdvanceChar(CurPtr, Result);
1679 }
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001682 if (NulCharacter && !isLexingRawMode())
1683 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001686 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001687 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001688 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689}
1690
1691
1692/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001693/// lexed either ' or L' or u' or U'.
1694void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1695 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 const char *NulCharacter = 0; // Does this character contain the \0 character?
1697
Richard Smith661a9962011-10-15 01:18:56 +00001698 if (!isLexingRawMode() &&
1699 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1700 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 char C = getAndAdvanceChar(CurPtr, Result);
1703 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001704 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001705 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001706 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001708 }
1709
1710 while (C != '\'') {
1711 // Skip escaped characters.
1712 if (C == '\\') {
1713 // Skip the escaped character.
1714 // FIXME: UCN's
1715 C = getAndAdvanceChar(CurPtr, Result);
1716 } else if (C == '\n' || C == '\r' || // Newline.
1717 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001718 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001719 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001720 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1721 return;
1722 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001723 if (isCodeCompletionPoint(CurPtr-1)) {
1724 PP->CodeCompleteNaturalLanguage();
1725 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1726 return cutOffLexing();
1727 }
1728
Chris Lattnerd80f7862010-07-07 23:24:27 +00001729 NulCharacter = CurPtr-1;
1730 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 C = getAndAdvanceChar(CurPtr, Result);
1732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattnerd80f7862010-07-07 23:24:27 +00001734 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001735 if (NulCharacter && !isLexingRawMode())
1736 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001737
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001739 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001740 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001741 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001742}
1743
1744/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1745/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001746///
1747/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1748///
1749bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 // Whitespace - Skip it, then return the token after the whitespace.
1751 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1752 while (1) {
1753 // Skip horizontal whitespace very aggressively.
1754 while (isHorizontalWhitespace(Char))
1755 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001757 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 if (Char != '\n' && Char != '\r')
1759 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 if (ParsingPreprocessorDirective) {
1762 // End of preprocessor directive line, let LexTokenInternal handle this.
1763 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001764 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 }
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // ok, but handle newline.
1768 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001769 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001771 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 Char = *++CurPtr;
1773 }
1774
1775 // If this isn't immediately after a newline, there is leading space.
1776 char PrevChar = CurPtr[-1];
1777 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001778 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779
Chris Lattnerd88dc482008-10-12 04:05:48 +00001780 // If the client wants us to return whitespace, return it now.
1781 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001782 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001783 return true;
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001787 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001788}
1789
1790// SkipBCPLComment - We have just read the // characters from input. Skip until
1791// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001792/// BufferPtr and return.
1793///
1794/// If we're in KeepCommentMode or any CommentHandler has inserted
1795/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001796bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 // If BCPL comments aren't explicitly enabled for this language, emit an
1798 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001799 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 // Mark them enabled so we only emit one warning for this translation
1803 // unit.
1804 Features.BCPLComment = true;
1805 }
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Reid Spencer5f016e22007-07-11 17:01:13 +00001807 // Scan over the body of the comment. The common case, when scanning, is that
1808 // the comment contains normal ascii characters with nothing interesting in
1809 // them. As such, optimize for this case with the inner loop.
1810 char C;
1811 do {
1812 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 // Skip over characters in the fast loop.
1814 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001815 C != '\n' && C != '\r') // Newline or DOS-style newline.
1816 C = *++CurPtr;
1817
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001818 const char *NextLine = CurPtr;
1819 if (C != 0) {
1820 // We found a newline, see if it's escaped.
1821 const char *EscapePtr = CurPtr-1;
1822 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1823 --EscapePtr;
1824
1825 if (*EscapePtr == '\\') // Escaped newline.
1826 CurPtr = EscapePtr;
1827 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1828 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1829 CurPtr = EscapePtr-2;
1830 else
1831 break; // This is a newline, we're done.
1832
1833 C = *CurPtr;
1834 }
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001837 // properly decode the character. Read it in raw mode to avoid emitting
1838 // diagnostics about things like trigraphs. If we see an escaped newline,
1839 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001841 bool OldRawMode = isLexingRawMode();
1842 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001844 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001845
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001846 // If we only read only one character, then no special handling is needed.
1847 // We're done and can skip forward to the newline.
1848 if (C != 0 && CurPtr == OldPtr+1) {
1849 CurPtr = NextLine;
1850 break;
1851 }
1852
Reid Spencer5f016e22007-07-11 17:01:13 +00001853 // If we read multiple characters, and one of those characters was a \r or
1854 // \n, then we had an escaped newline within the comment. Emit diagnostic
1855 // unless the next line is also a // comment.
1856 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1857 for (; OldPtr != CurPtr; ++OldPtr)
1858 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1859 // Okay, we found a // comment that ends in a newline, if the next
1860 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001861 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001863 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 ++ForwardPtr;
1865 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1866 break;
1867 }
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Chris Lattner74d15df2008-11-22 02:02:22 +00001869 if (!isLexingRawMode())
1870 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 break;
1872 }
1873 }
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Douglas Gregor55817af2010-08-25 17:04:25 +00001875 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001876 --CurPtr;
1877 break;
1878 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001879
1880 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1881 PP->CodeCompleteNaturalLanguage();
1882 cutOffLexing();
1883 return false;
1884 }
1885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 } while (C != '\n' && C != '\r');
1887
Chris Lattner3d0ad582010-02-03 21:06:21 +00001888 // Found but did not consume the newline. Notify comment handlers about the
1889 // comment unless we're in a #if 0 block.
1890 if (PP && !isLexingRawMode() &&
1891 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1892 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001893 BufferPtr = CurPtr;
1894 return true; // A token has to be returned.
1895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001898 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 return SaveBCPLComment(Result, CurPtr);
1900
1901 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001902 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1904 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001905 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001909 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001910 // contribute to another token), it isn't needed for correctness. Note that
1911 // this is ok even in KeepWhitespaceMode, because we would have returned the
1912 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001916 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001918 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001920 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001921}
1922
1923/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1924/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001925bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001926 // If we're not in a preprocessor directive, just return the // comment
1927 // directly.
1928 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Chris Lattner9e6293d2008-10-12 04:51:35 +00001930 if (!ParsingPreprocessorDirective)
1931 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Chris Lattner9e6293d2008-10-12 04:51:35 +00001933 // If this BCPL-style comment is in a macro definition, transmogrify it into
1934 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001935 bool Invalid = false;
1936 std::string Spelling = PP->getSpelling(Result, &Invalid);
1937 if (Invalid)
1938 return true;
1939
Chris Lattner9e6293d2008-10-12 04:51:35 +00001940 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1941 Spelling[1] = '*'; // Change prefix to "/*".
1942 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Chris Lattner9e6293d2008-10-12 04:51:35 +00001944 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001945 PP->CreateString(&Spelling[0], Spelling.size(), Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00001946 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001947 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001948}
1949
1950/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1951/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001952/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001953static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 Lexer *L) {
1955 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 // Back up off the newline.
1958 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 // If this is a two-character newline sequence, skip the other character.
1961 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1962 // \n\n or \r\r -> not escaped newline.
1963 if (CurPtr[0] == CurPtr[1])
1964 return false;
1965 // \n\r or \r\n -> skip the newline.
1966 --CurPtr;
1967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 // If we have horizontal whitespace, skip over it. We allow whitespace
1970 // between the slash and newline.
1971 bool HasSpace = false;
1972 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1973 --CurPtr;
1974 HasSpace = true;
1975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 // If we have a slash, we know this is an escaped newline.
1978 if (*CurPtr == '\\') {
1979 if (CurPtr[-1] != '*') return false;
1980 } else {
1981 // It isn't a slash, is it the ?? / trigraph?
1982 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1983 CurPtr[-3] != '*')
1984 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 // This is the trigraph ending the comment. Emit a stern warning!
1987 CurPtr -= 2;
1988
1989 // If no trigraphs are enabled, warn that we ignored this trigraph and
1990 // ignore this * character.
1991 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001992 if (!L->isLexingRawMode())
1993 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 return false;
1995 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001996 if (!L->isLexingRawMode())
1997 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002001 if (!L->isLexingRawMode())
2002 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002005 if (HasSpace && !L->isLexingRawMode())
2006 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 return true;
2009}
2010
2011#ifdef __SSE2__
2012#include <emmintrin.h>
2013#elif __ALTIVEC__
2014#include <altivec.h>
2015#undef bool
2016#endif
2017
2018/// SkipBlockComment - We have just read the /* characters from input. Read
2019/// until we find the */ characters that terminate the comment. Note that we
2020/// don't bother decoding trigraphs or escaped newlines in block comments,
2021/// because they cannot cause the comment to end. The only thing that can
2022/// happen is the comment could end with an escaped newline between the */ end
2023/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00002024///
Chris Lattner046c2272010-01-18 22:35:47 +00002025/// If we're in KeepCommentMode or any CommentHandler has inserted
2026/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002027bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002029 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 // optimization helps people who like to put a lot of * characters in their
2031 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002032
2033 // The first character we get with newlines and trigraphs skipped to handle
2034 // the degenerate /*/ case below correctly if the * has an escaped newline
2035 // after it.
2036 unsigned CharSize;
2037 unsigned char C = getCharAndSize(CurPtr, CharSize);
2038 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002040 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002041 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002042 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Chris Lattner31f0eca2008-10-12 04:19:49 +00002044 // KeepWhitespaceMode should return this broken comment as a token. Since
2045 // it isn't a well formed comment, just return it as an 'unknown' token.
2046 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002047 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002048 return true;
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Chris Lattner31f0eca2008-10-12 04:19:49 +00002051 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002052 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Chris Lattner8146b682007-07-21 23:43:37 +00002055 // Check to see if the first character after the '/*' is another /. If so,
2056 // then this slash does not end the block comment, it is part of it.
2057 if (C == '/')
2058 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 while (1) {
2061 // Skip over all non-interesting characters until we find end of buffer or a
2062 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002063 if (CurPtr + 24 < BufferEnd &&
2064 // If there is a code-completion point avoid the fast scan because it
2065 // doesn't check for '\0'.
2066 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 // While not aligned to a 16-byte boundary.
2068 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2069 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 if (C == '/') goto FoundSlash;
2072
2073#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002074 __m128i Slashes = _mm_set1_epi8('/');
2075 while (CurPtr+16 <= BufferEnd) {
2076 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
2077 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002078 // Adjust the pointer to point directly after the first slash. It's
2079 // not necessary to set C here, it will be overwritten at the end of
2080 // the outer loop.
2081 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002082 goto FoundSlash;
2083 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002085 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002086#elif __ALTIVEC__
2087 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002088 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 '/', '/', '/', '/', '/', '/', '/', '/'
2090 };
2091 while (CurPtr+16 <= BufferEnd &&
2092 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2093 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002094#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 // Scan for '/' quickly. Many block comments are very large.
2096 while (CurPtr[0] != '/' &&
2097 CurPtr[1] != '/' &&
2098 CurPtr[2] != '/' &&
2099 CurPtr[3] != '/' &&
2100 CurPtr+4 < BufferEnd) {
2101 CurPtr += 4;
2102 }
2103#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // It has to be one of the bytes scanned, increment to it and read one.
2106 C = *CurPtr++;
2107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 // Loop to scan the remainder.
2110 while (C != '/' && C != '\0')
2111 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002114 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 if (CurPtr[-2] == '*') // We found the final */. We're done!
2116 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2119 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2120 // We found the final */, though it had an escaped newline between the
2121 // * and /. We're done!
2122 break;
2123 }
2124 }
2125 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2126 // If this is a /* inside of the comment, emit a warning. Don't do this
2127 // if this is a /*/, which will end the comment. This misses cases with
2128 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002129 if (!isLexingRawMode())
2130 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 }
2132 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002133 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002134 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 // Note: the user probably forgot a */. We could continue immediately
2136 // after the /*, but this would involve lexing a lot of what really is the
2137 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002138 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002139
Chris Lattner31f0eca2008-10-12 04:19:49 +00002140 // KeepWhitespaceMode should return this broken comment as a token. Since
2141 // it isn't a well formed comment, just return it as an 'unknown' token.
2142 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002143 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002144 return true;
2145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattner31f0eca2008-10-12 04:19:49 +00002147 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002148 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002149 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2150 PP->CodeCompleteNaturalLanguage();
2151 cutOffLexing();
2152 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002154
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 C = *CurPtr++;
2156 }
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Chris Lattner3d0ad582010-02-03 21:06:21 +00002158 // Notify comment handlers about the comment unless we're in a #if 0 block.
2159 if (PP && !isLexingRawMode() &&
2160 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2161 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002162 BufferPtr = CurPtr;
2163 return true; // A token has to be returned.
2164 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002167 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002168 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002169 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 }
2171
2172 // It is common for the tokens immediately after a /**/ comment to be
2173 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002174 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2175 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002177 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002179 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 }
2181
2182 // Otherwise, just return so that the next character will be lexed as a token.
2183 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002184 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002185 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002186}
2187
2188//===----------------------------------------------------------------------===//
2189// Primary Lexing Entry Points
2190//===----------------------------------------------------------------------===//
2191
Reid Spencer5f016e22007-07-11 17:01:13 +00002192/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2193/// uninterpreted string. This switches the lexer out of directive mode.
2194std::string Lexer::ReadToEndOfLine() {
2195 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2196 "Must be in a preprocessing directive!");
2197 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002198 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002199
2200 // CurPtr - Cache BufferPtr in an automatic variable.
2201 const char *CurPtr = BufferPtr;
2202 while (1) {
2203 char Char = getAndAdvanceChar(CurPtr, Tmp);
2204 switch (Char) {
2205 default:
2206 Result += Char;
2207 break;
2208 case 0: // Null.
2209 // Found end of file?
2210 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002211 if (isCodeCompletionPoint(CurPtr-1)) {
2212 PP->CodeCompleteNaturalLanguage();
2213 cutOffLexing();
2214 return Result;
2215 }
2216
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 // Nope, normal character, continue.
2218 Result += Char;
2219 break;
2220 }
2221 // FALL THROUGH.
2222 case '\r':
2223 case '\n':
2224 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2225 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2226 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Peter Collingbourne84021552011-02-28 02:37:51 +00002228 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002230 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002231 if (PP)
2232 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002233 Lex(Tmp);
2234 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002235 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 // Finally, we're done, return the string we found.
2238 return Result;
2239 }
2240 }
2241}
2242
2243/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2244/// condition, reporting diagnostics and handling other edge cases as required.
2245/// This returns true if Result contains a token, false if PP.Lex should be
2246/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002247bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // If we hit the end of the file while parsing a preprocessor directive,
2249 // end the preprocessor directive first. The next token returned will
2250 // then be the end of file.
2251 if (ParsingPreprocessorDirective) {
2252 // Done parsing the "line".
2253 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002255 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002258 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002260 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002261
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 // If we are in raw mode, return this event as an EOF token. Let the caller
2263 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002264 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 Result.startToken();
2266 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002267 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002268 return true;
2269 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002270
Douglas Gregorf44e8542010-08-24 19:08:16 +00002271 // Issue diagnostics for unterminated #if and missing newline.
2272
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 // If we are in a #if directive, emit an error.
2274 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002275 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002276 PP->Diag(ConditionalStack.back().IfLoc,
2277 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 ConditionalStack.pop_back();
2279 }
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002281 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2282 // a pedwarn.
2283 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002284 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002285 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 BufferPtr = CurPtr;
2288
2289 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002290 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002291}
2292
2293/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2294/// the specified lexer will return a tok::l_paren token, 0 if it is something
2295/// else and 2 if there are no more tokens in the buffer controlled by the
2296/// lexer.
2297unsigned Lexer::isNextPPTokenLParen() {
2298 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 // Switch to 'skipping' mode. This will ensure that we can lex a token
2301 // without emitting diagnostics, disables macro expansion, and will cause EOF
2302 // to return an EOF token instead of popping the include stack.
2303 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 // Save state that can be changed while lexing so that we can restore it.
2306 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002307 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Chris Lattnerd2177732007-07-20 16:59:19 +00002309 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 Tok.startToken();
2311 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 // Restore state that may have changed.
2314 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002315 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 // Restore the lexer back to non-skipping mode.
2318 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002320 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002321 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002322 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002323}
2324
Chris Lattner34f349d2009-12-14 06:16:57 +00002325/// FindConflictEnd - Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002326static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2327 ConflictMarkerKind CMK) {
2328 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2329 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2330 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2331 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002332 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002333 // Must occur at start of line.
2334 if (RestOfBuffer[Pos-1] != '\r' &&
2335 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002336 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2337 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002338 continue;
2339 }
2340 return RestOfBuffer.data()+Pos;
2341 }
2342 return 0;
2343}
2344
2345/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2346/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2347/// and recover nicely. This returns true if it is a conflict marker and false
2348/// if not.
2349bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2350 // Only a conflict marker if it starts at the beginning of a line.
2351 if (CurPtr != BufferStart &&
2352 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2353 return false;
2354
Richard Smithd5e1d602011-10-12 00:37:51 +00002355 // Check to see if we have <<<<<<< or >>>>.
2356 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2357 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002358 return false;
2359
2360 // If we have a situation where we don't care about conflict markers, ignore
2361 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002362 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002363 return false;
2364
Richard Smithd5e1d602011-10-12 00:37:51 +00002365 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2366
2367 // Check to see if there is an ending marker somewhere in the buffer at the
2368 // start of a line to terminate this conflict marker.
2369 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002370 // We found a match. We are really in a conflict marker.
2371 // Diagnose this, and ignore to the end of line.
2372 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002373 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002374
2375 // Skip ahead to the end of line. We know this exists because the
2376 // end-of-conflict marker starts with \r or \n.
2377 while (*CurPtr != '\r' && *CurPtr != '\n') {
2378 assert(CurPtr != BufferEnd && "Didn't find end of line");
2379 ++CurPtr;
2380 }
2381 BufferPtr = CurPtr;
2382 return true;
2383 }
2384
2385 // No end of conflict marker found.
2386 return false;
2387}
2388
2389
Richard Smithd5e1d602011-10-12 00:37:51 +00002390/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2391/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2392/// is the end of a conflict marker. Handle it by ignoring up until the end of
2393/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002394bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2395 // Only a conflict marker if it starts at the beginning of a line.
2396 if (CurPtr != BufferStart &&
2397 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2398 return false;
2399
2400 // If we have a situation where we don't care about conflict markers, ignore
2401 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002402 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002403 return false;
2404
Richard Smithd5e1d602011-10-12 00:37:51 +00002405 // Check to see if we have the marker (4 characters in a row).
2406 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002407 if (CurPtr[i] != CurPtr[0])
2408 return false;
2409
2410 // If we do have it, search for the end of the conflict marker. This could
2411 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2412 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002413 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2414 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002415 CurPtr = End;
2416
2417 // Skip ahead to the end of line.
2418 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2419 ++CurPtr;
2420
2421 BufferPtr = CurPtr;
2422
2423 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002424 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002425 return true;
2426 }
2427
2428 return false;
2429}
2430
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002431bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2432 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002433 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002434 return Loc == PP->getCodeCompletionLoc();
2435 }
2436
2437 return false;
2438}
2439
Reid Spencer5f016e22007-07-11 17:01:13 +00002440
2441/// LexTokenInternal - This implements a simple C family lexer. It is an
2442/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002443/// has a null character at the end of the file. This returns a preprocessing
2444/// token, not a normal token, as such, it is an internal interface. It assumes
2445/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002446void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002447LexNextToken:
2448 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002449 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Reid Spencer5f016e22007-07-11 17:01:13 +00002452 // CurPtr - Cache BufferPtr in an automatic variable.
2453 const char *CurPtr = BufferPtr;
2454
2455 // Small amounts of horizontal whitespace is very common between tokens.
2456 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2457 ++CurPtr;
2458 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2459 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002460
Chris Lattnerd88dc482008-10-12 04:05:48 +00002461 // If we are keeping whitespace and other tokens, just return what we just
2462 // skipped. The next lexer invocation will return the token after the
2463 // whitespace.
2464 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002465 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002466 return;
2467 }
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002470 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 }
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Reid Spencer5f016e22007-07-11 17:01:13 +00002473 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Reid Spencer5f016e22007-07-11 17:01:13 +00002475 // Read a character, advancing over it.
2476 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002477 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 switch (Char) {
2480 case 0: // Null.
2481 // Found end of file?
2482 if (CurPtr-1 == BufferEnd) {
2483 // Read the PP instance variable into an automatic variable, because
2484 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002485 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002486 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2487 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002488 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2489 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002490 }
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002492 // Check if we are performing code completion.
2493 if (isCodeCompletionPoint(CurPtr-1)) {
2494 // Return the code-completion token.
2495 Result.startToken();
2496 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2497 return;
2498 }
2499
Chris Lattner74d15df2008-11-22 02:02:22 +00002500 if (!isLexingRawMode())
2501 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002502 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002503 if (SkipWhitespace(Result, CurPtr))
2504 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002505
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002507
2508 case 26: // DOS & CP/M EOF: "^Z".
2509 // If we're in Microsoft extensions mode, treat this as end of file.
Francois Pichet62ec1f22011-09-17 17:15:52 +00002510 if (Features.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002511 // Read the PP instance variable into an automatic variable, because
2512 // LexEndOfFile will often delete 'this'.
2513 Preprocessor *PPCache = PP;
2514 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2515 return; // Got a token to return.
2516 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2517 return PPCache->Lex(Result);
2518 }
2519 // If Microsoft extensions are disabled, this is just random garbage.
2520 Kind = tok::unknown;
2521 break;
2522
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 case '\n':
2524 case '\r':
2525 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002526 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 if (ParsingPreprocessorDirective) {
2528 // Done parsing the "line".
2529 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002532 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 // Since we consumed a newline, we are back at the start of a line.
2535 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Peter Collingbourne84021552011-02-28 02:37:51 +00002537 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 break;
2539 }
2540 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002541 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002543 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002544
Chris Lattnerd88dc482008-10-12 04:05:48 +00002545 if (SkipWhitespace(Result, CurPtr))
2546 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 goto LexNextToken; // GCC isn't tail call eliminating.
2548 case ' ':
2549 case '\t':
2550 case '\f':
2551 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002552 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002553 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002554 if (SkipWhitespace(Result, CurPtr))
2555 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002556
2557 SkipIgnoredUnits:
2558 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Chris Lattner8133cfc2007-07-22 06:29:05 +00002560 // If the next token is obviously a // or /* */ comment, skip it efficiently
2561 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002562 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002563 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002564 if (SkipBCPLComment(Result, CurPtr+2))
2565 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002566 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002567 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002568 if (SkipBlockComment(Result, CurPtr+2))
2569 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002570 goto SkipIgnoredUnits;
2571 } else if (isHorizontalWhitespace(*CurPtr)) {
2572 goto SkipHorizontalWhitespace;
2573 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002575
Chris Lattner3a570772008-01-03 17:58:54 +00002576 // C99 6.4.4.1: Integer Constants.
2577 // C99 6.4.4.2: Floating Constants.
2578 case '0': case '1': case '2': case '3': case '4':
2579 case '5': case '6': case '7': case '8': case '9':
2580 // Notify MIOpt that we read a non-whitespace/non-comment token.
2581 MIOpt.ReadToken();
2582 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Douglas Gregor5cee1192011-07-27 05:40:30 +00002584 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2585 // Notify MIOpt that we read a non-whitespace/non-comment token.
2586 MIOpt.ReadToken();
2587
2588 if (Features.CPlusPlus0x) {
2589 Char = getCharAndSize(CurPtr, SizeTmp);
2590
2591 // UTF-16 string literal
2592 if (Char == '"')
2593 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2594 tok::utf16_string_literal);
2595
2596 // UTF-16 character constant
2597 if (Char == '\'')
2598 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2599 tok::utf16_char_constant);
2600
Craig Topper2fa4e862011-08-11 04:06:15 +00002601 // UTF-16 raw string literal
2602 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2603 return LexRawStringLiteral(Result,
2604 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2605 SizeTmp2, Result),
2606 tok::utf16_string_literal);
2607
2608 if (Char == '8') {
2609 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2610
2611 // UTF-8 string literal
2612 if (Char2 == '"')
2613 return LexStringLiteral(Result,
2614 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2615 SizeTmp2, Result),
2616 tok::utf8_string_literal);
2617
2618 if (Char2 == 'R') {
2619 unsigned SizeTmp3;
2620 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2621 // UTF-8 raw string literal
2622 if (Char3 == '"') {
2623 return LexRawStringLiteral(Result,
2624 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2625 SizeTmp2, Result),
2626 SizeTmp3, Result),
2627 tok::utf8_string_literal);
2628 }
2629 }
2630 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002631 }
2632
2633 // treat u like the start of an identifier.
2634 return LexIdentifier(Result, CurPtr);
2635
2636 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2637 // Notify MIOpt that we read a non-whitespace/non-comment token.
2638 MIOpt.ReadToken();
2639
2640 if (Features.CPlusPlus0x) {
2641 Char = getCharAndSize(CurPtr, SizeTmp);
2642
2643 // UTF-32 string literal
2644 if (Char == '"')
2645 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2646 tok::utf32_string_literal);
2647
2648 // UTF-32 character constant
2649 if (Char == '\'')
2650 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2651 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002652
2653 // UTF-32 raw string literal
2654 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2655 return LexRawStringLiteral(Result,
2656 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2657 SizeTmp2, Result),
2658 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002659 }
2660
2661 // treat U like the start of an identifier.
2662 return LexIdentifier(Result, CurPtr);
2663
Craig Topper2fa4e862011-08-11 04:06:15 +00002664 case 'R': // Identifier or C++0x raw string literal
2665 // Notify MIOpt that we read a non-whitespace/non-comment token.
2666 MIOpt.ReadToken();
2667
2668 if (Features.CPlusPlus0x) {
2669 Char = getCharAndSize(CurPtr, SizeTmp);
2670
2671 if (Char == '"')
2672 return LexRawStringLiteral(Result,
2673 ConsumeChar(CurPtr, SizeTmp, Result),
2674 tok::string_literal);
2675 }
2676
2677 // treat R like the start of an identifier.
2678 return LexIdentifier(Result, CurPtr);
2679
Chris Lattner3a570772008-01-03 17:58:54 +00002680 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 // Notify MIOpt that we read a non-whitespace/non-comment token.
2682 MIOpt.ReadToken();
2683 Char = getCharAndSize(CurPtr, SizeTmp);
2684
2685 // Wide string literal.
2686 if (Char == '"')
2687 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002688 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002689
Craig Topper2fa4e862011-08-11 04:06:15 +00002690 // Wide raw string literal.
2691 if (Features.CPlusPlus0x && Char == 'R' &&
2692 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2693 return LexRawStringLiteral(Result,
2694 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2695 SizeTmp2, Result),
2696 tok::wide_string_literal);
2697
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 // Wide character constant.
2699 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002700 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2701 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 // C99 6.4.2: Identifiers.
2705 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2706 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002707 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2709 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2710 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002711 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002712 case 'v': case 'w': case 'x': case 'y': case 'z':
2713 case '_':
2714 // Notify MIOpt that we read a non-whitespace/non-comment token.
2715 MIOpt.ReadToken();
2716 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002717
2718 case '$': // $ in identifiers.
2719 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002720 if (!isLexingRawMode())
2721 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002722 // Notify MIOpt that we read a non-whitespace/non-comment token.
2723 MIOpt.ReadToken();
2724 return LexIdentifier(Result, CurPtr);
2725 }
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattner9e6293d2008-10-12 04:51:35 +00002727 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002728 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 // C99 6.4.4: Character Constants.
2731 case '\'':
2732 // Notify MIOpt that we read a non-whitespace/non-comment token.
2733 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002734 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002735
2736 // C99 6.4.5: String Literals.
2737 case '"':
2738 // Notify MIOpt that we read a non-whitespace/non-comment token.
2739 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002740 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002741
2742 // C99 6.4.6: Punctuators.
2743 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002744 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 break;
2746 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002747 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 break;
2749 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002750 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 break;
2752 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002753 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 break;
2755 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002756 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 break;
2758 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002759 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 break;
2761 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002762 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 break;
2764 case '.':
2765 Char = getCharAndSize(CurPtr, SizeTmp);
2766 if (Char >= '0' && Char <= '9') {
2767 // Notify MIOpt that we read a non-whitespace/non-comment token.
2768 MIOpt.ReadToken();
2769
2770 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2771 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002772 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 CurPtr += SizeTmp;
2774 } else if (Char == '.' &&
2775 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002776 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2778 SizeTmp2, Result);
2779 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002780 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 }
2782 break;
2783 case '&':
2784 Char = getCharAndSize(CurPtr, SizeTmp);
2785 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002786 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2788 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2791 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002792 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 }
2794 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002795 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002797 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2799 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002800 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
2802 break;
2803 case '+':
2804 Char = getCharAndSize(CurPtr, SizeTmp);
2805 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002807 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002810 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002812 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 }
2814 break;
2815 case '-':
2816 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002817 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002819 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002820 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002821 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2823 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002824 Kind = tok::arrowstar;
2825 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002827 Kind = tok::arrow;
2828 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002830 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002832 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 }
2834 break;
2835 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002836 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 break;
2838 case '!':
2839 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002840 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2842 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002843 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 }
2845 break;
2846 case '/':
2847 // 6.4.9: Comments
2848 Char = getCharAndSize(CurPtr, SizeTmp);
2849 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002850 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2851 // want to lex this as a comment. There is one problem with this though,
2852 // that in one particular corner case, this can change the behavior of the
2853 // resultant program. For example, In "foo //**/ bar", C89 would lex
2854 // this as "foo / bar" and langauges with BCPL comments would lex it as
2855 // "foo". Check to see if the character after the second slash is a '*'.
2856 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002857 // However, we never do this in -traditional-cpp mode.
2858 if ((Features.BCPLComment ||
2859 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2860 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002861 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002862 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Chris Lattner8402c732009-01-16 22:39:25 +00002864 // It is common for the tokens immediately after a // comment to be
2865 // whitespace (indentation for the next line). Instead of going through
2866 // the big switch, handle it efficiently now.
2867 goto SkipIgnoredUnits;
2868 }
2869 }
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Chris Lattner8402c732009-01-16 22:39:25 +00002871 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002872 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002873 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002874 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002875 }
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Chris Lattner8402c732009-01-16 22:39:25 +00002877 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002879 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002881 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 }
2883 break;
2884 case '%':
2885 Char = getCharAndSize(CurPtr, SizeTmp);
2886 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002887 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2889 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002890 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2892 } else if (Features.Digraphs && Char == ':') {
2893 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2894 Char = getCharAndSize(CurPtr, SizeTmp);
2895 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002896 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002897 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2898 SizeTmp2, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00002899 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002901 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00002902 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002903 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002904 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 // We parsed a # character. If this occurs at the start of the line,
2906 // it's actually the start of a preprocessing directive. Callback to
2907 // the preprocessor to handle it.
2908 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002909 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002910 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002911 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002912
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 // As an optimization, if the preprocessor didn't switch lexers, tail
2914 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002915 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002916 // Start a new token. If this is a #include or something, the PP may
2917 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002918 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002920 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002921 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 IsAtStartOfLine = false;
2923 }
2924 goto LexNextToken; // GCC isn't tail call eliminating.
2925 }
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Chris Lattner168ae2d2007-10-17 20:41:00 +00002927 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 }
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Chris Lattnere91e9322009-03-18 20:58:27 +00002930 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 }
2932 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002933 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 }
2935 break;
2936 case '<':
2937 Char = getCharAndSize(CurPtr, SizeTmp);
2938 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002939 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002941 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2942 if (After == '=') {
2943 Kind = tok::lesslessequal;
2944 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2945 SizeTmp2, Result);
2946 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2947 // If this is actually a '<<<<<<<' version control conflict marker,
2948 // recognize it as such and recover nicely.
2949 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00002950 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
2951 // If this is '<<<<' and we're in a Perforce-style conflict marker,
2952 // ignore it.
2953 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002954 } else if (Features.CUDA && After == '<') {
2955 Kind = tok::lesslessless;
2956 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2957 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002958 } else {
2959 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2960 Kind = tok::lessless;
2961 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002963 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002964 Kind = tok::lessequal;
2965 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002966 if (Features.CPlusPlus0x &&
2967 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2968 // C++0x [lex.pptoken]p3:
2969 // Otherwise, if the next three characters are <:: and the subsequent
2970 // character is neither : nor >, the < is treated as a preprocessor
2971 // token by itself and not as the first character of the alternative
2972 // token <:.
2973 unsigned SizeTmp3;
2974 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2975 if (After != ':' && After != '>') {
2976 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00002977 if (!isLexingRawMode())
2978 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00002979 break;
2980 }
2981 }
2982
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002984 Kind = tok::l_square;
2985 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002987 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002988 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002989 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 }
2991 break;
2992 case '>':
2993 Char = getCharAndSize(CurPtr, SizeTmp);
2994 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002996 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002998 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2999 if (After == '=') {
3000 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3001 SizeTmp2, Result);
3002 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003003 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3004 // If this is actually a '>>>>' conflict marker, recognize it as such
3005 // and recover nicely.
3006 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003007 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3008 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3009 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003010 } else if (Features.CUDA && After == '>') {
3011 Kind = tok::greatergreatergreater;
3012 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3013 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003014 } else {
3015 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3016 Kind = tok::greatergreater;
3017 }
3018
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003020 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 }
3022 break;
3023 case '^':
3024 Char = getCharAndSize(CurPtr, SizeTmp);
3025 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003027 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003029 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003030 }
3031 break;
3032 case '|':
3033 Char = getCharAndSize(CurPtr, SizeTmp);
3034 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003035 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3037 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003038 // If this is '|||||||' and we're in a conflict marker, ignore it.
3039 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3040 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003041 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003042 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3043 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003044 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 }
3046 break;
3047 case ':':
3048 Char = getCharAndSize(CurPtr, SizeTmp);
3049 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003050 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3052 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003053 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003055 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003056 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 }
3058 break;
3059 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003060 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003061 break;
3062 case '=':
3063 Char = getCharAndSize(CurPtr, SizeTmp);
3064 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003065 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003066 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3067 goto LexNextToken;
3068
Chris Lattner9e6293d2008-10-12 04:51:35 +00003069 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003070 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003071 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003072 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003073 }
3074 break;
3075 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003076 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003077 break;
3078 case '#':
3079 Char = getCharAndSize(CurPtr, SizeTmp);
3080 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003081 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003082 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Francois Pichet62ec1f22011-09-17 17:15:52 +00003083 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003084 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003085 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003086 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003087 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3088 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 // We parsed a # character. If this occurs at the start of the line,
3090 // it's actually the start of a preprocessing directive. Callback to
3091 // the preprocessor to handle it.
3092 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00003093 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00003094 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00003095 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 // As an optimization, if the preprocessor didn't switch lexers, tail
3098 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00003099 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 // Start a new token. If this is a #include or something, the PP may
3101 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00003102 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00003103 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00003104 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00003105 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00003106 IsAtStartOfLine = false;
3107 }
3108 goto LexNextToken; // GCC isn't tail call eliminating.
3109 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00003110 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003111 }
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Chris Lattnere91e9322009-03-18 20:58:27 +00003113 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003114 }
3115 break;
3116
Chris Lattner3a570772008-01-03 17:58:54 +00003117 case '@':
3118 // Objective C support.
3119 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003120 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003121 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003122 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003123 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Reid Spencer5f016e22007-07-11 17:01:13 +00003125 case '\\':
3126 // FIXME: UCN's.
3127 // FALL THROUGH.
3128 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00003129 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003130 break;
3131 }
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 // Notify MIOpt that we read a non-whitespace/non-comment token.
3134 MIOpt.ReadToken();
3135
3136 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003137 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00003138}