blob: 25f07c9e4f1d6ab9848ae837e8f955a48e9cc146 [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>
Douglas Gregordf95a132010-08-09 20:45:32 +0000508Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000509 // Create a lexer starting at the beginning of the file. Note that we use a
510 // "fake" file source location at offset 1 so that the lexer will track our
511 // position within the file.
512 const unsigned StartOffset = 1;
513 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
514 LangOptions LangOpts;
515 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
516 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);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000758 if (!SM.isBeforeInSourceLocationOffset(afterLoc, SM.getNextLocalOffset()))
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000759 return true; // We got past the last FileID, this points to the last token.
760
761 // FIXME: If the token comes from the macro token paste operator ('##')
762 // or the stringify operator ('#') this function will always return false;
763 if (FID == SM.getFileID(afterLoc))
764 return false; // Still in the same FileID, does not point to the last token.
765
Chandler Carruth433db062011-07-14 08:20:40 +0000766 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000767 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000768 if (expansionLoc.isFileID())
769 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000770
Chandler Carruth433db062011-07-14 08:20:40 +0000771 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000772}
773
Reid Spencer5f016e22007-07-11 17:01:13 +0000774//===----------------------------------------------------------------------===//
775// Character information.
776//===----------------------------------------------------------------------===//
777
Reid Spencer5f016e22007-07-11 17:01:13 +0000778enum {
779 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
780 CHAR_VERT_WS = 0x02, // '\r', '\n'
781 CHAR_LETTER = 0x04, // a-z,A-Z
782 CHAR_NUMBER = 0x08, // 0-9
783 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000784 CHAR_PERIOD = 0x20, // .
785 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000786};
787
Chris Lattner03b98662009-07-07 17:09:54 +0000788// Statically initialize CharInfo table based on ASCII character set
789// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000790static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000791{
792// 0 NUL 1 SOH 2 STX 3 ETX
793// 4 EOT 5 ENQ 6 ACK 7 BEL
794 0 , 0 , 0 , 0 ,
795 0 , 0 , 0 , 0 ,
796// 8 BS 9 HT 10 NL 11 VT
797//12 NP 13 CR 14 SO 15 SI
798 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
799 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
800//16 DLE 17 DC1 18 DC2 19 DC3
801//20 DC4 21 NAK 22 SYN 23 ETB
802 0 , 0 , 0 , 0 ,
803 0 , 0 , 0 , 0 ,
804//24 CAN 25 EM 26 SUB 27 ESC
805//28 FS 29 GS 30 RS 31 US
806 0 , 0 , 0 , 0 ,
807 0 , 0 , 0 , 0 ,
808//32 SP 33 ! 34 " 35 #
809//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000810 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
811 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000812//40 ( 41 ) 42 * 43 +
813//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000814 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
815 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000816//48 0 49 1 50 2 51 3
817//52 4 53 5 54 6 55 7
818 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
819 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
820//56 8 57 9 58 : 59 ;
821//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000822 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
823 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000824//64 @ 65 A 66 B 67 C
825//68 D 69 E 70 F 71 G
826 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
827 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
828//72 H 73 I 74 J 75 K
829//76 L 77 M 78 N 79 O
830 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
831 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
832//80 P 81 Q 82 R 83 S
833//84 T 85 U 86 V 87 W
834 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
835 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
836//88 X 89 Y 90 Z 91 [
837//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000838 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
839 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000840//96 ` 97 a 98 b 99 c
841//100 d 101 e 102 f 103 g
842 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
843 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
844//104 h 105 i 106 j 107 k
845//108 l 109 m 110 n 111 o
846 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
847 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
848//112 p 113 q 114 r 115 s
849//116 t 117 u 118 v 119 w
850 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
851 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
852//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000853//124 | 125 } 126 ~ 127 DEL
854 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
855 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000856};
857
Chris Lattnera2bf1052009-12-17 05:29:40 +0000858static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 static bool isInited = false;
860 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000861 // check the statically-initialized CharInfo table
862 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
863 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
864 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
865 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
866 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
867 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
868 assert(CHAR_UNDER == CharInfo[(int)'_']);
869 assert(CHAR_PERIOD == CharInfo[(int)'.']);
870 for (unsigned i = 'a'; i <= 'z'; ++i) {
871 assert(CHAR_LETTER == CharInfo[i]);
872 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
873 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000875 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000876
Chris Lattner03b98662009-07-07 17:09:54 +0000877 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000878}
879
Chris Lattner03b98662009-07-07 17:09:54 +0000880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881/// isIdentifierBody - Return true if this is the body character of an
882/// identifier, which is [a-zA-Z0-9_].
883static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000884 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
887/// isHorizontalWhitespace - Return true if this character is horizontal
888/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
889static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000890 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
892
Anna Zaksaca25bc2011-07-27 21:43:43 +0000893/// isVerticalWhitespace - Return true if this character is vertical
894/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
895static inline bool isVerticalWhitespace(unsigned char c) {
896 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
897}
898
Reid Spencer5f016e22007-07-11 17:01:13 +0000899/// isWhitespace - Return true if this character is horizontal or vertical
900/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
901/// for '\0'.
902static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000903 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000904}
905
906/// isNumberBody - Return true if this is the body character of an
907/// preprocessing number, which is [a-zA-Z0-9_.].
908static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000909 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000910 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000911}
912
Craig Topper2fa4e862011-08-11 04:06:15 +0000913/// isRawStringDelimBody - Return true if this is the body character of a
914/// raw string delimiter.
915static inline bool isRawStringDelimBody(unsigned char c) {
916 return (CharInfo[c] &
917 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
918 true : false;
919}
920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921
922//===----------------------------------------------------------------------===//
923// Diagnostics forwarding code.
924//===----------------------------------------------------------------------===//
925
Chris Lattner409a0362007-07-22 18:38:25 +0000926/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000927/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000928/// This is currently only used for _Pragma implementation, so it is the slow
929/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000930static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
931 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000932static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
933 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000934 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000935 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattner409a0362007-07-22 18:38:25 +0000937 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000938 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000939 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000940 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chandler Carruth433db062011-07-14 08:20:40 +0000942 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000943 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000944 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000945 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattnere7fb4842009-02-15 20:52:18 +0000947 // Figure out the expansion loc range, which is the range covered by the
948 // original _Pragma(...) sequence.
949 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000950 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Chandler Carruthbf340e42011-07-26 03:03:05 +0000952 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000953}
954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955/// getSourceLocation - Return a source location identifier for the specified
956/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000957SourceLocation Lexer::getSourceLocation(const char *Loc,
958 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000959 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000960 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000961
962 // In the normal case, we're just lexing from a simple file buffer, return
963 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000964 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000965 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000966 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner2b2453a2009-01-17 06:22:33 +0000968 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
969 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000970 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000971 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000972}
973
Reid Spencer5f016e22007-07-11 17:01:13 +0000974/// Diag - Forwarding function for diagnostics. This translate a source
975/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000976DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000977 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000978}
Reid Spencer5f016e22007-07-11 17:01:13 +0000979
980//===----------------------------------------------------------------------===//
981// Trigraph and Escaped Newline Handling Code.
982//===----------------------------------------------------------------------===//
983
984/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
985/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
986static char GetTrigraphCharForLetter(char Letter) {
987 switch (Letter) {
988 default: return 0;
989 case '=': return '#';
990 case ')': return ']';
991 case '(': return '[';
992 case '!': return '|';
993 case '\'': return '^';
994 case '>': return '}';
995 case '/': return '\\';
996 case '<': return '{';
997 case '-': return '~';
998 }
999}
1000
1001/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1002/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1003/// return the result character. Finally, emit a warning about trigraph use
1004/// whether trigraphs are enabled or not.
1005static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1006 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001007 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner3692b092008-11-18 07:59:24 +00001009 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001010 if (!L->isLexingRawMode())
1011 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001012 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Chris Lattner74d15df2008-11-22 02:02:22 +00001015 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001016 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 return Res;
1018}
1019
Chris Lattner24f0e482009-04-18 22:05:41 +00001020/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1021/// 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 +00001022/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001023unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1024 unsigned Size = 0;
1025 while (isWhitespace(Ptr[Size])) {
1026 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner24f0e482009-04-18 22:05:41 +00001028 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1029 continue;
1030
1031 // If this is a \r\n or \n\r, skip the other half.
1032 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1033 Ptr[Size-1] != Ptr[Size])
1034 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattner24f0e482009-04-18 22:05:41 +00001036 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001037 }
1038
Chris Lattner24f0e482009-04-18 22:05:41 +00001039 // Not an escaped newline, must be a \t or something else.
1040 return 0;
1041}
1042
Chris Lattner03374952009-04-18 22:27:02 +00001043/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1044/// them), skip over them and return the first non-escaped-newline found,
1045/// otherwise return P.
1046const char *Lexer::SkipEscapedNewLines(const char *P) {
1047 while (1) {
1048 const char *AfterEscape;
1049 if (*P == '\\') {
1050 AfterEscape = P+1;
1051 } else if (*P == '?') {
1052 // If not a trigraph for escape, bail out.
1053 if (P[1] != '?' || P[2] != '/')
1054 return P;
1055 AfterEscape = P+3;
1056 } else {
1057 return P;
1058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Chris Lattner03374952009-04-18 22:27:02 +00001060 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1061 if (NewLineSize == 0) return P;
1062 P = AfterEscape+NewLineSize;
1063 }
1064}
1065
Anna Zaksaca25bc2011-07-27 21:43:43 +00001066/// \brief Checks that the given token is the first token that occurs after the
1067/// given location (this excludes comments and whitespace). Returns the location
1068/// immediately after the specified token. If the token is not found or the
1069/// location is inside a macro, the returned source location will be invalid.
1070SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1071 tok::TokenKind TKind,
1072 const SourceManager &SM,
1073 const LangOptions &LangOpts,
1074 bool SkipTrailingWhitespaceAndNewLine) {
1075 if (Loc.isMacroID()) {
1076 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1077 return SourceLocation();
1078 Loc = SM.getExpansionRange(Loc).second;
1079 }
1080 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1081
1082 // Break down the source location.
1083 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1084
1085 // Try to load the file buffer.
1086 bool InvalidTemp = false;
1087 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1088 if (InvalidTemp)
1089 return SourceLocation();
1090
1091 const char *TokenBegin = File.data() + LocInfo.second;
1092
1093 // Lex from the start of the given location.
1094 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1095 TokenBegin, File.end());
1096 // Find the token.
1097 Token Tok;
1098 lexer.LexFromRawLexer(Tok);
1099 if (Tok.isNot(TKind))
1100 return SourceLocation();
1101 SourceLocation TokenLoc = Tok.getLocation();
1102
1103 // Calculate how much whitespace needs to be skipped if any.
1104 unsigned NumWhitespaceChars = 0;
1105 if (SkipTrailingWhitespaceAndNewLine) {
1106 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1107 Tok.getLength();
1108 unsigned char C = *TokenEnd;
1109 while (isHorizontalWhitespace(C)) {
1110 C = *(++TokenEnd);
1111 NumWhitespaceChars++;
1112 }
1113 if (isVerticalWhitespace(C))
1114 NumWhitespaceChars++;
1115 }
1116
1117 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1118}
Chris Lattner24f0e482009-04-18 22:05:41 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1121/// get its size, and return it. This is tricky in several cases:
1122/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1123/// then either return the trigraph (skipping 3 chars) or the '?',
1124/// depending on whether trigraphs are enabled or not.
1125/// 2. If this is an escaped newline (potentially with whitespace between
1126/// the backslash and newline), implicitly skip the newline and return
1127/// the char after it.
1128/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1129///
1130/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1131/// know that we can accumulate into Size, and that we have already incremented
1132/// Ptr by Size bytes.
1133///
1134/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1135/// be updated to match.
1136///
1137char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001138 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 // If we have a slash, look for an escaped newline.
1140 if (Ptr[0] == '\\') {
1141 ++Size;
1142 ++Ptr;
1143Slash:
1144 // Common case, backslash-char where the char is not whitespace.
1145 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Chris Lattner5636a3b2009-06-23 05:15:06 +00001147 // See if we have optional whitespace characters between the slash and
1148 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001149 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1150 // Remember that this token needs to be cleaned.
1151 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152
Chris Lattner24f0e482009-04-18 22:05:41 +00001153 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001154 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001155 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Chris Lattner24f0e482009-04-18 22:05:41 +00001157 // Found backslash<whitespace><newline>. Parse the char after it.
1158 Size += EscapedNewLineSize;
1159 Ptr += EscapedNewLineSize;
1160 // Use slow version to accumulate a correct size field.
1161 return getCharAndSizeSlow(Ptr, Size, Tok);
1162 }
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 // Otherwise, this is not an escaped newline, just return the slash.
1165 return '\\';
1166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 // If this is a trigraph, process it.
1169 if (Ptr[0] == '?' && Ptr[1] == '?') {
1170 // If this is actually a legal trigraph (not something like "??x"), emit
1171 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1172 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1173 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001174 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001175
1176 Ptr += 3;
1177 Size += 3;
1178 if (C == '\\') goto Slash;
1179 return C;
1180 }
1181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 // If this is neither, return a single character.
1184 ++Size;
1185 return *Ptr;
1186}
1187
1188
1189/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1190/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1191/// and that we have already incremented Ptr by Size bytes.
1192///
1193/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1194/// be updated to match.
1195char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1196 const LangOptions &Features) {
1197 // If we have a slash, look for an escaped newline.
1198 if (Ptr[0] == '\\') {
1199 ++Size;
1200 ++Ptr;
1201Slash:
1202 // Common case, backslash-char where the char is not whitespace.
1203 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001206 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1207 // Found backslash<whitespace><newline>. Parse the char after it.
1208 Size += EscapedNewLineSize;
1209 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattner24f0e482009-04-18 22:05:41 +00001211 // Use slow version to accumulate a correct size field.
1212 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1213 }
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // Otherwise, this is not an escaped newline, just return the slash.
1216 return '\\';
1217 }
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // If this is a trigraph, process it.
1220 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1221 // If this is actually a legal trigraph (not something like "??x"), return
1222 // it.
1223 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1224 Ptr += 3;
1225 Size += 3;
1226 if (C == '\\') goto Slash;
1227 return C;
1228 }
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 // If this is neither, return a single character.
1232 ++Size;
1233 return *Ptr;
1234}
1235
1236//===----------------------------------------------------------------------===//
1237// Helper methods for lexing.
1238//===----------------------------------------------------------------------===//
1239
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001240/// \brief Routine that indiscriminately skips bytes in the source file.
1241void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1242 BufferPtr += Bytes;
1243 if (BufferPtr > BufferEnd)
1244 BufferPtr = BufferEnd;
1245 IsAtStartOfLine = StartOfLine;
1246}
1247
Chris Lattnerd2177732007-07-20 16:59:19 +00001248void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1250 unsigned Size;
1251 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001252 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 --CurPtr; // Back up over the skipped character.
1256
1257 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1258 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1259 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001260 //
1261 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1262 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1264FinishIdentifier:
1265 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001266 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1267 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 // If we are in raw mode, return this identifier raw. There is no need to
1270 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001271 if (LexingRawMode)
1272 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001274 // Fill in Result.IdentifierInfo and update the token kind,
1275 // looking up the identifier in the identifier table.
1276 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 // Finally, now that we know we have an identifier, pass this off to the
1279 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001280 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001281 PP->HandleIdentifier(Result);
1282 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 C = getCharAndSize(CurPtr, Size);
1288 while (1) {
1289 if (C == '$') {
1290 // If we hit a $ and they are not supported in identifiers, we are done.
1291 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001294 if (!isLexingRawMode())
1295 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 CurPtr = ConsumeChar(CurPtr, Size, Result);
1297 C = getCharAndSize(CurPtr, Size);
1298 continue;
1299 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1300 // Found end of identifier.
1301 goto FinishIdentifier;
1302 }
1303
1304 // Otherwise, this character is good, consume it.
1305 CurPtr = ConsumeChar(CurPtr, Size, Result);
1306
1307 C = getCharAndSize(CurPtr, Size);
1308 while (isIdentifierBody(C)) { // FIXME: UCNs.
1309 CurPtr = ConsumeChar(CurPtr, Size, Result);
1310 C = getCharAndSize(CurPtr, Size);
1311 }
1312 }
1313}
1314
Douglas Gregora75ec432010-08-30 14:50:47 +00001315/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001316/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001317static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1318 unsigned Size;
1319 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1320 if (C1 != '0')
1321 return false;
1322 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1323 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001324}
Reid Spencer5f016e22007-07-11 17:01:13 +00001325
Nate Begeman5253c7f2008-04-14 02:26:39 +00001326/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001327/// constant. From[-1] is the first character lexed. Return the end of the
1328/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001329void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 unsigned Size;
1331 char C = getCharAndSize(CurPtr, Size);
1332 char PrevCh = 0;
1333 while (isNumberBody(C)) { // FIXME: UCNs?
1334 CurPtr = ConsumeChar(CurPtr, Size, Result);
1335 PrevCh = C;
1336 C = getCharAndSize(CurPtr, Size);
1337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001340 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1341 // If we are in Microsoft mode, don't continue if the constant is hex.
1342 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001343 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001344 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1345 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
1347 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001348 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001349 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001353 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001354 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001355 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001356}
1357
1358/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001359/// either " or L" or u8" or u" or U".
1360void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1361 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 char C = getAndAdvanceChar(CurPtr, Result);
1365 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001366 // Skip escaped characters. Escaped newlines will already be processed by
1367 // getAndAdvanceChar.
1368 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001370
Chris Lattner571339c2010-05-30 23:27:38 +00001371 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001372 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001373 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1374 PP->CodeCompleteNaturalLanguage();
1375 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001376 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001377 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
Chris Lattner571339c2010-05-30 23:27:38 +00001380
1381 if (C == 0)
1382 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 C = getAndAdvanceChar(CurPtr, Result);
1384 }
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001387 if (NulCharacter && !isLexingRawMode())
1388 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001391 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001392 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001393 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001394}
1395
Craig Topper2fa4e862011-08-11 04:06:15 +00001396/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1397/// having lexed R", LR", u8R", uR", or UR".
1398void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1399 tok::TokenKind Kind) {
1400 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1401 // Between the initial and final double quote characters of the raw string,
1402 // any transformations performed in phases 1 and 2 (trigraphs,
1403 // universal-character-names, and line splicing) are reverted.
1404
1405 unsigned PrefixLen = 0;
1406
1407 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1408 ++PrefixLen;
1409
1410 // If the last character was not a '(', then we didn't lex a valid delimiter.
1411 if (CurPtr[PrefixLen] != '(') {
1412 if (!isLexingRawMode()) {
1413 const char *PrefixEnd = &CurPtr[PrefixLen];
1414 if (PrefixLen == 16) {
1415 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1416 } else {
1417 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1418 << StringRef(PrefixEnd, 1);
1419 }
1420 }
1421
1422 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1423 // it's possible the '"' was intended to be part of the raw string, but
1424 // there's not much we can do about that.
1425 while (1) {
1426 char C = *CurPtr++;
1427
1428 if (C == '"')
1429 break;
1430 if (C == 0 && CurPtr-1 == BufferEnd) {
1431 --CurPtr;
1432 break;
1433 }
1434 }
1435
1436 FormTokenWithChars(Result, CurPtr, tok::unknown);
1437 return;
1438 }
1439
1440 // Save prefix and move CurPtr past it
1441 const char *Prefix = CurPtr;
1442 CurPtr += PrefixLen + 1; // skip over prefix and '('
1443
1444 while (1) {
1445 char C = *CurPtr++;
1446
1447 if (C == ')') {
1448 // Check for prefix match and closing quote.
1449 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1450 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1451 break;
1452 }
1453 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1454 if (!isLexingRawMode())
1455 Diag(BufferPtr, diag::err_unterminated_raw_string)
1456 << StringRef(Prefix, PrefixLen);
1457 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1458 return;
1459 }
1460 }
1461
1462 // Update the location of token as well as BufferPtr.
1463 const char *TokStart = BufferPtr;
1464 FormTokenWithChars(Result, CurPtr, Kind);
1465 Result.setLiteralData(TokStart);
1466}
1467
Reid Spencer5f016e22007-07-11 17:01:13 +00001468/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1469/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001470void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001472 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 char C = getAndAdvanceChar(CurPtr, Result);
1474 while (C != '>') {
1475 // Skip escaped characters.
1476 if (C == '\\') {
1477 // Skip the escaped character.
1478 C = getAndAdvanceChar(CurPtr, Result);
1479 } else if (C == '\n' || C == '\r' || // Newline.
1480 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001481 // If the filename is unterminated, then it must just be a lone <
1482 // character. Return this as such.
1483 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 return;
1485 } else if (C == 0) {
1486 NulCharacter = CurPtr-1;
1487 }
1488 C = getAndAdvanceChar(CurPtr, Result);
1489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001492 if (NulCharacter && !isLexingRawMode())
1493 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001496 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001497 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001498 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001499}
1500
1501
1502/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001503/// lexed either ' or L' or u' or U'.
1504void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1505 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 const char *NulCharacter = 0; // Does this character contain the \0 character?
1507
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 char C = getAndAdvanceChar(CurPtr, Result);
1509 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001510 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001511 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001512 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001514 }
1515
1516 while (C != '\'') {
1517 // Skip escaped characters.
1518 if (C == '\\') {
1519 // Skip the escaped character.
1520 // FIXME: UCN's
1521 C = getAndAdvanceChar(CurPtr, Result);
1522 } else if (C == '\n' || C == '\r' || // Newline.
1523 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001524 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1525 PP->CodeCompleteNaturalLanguage();
1526 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001527 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001528 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1529 return;
1530 } else if (C == 0) {
1531 NulCharacter = CurPtr-1;
1532 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 C = getAndAdvanceChar(CurPtr, Result);
1534 }
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Chris Lattnerd80f7862010-07-07 23:24:27 +00001536 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001537 if (NulCharacter && !isLexingRawMode())
1538 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001541 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001542 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001543 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001544}
1545
1546/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1547/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001548///
1549/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1550///
1551bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // Whitespace - Skip it, then return the token after the whitespace.
1553 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1554 while (1) {
1555 // Skip horizontal whitespace very aggressively.
1556 while (isHorizontalWhitespace(Char))
1557 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001559 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 if (Char != '\n' && Char != '\r')
1561 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 if (ParsingPreprocessorDirective) {
1564 // End of preprocessor directive line, let LexTokenInternal handle this.
1565 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001566 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // ok, but handle newline.
1570 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001571 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001573 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Char = *++CurPtr;
1575 }
1576
1577 // If this isn't immediately after a newline, there is leading space.
1578 char PrevChar = CurPtr[-1];
1579 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001580 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001581
Chris Lattnerd88dc482008-10-12 04:05:48 +00001582 // If the client wants us to return whitespace, return it now.
1583 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001584 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001585 return true;
1586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001589 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001590}
1591
1592// SkipBCPLComment - We have just read the // characters from input. Skip until
1593// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001594/// BufferPtr and return.
1595///
1596/// If we're in KeepCommentMode or any CommentHandler has inserted
1597/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001598bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // If BCPL comments aren't explicitly enabled for this language, emit an
1600 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001601 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // Mark them enabled so we only emit one warning for this translation
1605 // unit.
1606 Features.BCPLComment = true;
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // Scan over the body of the comment. The common case, when scanning, is that
1610 // the comment contains normal ascii characters with nothing interesting in
1611 // them. As such, optimize for this case with the inner loop.
1612 char C;
1613 do {
1614 C = *CurPtr;
1615 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1616 // If we find a \n character, scan backwards, checking to see if it's an
1617 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 // Skip over characters in the fast loop.
1620 while (C != 0 && // Potentially EOF.
1621 C != '\\' && // Potentially escaped newline.
1622 C != '?' && // Potentially trigraph.
1623 C != '\n' && C != '\r') // Newline or DOS-style newline.
1624 C = *++CurPtr;
1625
1626 // If this is a newline, we're done.
1627 if (C == '\n' || C == '\r')
1628 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001631 // properly decode the character. Read it in raw mode to avoid emitting
1632 // diagnostics about things like trigraphs. If we see an escaped newline,
1633 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001635 bool OldRawMode = isLexingRawMode();
1636 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001638 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001639
1640 // If the char that we finally got was a \n, then we must have had something
1641 // like \<newline><newline>. We don't want to have consumed the second
1642 // newline, we want CurPtr, to end up pointing to it down below.
1643 if (C == '\n' || C == '\r') {
1644 --CurPtr;
1645 C = 'x'; // doesn't matter what this is.
1646 }
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 // If we read multiple characters, and one of those characters was a \r or
1649 // \n, then we had an escaped newline within the comment. Emit diagnostic
1650 // unless the next line is also a // comment.
1651 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1652 for (; OldPtr != CurPtr; ++OldPtr)
1653 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1654 // Okay, we found a // comment that ends in a newline, if the next
1655 // line is also a // comment, but has spaces, don't emit a diagnostic.
1656 if (isspace(C)) {
1657 const char *ForwardPtr = CurPtr;
1658 while (isspace(*ForwardPtr)) // Skip whitespace.
1659 ++ForwardPtr;
1660 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1661 break;
1662 }
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Chris Lattner74d15df2008-11-22 02:02:22 +00001664 if (!isLexingRawMode())
1665 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 break;
1667 }
1668 }
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Douglas Gregor55817af2010-08-25 17:04:25 +00001670 if (CurPtr == BufferEnd+1) {
1671 if (PP && PP->isCodeCompletionFile(FileLoc))
1672 PP->CodeCompleteNaturalLanguage();
1673
1674 --CurPtr;
1675 break;
1676 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 } while (C != '\n' && C != '\r');
1678
Chris Lattner3d0ad582010-02-03 21:06:21 +00001679 // Found but did not consume the newline. Notify comment handlers about the
1680 // comment unless we're in a #if 0 block.
1681 if (PP && !isLexingRawMode() &&
1682 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1683 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001684 BufferPtr = CurPtr;
1685 return true; // A token has to be returned.
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001689 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 return SaveBCPLComment(Result, CurPtr);
1691
1692 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001693 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1695 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001696 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001700 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001701 // contribute to another token), it isn't needed for correctness. Note that
1702 // this is ok even in KeepWhitespaceMode, because we would have returned the
1703 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001707 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001709 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001711 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001712}
1713
1714/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1715/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001716bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001717 // If we're not in a preprocessor directive, just return the // comment
1718 // directly.
1719 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Chris Lattner9e6293d2008-10-12 04:51:35 +00001721 if (!ParsingPreprocessorDirective)
1722 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Chris Lattner9e6293d2008-10-12 04:51:35 +00001724 // If this BCPL-style comment is in a macro definition, transmogrify it into
1725 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001726 bool Invalid = false;
1727 std::string Spelling = PP->getSpelling(Result, &Invalid);
1728 if (Invalid)
1729 return true;
1730
Chris Lattner9e6293d2008-10-12 04:51:35 +00001731 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1732 Spelling[1] = '*'; // Change prefix to "/*".
1733 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Chris Lattner9e6293d2008-10-12 04:51:35 +00001735 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001736 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1737 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001738 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001739}
1740
1741/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1742/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001743/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001744static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 Lexer *L) {
1746 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 // Back up off the newline.
1749 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 // If this is a two-character newline sequence, skip the other character.
1752 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1753 // \n\n or \r\r -> not escaped newline.
1754 if (CurPtr[0] == CurPtr[1])
1755 return false;
1756 // \n\r or \r\n -> skip the newline.
1757 --CurPtr;
1758 }
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 // If we have horizontal whitespace, skip over it. We allow whitespace
1761 // between the slash and newline.
1762 bool HasSpace = false;
1763 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1764 --CurPtr;
1765 HasSpace = true;
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 // If we have a slash, we know this is an escaped newline.
1769 if (*CurPtr == '\\') {
1770 if (CurPtr[-1] != '*') return false;
1771 } else {
1772 // It isn't a slash, is it the ?? / trigraph?
1773 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1774 CurPtr[-3] != '*')
1775 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 // This is the trigraph ending the comment. Emit a stern warning!
1778 CurPtr -= 2;
1779
1780 // If no trigraphs are enabled, warn that we ignored this trigraph and
1781 // ignore this * character.
1782 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001783 if (!L->isLexingRawMode())
1784 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 return false;
1786 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001787 if (!L->isLexingRawMode())
1788 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001792 if (!L->isLexingRawMode())
1793 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001796 if (HasSpace && !L->isLexingRawMode())
1797 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 return true;
1800}
1801
1802#ifdef __SSE2__
1803#include <emmintrin.h>
1804#elif __ALTIVEC__
1805#include <altivec.h>
1806#undef bool
1807#endif
1808
1809/// SkipBlockComment - We have just read the /* characters from input. Read
1810/// until we find the */ characters that terminate the comment. Note that we
1811/// don't bother decoding trigraphs or escaped newlines in block comments,
1812/// because they cannot cause the comment to end. The only thing that can
1813/// happen is the comment could end with an escaped newline between the */ end
1814/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001815///
Chris Lattner046c2272010-01-18 22:35:47 +00001816/// If we're in KeepCommentMode or any CommentHandler has inserted
1817/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001818bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001820 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 // optimization helps people who like to put a lot of * characters in their
1822 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001823
1824 // The first character we get with newlines and trigraphs skipped to handle
1825 // the degenerate /*/ case below correctly if the * has an escaped newline
1826 // after it.
1827 unsigned CharSize;
1828 unsigned char C = getCharAndSize(CurPtr, CharSize);
1829 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001831 if (!isLexingRawMode() &&
1832 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001833 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001834 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Chris Lattner31f0eca2008-10-12 04:19:49 +00001836 // KeepWhitespaceMode should return this broken comment as a token. Since
1837 // it isn't a well formed comment, just return it as an 'unknown' token.
1838 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001839 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001840 return true;
1841 }
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Chris Lattner31f0eca2008-10-12 04:19:49 +00001843 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001844 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Chris Lattner8146b682007-07-21 23:43:37 +00001847 // Check to see if the first character after the '/*' is another /. If so,
1848 // then this slash does not end the block comment, it is part of it.
1849 if (C == '/')
1850 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 while (1) {
1853 // Skip over all non-interesting characters until we find end of buffer or a
1854 // (probably ending) '/' character.
1855 if (CurPtr + 24 < BufferEnd) {
1856 // While not aligned to a 16-byte boundary.
1857 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1858 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 if (C == '/') goto FoundSlash;
1861
1862#ifdef __SSE2__
1863 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1864 '/', '/', '/', '/', '/', '/', '/', '/');
1865 while (CurPtr+16 <= BufferEnd &&
1866 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1867 CurPtr += 16;
1868#elif __ALTIVEC__
1869 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001870 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 '/', '/', '/', '/', '/', '/', '/', '/'
1872 };
1873 while (CurPtr+16 <= BufferEnd &&
1874 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1875 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001876#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // Scan for '/' quickly. Many block comments are very large.
1878 while (CurPtr[0] != '/' &&
1879 CurPtr[1] != '/' &&
1880 CurPtr[2] != '/' &&
1881 CurPtr[3] != '/' &&
1882 CurPtr+4 < BufferEnd) {
1883 CurPtr += 4;
1884 }
1885#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 // It has to be one of the bytes scanned, increment to it and read one.
1888 C = *CurPtr++;
1889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // Loop to scan the remainder.
1892 while (C != '/' && C != '\0')
1893 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 FoundSlash:
1896 if (C == '/') {
1897 if (CurPtr[-2] == '*') // We found the final */. We're done!
1898 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1901 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1902 // We found the final */, though it had an escaped newline between the
1903 // * and /. We're done!
1904 break;
1905 }
1906 }
1907 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1908 // If this is a /* inside of the comment, emit a warning. Don't do this
1909 // if this is a /*/, which will end the comment. This misses cases with
1910 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001911 if (!isLexingRawMode())
1912 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 }
1914 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001915 if (PP && PP->isCodeCompletionFile(FileLoc))
1916 PP->CodeCompleteNaturalLanguage();
1917 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001918 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 // Note: the user probably forgot a */. We could continue immediately
1920 // after the /*, but this would involve lexing a lot of what really is the
1921 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001922 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Chris Lattner31f0eca2008-10-12 04:19:49 +00001924 // KeepWhitespaceMode should return this broken comment as a token. Since
1925 // it isn't a well formed comment, just return it as an 'unknown' token.
1926 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001927 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001928 return true;
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Chris Lattner31f0eca2008-10-12 04:19:49 +00001931 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001932 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 }
1934 C = *CurPtr++;
1935 }
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Chris Lattner3d0ad582010-02-03 21:06:21 +00001937 // Notify comment handlers about the comment unless we're in a #if 0 block.
1938 if (PP && !isLexingRawMode() &&
1939 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1940 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001941 BufferPtr = CurPtr;
1942 return true; // A token has to be returned.
1943 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001944
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001946 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001947 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001948 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 }
1950
1951 // It is common for the tokens immediately after a /**/ comment to be
1952 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001953 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1954 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001956 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001958 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 }
1960
1961 // Otherwise, just return so that the next character will be lexed as a token.
1962 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001963 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001964 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001965}
1966
1967//===----------------------------------------------------------------------===//
1968// Primary Lexing Entry Points
1969//===----------------------------------------------------------------------===//
1970
Reid Spencer5f016e22007-07-11 17:01:13 +00001971/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1972/// uninterpreted string. This switches the lexer out of directive mode.
1973std::string Lexer::ReadToEndOfLine() {
1974 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1975 "Must be in a preprocessing directive!");
1976 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001977 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001978
1979 // CurPtr - Cache BufferPtr in an automatic variable.
1980 const char *CurPtr = BufferPtr;
1981 while (1) {
1982 char Char = getAndAdvanceChar(CurPtr, Tmp);
1983 switch (Char) {
1984 default:
1985 Result += Char;
1986 break;
1987 case 0: // Null.
1988 // Found end of file?
1989 if (CurPtr-1 != BufferEnd) {
1990 // Nope, normal character, continue.
1991 Result += Char;
1992 break;
1993 }
1994 // FALL THROUGH.
1995 case '\r':
1996 case '\n':
1997 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1998 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1999 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Peter Collingbourne84021552011-02-28 02:37:51 +00002001 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002003 if (Tmp.is(tok::code_completion)) {
2004 if (PP && PP->getCodeCompletionHandler())
2005 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
2006 Lex(Tmp);
2007 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002008 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 // Finally, we're done, return the string we found.
2011 return Result;
2012 }
2013 }
2014}
2015
2016/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2017/// condition, reporting diagnostics and handling other edge cases as required.
2018/// This returns true if Result contains a token, false if PP.Lex should be
2019/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002020bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00002021 // Check if we are performing code completion.
2022 if (PP && PP->isCodeCompletionFile(FileLoc)) {
2023 // We're at the end of the file, but we've been asked to consider the
2024 // end of the file to be a code-completion token. Return the
2025 // code-completion token.
2026 Result.startToken();
2027 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2028
2029 // Only do the eof -> code_completion translation once.
2030 PP->SetCodeCompletionPoint(0, 0, 0);
2031
2032 // Silence any diagnostics that occur once we hit the code-completion point.
2033 PP->getDiagnostics().setSuppressAllDiagnostics(true);
2034 return true;
2035 }
2036
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // If we hit the end of the file while parsing a preprocessor directive,
2038 // end the preprocessor directive first. The next token returned will
2039 // then be the end of file.
2040 if (ParsingPreprocessorDirective) {
2041 // Done parsing the "line".
2042 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002044 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002047 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002049 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002050
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 // If we are in raw mode, return this event as an EOF token. Let the caller
2052 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002053 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 Result.startToken();
2055 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002056 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 return true;
2058 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002059
Douglas Gregorf44e8542010-08-24 19:08:16 +00002060 // Issue diagnostics for unterminated #if and missing newline.
2061
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 // If we are in a #if directive, emit an error.
2063 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002064 if (!PP->isCodeCompletionFile(FileLoc))
2065 PP->Diag(ConditionalStack.back().IfLoc,
2066 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 ConditionalStack.pop_back();
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002070 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2071 // a pedwarn.
2072 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002073 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002074 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 BufferPtr = CurPtr;
2077
2078 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002079 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002080}
2081
2082/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2083/// the specified lexer will return a tok::l_paren token, 0 if it is something
2084/// else and 2 if there are no more tokens in the buffer controlled by the
2085/// lexer.
2086unsigned Lexer::isNextPPTokenLParen() {
2087 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 // Switch to 'skipping' mode. This will ensure that we can lex a token
2090 // without emitting diagnostics, disables macro expansion, and will cause EOF
2091 // to return an EOF token instead of popping the include stack.
2092 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // Save state that can be changed while lexing so that we can restore it.
2095 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002096 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Chris Lattnerd2177732007-07-20 16:59:19 +00002098 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 Tok.startToken();
2100 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 // Restore state that may have changed.
2103 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002104 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // Restore the lexer back to non-skipping mode.
2107 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002109 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002111 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002112}
2113
Chris Lattner34f349d2009-12-14 06:16:57 +00002114/// FindConflictEnd - Find the end of a version control conflict marker.
2115static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002116 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002117 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002118 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002119 // Must occur at start of line.
2120 if (RestOfBuffer[Pos-1] != '\r' &&
2121 RestOfBuffer[Pos-1] != '\n') {
2122 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002123 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002124 continue;
2125 }
2126 return RestOfBuffer.data()+Pos;
2127 }
2128 return 0;
2129}
2130
2131/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2132/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2133/// and recover nicely. This returns true if it is a conflict marker and false
2134/// if not.
2135bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2136 // Only a conflict marker if it starts at the beginning of a line.
2137 if (CurPtr != BufferStart &&
2138 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2139 return false;
2140
2141 // Check to see if we have <<<<<<<.
2142 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002143 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002144 return false;
2145
2146 // If we have a situation where we don't care about conflict markers, ignore
2147 // it.
2148 if (IsInConflictMarker || isLexingRawMode())
2149 return false;
2150
2151 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2152 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002153 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002154 // We found a match. We are really in a conflict marker.
2155 // Diagnose this, and ignore to the end of line.
2156 Diag(CurPtr, diag::err_conflict_marker);
2157 IsInConflictMarker = true;
2158
2159 // Skip ahead to the end of line. We know this exists because the
2160 // end-of-conflict marker starts with \r or \n.
2161 while (*CurPtr != '\r' && *CurPtr != '\n') {
2162 assert(CurPtr != BufferEnd && "Didn't find end of line");
2163 ++CurPtr;
2164 }
2165 BufferPtr = CurPtr;
2166 return true;
2167 }
2168
2169 // No end of conflict marker found.
2170 return false;
2171}
2172
2173
2174/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2175/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2176/// until the end of the line. This returns true if it is a conflict marker and
2177/// false if not.
2178bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2179 // Only a conflict marker if it starts at the beginning of a line.
2180 if (CurPtr != BufferStart &&
2181 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2182 return false;
2183
2184 // If we have a situation where we don't care about conflict markers, ignore
2185 // it.
2186 if (!IsInConflictMarker || isLexingRawMode())
2187 return false;
2188
2189 // Check to see if we have the marker (7 characters in a row).
2190 for (unsigned i = 1; i != 7; ++i)
2191 if (CurPtr[i] != CurPtr[0])
2192 return false;
2193
2194 // If we do have it, search for the end of the conflict marker. This could
2195 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2196 // be the end of conflict marker.
2197 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2198 CurPtr = End;
2199
2200 // Skip ahead to the end of line.
2201 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2202 ++CurPtr;
2203
2204 BufferPtr = CurPtr;
2205
2206 // No longer in the conflict marker.
2207 IsInConflictMarker = false;
2208 return true;
2209 }
2210
2211 return false;
2212}
2213
Reid Spencer5f016e22007-07-11 17:01:13 +00002214
2215/// LexTokenInternal - This implements a simple C family lexer. It is an
2216/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002217/// has a null character at the end of the file. This returns a preprocessing
2218/// token, not a normal token, as such, it is an internal interface. It assumes
2219/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002220void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002221LexNextToken:
2222 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002223 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002224 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 // CurPtr - Cache BufferPtr in an automatic variable.
2227 const char *CurPtr = BufferPtr;
2228
2229 // Small amounts of horizontal whitespace is very common between tokens.
2230 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2231 ++CurPtr;
2232 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2233 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Chris Lattnerd88dc482008-10-12 04:05:48 +00002235 // If we are keeping whitespace and other tokens, just return what we just
2236 // skipped. The next lexer invocation will return the token after the
2237 // whitespace.
2238 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002239 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002240 return;
2241 }
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002244 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 }
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // Read a character, advancing over it.
2250 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002251 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 switch (Char) {
2254 case 0: // Null.
2255 // Found end of file?
2256 if (CurPtr-1 == BufferEnd) {
2257 // Read the PP instance variable into an automatic variable, because
2258 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002259 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2261 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002262 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2263 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002264 }
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Chris Lattner74d15df2008-11-22 02:02:22 +00002266 if (!isLexingRawMode())
2267 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002268 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002269 if (SkipWhitespace(Result, CurPtr))
2270 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002273
2274 case 26: // DOS & CP/M EOF: "^Z".
2275 // If we're in Microsoft extensions mode, treat this as end of file.
2276 if (Features.Microsoft) {
2277 // Read the PP instance variable into an automatic variable, because
2278 // LexEndOfFile will often delete 'this'.
2279 Preprocessor *PPCache = PP;
2280 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2281 return; // Got a token to return.
2282 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2283 return PPCache->Lex(Result);
2284 }
2285 // If Microsoft extensions are disabled, this is just random garbage.
2286 Kind = tok::unknown;
2287 break;
2288
Reid Spencer5f016e22007-07-11 17:01:13 +00002289 case '\n':
2290 case '\r':
2291 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002292 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 if (ParsingPreprocessorDirective) {
2294 // Done parsing the "line".
2295 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Reid Spencer5f016e22007-07-11 17:01:13 +00002297 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002298 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 // Since we consumed a newline, we are back at the start of a line.
2301 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Peter Collingbourne84021552011-02-28 02:37:51 +00002303 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 break;
2305 }
2306 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002307 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002308 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002309 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattnerd88dc482008-10-12 04:05:48 +00002311 if (SkipWhitespace(Result, CurPtr))
2312 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002313 goto LexNextToken; // GCC isn't tail call eliminating.
2314 case ' ':
2315 case '\t':
2316 case '\f':
2317 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002318 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002319 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002320 if (SkipWhitespace(Result, CurPtr))
2321 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002322
2323 SkipIgnoredUnits:
2324 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Chris Lattner8133cfc2007-07-22 06:29:05 +00002326 // If the next token is obviously a // or /* */ comment, skip it efficiently
2327 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002328 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002329 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002330 if (SkipBCPLComment(Result, CurPtr+2))
2331 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002332 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002333 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002334 if (SkipBlockComment(Result, CurPtr+2))
2335 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002336 goto SkipIgnoredUnits;
2337 } else if (isHorizontalWhitespace(*CurPtr)) {
2338 goto SkipHorizontalWhitespace;
2339 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002341
Chris Lattner3a570772008-01-03 17:58:54 +00002342 // C99 6.4.4.1: Integer Constants.
2343 // C99 6.4.4.2: Floating Constants.
2344 case '0': case '1': case '2': case '3': case '4':
2345 case '5': case '6': case '7': case '8': case '9':
2346 // Notify MIOpt that we read a non-whitespace/non-comment token.
2347 MIOpt.ReadToken();
2348 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Douglas Gregor5cee1192011-07-27 05:40:30 +00002350 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2351 // Notify MIOpt that we read a non-whitespace/non-comment token.
2352 MIOpt.ReadToken();
2353
2354 if (Features.CPlusPlus0x) {
2355 Char = getCharAndSize(CurPtr, SizeTmp);
2356
2357 // UTF-16 string literal
2358 if (Char == '"')
2359 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2360 tok::utf16_string_literal);
2361
2362 // UTF-16 character constant
2363 if (Char == '\'')
2364 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2365 tok::utf16_char_constant);
2366
Craig Topper2fa4e862011-08-11 04:06:15 +00002367 // UTF-16 raw string literal
2368 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2369 return LexRawStringLiteral(Result,
2370 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2371 SizeTmp2, Result),
2372 tok::utf16_string_literal);
2373
2374 if (Char == '8') {
2375 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2376
2377 // UTF-8 string literal
2378 if (Char2 == '"')
2379 return LexStringLiteral(Result,
2380 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2381 SizeTmp2, Result),
2382 tok::utf8_string_literal);
2383
2384 if (Char2 == 'R') {
2385 unsigned SizeTmp3;
2386 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2387 // UTF-8 raw string literal
2388 if (Char3 == '"') {
2389 return LexRawStringLiteral(Result,
2390 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2391 SizeTmp2, Result),
2392 SizeTmp3, Result),
2393 tok::utf8_string_literal);
2394 }
2395 }
2396 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002397 }
2398
2399 // treat u like the start of an identifier.
2400 return LexIdentifier(Result, CurPtr);
2401
2402 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2403 // Notify MIOpt that we read a non-whitespace/non-comment token.
2404 MIOpt.ReadToken();
2405
2406 if (Features.CPlusPlus0x) {
2407 Char = getCharAndSize(CurPtr, SizeTmp);
2408
2409 // UTF-32 string literal
2410 if (Char == '"')
2411 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2412 tok::utf32_string_literal);
2413
2414 // UTF-32 character constant
2415 if (Char == '\'')
2416 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2417 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002418
2419 // UTF-32 raw string literal
2420 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2421 return LexRawStringLiteral(Result,
2422 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2423 SizeTmp2, Result),
2424 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002425 }
2426
2427 // treat U like the start of an identifier.
2428 return LexIdentifier(Result, CurPtr);
2429
Craig Topper2fa4e862011-08-11 04:06:15 +00002430 case 'R': // Identifier or C++0x raw string literal
2431 // Notify MIOpt that we read a non-whitespace/non-comment token.
2432 MIOpt.ReadToken();
2433
2434 if (Features.CPlusPlus0x) {
2435 Char = getCharAndSize(CurPtr, SizeTmp);
2436
2437 if (Char == '"')
2438 return LexRawStringLiteral(Result,
2439 ConsumeChar(CurPtr, SizeTmp, Result),
2440 tok::string_literal);
2441 }
2442
2443 // treat R like the start of an identifier.
2444 return LexIdentifier(Result, CurPtr);
2445
Chris Lattner3a570772008-01-03 17:58:54 +00002446 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 // Notify MIOpt that we read a non-whitespace/non-comment token.
2448 MIOpt.ReadToken();
2449 Char = getCharAndSize(CurPtr, SizeTmp);
2450
2451 // Wide string literal.
2452 if (Char == '"')
2453 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002454 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002455
Craig Topper2fa4e862011-08-11 04:06:15 +00002456 // Wide raw string literal.
2457 if (Features.CPlusPlus0x && Char == 'R' &&
2458 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2459 return LexRawStringLiteral(Result,
2460 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2461 SizeTmp2, Result),
2462 tok::wide_string_literal);
2463
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 // Wide character constant.
2465 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002466 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2467 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Reid Spencer5f016e22007-07-11 17:01:13 +00002470 // C99 6.4.2: Identifiers.
2471 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2472 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002473 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002474 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2475 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2476 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002477 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002478 case 'v': case 'w': case 'x': case 'y': case 'z':
2479 case '_':
2480 // Notify MIOpt that we read a non-whitespace/non-comment token.
2481 MIOpt.ReadToken();
2482 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002483
2484 case '$': // $ in identifiers.
2485 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002486 if (!isLexingRawMode())
2487 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002488 // Notify MIOpt that we read a non-whitespace/non-comment token.
2489 MIOpt.ReadToken();
2490 return LexIdentifier(Result, CurPtr);
2491 }
Mike Stump1eb44332009-09-09 15:08:12 +00002492
Chris Lattner9e6293d2008-10-12 04:51:35 +00002493 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002494 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 // C99 6.4.4: Character Constants.
2497 case '\'':
2498 // Notify MIOpt that we read a non-whitespace/non-comment token.
2499 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002500 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002501
2502 // C99 6.4.5: String Literals.
2503 case '"':
2504 // Notify MIOpt that we read a non-whitespace/non-comment token.
2505 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002506 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002507
2508 // C99 6.4.6: Punctuators.
2509 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002510 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 break;
2512 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002513 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 break;
2515 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002516 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 break;
2518 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002519 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 break;
2521 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002522 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 break;
2524 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002525 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 break;
2527 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002528 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 break;
2530 case '.':
2531 Char = getCharAndSize(CurPtr, SizeTmp);
2532 if (Char >= '0' && Char <= '9') {
2533 // Notify MIOpt that we read a non-whitespace/non-comment token.
2534 MIOpt.ReadToken();
2535
2536 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2537 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002538 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 CurPtr += SizeTmp;
2540 } else if (Char == '.' &&
2541 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002542 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2544 SizeTmp2, Result);
2545 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002546 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 }
2548 break;
2549 case '&':
2550 Char = getCharAndSize(CurPtr, SizeTmp);
2551 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002552 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2554 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002555 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2557 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002558 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 }
2560 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002561 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002562 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002563 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2565 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002566 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 }
2568 break;
2569 case '+':
2570 Char = getCharAndSize(CurPtr, SizeTmp);
2571 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002573 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002576 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002578 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
2580 break;
2581 case '-':
2582 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002583 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002584 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002585 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002586 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002587 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2589 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002590 Kind = tok::arrowstar;
2591 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002593 Kind = tok::arrow;
2594 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002595 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002596 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002598 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 }
2600 break;
2601 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002602 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 break;
2604 case '!':
2605 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002606 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2608 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002609 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 }
2611 break;
2612 case '/':
2613 // 6.4.9: Comments
2614 Char = getCharAndSize(CurPtr, SizeTmp);
2615 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002616 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2617 // want to lex this as a comment. There is one problem with this though,
2618 // that in one particular corner case, this can change the behavior of the
2619 // resultant program. For example, In "foo //**/ bar", C89 would lex
2620 // this as "foo / bar" and langauges with BCPL comments would lex it as
2621 // "foo". Check to see if the character after the second slash is a '*'.
2622 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002623 // However, we never do this in -traditional-cpp mode.
2624 if ((Features.BCPLComment ||
2625 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2626 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002627 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002628 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Chris Lattner8402c732009-01-16 22:39:25 +00002630 // It is common for the tokens immediately after a // comment to be
2631 // whitespace (indentation for the next line). Instead of going through
2632 // the big switch, handle it efficiently now.
2633 goto SkipIgnoredUnits;
2634 }
2635 }
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Chris Lattner8402c732009-01-16 22:39:25 +00002637 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002639 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002640 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002641 }
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Chris Lattner8402c732009-01-16 22:39:25 +00002643 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002645 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002647 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 }
2649 break;
2650 case '%':
2651 Char = getCharAndSize(CurPtr, SizeTmp);
2652 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002653 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2655 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002656 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2658 } else if (Features.Digraphs && Char == ':') {
2659 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2660 Char = getCharAndSize(CurPtr, SizeTmp);
2661 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002662 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2664 SizeTmp2, Result);
2665 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002667 if (!isLexingRawMode())
2668 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002669 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002670 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 // We parsed a # character. If this occurs at the start of the line,
2672 // it's actually the start of a preprocessing directive. Callback to
2673 // the preprocessor to handle it.
2674 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002675 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002676 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002677 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 // As an optimization, if the preprocessor didn't switch lexers, tail
2680 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002681 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 // Start a new token. If this is a #include or something, the PP may
2683 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002684 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002686 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002687 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 IsAtStartOfLine = false;
2689 }
2690 goto LexNextToken; // GCC isn't tail call eliminating.
2691 }
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Chris Lattner168ae2d2007-10-17 20:41:00 +00002693 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 }
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Chris Lattnere91e9322009-03-18 20:58:27 +00002696 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 }
2698 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002699 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002700 }
2701 break;
2702 case '<':
2703 Char = getCharAndSize(CurPtr, SizeTmp);
2704 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002705 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002707 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2708 if (After == '=') {
2709 Kind = tok::lesslessequal;
2710 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2711 SizeTmp2, Result);
2712 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2713 // If this is actually a '<<<<<<<' version control conflict marker,
2714 // recognize it as such and recover nicely.
2715 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002716 } else if (Features.CUDA && After == '<') {
2717 Kind = tok::lesslessless;
2718 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2719 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002720 } else {
2721 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2722 Kind = tok::lessless;
2723 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002726 Kind = tok::lessequal;
2727 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002728 if (Features.CPlusPlus0x &&
2729 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2730 // C++0x [lex.pptoken]p3:
2731 // Otherwise, if the next three characters are <:: and the subsequent
2732 // character is neither : nor >, the < is treated as a preprocessor
2733 // token by itself and not as the first character of the alternative
2734 // token <:.
2735 unsigned SizeTmp3;
2736 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2737 if (After != ':' && After != '>') {
2738 Kind = tok::less;
2739 break;
2740 }
2741 }
2742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002744 Kind = tok::l_square;
2745 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002747 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002749 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 }
2751 break;
2752 case '>':
2753 Char = getCharAndSize(CurPtr, SizeTmp);
2754 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002756 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002758 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2759 if (After == '=') {
2760 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2761 SizeTmp2, Result);
2762 Kind = tok::greatergreaterequal;
2763 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2764 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2765 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002766 } else if (Features.CUDA && After == '>') {
2767 Kind = tok::greatergreatergreater;
2768 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2769 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002770 } else {
2771 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2772 Kind = tok::greatergreater;
2773 }
2774
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002776 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 }
2778 break;
2779 case '^':
2780 Char = getCharAndSize(CurPtr, SizeTmp);
2781 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002783 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002785 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 }
2787 break;
2788 case '|':
2789 Char = getCharAndSize(CurPtr, SizeTmp);
2790 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002791 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2793 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002794 // If this is '|||||||' and we're in a conflict marker, ignore it.
2795 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2796 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002797 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2799 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002800 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 }
2802 break;
2803 case ':':
2804 Char = getCharAndSize(CurPtr, SizeTmp);
2805 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002806 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2808 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002809 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002811 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002812 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 }
2814 break;
2815 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002816 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 break;
2818 case '=':
2819 Char = getCharAndSize(CurPtr, SizeTmp);
2820 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002821 // If this is '=======' and we're in a conflict marker, ignore it.
2822 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2823 goto LexNextToken;
2824
Chris Lattner9e6293d2008-10-12 04:51:35 +00002825 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002827 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002828 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 }
2830 break;
2831 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002832 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 break;
2834 case '#':
2835 Char = getCharAndSize(CurPtr, SizeTmp);
2836 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002837 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2839 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002840 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002841 if (!isLexingRawMode())
2842 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2844 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 // We parsed a # character. If this occurs at the start of the line,
2846 // it's actually the start of a preprocessing directive. Callback to
2847 // the preprocessor to handle it.
2848 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002849 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002850 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002851 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 // As an optimization, if the preprocessor didn't switch lexers, tail
2854 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002855 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002856 // Start a new token. If this is a #include or something, the PP may
2857 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002858 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002860 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002861 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002862 IsAtStartOfLine = false;
2863 }
2864 goto LexNextToken; // GCC isn't tail call eliminating.
2865 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002866 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 }
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Chris Lattnere91e9322009-03-18 20:58:27 +00002869 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 }
2871 break;
2872
Chris Lattner3a570772008-01-03 17:58:54 +00002873 case '@':
2874 // Objective C support.
2875 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002876 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002877 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002878 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002879 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 case '\\':
2882 // FIXME: UCN's.
2883 // FALL THROUGH.
2884 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002885 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 break;
2887 }
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 // Notify MIOpt that we read a non-whitespace/non-comment token.
2890 MIOpt.ReadToken();
2891
2892 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002893 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002894}