blob: 1ec50cd2c5d68c9d4068f4daf005bcdfeb38e195 [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"
Chris Lattner409a0362007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/Support/MemoryBuffer.h"
35#include <cctype>
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
Mike Stump1eb44332009-09-09 15:08:12 +000063void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000064 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000065 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner22d91ca2009-01-17 06:55:17 +000067 BufferStart = BufStart;
68 BufferPtr = BufPtr;
69 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner22d91ca2009-01-17 06:55:17 +000071 assert(BufEnd[0] == 0 &&
72 "We assume that the input buffer has a null character at the end"
73 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000074
Eric Christopher156119d2011-04-09 00:01:04 +000075 // Check whether we have a BOM in the beginning of the buffer. If yes - act
76 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
77 // skip the UTF-8 BOM if it's present.
78 if (BufferStart == BufferPtr) {
79 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000081 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000082 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
83 .Default(0);
84
85 // Skip the BOM.
86 BufferPtr += BOMLength;
87 }
88
Chris Lattner22d91ca2009-01-17 06:55:17 +000089 Is_PragmaLexer = false;
Chris Lattner34f349d2009-12-14 06:16:57 +000090 IsInConflictMarker = false;
Eric Christopher156119d2011-04-09 00:01:04 +000091
Chris Lattner22d91ca2009-01-17 06:55:17 +000092 // Start of the file is a start of line.
93 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner22d91ca2009-01-17 06:55:17 +000095 // We are not after parsing a #.
96 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner22d91ca2009-01-17 06:55:17 +000098 // We are not after parsing #include.
99 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Chris Lattner22d91ca2009-01-17 06:55:17 +0000101 // We are not in raw mode. Raw mode disables diagnostics and interpretation
102 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
103 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
104 // or otherwise skipping over tokens.
105 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner22d91ca2009-01-17 06:55:17 +0000107 // Default to not keeping comments.
108 ExtendedTokenMode = 0;
109}
110
Chris Lattner0770dab2009-01-17 07:56:59 +0000111/// Lexer constructor - Create a new lexer object for the specified buffer
112/// with the specified preprocessor managing the lexing process. This lexer
113/// assumes that the associated file buffer and Preprocessor objects will
114/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000115Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000116 : PreprocessorLexer(&PP, FID),
117 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
118 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattner0770dab2009-01-17 07:56:59 +0000120 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
121 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Chris Lattner0770dab2009-01-17 07:56:59 +0000123 // Default to keeping comments if the preprocessor wants them.
124 SetCommentRetentionState(PP.getCommentRetentionState());
125}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000126
Chris Lattner168ae2d2007-10-17 20:41:00 +0000127/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000128/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
129/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000130Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000131 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000132 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000133
Chris Lattner22d91ca2009-01-17 06:55:17 +0000134 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattner168ae2d2007-10-17 20:41:00 +0000136 // We *are* in raw mode.
137 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000138}
139
Chris Lattner025c3a62009-01-17 07:35:14 +0000140/// Lexer constructor - Create a new raw lexer object. This object is only
141/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
142/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000143Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
144 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000145 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000146
Mike Stump1eb44332009-09-09 15:08:12 +0000147 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000148 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 // We *are* in raw mode.
151 LexingRawMode = true;
152}
153
Chris Lattner42e00d12009-01-17 08:27:52 +0000154/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
155/// _Pragma expansion. This has a variety of magic semantics that this method
156/// sets up. It returns a new'd Lexer that must be delete'd when done.
157///
158/// On entrance to this routine, TokStartLoc is a macro location which has a
159/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000160/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000161/// "expanded from".
162///
163/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
164/// normal lexer that remaps tokens as they fly by. This would require making
165/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
166/// interface that could handle this stuff. This would pull GetMappedTokenLoc
167/// out of the critical path of the lexer!
168///
Mike Stump1eb44332009-09-09 15:08:12 +0000169Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000170 SourceLocation ExpansionLocStart,
171 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000172 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000173 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000174
175 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000176 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000177 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
178 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner42e00d12009-01-17 08:27:52 +0000180 // Now that the lexer is created, change the start/end locations so that we
181 // just lex the subsection of the file that we want. This is lexing from a
182 // scratch buffer.
183 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner42e00d12009-01-17 08:27:52 +0000185 L->BufferPtr = StrData;
186 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000187 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000188
189 // Set the SourceLocation with the remapping information. This ensures that
190 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000191 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
192 ExpansionLocStart,
193 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner42e00d12009-01-17 08:27:52 +0000195 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000196 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 // This lexer really is for _Pragma.
200 L->Is_PragmaLexer = true;
201 return L;
202}
203
Chris Lattner168ae2d2007-10-17 20:41:00 +0000204
Reid Spencer5f016e22007-07-11 17:01:13 +0000205/// Stringify - Convert the specified string into a C string, with surrounding
206/// ""'s, and with escaped \ and " characters.
207std::string Lexer::Stringify(const std::string &Str, bool Charify) {
208 std::string Result = Str;
209 char Quote = Charify ? '\'' : '"';
210 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
211 if (Result[i] == '\\' || Result[i] == Quote) {
212 Result.insert(Result.begin()+i, '\\');
213 ++i; ++e;
214 }
215 }
216 return Result;
217}
218
Chris Lattnerd8e30832007-07-24 06:57:14 +0000219/// Stringify - Convert the specified string into a C string by escaping '\'
220/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000222 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
223 if (Str[i] == '\\' || Str[i] == '"') {
224 Str.insert(Str.begin()+i, '\\');
225 ++i; ++e;
226 }
227 }
228}
229
Chris Lattnerb0607272010-11-17 07:26:20 +0000230//===----------------------------------------------------------------------===//
231// Token Spelling
232//===----------------------------------------------------------------------===//
233
234/// getSpelling() - Return the 'spelling' of this token. The spelling of a
235/// token are the characters used to represent the token in the source file
236/// after trigraph expansion and escaped-newline folding. In particular, this
237/// wants to get the true, uncanonicalized, spelling of things like digraphs
238/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000239StringRef Lexer::getSpelling(SourceLocation loc,
240 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000241 const SourceManager &SM,
242 const LangOptions &options,
243 bool *invalid) {
244 // Break down the source location.
245 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
246
247 // Try to the load the file buffer.
248 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000250 if (invalidTemp) {
251 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000253 }
254
255 const char *tokenBegin = file.data() + locInfo.second;
256
257 // Lex from the start of the given location.
258 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
259 file.begin(), tokenBegin, file.end());
260 Token token;
261 lexer.LexFromRawLexer(token);
262
263 unsigned length = token.getLength();
264
265 // Common case: no need for cleaning.
266 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000267 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000268
269 // Hard case, we need to relex the characters into the string.
270 buffer.clear();
271 buffer.reserve(length);
272
273 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
274 unsigned charSize;
275 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
276 ti += charSize;
277 }
278
Chris Lattner5f9e2722011-07-23 10:55:15 +0000279 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000280}
281
282/// getSpelling() - Return the 'spelling' of this token. The spelling of a
283/// token are the characters used to represent the token in the source file
284/// after trigraph expansion and escaped-newline folding. In particular, this
285/// wants to get the true, uncanonicalized, spelling of things like digraphs
286/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000287std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
288 const LangOptions &Features, bool *Invalid) {
289 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
290
291 // If this token contains nothing interesting, return it directly.
292 bool CharDataInvalid = false;
293 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
294 &CharDataInvalid);
295 if (Invalid)
296 *Invalid = CharDataInvalid;
297 if (CharDataInvalid)
298 return std::string();
299
300 if (!Tok.needsCleaning())
301 return std::string(TokStart, TokStart+Tok.getLength());
302
303 std::string Result;
304 Result.reserve(Tok.getLength());
305
306 // Otherwise, hard case, relex the characters into the string.
307 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
308 Ptr != End; ) {
309 unsigned CharSize;
310 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
311 Ptr += CharSize;
312 }
313 assert(Result.size() != unsigned(Tok.getLength()) &&
314 "NeedsCleaning flag set on something that didn't need cleaning!");
315 return Result;
316}
317
318/// getSpelling - This method is used to get the spelling of a token into a
319/// preallocated buffer, instead of as an std::string. The caller is required
320/// to allocate enough space for the token, which is guaranteed to be at least
321/// Tok.getLength() bytes long. The actual length of the token is returned.
322///
323/// Note that this method may do two possible things: it may either fill in
324/// the buffer specified with characters, or it may *change the input pointer*
325/// to point to a constant buffer with the data already in it (avoiding a
326/// copy). The caller is not allowed to modify the returned buffer pointer
327/// if an internal buffer is returned.
328unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
329 const SourceManager &SourceMgr,
330 const LangOptions &Features, bool *Invalid) {
331 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000332
333 const char *TokStart = 0;
334 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
335 if (Tok.is(tok::raw_identifier))
336 TokStart = Tok.getRawIdentifierData();
337 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
338 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 Buffer = II->getNameStart();
340 return II->getLength();
341 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000342
343 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000344 if (Tok.isLiteral())
345 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000346
Chris Lattnerb0607272010-11-17 07:26:20 +0000347 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000348 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 bool CharDataInvalid = false;
350 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
351 if (Invalid)
352 *Invalid = CharDataInvalid;
353 if (CharDataInvalid) {
354 Buffer = "";
355 return 0;
356 }
357 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000358
Chris Lattnerb0607272010-11-17 07:26:20 +0000359 // If this token contains nothing interesting, return it directly.
360 if (!Tok.needsCleaning()) {
361 Buffer = TokStart;
362 return Tok.getLength();
363 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000364
Chris Lattnerb0607272010-11-17 07:26:20 +0000365 // Otherwise, hard case, relex the characters into the string.
366 char *OutBuf = const_cast<char*>(Buffer);
367 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
368 Ptr != End; ) {
369 unsigned CharSize;
370 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
371 Ptr += CharSize;
372 }
373 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
374 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000375
Chris Lattnerb0607272010-11-17 07:26:20 +0000376 return OutBuf-Buffer;
377}
378
379
380
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000382
Chris Lattner9a611942007-10-17 21:18:47 +0000383/// MeasureTokenLength - Relex the token at the specified location and return
384/// its length in bytes in the input file. If the token needs cleaning (e.g.
385/// includes a trigraph or an escaped newline) then this count includes bytes
386/// that are part of that.
387unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000388 const SourceManager &SM,
389 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000390 // TODO: this could be special cased for common tokens like identifiers, ')',
391 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000392 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000393 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
394 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000395
396 // If this comes from a macro expansion, we really do want the macro name, not
397 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000398 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000399 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000400 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000401 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000402 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000403 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000404
405 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000406
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 if (isWhitespace(StrData[0]))
408 return 0;
409
Chris Lattner9a611942007-10-17 21:18:47 +0000410 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000411 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
412 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000413 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000414 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000415 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000416 return TheTok.getLength();
417}
418
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000419static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
420 const SourceManager &SM,
421 const LangOptions &LangOpts) {
422 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000423 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000424 if (LocInfo.first.isInvalid())
425 return Loc;
426
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000427 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000428 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000429 if (Invalid)
430 return Loc;
431
432 // Back up from the current location until we hit the beginning of a line
433 // (or the buffer). We'll relex from that point.
434 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000435 if (LocInfo.second >= Buffer.size())
436 return Loc;
437
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000438 const char *StrData = BufStart+LocInfo.second;
439 if (StrData[0] == '\n' || StrData[0] == '\r')
440 return Loc;
441
442 const char *LexStart = StrData;
443 while (LexStart != BufStart) {
444 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
445 ++LexStart;
446 break;
447 }
448
449 --LexStart;
450 }
451
452 // Create a lexer starting at the beginning of this token.
453 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
454 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
455 TheLexer.SetCommentRetentionState(true);
456
457 // Lex tokens until we find the token that contains the source location.
458 Token TheTok;
459 do {
460 TheLexer.LexFromRawLexer(TheTok);
461
462 if (TheLexer.getBufferLocation() > StrData) {
463 // Lexing this token has taken the lexer past the source location we're
464 // looking for. If the current token encompasses our source location,
465 // return the beginning of that token.
466 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
467 return TheTok.getLocation();
468
469 // We ended up skipping over the source location entirely, which means
470 // that it points into whitespace. We're done here.
471 break;
472 }
473 } while (TheTok.getKind() != tok::eof);
474
475 // We've passed our source location; just return the original source location.
476 return Loc;
477}
478
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000479SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
480 const SourceManager &SM,
481 const LangOptions &LangOpts) {
482 if (Loc.isFileID())
483 return getBeginningOfFileToken(Loc, SM, LangOpts);
484
485 if (!SM.isMacroArgExpansion(Loc))
486 return Loc;
487
488 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
489 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
490 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
491 std::pair<FileID, unsigned> BeginFileLocInfo= SM.getDecomposedLoc(BeginFileLoc);
492 assert(FileLocInfo.first == BeginFileLocInfo.first &&
493 FileLocInfo.second >= BeginFileLocInfo.second);
494 return Loc.getFileLocWithOffset(SM.getDecomposedLoc(BeginFileLoc).second -
495 SM.getDecomposedLoc(FileLoc).second);
496}
497
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000498namespace {
499 enum PreambleDirectiveKind {
500 PDK_Skipped,
501 PDK_StartIf,
502 PDK_EndIf,
503 PDK_Unknown
504 };
505}
506
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000507std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000508Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
509 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000510 // Create a lexer starting at the beginning of the file. Note that we use a
511 // "fake" file source location at offset 1 so that the lexer will track our
512 // position within the file.
513 const unsigned StartOffset = 1;
514 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000515 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000516 Buffer->getBufferStart(), Buffer->getBufferEnd());
517
518 bool InPreprocessorDirective = false;
519 Token TheTok;
520 Token IfStartTok;
521 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000522 unsigned Line = 0;
523
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000524 do {
525 TheLexer.LexFromRawLexer(TheTok);
526
527 if (InPreprocessorDirective) {
528 // If we've hit the end of the file, we're done.
529 if (TheTok.getKind() == tok::eof) {
530 InPreprocessorDirective = false;
531 break;
532 }
533
534 // If we haven't hit the end of the preprocessor directive, skip this
535 // token.
536 if (!TheTok.isAtStartOfLine())
537 continue;
538
539 // We've passed the end of the preprocessor directive, and will look
540 // at this token again below.
541 InPreprocessorDirective = false;
542 }
543
Douglas Gregordf95a132010-08-09 20:45:32 +0000544 // Keep track of the # of lines in the preamble.
545 if (TheTok.isAtStartOfLine()) {
546 ++Line;
547
548 // If we were asked to limit the number of lines in the preamble,
549 // and we're about to exceed that limit, we're done.
550 if (MaxLines && Line >= MaxLines)
551 break;
552 }
553
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000554 // Comments are okay; skip over them.
555 if (TheTok.getKind() == tok::comment)
556 continue;
557
558 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
559 // This is the start of a preprocessor directive.
560 Token HashTok = TheTok;
561 InPreprocessorDirective = true;
562
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000563 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000564 // we don't have an identifier table available. Instead, just look at
565 // the raw identifier to recognize and categorize preprocessor directives.
566 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000567 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000569 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000570 PreambleDirectiveKind PDK
571 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
572 .Case("include", PDK_Skipped)
573 .Case("__include_macros", PDK_Skipped)
574 .Case("define", PDK_Skipped)
575 .Case("undef", PDK_Skipped)
576 .Case("line", PDK_Skipped)
577 .Case("error", PDK_Skipped)
578 .Case("pragma", PDK_Skipped)
579 .Case("import", PDK_Skipped)
580 .Case("include_next", PDK_Skipped)
581 .Case("warning", PDK_Skipped)
582 .Case("ident", PDK_Skipped)
583 .Case("sccs", PDK_Skipped)
584 .Case("assert", PDK_Skipped)
585 .Case("unassert", PDK_Skipped)
586 .Case("if", PDK_StartIf)
587 .Case("ifdef", PDK_StartIf)
588 .Case("ifndef", PDK_StartIf)
589 .Case("elif", PDK_Skipped)
590 .Case("else", PDK_Skipped)
591 .Case("endif", PDK_EndIf)
592 .Default(PDK_Unknown);
593
594 switch (PDK) {
595 case PDK_Skipped:
596 continue;
597
598 case PDK_StartIf:
599 if (IfCount == 0)
600 IfStartTok = HashTok;
601
602 ++IfCount;
603 continue;
604
605 case PDK_EndIf:
606 // Mismatched #endif. The preamble ends here.
607 if (IfCount == 0)
608 break;
609
610 --IfCount;
611 continue;
612
613 case PDK_Unknown:
614 // We don't know what this directive is; stop at the '#'.
615 break;
616 }
617 }
618
619 // We only end up here if we didn't recognize the preprocessor
620 // directive or it was one that can't occur in the preamble at this
621 // point. Roll back the current token to the location of the '#'.
622 InPreprocessorDirective = false;
623 TheTok = HashTok;
624 }
625
Douglas Gregordf95a132010-08-09 20:45:32 +0000626 // We hit a token that we don't recognize as being in the
627 // "preprocessing only" part of the file, so we're no longer in
628 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000629 break;
630 } while (true);
631
632 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000633 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
634 IfCount? IfStartTok.isAtStartOfLine()
635 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000636}
637
Chris Lattner7ef5c272010-11-17 07:05:50 +0000638
639/// AdvanceToTokenCharacter - Given a location that specifies the start of a
640/// token, return a new location that specifies a character within the token.
641SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
642 unsigned CharNo,
643 const SourceManager &SM,
644 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000645 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000646 // character is. This needs to take into consideration newlines and
647 // trigraphs.
648 bool Invalid = false;
649 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
650
651 // If they request the first char of the token, we're trivially done.
652 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
653 return TokStart;
654
655 unsigned PhysOffset = 0;
656
657 // The usual case is that tokens don't contain anything interesting. Skip
658 // over the uninteresting characters. If a token only consists of simple
659 // chars, this method is extremely fast.
660 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
661 if (CharNo == 0)
662 return TokStart.getFileLocWithOffset(PhysOffset);
663 ++TokPtr, --CharNo, ++PhysOffset;
664 }
665
666 // If we have a character that may be a trigraph or escaped newline, use a
667 // lexer to parse it correctly.
668 for (; CharNo; --CharNo) {
669 unsigned Size;
670 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
671 TokPtr += Size;
672 PhysOffset += Size;
673 }
674
675 // Final detail: if we end up on an escaped newline, we want to return the
676 // location of the actual byte of the token. For example foo\<newline>bar
677 // advanced by 3 should return the location of b, not of \\. One compounding
678 // detail of this is that the escape may be made by a trigraph.
679 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
680 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
681
682 return TokStart.getFileLocWithOffset(PhysOffset);
683}
684
685/// \brief Computes the source location just past the end of the
686/// token at this source location.
687///
688/// This routine can be used to produce a source location that
689/// points just past the end of the token referenced by \p Loc, and
690/// is generally used when a diagnostic needs to point just after a
691/// token where it expected something different that it received. If
692/// the returned source location would not be meaningful (e.g., if
693/// it points into a macro), this routine returns an invalid
694/// source location.
695///
696/// \param Offset an offset from the end of the token, where the source
697/// location should refer to. The default offset (0) produces a source
698/// location pointing just past the end of the token; an offset of 1 produces
699/// a source location pointing to the last character in the token, etc.
700SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
701 const SourceManager &SM,
702 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000703 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000704 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000705
706 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000707 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
708 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000709
Chandler Carruth433db062011-07-14 08:20:40 +0000710 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000711 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000712 }
713
Chris Lattner7ef5c272010-11-17 07:05:50 +0000714 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
715 if (Len > Offset)
716 Len = Len - Offset;
717 else
718 return Loc;
719
John McCall77ebb382011-04-06 01:50:22 +0000720 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000721}
722
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000723/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000724/// token of the macro expansion.
725bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000726 const SourceManager &SM,
727 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000728 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
729
730 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
731 // FIXME: If the token comes from the macro token paste operator ('##')
732 // this function will always return false;
733 if (infoLoc.second > 0)
734 return false; // Does not point at the start of token.
735
Chandler Carruth433db062011-07-14 08:20:40 +0000736 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000737 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000738 if (expansionLoc.isFileID())
739 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000740
Chandler Carruth433db062011-07-14 08:20:40 +0000741 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000742}
743
744/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000745/// token of the macro expansion.
746bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000747 const SourceManager &SM,
748 const LangOptions &LangOpts) {
749 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
750
751 SourceLocation spellLoc = SM.getSpellingLoc(loc);
752 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
753 if (tokLen == 0)
754 return false;
755
756 FileID FID = SM.getFileID(loc);
757 SourceLocation afterLoc = loc.getFileLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000758 if (SM.isInFileID(afterLoc, FID))
759 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000760
761 // FIXME: If the token comes from the macro token paste operator ('##')
762 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000763
Chandler Carruth433db062011-07-14 08:20:40 +0000764 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000765 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000766 if (expansionLoc.isFileID())
767 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000768
Chandler Carruth433db062011-07-14 08:20:40 +0000769 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000770}
771
Reid Spencer5f016e22007-07-11 17:01:13 +0000772//===----------------------------------------------------------------------===//
773// Character information.
774//===----------------------------------------------------------------------===//
775
Reid Spencer5f016e22007-07-11 17:01:13 +0000776enum {
777 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
778 CHAR_VERT_WS = 0x02, // '\r', '\n'
779 CHAR_LETTER = 0x04, // a-z,A-Z
780 CHAR_NUMBER = 0x08, // 0-9
781 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000782 CHAR_PERIOD = 0x20, // .
783 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000784};
785
Chris Lattner03b98662009-07-07 17:09:54 +0000786// Statically initialize CharInfo table based on ASCII character set
787// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000788static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000789{
790// 0 NUL 1 SOH 2 STX 3 ETX
791// 4 EOT 5 ENQ 6 ACK 7 BEL
792 0 , 0 , 0 , 0 ,
793 0 , 0 , 0 , 0 ,
794// 8 BS 9 HT 10 NL 11 VT
795//12 NP 13 CR 14 SO 15 SI
796 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
797 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
798//16 DLE 17 DC1 18 DC2 19 DC3
799//20 DC4 21 NAK 22 SYN 23 ETB
800 0 , 0 , 0 , 0 ,
801 0 , 0 , 0 , 0 ,
802//24 CAN 25 EM 26 SUB 27 ESC
803//28 FS 29 GS 30 RS 31 US
804 0 , 0 , 0 , 0 ,
805 0 , 0 , 0 , 0 ,
806//32 SP 33 ! 34 " 35 #
807//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000808 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
809 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000810//40 ( 41 ) 42 * 43 +
811//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000812 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
813 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000814//48 0 49 1 50 2 51 3
815//52 4 53 5 54 6 55 7
816 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
817 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
818//56 8 57 9 58 : 59 ;
819//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000820 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
821 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000822//64 @ 65 A 66 B 67 C
823//68 D 69 E 70 F 71 G
824 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
825 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
826//72 H 73 I 74 J 75 K
827//76 L 77 M 78 N 79 O
828 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
829 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
830//80 P 81 Q 82 R 83 S
831//84 T 85 U 86 V 87 W
832 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
833 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
834//88 X 89 Y 90 Z 91 [
835//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000836 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
837 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000838//96 ` 97 a 98 b 99 c
839//100 d 101 e 102 f 103 g
840 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
841 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
842//104 h 105 i 106 j 107 k
843//108 l 109 m 110 n 111 o
844 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
845 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
846//112 p 113 q 114 r 115 s
847//116 t 117 u 118 v 119 w
848 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
849 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
850//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000851//124 | 125 } 126 ~ 127 DEL
852 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
853 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000854};
855
Chris Lattnera2bf1052009-12-17 05:29:40 +0000856static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 static bool isInited = false;
858 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000859 // check the statically-initialized CharInfo table
860 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
861 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
862 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
863 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
864 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
865 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
866 assert(CHAR_UNDER == CharInfo[(int)'_']);
867 assert(CHAR_PERIOD == CharInfo[(int)'.']);
868 for (unsigned i = 'a'; i <= 'z'; ++i) {
869 assert(CHAR_LETTER == CharInfo[i]);
870 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
871 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000873 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000874
Chris Lattner03b98662009-07-07 17:09:54 +0000875 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}
877
Chris Lattner03b98662009-07-07 17:09:54 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// isIdentifierBody - Return true if this is the body character of an
880/// identifier, which is [a-zA-Z0-9_].
881static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000882 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000883}
884
885/// isHorizontalWhitespace - Return true if this character is horizontal
886/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
887static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000888 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000889}
890
Anna Zaksaca25bc2011-07-27 21:43:43 +0000891/// isVerticalWhitespace - Return true if this character is vertical
892/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
893static inline bool isVerticalWhitespace(unsigned char c) {
894 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
895}
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897/// isWhitespace - Return true if this character is horizontal or vertical
898/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
899/// for '\0'.
900static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000901 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000902}
903
904/// isNumberBody - Return true if this is the body character of an
905/// preprocessing number, which is [a-zA-Z0-9_.].
906static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000907 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000908 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000909}
910
Craig Topper2fa4e862011-08-11 04:06:15 +0000911/// isRawStringDelimBody - Return true if this is the body character of a
912/// raw string delimiter.
913static inline bool isRawStringDelimBody(unsigned char c) {
914 return (CharInfo[c] &
915 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
916 true : false;
917}
918
Reid Spencer5f016e22007-07-11 17:01:13 +0000919
920//===----------------------------------------------------------------------===//
921// Diagnostics forwarding code.
922//===----------------------------------------------------------------------===//
923
Chris Lattner409a0362007-07-22 18:38:25 +0000924/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000925/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000926/// This is currently only used for _Pragma implementation, so it is the slow
927/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000928static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
929 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000930static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
931 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000932 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000933 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner409a0362007-07-22 18:38:25 +0000935 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000936 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000937 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000938 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chandler Carruth433db062011-07-14 08:20:40 +0000940 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000941 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000942 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000943 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattnere7fb4842009-02-15 20:52:18 +0000945 // Figure out the expansion loc range, which is the range covered by the
946 // original _Pragma(...) sequence.
947 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000948 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chandler Carruthbf340e42011-07-26 03:03:05 +0000950 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000951}
952
Reid Spencer5f016e22007-07-11 17:01:13 +0000953/// getSourceLocation - Return a source location identifier for the specified
954/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000955SourceLocation Lexer::getSourceLocation(const char *Loc,
956 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000957 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000959
960 // In the normal case, we're just lexing from a simple file buffer, return
961 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000962 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000963 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000964 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner2b2453a2009-01-17 06:22:33 +0000966 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
967 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000968 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000969 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000970}
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972/// Diag - Forwarding function for diagnostics. This translate a source
973/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000974DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000975 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976}
Reid Spencer5f016e22007-07-11 17:01:13 +0000977
978//===----------------------------------------------------------------------===//
979// Trigraph and Escaped Newline Handling Code.
980//===----------------------------------------------------------------------===//
981
982/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
983/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
984static char GetTrigraphCharForLetter(char Letter) {
985 switch (Letter) {
986 default: return 0;
987 case '=': return '#';
988 case ')': return ']';
989 case '(': return '[';
990 case '!': return '|';
991 case '\'': return '^';
992 case '>': return '}';
993 case '/': return '\\';
994 case '<': return '{';
995 case '-': return '~';
996 }
997}
998
999/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1000/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1001/// return the result character. Finally, emit a warning about trigraph use
1002/// whether trigraphs are enabled or not.
1003static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1004 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001005 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner3692b092008-11-18 07:59:24 +00001007 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001008 if (!L->isLexingRawMode())
1009 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001010 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner74d15df2008-11-22 02:02:22 +00001013 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 return Res;
1016}
1017
Chris Lattner24f0e482009-04-18 22:05:41 +00001018/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1019/// 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 +00001020/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001021unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1022 unsigned Size = 0;
1023 while (isWhitespace(Ptr[Size])) {
1024 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner24f0e482009-04-18 22:05:41 +00001026 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1027 continue;
1028
1029 // If this is a \r\n or \n\r, skip the other half.
1030 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1031 Ptr[Size-1] != Ptr[Size])
1032 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner24f0e482009-04-18 22:05:41 +00001034 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001035 }
1036
Chris Lattner24f0e482009-04-18 22:05:41 +00001037 // Not an escaped newline, must be a \t or something else.
1038 return 0;
1039}
1040
Chris Lattner03374952009-04-18 22:27:02 +00001041/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1042/// them), skip over them and return the first non-escaped-newline found,
1043/// otherwise return P.
1044const char *Lexer::SkipEscapedNewLines(const char *P) {
1045 while (1) {
1046 const char *AfterEscape;
1047 if (*P == '\\') {
1048 AfterEscape = P+1;
1049 } else if (*P == '?') {
1050 // If not a trigraph for escape, bail out.
1051 if (P[1] != '?' || P[2] != '/')
1052 return P;
1053 AfterEscape = P+3;
1054 } else {
1055 return P;
1056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner03374952009-04-18 22:27:02 +00001058 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1059 if (NewLineSize == 0) return P;
1060 P = AfterEscape+NewLineSize;
1061 }
1062}
1063
Anna Zaksaca25bc2011-07-27 21:43:43 +00001064/// \brief Checks that the given token is the first token that occurs after the
1065/// given location (this excludes comments and whitespace). Returns the location
1066/// immediately after the specified token. If the token is not found or the
1067/// location is inside a macro, the returned source location will be invalid.
1068SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1069 tok::TokenKind TKind,
1070 const SourceManager &SM,
1071 const LangOptions &LangOpts,
1072 bool SkipTrailingWhitespaceAndNewLine) {
1073 if (Loc.isMacroID()) {
1074 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1075 return SourceLocation();
1076 Loc = SM.getExpansionRange(Loc).second;
1077 }
1078 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1079
1080 // Break down the source location.
1081 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1082
1083 // Try to load the file buffer.
1084 bool InvalidTemp = false;
1085 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1086 if (InvalidTemp)
1087 return SourceLocation();
1088
1089 const char *TokenBegin = File.data() + LocInfo.second;
1090
1091 // Lex from the start of the given location.
1092 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1093 TokenBegin, File.end());
1094 // Find the token.
1095 Token Tok;
1096 lexer.LexFromRawLexer(Tok);
1097 if (Tok.isNot(TKind))
1098 return SourceLocation();
1099 SourceLocation TokenLoc = Tok.getLocation();
1100
1101 // Calculate how much whitespace needs to be skipped if any.
1102 unsigned NumWhitespaceChars = 0;
1103 if (SkipTrailingWhitespaceAndNewLine) {
1104 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1105 Tok.getLength();
1106 unsigned char C = *TokenEnd;
1107 while (isHorizontalWhitespace(C)) {
1108 C = *(++TokenEnd);
1109 NumWhitespaceChars++;
1110 }
1111 if (isVerticalWhitespace(C))
1112 NumWhitespaceChars++;
1113 }
1114
1115 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1116}
Chris Lattner24f0e482009-04-18 22:05:41 +00001117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1119/// get its size, and return it. This is tricky in several cases:
1120/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1121/// then either return the trigraph (skipping 3 chars) or the '?',
1122/// depending on whether trigraphs are enabled or not.
1123/// 2. If this is an escaped newline (potentially with whitespace between
1124/// the backslash and newline), implicitly skip the newline and return
1125/// the char after it.
1126/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1127///
1128/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1129/// know that we can accumulate into Size, and that we have already incremented
1130/// Ptr by Size bytes.
1131///
1132/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1133/// be updated to match.
1134///
1135char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001136 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // If we have a slash, look for an escaped newline.
1138 if (Ptr[0] == '\\') {
1139 ++Size;
1140 ++Ptr;
1141Slash:
1142 // Common case, backslash-char where the char is not whitespace.
1143 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Chris Lattner5636a3b2009-06-23 05:15:06 +00001145 // See if we have optional whitespace characters between the slash and
1146 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001147 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1148 // Remember that this token needs to be cleaned.
1149 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001150
Chris Lattner24f0e482009-04-18 22:05:41 +00001151 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001152 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001153 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Chris Lattner24f0e482009-04-18 22:05:41 +00001155 // Found backslash<whitespace><newline>. Parse the char after it.
1156 Size += EscapedNewLineSize;
1157 Ptr += EscapedNewLineSize;
1158 // Use slow version to accumulate a correct size field.
1159 return getCharAndSizeSlow(Ptr, Size, Tok);
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 // Otherwise, this is not an escaped newline, just return the slash.
1163 return '\\';
1164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // If this is a trigraph, process it.
1167 if (Ptr[0] == '?' && Ptr[1] == '?') {
1168 // If this is actually a legal trigraph (not something like "??x"), emit
1169 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1170 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1171 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001172 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 Ptr += 3;
1175 Size += 3;
1176 if (C == '\\') goto Slash;
1177 return C;
1178 }
1179 }
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // If this is neither, return a single character.
1182 ++Size;
1183 return *Ptr;
1184}
1185
1186
1187/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1188/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1189/// and that we have already incremented Ptr by Size bytes.
1190///
1191/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1192/// be updated to match.
1193char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1194 const LangOptions &Features) {
1195 // If we have a slash, look for an escaped newline.
1196 if (Ptr[0] == '\\') {
1197 ++Size;
1198 ++Ptr;
1199Slash:
1200 // Common case, backslash-char where the char is not whitespace.
1201 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001204 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1205 // Found backslash<whitespace><newline>. Parse the char after it.
1206 Size += EscapedNewLineSize;
1207 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattner24f0e482009-04-18 22:05:41 +00001209 // Use slow version to accumulate a correct size field.
1210 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 // Otherwise, this is not an escaped newline, just return the slash.
1214 return '\\';
1215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 // If this is a trigraph, process it.
1218 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1219 // If this is actually a legal trigraph (not something like "??x"), return
1220 // it.
1221 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1222 Ptr += 3;
1223 Size += 3;
1224 if (C == '\\') goto Slash;
1225 return C;
1226 }
1227 }
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // If this is neither, return a single character.
1230 ++Size;
1231 return *Ptr;
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// Helper methods for lexing.
1236//===----------------------------------------------------------------------===//
1237
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001238/// \brief Routine that indiscriminately skips bytes in the source file.
1239void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1240 BufferPtr += Bytes;
1241 if (BufferPtr > BufferEnd)
1242 BufferPtr = BufferEnd;
1243 IsAtStartOfLine = StartOfLine;
1244}
1245
Chris Lattnerd2177732007-07-20 16:59:19 +00001246void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1248 unsigned Size;
1249 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001250 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 --CurPtr; // Back up over the skipped character.
1254
1255 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1256 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1257 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001258 //
1259 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1260 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1262FinishIdentifier:
1263 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001264 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1265 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // If we are in raw mode, return this identifier raw. There is no need to
1268 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001269 if (LexingRawMode)
1270 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001272 // Fill in Result.IdentifierInfo and update the token kind,
1273 // looking up the identifier in the identifier table.
1274 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // Finally, now that we know we have an identifier, pass this off to the
1277 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001278 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001279 PP->HandleIdentifier(Result);
1280 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 C = getCharAndSize(CurPtr, Size);
1286 while (1) {
1287 if (C == '$') {
1288 // If we hit a $ and they are not supported in identifiers, we are done.
1289 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001292 if (!isLexingRawMode())
1293 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 CurPtr = ConsumeChar(CurPtr, Size, Result);
1295 C = getCharAndSize(CurPtr, Size);
1296 continue;
1297 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1298 // Found end of identifier.
1299 goto FinishIdentifier;
1300 }
1301
1302 // Otherwise, this character is good, consume it.
1303 CurPtr = ConsumeChar(CurPtr, Size, Result);
1304
1305 C = getCharAndSize(CurPtr, Size);
1306 while (isIdentifierBody(C)) { // FIXME: UCNs.
1307 CurPtr = ConsumeChar(CurPtr, Size, Result);
1308 C = getCharAndSize(CurPtr, Size);
1309 }
1310 }
1311}
1312
Douglas Gregora75ec432010-08-30 14:50:47 +00001313/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001314/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001315static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1316 unsigned Size;
1317 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1318 if (C1 != '0')
1319 return false;
1320 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1321 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001322}
Reid Spencer5f016e22007-07-11 17:01:13 +00001323
Nate Begeman5253c7f2008-04-14 02:26:39 +00001324/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001325/// constant. From[-1] is the first character lexed. Return the end of the
1326/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001327void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 unsigned Size;
1329 char C = getCharAndSize(CurPtr, Size);
1330 char PrevCh = 0;
1331 while (isNumberBody(C)) { // FIXME: UCNs?
1332 CurPtr = ConsumeChar(CurPtr, Size, Result);
1333 PrevCh = C;
1334 C = getCharAndSize(CurPtr, Size);
1335 }
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001338 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1339 // If we are in Microsoft mode, don't continue if the constant is hex.
1340 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001341 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001342 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1343 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001344
1345 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001346 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001347 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001351 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001352 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001353 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001354}
1355
1356/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001357/// either " or L" or u8" or u" or U".
1358void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1359 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 char C = getAndAdvanceChar(CurPtr, Result);
1363 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001364 // Skip escaped characters. Escaped newlines will already be processed by
1365 // getAndAdvanceChar.
1366 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001368
Chris Lattner571339c2010-05-30 23:27:38 +00001369 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001370 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001371 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1372 PP->CodeCompleteNaturalLanguage();
1373 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001374 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001375 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 }
Chris Lattner571339c2010-05-30 23:27:38 +00001378
1379 if (C == 0)
1380 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 C = getAndAdvanceChar(CurPtr, Result);
1382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001385 if (NulCharacter && !isLexingRawMode())
1386 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001389 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001390 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001391 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392}
1393
Craig Topper2fa4e862011-08-11 04:06:15 +00001394/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1395/// having lexed R", LR", u8R", uR", or UR".
1396void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1397 tok::TokenKind Kind) {
1398 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1399 // Between the initial and final double quote characters of the raw string,
1400 // any transformations performed in phases 1 and 2 (trigraphs,
1401 // universal-character-names, and line splicing) are reverted.
1402
1403 unsigned PrefixLen = 0;
1404
1405 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1406 ++PrefixLen;
1407
1408 // If the last character was not a '(', then we didn't lex a valid delimiter.
1409 if (CurPtr[PrefixLen] != '(') {
1410 if (!isLexingRawMode()) {
1411 const char *PrefixEnd = &CurPtr[PrefixLen];
1412 if (PrefixLen == 16) {
1413 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1414 } else {
1415 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1416 << StringRef(PrefixEnd, 1);
1417 }
1418 }
1419
1420 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1421 // it's possible the '"' was intended to be part of the raw string, but
1422 // there's not much we can do about that.
1423 while (1) {
1424 char C = *CurPtr++;
1425
1426 if (C == '"')
1427 break;
1428 if (C == 0 && CurPtr-1 == BufferEnd) {
1429 --CurPtr;
1430 break;
1431 }
1432 }
1433
1434 FormTokenWithChars(Result, CurPtr, tok::unknown);
1435 return;
1436 }
1437
1438 // Save prefix and move CurPtr past it
1439 const char *Prefix = CurPtr;
1440 CurPtr += PrefixLen + 1; // skip over prefix and '('
1441
1442 while (1) {
1443 char C = *CurPtr++;
1444
1445 if (C == ')') {
1446 // Check for prefix match and closing quote.
1447 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1448 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1449 break;
1450 }
1451 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1452 if (!isLexingRawMode())
1453 Diag(BufferPtr, diag::err_unterminated_raw_string)
1454 << StringRef(Prefix, PrefixLen);
1455 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1456 return;
1457 }
1458 }
1459
1460 // Update the location of token as well as BufferPtr.
1461 const char *TokStart = BufferPtr;
1462 FormTokenWithChars(Result, CurPtr, Kind);
1463 Result.setLiteralData(TokStart);
1464}
1465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1467/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001468void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001470 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 char C = getAndAdvanceChar(CurPtr, Result);
1472 while (C != '>') {
1473 // Skip escaped characters.
1474 if (C == '\\') {
1475 // Skip the escaped character.
1476 C = getAndAdvanceChar(CurPtr, Result);
1477 } else if (C == '\n' || C == '\r' || // Newline.
1478 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001479 // If the filename is unterminated, then it must just be a lone <
1480 // character. Return this as such.
1481 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 return;
1483 } else if (C == 0) {
1484 NulCharacter = CurPtr-1;
1485 }
1486 C = getAndAdvanceChar(CurPtr, Result);
1487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001490 if (NulCharacter && !isLexingRawMode())
1491 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001494 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001495 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001496 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497}
1498
1499
1500/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001501/// lexed either ' or L' or u' or U'.
1502void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1503 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 const char *NulCharacter = 0; // Does this character contain the \0 character?
1505
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 char C = getAndAdvanceChar(CurPtr, Result);
1507 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001508 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001509 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001510 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001512 }
1513
1514 while (C != '\'') {
1515 // Skip escaped characters.
1516 if (C == '\\') {
1517 // Skip the escaped character.
1518 // FIXME: UCN's
1519 C = getAndAdvanceChar(CurPtr, Result);
1520 } else if (C == '\n' || C == '\r' || // Newline.
1521 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001522 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1523 PP->CodeCompleteNaturalLanguage();
1524 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001525 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001526 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1527 return;
1528 } else if (C == 0) {
1529 NulCharacter = CurPtr-1;
1530 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 C = getAndAdvanceChar(CurPtr, Result);
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Chris Lattnerd80f7862010-07-07 23:24:27 +00001534 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001535 if (NulCharacter && !isLexingRawMode())
1536 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001539 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001540 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001541 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001542}
1543
1544/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1545/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001546///
1547/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1548///
1549bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 // Whitespace - Skip it, then return the token after the whitespace.
1551 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1552 while (1) {
1553 // Skip horizontal whitespace very aggressively.
1554 while (isHorizontalWhitespace(Char))
1555 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001557 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 if (Char != '\n' && Char != '\r')
1559 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 if (ParsingPreprocessorDirective) {
1562 // End of preprocessor directive line, let LexTokenInternal handle this.
1563 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001564 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 }
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 // ok, but handle newline.
1568 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001569 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001571 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 Char = *++CurPtr;
1573 }
1574
1575 // If this isn't immediately after a newline, there is leading space.
1576 char PrevChar = CurPtr[-1];
1577 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001578 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579
Chris Lattnerd88dc482008-10-12 04:05:48 +00001580 // If the client wants us to return whitespace, return it now.
1581 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001582 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001583 return true;
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001587 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001588}
1589
1590// SkipBCPLComment - We have just read the // characters from input. Skip until
1591// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001592/// BufferPtr and return.
1593///
1594/// If we're in KeepCommentMode or any CommentHandler has inserted
1595/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001596bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // If BCPL comments aren't explicitly enabled for this language, emit an
1598 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001599 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 // Mark them enabled so we only emit one warning for this translation
1603 // unit.
1604 Features.BCPLComment = true;
1605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // Scan over the body of the comment. The common case, when scanning, is that
1608 // the comment contains normal ascii characters with nothing interesting in
1609 // them. As such, optimize for this case with the inner loop.
1610 char C;
1611 do {
1612 C = *CurPtr;
1613 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1614 // If we find a \n character, scan backwards, checking to see if it's an
1615 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 // Skip over characters in the fast loop.
1618 while (C != 0 && // Potentially EOF.
1619 C != '\\' && // Potentially escaped newline.
1620 C != '?' && // Potentially trigraph.
1621 C != '\n' && C != '\r') // Newline or DOS-style newline.
1622 C = *++CurPtr;
1623
1624 // If this is a newline, we're done.
1625 if (C == '\n' || C == '\r')
1626 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001629 // properly decode the character. Read it in raw mode to avoid emitting
1630 // diagnostics about things like trigraphs. If we see an escaped newline,
1631 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001633 bool OldRawMode = isLexingRawMode();
1634 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001636 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001637
1638 // If the char that we finally got was a \n, then we must have had something
1639 // like \<newline><newline>. We don't want to have consumed the second
1640 // newline, we want CurPtr, to end up pointing to it down below.
1641 if (C == '\n' || C == '\r') {
1642 --CurPtr;
1643 C = 'x'; // doesn't matter what this is.
1644 }
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 // If we read multiple characters, and one of those characters was a \r or
1647 // \n, then we had an escaped newline within the comment. Emit diagnostic
1648 // unless the next line is also a // comment.
1649 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1650 for (; OldPtr != CurPtr; ++OldPtr)
1651 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1652 // Okay, we found a // comment that ends in a newline, if the next
1653 // line is also a // comment, but has spaces, don't emit a diagnostic.
1654 if (isspace(C)) {
1655 const char *ForwardPtr = CurPtr;
1656 while (isspace(*ForwardPtr)) // Skip whitespace.
1657 ++ForwardPtr;
1658 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1659 break;
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Chris Lattner74d15df2008-11-22 02:02:22 +00001662 if (!isLexingRawMode())
1663 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 break;
1665 }
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor55817af2010-08-25 17:04:25 +00001668 if (CurPtr == BufferEnd+1) {
1669 if (PP && PP->isCodeCompletionFile(FileLoc))
1670 PP->CodeCompleteNaturalLanguage();
1671
1672 --CurPtr;
1673 break;
1674 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 } while (C != '\n' && C != '\r');
1676
Chris Lattner3d0ad582010-02-03 21:06:21 +00001677 // Found but did not consume the newline. Notify comment handlers about the
1678 // comment unless we're in a #if 0 block.
1679 if (PP && !isLexingRawMode() &&
1680 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1681 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001682 BufferPtr = CurPtr;
1683 return true; // A token has to be returned.
1684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001687 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 return SaveBCPLComment(Result, CurPtr);
1689
1690 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001691 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1693 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001694 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001698 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001699 // contribute to another token), it isn't needed for correctness. Note that
1700 // this is ok even in KeepWhitespaceMode, because we would have returned the
1701 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001705 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001707 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001709 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001710}
1711
1712/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1713/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001714bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001715 // If we're not in a preprocessor directive, just return the // comment
1716 // directly.
1717 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Chris Lattner9e6293d2008-10-12 04:51:35 +00001719 if (!ParsingPreprocessorDirective)
1720 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner9e6293d2008-10-12 04:51:35 +00001722 // If this BCPL-style comment is in a macro definition, transmogrify it into
1723 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001724 bool Invalid = false;
1725 std::string Spelling = PP->getSpelling(Result, &Invalid);
1726 if (Invalid)
1727 return true;
1728
Chris Lattner9e6293d2008-10-12 04:51:35 +00001729 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1730 Spelling[1] = '*'; // Change prefix to "/*".
1731 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Chris Lattner9e6293d2008-10-12 04:51:35 +00001733 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001734 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1735 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001736 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001737}
1738
1739/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1740/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001741/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001742static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 Lexer *L) {
1744 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 // Back up off the newline.
1747 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 // If this is a two-character newline sequence, skip the other character.
1750 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1751 // \n\n or \r\r -> not escaped newline.
1752 if (CurPtr[0] == CurPtr[1])
1753 return false;
1754 // \n\r or \r\n -> skip the newline.
1755 --CurPtr;
1756 }
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 // If we have horizontal whitespace, skip over it. We allow whitespace
1759 // between the slash and newline.
1760 bool HasSpace = false;
1761 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1762 --CurPtr;
1763 HasSpace = true;
1764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 // If we have a slash, we know this is an escaped newline.
1767 if (*CurPtr == '\\') {
1768 if (CurPtr[-1] != '*') return false;
1769 } else {
1770 // It isn't a slash, is it the ?? / trigraph?
1771 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1772 CurPtr[-3] != '*')
1773 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 // This is the trigraph ending the comment. Emit a stern warning!
1776 CurPtr -= 2;
1777
1778 // If no trigraphs are enabled, warn that we ignored this trigraph and
1779 // ignore this * character.
1780 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001781 if (!L->isLexingRawMode())
1782 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 return false;
1784 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001785 if (!L->isLexingRawMode())
1786 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001790 if (!L->isLexingRawMode())
1791 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001794 if (HasSpace && !L->isLexingRawMode())
1795 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 return true;
1798}
1799
1800#ifdef __SSE2__
1801#include <emmintrin.h>
1802#elif __ALTIVEC__
1803#include <altivec.h>
1804#undef bool
1805#endif
1806
1807/// SkipBlockComment - We have just read the /* characters from input. Read
1808/// until we find the */ characters that terminate the comment. Note that we
1809/// don't bother decoding trigraphs or escaped newlines in block comments,
1810/// because they cannot cause the comment to end. The only thing that can
1811/// happen is the comment could end with an escaped newline between the */ end
1812/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001813///
Chris Lattner046c2272010-01-18 22:35:47 +00001814/// If we're in KeepCommentMode or any CommentHandler has inserted
1815/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001816bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001818 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 // optimization helps people who like to put a lot of * characters in their
1820 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001821
1822 // The first character we get with newlines and trigraphs skipped to handle
1823 // the degenerate /*/ case below correctly if the * has an escaped newline
1824 // after it.
1825 unsigned CharSize;
1826 unsigned char C = getCharAndSize(CurPtr, CharSize);
1827 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001829 if (!isLexingRawMode() &&
1830 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001831 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001832 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Chris Lattner31f0eca2008-10-12 04:19:49 +00001834 // KeepWhitespaceMode should return this broken comment as a token. Since
1835 // it isn't a well formed comment, just return it as an 'unknown' token.
1836 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001837 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001838 return true;
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Chris Lattner31f0eca2008-10-12 04:19:49 +00001841 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001842 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 }
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Chris Lattner8146b682007-07-21 23:43:37 +00001845 // Check to see if the first character after the '/*' is another /. If so,
1846 // then this slash does not end the block comment, it is part of it.
1847 if (C == '/')
1848 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 while (1) {
1851 // Skip over all non-interesting characters until we find end of buffer or a
1852 // (probably ending) '/' character.
1853 if (CurPtr + 24 < BufferEnd) {
1854 // While not aligned to a 16-byte boundary.
1855 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1856 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 if (C == '/') goto FoundSlash;
1859
1860#ifdef __SSE2__
1861 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1862 '/', '/', '/', '/', '/', '/', '/', '/');
1863 while (CurPtr+16 <= BufferEnd &&
1864 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1865 CurPtr += 16;
1866#elif __ALTIVEC__
1867 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001868 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 '/', '/', '/', '/', '/', '/', '/', '/'
1870 };
1871 while (CurPtr+16 <= BufferEnd &&
1872 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1873 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001874#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 // Scan for '/' quickly. Many block comments are very large.
1876 while (CurPtr[0] != '/' &&
1877 CurPtr[1] != '/' &&
1878 CurPtr[2] != '/' &&
1879 CurPtr[3] != '/' &&
1880 CurPtr+4 < BufferEnd) {
1881 CurPtr += 4;
1882 }
1883#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // It has to be one of the bytes scanned, increment to it and read one.
1886 C = *CurPtr++;
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 // Loop to scan the remainder.
1890 while (C != '/' && C != '\0')
1891 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 FoundSlash:
1894 if (C == '/') {
1895 if (CurPtr[-2] == '*') // We found the final */. We're done!
1896 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1899 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1900 // We found the final */, though it had an escaped newline between the
1901 // * and /. We're done!
1902 break;
1903 }
1904 }
1905 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1906 // If this is a /* inside of the comment, emit a warning. Don't do this
1907 // if this is a /*/, which will end the comment. This misses cases with
1908 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001909 if (!isLexingRawMode())
1910 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 }
1912 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001913 if (PP && PP->isCodeCompletionFile(FileLoc))
1914 PP->CodeCompleteNaturalLanguage();
1915 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001916 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // Note: the user probably forgot a */. We could continue immediately
1918 // after the /*, but this would involve lexing a lot of what really is the
1919 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001920 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Chris Lattner31f0eca2008-10-12 04:19:49 +00001922 // KeepWhitespaceMode should return this broken comment as a token. Since
1923 // it isn't a well formed comment, just return it as an 'unknown' token.
1924 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001925 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001926 return true;
1927 }
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Chris Lattner31f0eca2008-10-12 04:19:49 +00001929 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001930 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
1932 C = *CurPtr++;
1933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattner3d0ad582010-02-03 21:06:21 +00001935 // Notify comment handlers about the comment unless we're in a #if 0 block.
1936 if (PP && !isLexingRawMode() &&
1937 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1938 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001939 BufferPtr = CurPtr;
1940 return true; // A token has to be returned.
1941 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001942
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001944 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001945 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001946 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 }
1948
1949 // It is common for the tokens immediately after a /**/ comment to be
1950 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001951 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1952 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001954 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001956 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 }
1958
1959 // Otherwise, just return so that the next character will be lexed as a token.
1960 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001961 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001962 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963}
1964
1965//===----------------------------------------------------------------------===//
1966// Primary Lexing Entry Points
1967//===----------------------------------------------------------------------===//
1968
Reid Spencer5f016e22007-07-11 17:01:13 +00001969/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1970/// uninterpreted string. This switches the lexer out of directive mode.
1971std::string Lexer::ReadToEndOfLine() {
1972 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1973 "Must be in a preprocessing directive!");
1974 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001975 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001976
1977 // CurPtr - Cache BufferPtr in an automatic variable.
1978 const char *CurPtr = BufferPtr;
1979 while (1) {
1980 char Char = getAndAdvanceChar(CurPtr, Tmp);
1981 switch (Char) {
1982 default:
1983 Result += Char;
1984 break;
1985 case 0: // Null.
1986 // Found end of file?
1987 if (CurPtr-1 != BufferEnd) {
1988 // Nope, normal character, continue.
1989 Result += Char;
1990 break;
1991 }
1992 // FALL THROUGH.
1993 case '\r':
1994 case '\n':
1995 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1996 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1997 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Peter Collingbourne84021552011-02-28 02:37:51 +00001999 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002001 if (Tmp.is(tok::code_completion)) {
2002 if (PP && PP->getCodeCompletionHandler())
2003 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
2004 Lex(Tmp);
2005 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002006 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 // Finally, we're done, return the string we found.
2009 return Result;
2010 }
2011 }
2012}
2013
2014/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2015/// condition, reporting diagnostics and handling other edge cases as required.
2016/// This returns true if Result contains a token, false if PP.Lex should be
2017/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002018bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00002019 // Check if we are performing code completion.
2020 if (PP && PP->isCodeCompletionFile(FileLoc)) {
2021 // We're at the end of the file, but we've been asked to consider the
2022 // end of the file to be a code-completion token. Return the
2023 // code-completion token.
2024 Result.startToken();
2025 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2026
2027 // Only do the eof -> code_completion translation once.
2028 PP->SetCodeCompletionPoint(0, 0, 0);
2029
2030 // Silence any diagnostics that occur once we hit the code-completion point.
2031 PP->getDiagnostics().setSuppressAllDiagnostics(true);
2032 return true;
2033 }
2034
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 // If we hit the end of the file while parsing a preprocessor directive,
2036 // end the preprocessor directive first. The next token returned will
2037 // then be the end of file.
2038 if (ParsingPreprocessorDirective) {
2039 // Done parsing the "line".
2040 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002042 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002045 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002047 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // If we are in raw mode, return this event as an EOF token. Let the caller
2050 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002051 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 Result.startToken();
2053 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002054 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 return true;
2056 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002057
Douglas Gregorf44e8542010-08-24 19:08:16 +00002058 // Issue diagnostics for unterminated #if and missing newline.
2059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // If we are in a #if directive, emit an error.
2061 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002062 if (!PP->isCodeCompletionFile(FileLoc))
2063 PP->Diag(ConditionalStack.back().IfLoc,
2064 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 ConditionalStack.pop_back();
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002068 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2069 // a pedwarn.
2070 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002071 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002072 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 BufferPtr = CurPtr;
2075
2076 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002077 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002078}
2079
2080/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2081/// the specified lexer will return a tok::l_paren token, 0 if it is something
2082/// else and 2 if there are no more tokens in the buffer controlled by the
2083/// lexer.
2084unsigned Lexer::isNextPPTokenLParen() {
2085 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Switch to 'skipping' mode. This will ensure that we can lex a token
2088 // without emitting diagnostics, disables macro expansion, and will cause EOF
2089 // to return an EOF token instead of popping the include stack.
2090 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // Save state that can be changed while lexing so that we can restore it.
2093 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002094 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Chris Lattnerd2177732007-07-20 16:59:19 +00002096 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 Tok.startToken();
2098 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 // Restore state that may have changed.
2101 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002102 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Restore the lexer back to non-skipping mode.
2105 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002107 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002109 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002110}
2111
Chris Lattner34f349d2009-12-14 06:16:57 +00002112/// FindConflictEnd - Find the end of a version control conflict marker.
2113static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002114 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002115 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002116 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002117 // Must occur at start of line.
2118 if (RestOfBuffer[Pos-1] != '\r' &&
2119 RestOfBuffer[Pos-1] != '\n') {
2120 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002121 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002122 continue;
2123 }
2124 return RestOfBuffer.data()+Pos;
2125 }
2126 return 0;
2127}
2128
2129/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2130/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2131/// and recover nicely. This returns true if it is a conflict marker and false
2132/// if not.
2133bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2134 // Only a conflict marker if it starts at the beginning of a line.
2135 if (CurPtr != BufferStart &&
2136 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2137 return false;
2138
2139 // Check to see if we have <<<<<<<.
2140 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002141 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002142 return false;
2143
2144 // If we have a situation where we don't care about conflict markers, ignore
2145 // it.
2146 if (IsInConflictMarker || isLexingRawMode())
2147 return false;
2148
2149 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2150 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002151 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002152 // We found a match. We are really in a conflict marker.
2153 // Diagnose this, and ignore to the end of line.
2154 Diag(CurPtr, diag::err_conflict_marker);
2155 IsInConflictMarker = true;
2156
2157 // Skip ahead to the end of line. We know this exists because the
2158 // end-of-conflict marker starts with \r or \n.
2159 while (*CurPtr != '\r' && *CurPtr != '\n') {
2160 assert(CurPtr != BufferEnd && "Didn't find end of line");
2161 ++CurPtr;
2162 }
2163 BufferPtr = CurPtr;
2164 return true;
2165 }
2166
2167 // No end of conflict marker found.
2168 return false;
2169}
2170
2171
2172/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2173/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2174/// until the end of the line. This returns true if it is a conflict marker and
2175/// false if not.
2176bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2177 // Only a conflict marker if it starts at the beginning of a line.
2178 if (CurPtr != BufferStart &&
2179 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2180 return false;
2181
2182 // If we have a situation where we don't care about conflict markers, ignore
2183 // it.
2184 if (!IsInConflictMarker || isLexingRawMode())
2185 return false;
2186
2187 // Check to see if we have the marker (7 characters in a row).
2188 for (unsigned i = 1; i != 7; ++i)
2189 if (CurPtr[i] != CurPtr[0])
2190 return false;
2191
2192 // If we do have it, search for the end of the conflict marker. This could
2193 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2194 // be the end of conflict marker.
2195 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2196 CurPtr = End;
2197
2198 // Skip ahead to the end of line.
2199 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2200 ++CurPtr;
2201
2202 BufferPtr = CurPtr;
2203
2204 // No longer in the conflict marker.
2205 IsInConflictMarker = false;
2206 return true;
2207 }
2208
2209 return false;
2210}
2211
Reid Spencer5f016e22007-07-11 17:01:13 +00002212
2213/// LexTokenInternal - This implements a simple C family lexer. It is an
2214/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002215/// has a null character at the end of the file. This returns a preprocessing
2216/// token, not a normal token, as such, it is an internal interface. It assumes
2217/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002218void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002219LexNextToken:
2220 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002221 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Reid Spencer5f016e22007-07-11 17:01:13 +00002224 // CurPtr - Cache BufferPtr in an automatic variable.
2225 const char *CurPtr = BufferPtr;
2226
2227 // Small amounts of horizontal whitespace is very common between tokens.
2228 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2229 ++CurPtr;
2230 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2231 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Chris Lattnerd88dc482008-10-12 04:05:48 +00002233 // If we are keeping whitespace and other tokens, just return what we just
2234 // skipped. The next lexer invocation will return the token after the
2235 // whitespace.
2236 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002237 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002238 return;
2239 }
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002242 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 }
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 // Read a character, advancing over it.
2248 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002249 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 switch (Char) {
2252 case 0: // Null.
2253 // Found end of file?
2254 if (CurPtr-1 == BufferEnd) {
2255 // Read the PP instance variable into an automatic variable, because
2256 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002257 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2259 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002260 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2261 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 }
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chris Lattner74d15df2008-11-22 02:02:22 +00002264 if (!isLexingRawMode())
2265 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002266 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002267 if (SkipWhitespace(Result, CurPtr))
2268 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002271
2272 case 26: // DOS & CP/M EOF: "^Z".
2273 // If we're in Microsoft extensions mode, treat this as end of file.
2274 if (Features.Microsoft) {
2275 // Read the PP instance variable into an automatic variable, because
2276 // LexEndOfFile will often delete 'this'.
2277 Preprocessor *PPCache = PP;
2278 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2279 return; // Got a token to return.
2280 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2281 return PPCache->Lex(Result);
2282 }
2283 // If Microsoft extensions are disabled, this is just random garbage.
2284 Kind = tok::unknown;
2285 break;
2286
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 case '\n':
2288 case '\r':
2289 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002290 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 if (ParsingPreprocessorDirective) {
2292 // Done parsing the "line".
2293 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002296 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Reid Spencer5f016e22007-07-11 17:01:13 +00002298 // Since we consumed a newline, we are back at the start of a line.
2299 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Peter Collingbourne84021552011-02-28 02:37:51 +00002301 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 break;
2303 }
2304 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002305 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002307 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Chris Lattnerd88dc482008-10-12 04:05:48 +00002309 if (SkipWhitespace(Result, CurPtr))
2310 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 goto LexNextToken; // GCC isn't tail call eliminating.
2312 case ' ':
2313 case '\t':
2314 case '\f':
2315 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002316 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002317 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002318 if (SkipWhitespace(Result, CurPtr))
2319 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002320
2321 SkipIgnoredUnits:
2322 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Chris Lattner8133cfc2007-07-22 06:29:05 +00002324 // If the next token is obviously a // or /* */ comment, skip it efficiently
2325 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002326 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002327 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002328 if (SkipBCPLComment(Result, CurPtr+2))
2329 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002330 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002331 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002332 if (SkipBlockComment(Result, CurPtr+2))
2333 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002334 goto SkipIgnoredUnits;
2335 } else if (isHorizontalWhitespace(*CurPtr)) {
2336 goto SkipHorizontalWhitespace;
2337 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002339
Chris Lattner3a570772008-01-03 17:58:54 +00002340 // C99 6.4.4.1: Integer Constants.
2341 // C99 6.4.4.2: Floating Constants.
2342 case '0': case '1': case '2': case '3': case '4':
2343 case '5': case '6': case '7': case '8': case '9':
2344 // Notify MIOpt that we read a non-whitespace/non-comment token.
2345 MIOpt.ReadToken();
2346 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor5cee1192011-07-27 05:40:30 +00002348 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2349 // Notify MIOpt that we read a non-whitespace/non-comment token.
2350 MIOpt.ReadToken();
2351
2352 if (Features.CPlusPlus0x) {
2353 Char = getCharAndSize(CurPtr, SizeTmp);
2354
2355 // UTF-16 string literal
2356 if (Char == '"')
2357 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2358 tok::utf16_string_literal);
2359
2360 // UTF-16 character constant
2361 if (Char == '\'')
2362 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2363 tok::utf16_char_constant);
2364
Craig Topper2fa4e862011-08-11 04:06:15 +00002365 // UTF-16 raw string literal
2366 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2367 return LexRawStringLiteral(Result,
2368 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2369 SizeTmp2, Result),
2370 tok::utf16_string_literal);
2371
2372 if (Char == '8') {
2373 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2374
2375 // UTF-8 string literal
2376 if (Char2 == '"')
2377 return LexStringLiteral(Result,
2378 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2379 SizeTmp2, Result),
2380 tok::utf8_string_literal);
2381
2382 if (Char2 == 'R') {
2383 unsigned SizeTmp3;
2384 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2385 // UTF-8 raw string literal
2386 if (Char3 == '"') {
2387 return LexRawStringLiteral(Result,
2388 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2389 SizeTmp2, Result),
2390 SizeTmp3, Result),
2391 tok::utf8_string_literal);
2392 }
2393 }
2394 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002395 }
2396
2397 // treat u like the start of an identifier.
2398 return LexIdentifier(Result, CurPtr);
2399
2400 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2401 // Notify MIOpt that we read a non-whitespace/non-comment token.
2402 MIOpt.ReadToken();
2403
2404 if (Features.CPlusPlus0x) {
2405 Char = getCharAndSize(CurPtr, SizeTmp);
2406
2407 // UTF-32 string literal
2408 if (Char == '"')
2409 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2410 tok::utf32_string_literal);
2411
2412 // UTF-32 character constant
2413 if (Char == '\'')
2414 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2415 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002416
2417 // UTF-32 raw string literal
2418 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2419 return LexRawStringLiteral(Result,
2420 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2421 SizeTmp2, Result),
2422 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002423 }
2424
2425 // treat U like the start of an identifier.
2426 return LexIdentifier(Result, CurPtr);
2427
Craig Topper2fa4e862011-08-11 04:06:15 +00002428 case 'R': // Identifier or C++0x raw string literal
2429 // Notify MIOpt that we read a non-whitespace/non-comment token.
2430 MIOpt.ReadToken();
2431
2432 if (Features.CPlusPlus0x) {
2433 Char = getCharAndSize(CurPtr, SizeTmp);
2434
2435 if (Char == '"')
2436 return LexRawStringLiteral(Result,
2437 ConsumeChar(CurPtr, SizeTmp, Result),
2438 tok::string_literal);
2439 }
2440
2441 // treat R like the start of an identifier.
2442 return LexIdentifier(Result, CurPtr);
2443
Chris Lattner3a570772008-01-03 17:58:54 +00002444 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 // Notify MIOpt that we read a non-whitespace/non-comment token.
2446 MIOpt.ReadToken();
2447 Char = getCharAndSize(CurPtr, SizeTmp);
2448
2449 // Wide string literal.
2450 if (Char == '"')
2451 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002452 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002453
Craig Topper2fa4e862011-08-11 04:06:15 +00002454 // Wide raw string literal.
2455 if (Features.CPlusPlus0x && Char == 'R' &&
2456 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2457 return LexRawStringLiteral(Result,
2458 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2459 SizeTmp2, Result),
2460 tok::wide_string_literal);
2461
Reid Spencer5f016e22007-07-11 17:01:13 +00002462 // Wide character constant.
2463 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002464 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2465 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002466 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 // C99 6.4.2: Identifiers.
2469 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2470 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002471 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002472 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2473 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2474 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002475 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 case 'v': case 'w': case 'x': case 'y': case 'z':
2477 case '_':
2478 // Notify MIOpt that we read a non-whitespace/non-comment token.
2479 MIOpt.ReadToken();
2480 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002481
2482 case '$': // $ in identifiers.
2483 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002484 if (!isLexingRawMode())
2485 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002486 // Notify MIOpt that we read a non-whitespace/non-comment token.
2487 MIOpt.ReadToken();
2488 return LexIdentifier(Result, CurPtr);
2489 }
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Chris Lattner9e6293d2008-10-12 04:51:35 +00002491 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002492 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 // C99 6.4.4: Character Constants.
2495 case '\'':
2496 // Notify MIOpt that we read a non-whitespace/non-comment token.
2497 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002498 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002499
2500 // C99 6.4.5: String Literals.
2501 case '"':
2502 // Notify MIOpt that we read a non-whitespace/non-comment token.
2503 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002504 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002505
2506 // C99 6.4.6: Punctuators.
2507 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002508 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 break;
2510 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002511 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 break;
2513 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002514 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 break;
2516 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002517 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 break;
2519 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002520 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002521 break;
2522 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002523 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 break;
2525 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002526 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 break;
2528 case '.':
2529 Char = getCharAndSize(CurPtr, SizeTmp);
2530 if (Char >= '0' && Char <= '9') {
2531 // Notify MIOpt that we read a non-whitespace/non-comment token.
2532 MIOpt.ReadToken();
2533
2534 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2535 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002536 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 CurPtr += SizeTmp;
2538 } else if (Char == '.' &&
2539 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002540 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2542 SizeTmp2, Result);
2543 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002544 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 }
2546 break;
2547 case '&':
2548 Char = getCharAndSize(CurPtr, SizeTmp);
2549 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002550 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2552 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002553 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2555 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002556 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 }
2558 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002559 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002561 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2563 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002564 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 }
2566 break;
2567 case '+':
2568 Char = getCharAndSize(CurPtr, SizeTmp);
2569 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002571 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002574 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002576 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 }
2578 break;
2579 case '-':
2580 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002581 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002583 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002584 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002585 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2587 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002588 Kind = tok::arrowstar;
2589 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002591 Kind = tok::arrow;
2592 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002594 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002596 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 }
2598 break;
2599 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002600 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 break;
2602 case '!':
2603 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002604 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2606 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002607 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 }
2609 break;
2610 case '/':
2611 // 6.4.9: Comments
2612 Char = getCharAndSize(CurPtr, SizeTmp);
2613 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002614 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2615 // want to lex this as a comment. There is one problem with this though,
2616 // that in one particular corner case, this can change the behavior of the
2617 // resultant program. For example, In "foo //**/ bar", C89 would lex
2618 // this as "foo / bar" and langauges with BCPL comments would lex it as
2619 // "foo". Check to see if the character after the second slash is a '*'.
2620 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002621 // However, we never do this in -traditional-cpp mode.
2622 if ((Features.BCPLComment ||
2623 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2624 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002625 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002626 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Chris Lattner8402c732009-01-16 22:39:25 +00002628 // It is common for the tokens immediately after a // comment to be
2629 // whitespace (indentation for the next line). Instead of going through
2630 // the big switch, handle it efficiently now.
2631 goto SkipIgnoredUnits;
2632 }
2633 }
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Chris Lattner8402c732009-01-16 22:39:25 +00002635 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002637 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002638 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002639 }
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Chris Lattner8402c732009-01-16 22:39:25 +00002641 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002642 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002643 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002645 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 }
2647 break;
2648 case '%':
2649 Char = getCharAndSize(CurPtr, SizeTmp);
2650 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002651 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2653 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002654 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2656 } else if (Features.Digraphs && Char == ':') {
2657 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2658 Char = getCharAndSize(CurPtr, SizeTmp);
2659 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002660 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2662 SizeTmp2, Result);
2663 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002665 if (!isLexingRawMode())
2666 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002667 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002668 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002669 // We parsed a # character. If this occurs at the start of the line,
2670 // it's actually the start of a preprocessing directive. Callback to
2671 // the preprocessor to handle it.
2672 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002673 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002674 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002675 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 // As an optimization, if the preprocessor didn't switch lexers, tail
2678 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002679 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 // Start a new token. If this is a #include or something, the PP may
2681 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002682 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002684 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002685 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 IsAtStartOfLine = false;
2687 }
2688 goto LexNextToken; // GCC isn't tail call eliminating.
2689 }
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Chris Lattner168ae2d2007-10-17 20:41:00 +00002691 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Chris Lattnere91e9322009-03-18 20:58:27 +00002694 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 }
2696 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002697 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 }
2699 break;
2700 case '<':
2701 Char = getCharAndSize(CurPtr, SizeTmp);
2702 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002703 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002705 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2706 if (After == '=') {
2707 Kind = tok::lesslessequal;
2708 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2709 SizeTmp2, Result);
2710 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2711 // If this is actually a '<<<<<<<' version control conflict marker,
2712 // recognize it as such and recover nicely.
2713 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002714 } else if (Features.CUDA && After == '<') {
2715 Kind = tok::lesslessless;
2716 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2717 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002718 } else {
2719 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2720 Kind = tok::lessless;
2721 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002724 Kind = tok::lessequal;
2725 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002726 if (Features.CPlusPlus0x &&
2727 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2728 // C++0x [lex.pptoken]p3:
2729 // Otherwise, if the next three characters are <:: and the subsequent
2730 // character is neither : nor >, the < is treated as a preprocessor
2731 // token by itself and not as the first character of the alternative
2732 // token <:.
2733 unsigned SizeTmp3;
2734 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2735 if (After != ':' && After != '>') {
2736 Kind = tok::less;
2737 break;
2738 }
2739 }
2740
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002742 Kind = tok::l_square;
2743 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002745 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002747 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 }
2749 break;
2750 case '>':
2751 Char = getCharAndSize(CurPtr, SizeTmp);
2752 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002754 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002756 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2757 if (After == '=') {
2758 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2759 SizeTmp2, Result);
2760 Kind = tok::greatergreaterequal;
2761 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2762 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2763 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002764 } else if (Features.CUDA && After == '>') {
2765 Kind = tok::greatergreatergreater;
2766 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2767 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002768 } else {
2769 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2770 Kind = tok::greatergreater;
2771 }
2772
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002774 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 }
2776 break;
2777 case '^':
2778 Char = getCharAndSize(CurPtr, SizeTmp);
2779 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002781 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002783 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 }
2785 break;
2786 case '|':
2787 Char = getCharAndSize(CurPtr, SizeTmp);
2788 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2791 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002792 // If this is '|||||||' and we're in a conflict marker, ignore it.
2793 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2794 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002795 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2797 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002798 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 }
2800 break;
2801 case ':':
2802 Char = getCharAndSize(CurPtr, SizeTmp);
2803 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002804 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2806 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002807 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002809 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002810 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 }
2812 break;
2813 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002814 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 break;
2816 case '=':
2817 Char = getCharAndSize(CurPtr, SizeTmp);
2818 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002819 // If this is '=======' and we're in a conflict marker, ignore it.
2820 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2821 goto LexNextToken;
2822
Chris Lattner9e6293d2008-10-12 04:51:35 +00002823 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002825 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002826 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
2828 break;
2829 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002830 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 break;
2832 case '#':
2833 Char = getCharAndSize(CurPtr, SizeTmp);
2834 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002835 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2837 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002838 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002839 if (!isLexingRawMode())
2840 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2842 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 // We parsed a # character. If this occurs at the start of the line,
2844 // it's actually the start of a preprocessing directive. Callback to
2845 // the preprocessor to handle it.
2846 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002847 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002848 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002849 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 // As an optimization, if the preprocessor didn't switch lexers, tail
2852 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002853 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002854 // Start a new token. If this is a #include or something, the PP may
2855 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002856 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002858 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002859 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 IsAtStartOfLine = false;
2861 }
2862 goto LexNextToken; // GCC isn't tail call eliminating.
2863 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002864 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002865 }
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Chris Lattnere91e9322009-03-18 20:58:27 +00002867 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 }
2869 break;
2870
Chris Lattner3a570772008-01-03 17:58:54 +00002871 case '@':
2872 // Objective C support.
2873 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002874 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002875 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002876 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002877 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Reid Spencer5f016e22007-07-11 17:01:13 +00002879 case '\\':
2880 // FIXME: UCN's.
2881 // FALL THROUGH.
2882 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002883 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 break;
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Reid Spencer5f016e22007-07-11 17:01:13 +00002887 // Notify MIOpt that we read a non-whitespace/non-comment token.
2888 MIOpt.ReadToken();
2889
2890 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002891 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002892}