blob: 64b87449226e8141dcae905d2cfa1529d134b546 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerd2177732007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
22// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000029#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor55817af2010-08-25 17:04:25 +000030#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000032#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000033#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/Support/MemoryBuffer.h"
35#include <cctype>
Craig Topper2fa4e862011-08-11 04:06:15 +000036#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Chris Lattnera2bf1052009-12-17 05:29:40 +000039static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000040
Chris Lattnerdbf388b2007-10-07 08:47:24 +000041//===----------------------------------------------------------------------===//
42// Token Class Implementation
43//===----------------------------------------------------------------------===//
44
Mike Stump1eb44332009-09-09 15:08:12 +000045/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000046bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000047 if (IdentifierInfo *II = getIdentifierInfo())
48 return II->getObjCKeywordID() == objcKey;
49 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000050}
51
52/// getObjCKeywordID - Return the ObjC keyword kind.
53tok::ObjCKeywordKind Token::getObjCKeywordID() const {
54 IdentifierInfo *specId = getIdentifierInfo();
55 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
56}
57
Chris Lattner53702cd2007-12-13 01:59:49 +000058
Chris Lattnerdbf388b2007-10-07 08:47:24 +000059//===----------------------------------------------------------------------===//
60// Lexer Class Implementation
61//===----------------------------------------------------------------------===//
62
Mike Stump1eb44332009-09-09 15:08:12 +000063void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000064 const char *BufEnd) {
Chris Lattnera2bf1052009-12-17 05:29:40 +000065 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner22d91ca2009-01-17 06:55:17 +000067 BufferStart = BufStart;
68 BufferPtr = BufPtr;
69 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner22d91ca2009-01-17 06:55:17 +000071 assert(BufEnd[0] == 0 &&
72 "We assume that the input buffer has a null character at the end"
73 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000074
Eric Christopher156119d2011-04-09 00:01:04 +000075 // Check whether we have a BOM in the beginning of the buffer. If yes - act
76 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
77 // skip the UTF-8 BOM if it's present.
78 if (BufferStart == BufferPtr) {
79 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000081 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000082 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
83 .Default(0);
84
85 // Skip the BOM.
86 BufferPtr += BOMLength;
87 }
88
Chris Lattner22d91ca2009-01-17 06:55:17 +000089 Is_PragmaLexer = false;
Chris Lattner34f349d2009-12-14 06:16:57 +000090 IsInConflictMarker = false;
Eric Christopher156119d2011-04-09 00:01:04 +000091
Chris Lattner22d91ca2009-01-17 06:55:17 +000092 // Start of the file is a start of line.
93 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner22d91ca2009-01-17 06:55:17 +000095 // We are not after parsing a #.
96 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000097
Chris Lattner22d91ca2009-01-17 06:55:17 +000098 // We are not after parsing #include.
99 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Chris Lattner22d91ca2009-01-17 06:55:17 +0000101 // We are not in raw mode. Raw mode disables diagnostics and interpretation
102 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
103 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
104 // or otherwise skipping over tokens.
105 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner22d91ca2009-01-17 06:55:17 +0000107 // Default to not keeping comments.
108 ExtendedTokenMode = 0;
109}
110
Chris Lattner0770dab2009-01-17 07:56:59 +0000111/// Lexer constructor - Create a new lexer object for the specified buffer
112/// with the specified preprocessor managing the lexing process. This lexer
113/// assumes that the associated file buffer and Preprocessor objects will
114/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000115Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000116 : PreprocessorLexer(&PP, FID),
117 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
118 Features(PP.getLangOptions()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattner0770dab2009-01-17 07:56:59 +0000120 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
121 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Chris Lattner0770dab2009-01-17 07:56:59 +0000123 // Default to keeping comments if the preprocessor wants them.
124 SetCommentRetentionState(PP.getCommentRetentionState());
125}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000126
Chris Lattner168ae2d2007-10-17 20:41:00 +0000127/// Lexer constructor - Create a new raw lexer object. This object is only
Chris Lattner590f0cc2008-10-12 01:15:46 +0000128/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
129/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000130Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000131 const char *BufStart, const char *BufPtr, const char *BufEnd)
Chris Lattnerc6fe32a2009-01-17 03:48:08 +0000132 : FileLoc(fileloc), Features(features) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000133
Chris Lattner22d91ca2009-01-17 06:55:17 +0000134 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattner168ae2d2007-10-17 20:41:00 +0000136 // We *are* in raw mode.
137 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000138}
139
Chris Lattner025c3a62009-01-17 07:35:14 +0000140/// Lexer constructor - Create a new raw lexer object. This object is only
141/// suitable for calls to 'LexRawToken'. This lexer assumes that the text
142/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000143Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
144 const SourceManager &SM, const LangOptions &features)
Chris Lattner025c3a62009-01-17 07:35:14 +0000145 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000146
Mike Stump1eb44332009-09-09 15:08:12 +0000147 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000148 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 // We *are* in raw mode.
151 LexingRawMode = true;
152}
153
Chris Lattner42e00d12009-01-17 08:27:52 +0000154/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
155/// _Pragma expansion. This has a variety of magic semantics that this method
156/// sets up. It returns a new'd Lexer that must be delete'd when done.
157///
158/// On entrance to this routine, TokStartLoc is a macro location which has a
159/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000160/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000161/// "expanded from".
162///
163/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
164/// normal lexer that remaps tokens as they fly by. This would require making
165/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
166/// interface that could handle this stuff. This would pull GetMappedTokenLoc
167/// out of the critical path of the lexer!
168///
Mike Stump1eb44332009-09-09 15:08:12 +0000169Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000170 SourceLocation ExpansionLocStart,
171 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000172 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000173 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000174
175 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000176 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000177 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
178 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner42e00d12009-01-17 08:27:52 +0000180 // Now that the lexer is created, change the start/end locations so that we
181 // just lex the subsection of the file that we want. This is lexing from a
182 // scratch buffer.
183 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattner42e00d12009-01-17 08:27:52 +0000185 L->BufferPtr = StrData;
186 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000187 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000188
189 // Set the SourceLocation with the remapping information. This ensures that
190 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000191 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
192 ExpansionLocStart,
193 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner42e00d12009-01-17 08:27:52 +0000195 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000196 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 // This lexer really is for _Pragma.
200 L->Is_PragmaLexer = true;
201 return L;
202}
203
Chris Lattner168ae2d2007-10-17 20:41:00 +0000204
Reid Spencer5f016e22007-07-11 17:01:13 +0000205/// Stringify - Convert the specified string into a C string, with surrounding
206/// ""'s, and with escaped \ and " characters.
207std::string Lexer::Stringify(const std::string &Str, bool Charify) {
208 std::string Result = Str;
209 char Quote = Charify ? '\'' : '"';
210 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
211 if (Result[i] == '\\' || Result[i] == Quote) {
212 Result.insert(Result.begin()+i, '\\');
213 ++i; ++e;
214 }
215 }
216 return Result;
217}
218
Chris Lattnerd8e30832007-07-24 06:57:14 +0000219/// Stringify - Convert the specified string into a C string by escaping '\'
220/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000221void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000222 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
223 if (Str[i] == '\\' || Str[i] == '"') {
224 Str.insert(Str.begin()+i, '\\');
225 ++i; ++e;
226 }
227 }
228}
229
Chris Lattnerb0607272010-11-17 07:26:20 +0000230//===----------------------------------------------------------------------===//
231// Token Spelling
232//===----------------------------------------------------------------------===//
233
234/// getSpelling() - Return the 'spelling' of this token. The spelling of a
235/// token are the characters used to represent the token in the source file
236/// after trigraph expansion and escaped-newline folding. In particular, this
237/// wants to get the true, uncanonicalized, spelling of things like digraphs
238/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000239StringRef Lexer::getSpelling(SourceLocation loc,
240 SmallVectorImpl<char> &buffer,
John McCall834e3f62011-03-08 07:59:04 +0000241 const SourceManager &SM,
242 const LangOptions &options,
243 bool *invalid) {
244 // Break down the source location.
245 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
246
247 // Try to the load the file buffer.
248 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000250 if (invalidTemp) {
251 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000252 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000253 }
254
255 const char *tokenBegin = file.data() + locInfo.second;
256
257 // Lex from the start of the given location.
258 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
259 file.begin(), tokenBegin, file.end());
260 Token token;
261 lexer.LexFromRawLexer(token);
262
263 unsigned length = token.getLength();
264
265 // Common case: no need for cleaning.
266 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000267 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000268
269 // Hard case, we need to relex the characters into the string.
270 buffer.clear();
271 buffer.reserve(length);
272
273 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
274 unsigned charSize;
275 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
276 ti += charSize;
277 }
278
Chris Lattner5f9e2722011-07-23 10:55:15 +0000279 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000280}
281
282/// getSpelling() - Return the 'spelling' of this token. The spelling of a
283/// token are the characters used to represent the token in the source file
284/// after trigraph expansion and escaped-newline folding. In particular, this
285/// wants to get the true, uncanonicalized, spelling of things like digraphs
286/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000287std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
288 const LangOptions &Features, bool *Invalid) {
289 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
290
291 // If this token contains nothing interesting, return it directly.
292 bool CharDataInvalid = false;
293 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
294 &CharDataInvalid);
295 if (Invalid)
296 *Invalid = CharDataInvalid;
297 if (CharDataInvalid)
298 return std::string();
299
300 if (!Tok.needsCleaning())
301 return std::string(TokStart, TokStart+Tok.getLength());
302
303 std::string Result;
304 Result.reserve(Tok.getLength());
305
306 // Otherwise, hard case, relex the characters into the string.
307 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
308 Ptr != End; ) {
309 unsigned CharSize;
310 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
311 Ptr += CharSize;
312 }
313 assert(Result.size() != unsigned(Tok.getLength()) &&
314 "NeedsCleaning flag set on something that didn't need cleaning!");
315 return Result;
316}
317
318/// getSpelling - This method is used to get the spelling of a token into a
319/// preallocated buffer, instead of as an std::string. The caller is required
320/// to allocate enough space for the token, which is guaranteed to be at least
321/// Tok.getLength() bytes long. The actual length of the token is returned.
322///
323/// Note that this method may do two possible things: it may either fill in
324/// the buffer specified with characters, or it may *change the input pointer*
325/// to point to a constant buffer with the data already in it (avoiding a
326/// copy). The caller is not allowed to modify the returned buffer pointer
327/// if an internal buffer is returned.
328unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
329 const SourceManager &SourceMgr,
330 const LangOptions &Features, bool *Invalid) {
331 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000332
333 const char *TokStart = 0;
334 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
335 if (Tok.is(tok::raw_identifier))
336 TokStart = Tok.getRawIdentifierData();
337 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
338 // Just return the string from the identifier table, which is very quick.
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 Buffer = II->getNameStart();
340 return II->getLength();
341 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000342
343 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000344 if (Tok.isLiteral())
345 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000346
Chris Lattnerb0607272010-11-17 07:26:20 +0000347 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000348 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 bool CharDataInvalid = false;
350 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
351 if (Invalid)
352 *Invalid = CharDataInvalid;
353 if (CharDataInvalid) {
354 Buffer = "";
355 return 0;
356 }
357 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000358
Chris Lattnerb0607272010-11-17 07:26:20 +0000359 // If this token contains nothing interesting, return it directly.
360 if (!Tok.needsCleaning()) {
361 Buffer = TokStart;
362 return Tok.getLength();
363 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000364
Chris Lattnerb0607272010-11-17 07:26:20 +0000365 // Otherwise, hard case, relex the characters into the string.
366 char *OutBuf = const_cast<char*>(Buffer);
367 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
368 Ptr != End; ) {
369 unsigned CharSize;
370 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
371 Ptr += CharSize;
372 }
373 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
374 "NeedsCleaning flag set on something that didn't need cleaning!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000375
Chris Lattnerb0607272010-11-17 07:26:20 +0000376 return OutBuf-Buffer;
377}
378
379
380
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000381static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000382
Chris Lattner9a611942007-10-17 21:18:47 +0000383/// MeasureTokenLength - Relex the token at the specified location and return
384/// its length in bytes in the input file. If the token needs cleaning (e.g.
385/// includes a trigraph or an escaped newline) then this count includes bytes
386/// that are part of that.
387unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000388 const SourceManager &SM,
389 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000390 // TODO: this could be special cased for common tokens like identifiers, ')',
391 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000392 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000393 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
394 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000395
396 // If this comes from a macro expansion, we really do want the macro name, not
397 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000398 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000399 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000400 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000401 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000402 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000403 return 0;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000404
405 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000406
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000407 if (isWhitespace(StrData[0]))
408 return 0;
409
Chris Lattner9a611942007-10-17 21:18:47 +0000410 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000411 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
412 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000413 TheLexer.SetCommentRetentionState(true);
Chris Lattner9a611942007-10-17 21:18:47 +0000414 Token TheTok;
Chris Lattner590f0cc2008-10-12 01:15:46 +0000415 TheLexer.LexFromRawLexer(TheTok);
Chris Lattner9a611942007-10-17 21:18:47 +0000416 return TheTok.getLength();
417}
418
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000419static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
420 const SourceManager &SM,
421 const LangOptions &LangOpts) {
422 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000423 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000424 if (LocInfo.first.isInvalid())
425 return Loc;
426
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000427 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000428 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000429 if (Invalid)
430 return Loc;
431
432 // Back up from the current location until we hit the beginning of a line
433 // (or the buffer). We'll relex from that point.
434 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000435 if (LocInfo.second >= Buffer.size())
436 return Loc;
437
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000438 const char *StrData = BufStart+LocInfo.second;
439 if (StrData[0] == '\n' || StrData[0] == '\r')
440 return Loc;
441
442 const char *LexStart = StrData;
443 while (LexStart != BufStart) {
444 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
445 ++LexStart;
446 break;
447 }
448
449 --LexStart;
450 }
451
452 // Create a lexer starting at the beginning of this token.
453 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
454 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
455 TheLexer.SetCommentRetentionState(true);
456
457 // Lex tokens until we find the token that contains the source location.
458 Token TheTok;
459 do {
460 TheLexer.LexFromRawLexer(TheTok);
461
462 if (TheLexer.getBufferLocation() > StrData) {
463 // Lexing this token has taken the lexer past the source location we're
464 // looking for. If the current token encompasses our source location,
465 // return the beginning of that token.
466 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
467 return TheTok.getLocation();
468
469 // We ended up skipping over the source location entirely, which means
470 // that it points into whitespace. We're done here.
471 break;
472 }
473 } while (TheTok.getKind() != tok::eof);
474
475 // We've passed our source location; just return the original source location.
476 return Loc;
477}
478
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000479SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
480 const SourceManager &SM,
481 const LangOptions &LangOpts) {
482 if (Loc.isFileID())
483 return getBeginningOfFileToken(Loc, SM, LangOpts);
484
485 if (!SM.isMacroArgExpansion(Loc))
486 return Loc;
487
488 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
489 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
490 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
491 std::pair<FileID, unsigned> BeginFileLocInfo= SM.getDecomposedLoc(BeginFileLoc);
492 assert(FileLocInfo.first == BeginFileLocInfo.first &&
493 FileLocInfo.second >= BeginFileLocInfo.second);
494 return Loc.getFileLocWithOffset(SM.getDecomposedLoc(BeginFileLoc).second -
495 SM.getDecomposedLoc(FileLoc).second);
496}
497
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000498namespace {
499 enum PreambleDirectiveKind {
500 PDK_Skipped,
501 PDK_StartIf,
502 PDK_EndIf,
503 PDK_Unknown
504 };
505}
506
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000507std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000508Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
509 const LangOptions &Features, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000510 // Create a lexer starting at the beginning of the file. Note that we use a
511 // "fake" file source location at offset 1 so that the lexer will track our
512 // position within the file.
513 const unsigned StartOffset = 1;
514 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000515 Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000516 Buffer->getBufferStart(), Buffer->getBufferEnd());
517
518 bool InPreprocessorDirective = false;
519 Token TheTok;
520 Token IfStartTok;
521 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000522 unsigned Line = 0;
523
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000524 do {
525 TheLexer.LexFromRawLexer(TheTok);
526
527 if (InPreprocessorDirective) {
528 // If we've hit the end of the file, we're done.
529 if (TheTok.getKind() == tok::eof) {
530 InPreprocessorDirective = false;
531 break;
532 }
533
534 // If we haven't hit the end of the preprocessor directive, skip this
535 // token.
536 if (!TheTok.isAtStartOfLine())
537 continue;
538
539 // We've passed the end of the preprocessor directive, and will look
540 // at this token again below.
541 InPreprocessorDirective = false;
542 }
543
Douglas Gregordf95a132010-08-09 20:45:32 +0000544 // Keep track of the # of lines in the preamble.
545 if (TheTok.isAtStartOfLine()) {
546 ++Line;
547
548 // If we were asked to limit the number of lines in the preamble,
549 // and we're about to exceed that limit, we're done.
550 if (MaxLines && Line >= MaxLines)
551 break;
552 }
553
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000554 // Comments are okay; skip over them.
555 if (TheTok.getKind() == tok::comment)
556 continue;
557
558 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
559 // This is the start of a preprocessor directive.
560 Token HashTok = TheTok;
561 InPreprocessorDirective = true;
562
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000563 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000564 // we don't have an identifier table available. Instead, just look at
565 // the raw identifier to recognize and categorize preprocessor directives.
566 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000567 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000569 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000570 PreambleDirectiveKind PDK
571 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
572 .Case("include", PDK_Skipped)
573 .Case("__include_macros", PDK_Skipped)
574 .Case("define", PDK_Skipped)
575 .Case("undef", PDK_Skipped)
576 .Case("line", PDK_Skipped)
577 .Case("error", PDK_Skipped)
578 .Case("pragma", PDK_Skipped)
579 .Case("import", PDK_Skipped)
580 .Case("include_next", PDK_Skipped)
581 .Case("warning", PDK_Skipped)
582 .Case("ident", PDK_Skipped)
583 .Case("sccs", PDK_Skipped)
584 .Case("assert", PDK_Skipped)
585 .Case("unassert", PDK_Skipped)
586 .Case("if", PDK_StartIf)
587 .Case("ifdef", PDK_StartIf)
588 .Case("ifndef", PDK_StartIf)
589 .Case("elif", PDK_Skipped)
590 .Case("else", PDK_Skipped)
591 .Case("endif", PDK_EndIf)
592 .Default(PDK_Unknown);
593
594 switch (PDK) {
595 case PDK_Skipped:
596 continue;
597
598 case PDK_StartIf:
599 if (IfCount == 0)
600 IfStartTok = HashTok;
601
602 ++IfCount;
603 continue;
604
605 case PDK_EndIf:
606 // Mismatched #endif. The preamble ends here.
607 if (IfCount == 0)
608 break;
609
610 --IfCount;
611 continue;
612
613 case PDK_Unknown:
614 // We don't know what this directive is; stop at the '#'.
615 break;
616 }
617 }
618
619 // We only end up here if we didn't recognize the preprocessor
620 // directive or it was one that can't occur in the preamble at this
621 // point. Roll back the current token to the location of the '#'.
622 InPreprocessorDirective = false;
623 TheTok = HashTok;
624 }
625
Douglas Gregordf95a132010-08-09 20:45:32 +0000626 // We hit a token that we don't recognize as being in the
627 // "preprocessing only" part of the file, so we're no longer in
628 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000629 break;
630 } while (true);
631
632 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000633 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
634 IfCount? IfStartTok.isAtStartOfLine()
635 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000636}
637
Chris Lattner7ef5c272010-11-17 07:05:50 +0000638
639/// AdvanceToTokenCharacter - Given a location that specifies the start of a
640/// token, return a new location that specifies a character within the token.
641SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
642 unsigned CharNo,
643 const SourceManager &SM,
644 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000645 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000646 // character is. This needs to take into consideration newlines and
647 // trigraphs.
648 bool Invalid = false;
649 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
650
651 // If they request the first char of the token, we're trivially done.
652 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
653 return TokStart;
654
655 unsigned PhysOffset = 0;
656
657 // The usual case is that tokens don't contain anything interesting. Skip
658 // over the uninteresting characters. If a token only consists of simple
659 // chars, this method is extremely fast.
660 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
661 if (CharNo == 0)
662 return TokStart.getFileLocWithOffset(PhysOffset);
663 ++TokPtr, --CharNo, ++PhysOffset;
664 }
665
666 // If we have a character that may be a trigraph or escaped newline, use a
667 // lexer to parse it correctly.
668 for (; CharNo; --CharNo) {
669 unsigned Size;
670 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
671 TokPtr += Size;
672 PhysOffset += Size;
673 }
674
675 // Final detail: if we end up on an escaped newline, we want to return the
676 // location of the actual byte of the token. For example foo\<newline>bar
677 // advanced by 3 should return the location of b, not of \\. One compounding
678 // detail of this is that the escape may be made by a trigraph.
679 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
680 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
681
682 return TokStart.getFileLocWithOffset(PhysOffset);
683}
684
685/// \brief Computes the source location just past the end of the
686/// token at this source location.
687///
688/// This routine can be used to produce a source location that
689/// points just past the end of the token referenced by \p Loc, and
690/// is generally used when a diagnostic needs to point just after a
691/// token where it expected something different that it received. If
692/// the returned source location would not be meaningful (e.g., if
693/// it points into a macro), this routine returns an invalid
694/// source location.
695///
696/// \param Offset an offset from the end of the token, where the source
697/// location should refer to. The default offset (0) produces a source
698/// location pointing just past the end of the token; an offset of 1 produces
699/// a source location pointing to the last character in the token, etc.
700SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
701 const SourceManager &SM,
702 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000703 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000704 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000705
706 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000707 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
708 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000709
Chandler Carruth433db062011-07-14 08:20:40 +0000710 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000711 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000712 }
713
Chris Lattner7ef5c272010-11-17 07:05:50 +0000714 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
715 if (Len > Offset)
716 Len = Len - Offset;
717 else
718 return Loc;
719
John McCall77ebb382011-04-06 01:50:22 +0000720 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000721}
722
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000723/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000724/// token of the macro expansion.
725bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000726 const SourceManager &SM,
727 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000728 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
729
730 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
731 // FIXME: If the token comes from the macro token paste operator ('##')
732 // this function will always return false;
733 if (infoLoc.second > 0)
734 return false; // Does not point at the start of token.
735
Chandler Carruth433db062011-07-14 08:20:40 +0000736 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000737 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000738 if (expansionLoc.isFileID())
739 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000740
Chandler Carruth433db062011-07-14 08:20:40 +0000741 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000742}
743
744/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000745/// token of the macro expansion.
746bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000747 const SourceManager &SM,
748 const LangOptions &LangOpts) {
749 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
750
751 SourceLocation spellLoc = SM.getSpellingLoc(loc);
752 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
753 if (tokLen == 0)
754 return false;
755
756 FileID FID = SM.getFileID(loc);
757 SourceLocation afterLoc = loc.getFileLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000758 if (SM.isInFileID(afterLoc, FID))
759 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000760
761 // FIXME: If the token comes from the macro token paste operator ('##')
762 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000763
Chandler Carruth433db062011-07-14 08:20:40 +0000764 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000765 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000766 if (expansionLoc.isFileID())
767 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000768
Chandler Carruth433db062011-07-14 08:20:40 +0000769 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000770}
771
Reid Spencer5f016e22007-07-11 17:01:13 +0000772//===----------------------------------------------------------------------===//
773// Character information.
774//===----------------------------------------------------------------------===//
775
Reid Spencer5f016e22007-07-11 17:01:13 +0000776enum {
777 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
778 CHAR_VERT_WS = 0x02, // '\r', '\n'
779 CHAR_LETTER = 0x04, // a-z,A-Z
780 CHAR_NUMBER = 0x08, // 0-9
781 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000782 CHAR_PERIOD = 0x20, // .
783 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000784};
785
Chris Lattner03b98662009-07-07 17:09:54 +0000786// Statically initialize CharInfo table based on ASCII character set
787// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000788static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000789{
790// 0 NUL 1 SOH 2 STX 3 ETX
791// 4 EOT 5 ENQ 6 ACK 7 BEL
792 0 , 0 , 0 , 0 ,
793 0 , 0 , 0 , 0 ,
794// 8 BS 9 HT 10 NL 11 VT
795//12 NP 13 CR 14 SO 15 SI
796 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
797 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
798//16 DLE 17 DC1 18 DC2 19 DC3
799//20 DC4 21 NAK 22 SYN 23 ETB
800 0 , 0 , 0 , 0 ,
801 0 , 0 , 0 , 0 ,
802//24 CAN 25 EM 26 SUB 27 ESC
803//28 FS 29 GS 30 RS 31 US
804 0 , 0 , 0 , 0 ,
805 0 , 0 , 0 , 0 ,
806//32 SP 33 ! 34 " 35 #
807//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000808 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
809 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000810//40 ( 41 ) 42 * 43 +
811//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000812 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
813 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000814//48 0 49 1 50 2 51 3
815//52 4 53 5 54 6 55 7
816 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
817 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
818//56 8 57 9 58 : 59 ;
819//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000820 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
821 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000822//64 @ 65 A 66 B 67 C
823//68 D 69 E 70 F 71 G
824 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
825 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
826//72 H 73 I 74 J 75 K
827//76 L 77 M 78 N 79 O
828 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
829 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
830//80 P 81 Q 82 R 83 S
831//84 T 85 U 86 V 87 W
832 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
833 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
834//88 X 89 Y 90 Z 91 [
835//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000836 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
837 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000838//96 ` 97 a 98 b 99 c
839//100 d 101 e 102 f 103 g
840 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
841 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
842//104 h 105 i 106 j 107 k
843//108 l 109 m 110 n 111 o
844 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
845 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
846//112 p 113 q 114 r 115 s
847//116 t 117 u 118 v 119 w
848 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
849 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
850//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000851//124 | 125 } 126 ~ 127 DEL
852 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
853 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000854};
855
Chris Lattnera2bf1052009-12-17 05:29:40 +0000856static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 static bool isInited = false;
858 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000859 // check the statically-initialized CharInfo table
860 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
861 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
862 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
863 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
864 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
865 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
866 assert(CHAR_UNDER == CharInfo[(int)'_']);
867 assert(CHAR_PERIOD == CharInfo[(int)'.']);
868 for (unsigned i = 'a'; i <= 'z'; ++i) {
869 assert(CHAR_LETTER == CharInfo[i]);
870 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
871 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000873 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000874
Chris Lattner03b98662009-07-07 17:09:54 +0000875 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}
877
Chris Lattner03b98662009-07-07 17:09:54 +0000878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// isIdentifierBody - Return true if this is the body character of an
880/// identifier, which is [a-zA-Z0-9_].
881static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000882 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000883}
884
885/// isHorizontalWhitespace - Return true if this character is horizontal
886/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
887static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000888 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000889}
890
Anna Zaksaca25bc2011-07-27 21:43:43 +0000891/// isVerticalWhitespace - Return true if this character is vertical
892/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
893static inline bool isVerticalWhitespace(unsigned char c) {
894 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
895}
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897/// isWhitespace - Return true if this character is horizontal or vertical
898/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
899/// for '\0'.
900static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000901 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000902}
903
904/// isNumberBody - Return true if this is the body character of an
905/// preprocessing number, which is [a-zA-Z0-9_.].
906static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000907 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000908 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000909}
910
Craig Topper2fa4e862011-08-11 04:06:15 +0000911/// isRawStringDelimBody - Return true if this is the body character of a
912/// raw string delimiter.
913static inline bool isRawStringDelimBody(unsigned char c) {
914 return (CharInfo[c] &
915 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
916 true : false;
917}
918
Reid Spencer5f016e22007-07-11 17:01:13 +0000919
920//===----------------------------------------------------------------------===//
921// Diagnostics forwarding code.
922//===----------------------------------------------------------------------===//
923
Chris Lattner409a0362007-07-22 18:38:25 +0000924/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000925/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000926/// This is currently only used for _Pragma implementation, so it is the slow
927/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000928static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
929 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000930static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
931 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000932 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000933 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner409a0362007-07-22 18:38:25 +0000935 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000936 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000937 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000938 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chandler Carruth433db062011-07-14 08:20:40 +0000940 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000941 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000942 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000943 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Chris Lattnere7fb4842009-02-15 20:52:18 +0000945 // Figure out the expansion loc range, which is the range covered by the
946 // original _Pragma(...) sequence.
947 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000948 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chandler Carruthbf340e42011-07-26 03:03:05 +0000950 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000951}
952
Reid Spencer5f016e22007-07-11 17:01:13 +0000953/// getSourceLocation - Return a source location identifier for the specified
954/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000955SourceLocation Lexer::getSourceLocation(const char *Loc,
956 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000957 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000959
960 // In the normal case, we're just lexing from a simple file buffer, return
961 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000962 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000963 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000964 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner2b2453a2009-01-17 06:22:33 +0000966 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
967 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000968 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000969 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000970}
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972/// Diag - Forwarding function for diagnostics. This translate a source
973/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000974DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000975 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976}
Reid Spencer5f016e22007-07-11 17:01:13 +0000977
978//===----------------------------------------------------------------------===//
979// Trigraph and Escaped Newline Handling Code.
980//===----------------------------------------------------------------------===//
981
982/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
983/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
984static char GetTrigraphCharForLetter(char Letter) {
985 switch (Letter) {
986 default: return 0;
987 case '=': return '#';
988 case ')': return ']';
989 case '(': return '[';
990 case '!': return '|';
991 case '\'': return '^';
992 case '>': return '}';
993 case '/': return '\\';
994 case '<': return '{';
995 case '-': return '~';
996 }
997}
998
999/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1000/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1001/// return the result character. Finally, emit a warning about trigraph use
1002/// whether trigraphs are enabled or not.
1003static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1004 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001005 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner3692b092008-11-18 07:59:24 +00001007 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001008 if (!L->isLexingRawMode())
1009 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001010 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner74d15df2008-11-22 02:02:22 +00001013 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 return Res;
1016}
1017
Chris Lattner24f0e482009-04-18 22:05:41 +00001018/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1019/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump1eb44332009-09-09 15:08:12 +00001020/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001021unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1022 unsigned Size = 0;
1023 while (isWhitespace(Ptr[Size])) {
1024 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner24f0e482009-04-18 22:05:41 +00001026 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1027 continue;
1028
1029 // If this is a \r\n or \n\r, skip the other half.
1030 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1031 Ptr[Size-1] != Ptr[Size])
1032 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Chris Lattner24f0e482009-04-18 22:05:41 +00001034 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001035 }
1036
Chris Lattner24f0e482009-04-18 22:05:41 +00001037 // Not an escaped newline, must be a \t or something else.
1038 return 0;
1039}
1040
Chris Lattner03374952009-04-18 22:27:02 +00001041/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1042/// them), skip over them and return the first non-escaped-newline found,
1043/// otherwise return P.
1044const char *Lexer::SkipEscapedNewLines(const char *P) {
1045 while (1) {
1046 const char *AfterEscape;
1047 if (*P == '\\') {
1048 AfterEscape = P+1;
1049 } else if (*P == '?') {
1050 // If not a trigraph for escape, bail out.
1051 if (P[1] != '?' || P[2] != '/')
1052 return P;
1053 AfterEscape = P+3;
1054 } else {
1055 return P;
1056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner03374952009-04-18 22:27:02 +00001058 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1059 if (NewLineSize == 0) return P;
1060 P = AfterEscape+NewLineSize;
1061 }
1062}
1063
Anna Zaksaca25bc2011-07-27 21:43:43 +00001064/// \brief Checks that the given token is the first token that occurs after the
1065/// given location (this excludes comments and whitespace). Returns the location
1066/// immediately after the specified token. If the token is not found or the
1067/// location is inside a macro, the returned source location will be invalid.
1068SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1069 tok::TokenKind TKind,
1070 const SourceManager &SM,
1071 const LangOptions &LangOpts,
1072 bool SkipTrailingWhitespaceAndNewLine) {
1073 if (Loc.isMacroID()) {
1074 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1075 return SourceLocation();
1076 Loc = SM.getExpansionRange(Loc).second;
1077 }
1078 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1079
1080 // Break down the source location.
1081 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1082
1083 // Try to load the file buffer.
1084 bool InvalidTemp = false;
1085 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1086 if (InvalidTemp)
1087 return SourceLocation();
1088
1089 const char *TokenBegin = File.data() + LocInfo.second;
1090
1091 // Lex from the start of the given location.
1092 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1093 TokenBegin, File.end());
1094 // Find the token.
1095 Token Tok;
1096 lexer.LexFromRawLexer(Tok);
1097 if (Tok.isNot(TKind))
1098 return SourceLocation();
1099 SourceLocation TokenLoc = Tok.getLocation();
1100
1101 // Calculate how much whitespace needs to be skipped if any.
1102 unsigned NumWhitespaceChars = 0;
1103 if (SkipTrailingWhitespaceAndNewLine) {
1104 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1105 Tok.getLength();
1106 unsigned char C = *TokenEnd;
1107 while (isHorizontalWhitespace(C)) {
1108 C = *(++TokenEnd);
1109 NumWhitespaceChars++;
1110 }
1111 if (isVerticalWhitespace(C))
1112 NumWhitespaceChars++;
1113 }
1114
1115 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1116}
Chris Lattner24f0e482009-04-18 22:05:41 +00001117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1119/// get its size, and return it. This is tricky in several cases:
1120/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1121/// then either return the trigraph (skipping 3 chars) or the '?',
1122/// depending on whether trigraphs are enabled or not.
1123/// 2. If this is an escaped newline (potentially with whitespace between
1124/// the backslash and newline), implicitly skip the newline and return
1125/// the char after it.
1126/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1127///
1128/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1129/// know that we can accumulate into Size, and that we have already incremented
1130/// Ptr by Size bytes.
1131///
1132/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1133/// be updated to match.
1134///
1135char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001136 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // If we have a slash, look for an escaped newline.
1138 if (Ptr[0] == '\\') {
1139 ++Size;
1140 ++Ptr;
1141Slash:
1142 // Common case, backslash-char where the char is not whitespace.
1143 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Chris Lattner5636a3b2009-06-23 05:15:06 +00001145 // See if we have optional whitespace characters between the slash and
1146 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001147 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1148 // Remember that this token needs to be cleaned.
1149 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001150
Chris Lattner24f0e482009-04-18 22:05:41 +00001151 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001152 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001153 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Chris Lattner24f0e482009-04-18 22:05:41 +00001155 // Found backslash<whitespace><newline>. Parse the char after it.
1156 Size += EscapedNewLineSize;
1157 Ptr += EscapedNewLineSize;
1158 // Use slow version to accumulate a correct size field.
1159 return getCharAndSizeSlow(Ptr, Size, Tok);
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 // Otherwise, this is not an escaped newline, just return the slash.
1163 return '\\';
1164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 // If this is a trigraph, process it.
1167 if (Ptr[0] == '?' && Ptr[1] == '?') {
1168 // If this is actually a legal trigraph (not something like "??x"), emit
1169 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1170 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1171 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001172 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 Ptr += 3;
1175 Size += 3;
1176 if (C == '\\') goto Slash;
1177 return C;
1178 }
1179 }
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // If this is neither, return a single character.
1182 ++Size;
1183 return *Ptr;
1184}
1185
1186
1187/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1188/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1189/// and that we have already incremented Ptr by Size bytes.
1190///
1191/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1192/// be updated to match.
1193char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1194 const LangOptions &Features) {
1195 // If we have a slash, look for an escaped newline.
1196 if (Ptr[0] == '\\') {
1197 ++Size;
1198 ++Ptr;
1199Slash:
1200 // Common case, backslash-char where the char is not whitespace.
1201 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001204 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1205 // Found backslash<whitespace><newline>. Parse the char after it.
1206 Size += EscapedNewLineSize;
1207 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattner24f0e482009-04-18 22:05:41 +00001209 // Use slow version to accumulate a correct size field.
1210 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 // Otherwise, this is not an escaped newline, just return the slash.
1214 return '\\';
1215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 // If this is a trigraph, process it.
1218 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1219 // If this is actually a legal trigraph (not something like "??x"), return
1220 // it.
1221 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1222 Ptr += 3;
1223 Size += 3;
1224 if (C == '\\') goto Slash;
1225 return C;
1226 }
1227 }
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // If this is neither, return a single character.
1230 ++Size;
1231 return *Ptr;
1232}
1233
1234//===----------------------------------------------------------------------===//
1235// Helper methods for lexing.
1236//===----------------------------------------------------------------------===//
1237
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001238/// \brief Routine that indiscriminately skips bytes in the source file.
1239void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1240 BufferPtr += Bytes;
1241 if (BufferPtr > BufferEnd)
1242 BufferPtr = BufferEnd;
1243 IsAtStartOfLine = StartOfLine;
1244}
1245
Chris Lattnerd2177732007-07-20 16:59:19 +00001246void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1248 unsigned Size;
1249 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001250 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001252
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 --CurPtr; // Back up over the skipped character.
1254
1255 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1256 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1257 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001258 //
1259 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1260 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1262FinishIdentifier:
1263 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001264 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1265 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 // If we are in raw mode, return this identifier raw. There is no need to
1268 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001269 if (LexingRawMode)
1270 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001272 // Fill in Result.IdentifierInfo and update the token kind,
1273 // looking up the identifier in the identifier table.
1274 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // Finally, now that we know we have an identifier, pass this off to the
1277 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001278 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001279 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001280
Chris Lattner6a170eb2009-01-21 07:43:11 +00001281 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 }
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 C = getCharAndSize(CurPtr, Size);
1287 while (1) {
1288 if (C == '$') {
1289 // If we hit a $ and they are not supported in identifiers, we are done.
1290 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001293 if (!isLexingRawMode())
1294 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 CurPtr = ConsumeChar(CurPtr, Size, Result);
1296 C = getCharAndSize(CurPtr, Size);
1297 continue;
1298 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1299 // Found end of identifier.
1300 goto FinishIdentifier;
1301 }
1302
1303 // Otherwise, this character is good, consume it.
1304 CurPtr = ConsumeChar(CurPtr, Size, Result);
1305
1306 C = getCharAndSize(CurPtr, Size);
1307 while (isIdentifierBody(C)) { // FIXME: UCNs.
1308 CurPtr = ConsumeChar(CurPtr, Size, Result);
1309 C = getCharAndSize(CurPtr, Size);
1310 }
1311 }
1312}
1313
Douglas Gregora75ec432010-08-30 14:50:47 +00001314/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001315/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001316static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1317 unsigned Size;
1318 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1319 if (C1 != '0')
1320 return false;
1321 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1322 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001323}
Reid Spencer5f016e22007-07-11 17:01:13 +00001324
Nate Begeman5253c7f2008-04-14 02:26:39 +00001325/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001326/// constant. From[-1] is the first character lexed. Return the end of the
1327/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001328void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 unsigned Size;
1330 char C = getCharAndSize(CurPtr, Size);
1331 char PrevCh = 0;
1332 while (isNumberBody(C)) { // FIXME: UCNs?
1333 CurPtr = ConsumeChar(CurPtr, Size, Result);
1334 PrevCh = C;
1335 C = getCharAndSize(CurPtr, Size);
1336 }
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001339 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1340 // If we are in Microsoft mode, don't continue if the constant is hex.
1341 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001342 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001343 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1344 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001345
1346 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001347 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001348 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001352 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001353 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001354 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001355}
1356
1357/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001358/// either " or L" or u8" or u" or U".
1359void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1360 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 char C = getAndAdvanceChar(CurPtr, Result);
1364 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001365 // Skip escaped characters. Escaped newlines will already be processed by
1366 // getAndAdvanceChar.
1367 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001369
Chris Lattner571339c2010-05-30 23:27:38 +00001370 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001371 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001372 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1373 PP->CodeCompleteNaturalLanguage();
1374 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001375 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001376 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 }
Chris Lattner571339c2010-05-30 23:27:38 +00001379
1380 if (C == 0)
1381 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 C = getAndAdvanceChar(CurPtr, Result);
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001386 if (NulCharacter && !isLexingRawMode())
1387 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001390 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001391 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001392 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393}
1394
Craig Topper2fa4e862011-08-11 04:06:15 +00001395/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1396/// having lexed R", LR", u8R", uR", or UR".
1397void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1398 tok::TokenKind Kind) {
1399 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1400 // Between the initial and final double quote characters of the raw string,
1401 // any transformations performed in phases 1 and 2 (trigraphs,
1402 // universal-character-names, and line splicing) are reverted.
1403
1404 unsigned PrefixLen = 0;
1405
1406 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1407 ++PrefixLen;
1408
1409 // If the last character was not a '(', then we didn't lex a valid delimiter.
1410 if (CurPtr[PrefixLen] != '(') {
1411 if (!isLexingRawMode()) {
1412 const char *PrefixEnd = &CurPtr[PrefixLen];
1413 if (PrefixLen == 16) {
1414 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1415 } else {
1416 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1417 << StringRef(PrefixEnd, 1);
1418 }
1419 }
1420
1421 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1422 // it's possible the '"' was intended to be part of the raw string, but
1423 // there's not much we can do about that.
1424 while (1) {
1425 char C = *CurPtr++;
1426
1427 if (C == '"')
1428 break;
1429 if (C == 0 && CurPtr-1 == BufferEnd) {
1430 --CurPtr;
1431 break;
1432 }
1433 }
1434
1435 FormTokenWithChars(Result, CurPtr, tok::unknown);
1436 return;
1437 }
1438
1439 // Save prefix and move CurPtr past it
1440 const char *Prefix = CurPtr;
1441 CurPtr += PrefixLen + 1; // skip over prefix and '('
1442
1443 while (1) {
1444 char C = *CurPtr++;
1445
1446 if (C == ')') {
1447 // Check for prefix match and closing quote.
1448 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1449 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1450 break;
1451 }
1452 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1453 if (!isLexingRawMode())
1454 Diag(BufferPtr, diag::err_unterminated_raw_string)
1455 << StringRef(Prefix, PrefixLen);
1456 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1457 return;
1458 }
1459 }
1460
1461 // Update the location of token as well as BufferPtr.
1462 const char *TokStart = BufferPtr;
1463 FormTokenWithChars(Result, CurPtr, Kind);
1464 Result.setLiteralData(TokStart);
1465}
1466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1468/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001469void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001471 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 char C = getAndAdvanceChar(CurPtr, Result);
1473 while (C != '>') {
1474 // Skip escaped characters.
1475 if (C == '\\') {
1476 // Skip the escaped character.
1477 C = getAndAdvanceChar(CurPtr, Result);
1478 } else if (C == '\n' || C == '\r' || // Newline.
1479 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001480 // If the filename is unterminated, then it must just be a lone <
1481 // character. Return this as such.
1482 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 return;
1484 } else if (C == 0) {
1485 NulCharacter = CurPtr-1;
1486 }
1487 C = getAndAdvanceChar(CurPtr, Result);
1488 }
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001491 if (NulCharacter && !isLexingRawMode())
1492 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001495 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001496 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001497 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498}
1499
1500
1501/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001502/// lexed either ' or L' or u' or U'.
1503void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1504 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 const char *NulCharacter = 0; // Does this character contain the \0 character?
1506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 char C = getAndAdvanceChar(CurPtr, Result);
1508 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001509 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001510 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001511 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001513 }
1514
1515 while (C != '\'') {
1516 // Skip escaped characters.
1517 if (C == '\\') {
1518 // Skip the escaped character.
1519 // FIXME: UCN's
1520 C = getAndAdvanceChar(CurPtr, Result);
1521 } else if (C == '\n' || C == '\r' || // Newline.
1522 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001523 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1524 PP->CodeCompleteNaturalLanguage();
1525 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001526 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001527 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1528 return;
1529 } else if (C == 0) {
1530 NulCharacter = CurPtr-1;
1531 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 C = getAndAdvanceChar(CurPtr, Result);
1533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Chris Lattnerd80f7862010-07-07 23:24:27 +00001535 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001536 if (NulCharacter && !isLexingRawMode())
1537 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001538
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001540 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001541 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001542 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001543}
1544
1545/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1546/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001547///
1548/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1549///
1550bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 // Whitespace - Skip it, then return the token after the whitespace.
1552 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1553 while (1) {
1554 // Skip horizontal whitespace very aggressively.
1555 while (isHorizontalWhitespace(Char))
1556 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001558 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 if (Char != '\n' && Char != '\r')
1560 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 if (ParsingPreprocessorDirective) {
1563 // End of preprocessor directive line, let LexTokenInternal handle this.
1564 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001565 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 // ok, but handle newline.
1569 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001570 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001572 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 Char = *++CurPtr;
1574 }
1575
1576 // If this isn't immediately after a newline, there is leading space.
1577 char PrevChar = CurPtr[-1];
1578 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001579 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580
Chris Lattnerd88dc482008-10-12 04:05:48 +00001581 // If the client wants us to return whitespace, return it now.
1582 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001583 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001584 return true;
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001588 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589}
1590
1591// SkipBCPLComment - We have just read the // characters from input. Skip until
1592// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001593/// BufferPtr and return.
1594///
1595/// If we're in KeepCommentMode or any CommentHandler has inserted
1596/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001597bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 // If BCPL comments aren't explicitly enabled for this language, emit an
1599 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001600 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 // Mark them enabled so we only emit one warning for this translation
1604 // unit.
1605 Features.BCPLComment = true;
1606 }
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // Scan over the body of the comment. The common case, when scanning, is that
1609 // the comment contains normal ascii characters with nothing interesting in
1610 // them. As such, optimize for this case with the inner loop.
1611 char C;
1612 do {
1613 C = *CurPtr;
1614 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1615 // If we find a \n character, scan backwards, checking to see if it's an
1616 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 // Skip over characters in the fast loop.
1619 while (C != 0 && // Potentially EOF.
1620 C != '\\' && // Potentially escaped newline.
1621 C != '?' && // Potentially trigraph.
1622 C != '\n' && C != '\r') // Newline or DOS-style newline.
1623 C = *++CurPtr;
1624
1625 // If this is a newline, we're done.
1626 if (C == '\n' || C == '\r')
1627 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001630 // properly decode the character. Read it in raw mode to avoid emitting
1631 // diagnostics about things like trigraphs. If we see an escaped newline,
1632 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001634 bool OldRawMode = isLexingRawMode();
1635 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001637 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001638
1639 // If the char that we finally got was a \n, then we must have had something
1640 // like \<newline><newline>. We don't want to have consumed the second
1641 // newline, we want CurPtr, to end up pointing to it down below.
1642 if (C == '\n' || C == '\r') {
1643 --CurPtr;
1644 C = 'x'; // doesn't matter what this is.
1645 }
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 // If we read multiple characters, and one of those characters was a \r or
1648 // \n, then we had an escaped newline within the comment. Emit diagnostic
1649 // unless the next line is also a // comment.
1650 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1651 for (; OldPtr != CurPtr; ++OldPtr)
1652 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1653 // Okay, we found a // comment that ends in a newline, if the next
1654 // line is also a // comment, but has spaces, don't emit a diagnostic.
1655 if (isspace(C)) {
1656 const char *ForwardPtr = CurPtr;
1657 while (isspace(*ForwardPtr)) // Skip whitespace.
1658 ++ForwardPtr;
1659 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1660 break;
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Chris Lattner74d15df2008-11-22 02:02:22 +00001663 if (!isLexingRawMode())
1664 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 break;
1666 }
1667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Douglas Gregor55817af2010-08-25 17:04:25 +00001669 if (CurPtr == BufferEnd+1) {
1670 if (PP && PP->isCodeCompletionFile(FileLoc))
1671 PP->CodeCompleteNaturalLanguage();
1672
1673 --CurPtr;
1674 break;
1675 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 } while (C != '\n' && C != '\r');
1677
Chris Lattner3d0ad582010-02-03 21:06:21 +00001678 // Found but did not consume the newline. Notify comment handlers about the
1679 // comment unless we're in a #if 0 block.
1680 if (PP && !isLexingRawMode() &&
1681 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1682 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001683 BufferPtr = CurPtr;
1684 return true; // A token has to be returned.
1685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001688 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 return SaveBCPLComment(Result, CurPtr);
1690
1691 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001692 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1694 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001695 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 }
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001699 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001700 // contribute to another token), it isn't needed for correctness. Note that
1701 // this is ok even in KeepWhitespaceMode, because we would have returned the
1702 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001706 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001708 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001710 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711}
1712
1713/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1714/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001715bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001716 // If we're not in a preprocessor directive, just return the // comment
1717 // directly.
1718 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Chris Lattner9e6293d2008-10-12 04:51:35 +00001720 if (!ParsingPreprocessorDirective)
1721 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Chris Lattner9e6293d2008-10-12 04:51:35 +00001723 // If this BCPL-style comment is in a macro definition, transmogrify it into
1724 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001725 bool Invalid = false;
1726 std::string Spelling = PP->getSpelling(Result, &Invalid);
1727 if (Invalid)
1728 return true;
1729
Chris Lattner9e6293d2008-10-12 04:51:35 +00001730 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1731 Spelling[1] = '*'; // Change prefix to "/*".
1732 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Chris Lattner9e6293d2008-10-12 04:51:35 +00001734 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001735 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1736 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001737 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001738}
1739
1740/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1741/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001742/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001743static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 Lexer *L) {
1745 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // Back up off the newline.
1748 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 // If this is a two-character newline sequence, skip the other character.
1751 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1752 // \n\n or \r\r -> not escaped newline.
1753 if (CurPtr[0] == CurPtr[1])
1754 return false;
1755 // \n\r or \r\n -> skip the newline.
1756 --CurPtr;
1757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 // If we have horizontal whitespace, skip over it. We allow whitespace
1760 // between the slash and newline.
1761 bool HasSpace = false;
1762 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1763 --CurPtr;
1764 HasSpace = true;
1765 }
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 // If we have a slash, we know this is an escaped newline.
1768 if (*CurPtr == '\\') {
1769 if (CurPtr[-1] != '*') return false;
1770 } else {
1771 // It isn't a slash, is it the ?? / trigraph?
1772 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1773 CurPtr[-3] != '*')
1774 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // This is the trigraph ending the comment. Emit a stern warning!
1777 CurPtr -= 2;
1778
1779 // If no trigraphs are enabled, warn that we ignored this trigraph and
1780 // ignore this * character.
1781 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001782 if (!L->isLexingRawMode())
1783 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 return false;
1785 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001786 if (!L->isLexingRawMode())
1787 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001791 if (!L->isLexingRawMode())
1792 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001795 if (HasSpace && !L->isLexingRawMode())
1796 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 return true;
1799}
1800
1801#ifdef __SSE2__
1802#include <emmintrin.h>
1803#elif __ALTIVEC__
1804#include <altivec.h>
1805#undef bool
1806#endif
1807
1808/// SkipBlockComment - We have just read the /* characters from input. Read
1809/// until we find the */ characters that terminate the comment. Note that we
1810/// don't bother decoding trigraphs or escaped newlines in block comments,
1811/// because they cannot cause the comment to end. The only thing that can
1812/// happen is the comment could end with an escaped newline between the */ end
1813/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001814///
Chris Lattner046c2272010-01-18 22:35:47 +00001815/// If we're in KeepCommentMode or any CommentHandler has inserted
1816/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001817bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001819 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 // optimization helps people who like to put a lot of * characters in their
1821 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001822
1823 // The first character we get with newlines and trigraphs skipped to handle
1824 // the degenerate /*/ case below correctly if the * has an escaped newline
1825 // after it.
1826 unsigned CharSize;
1827 unsigned char C = getCharAndSize(CurPtr, CharSize);
1828 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001830 if (!isLexingRawMode() &&
1831 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001832 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001833 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Chris Lattner31f0eca2008-10-12 04:19:49 +00001835 // KeepWhitespaceMode should return this broken comment as a token. Since
1836 // it isn't a well formed comment, just return it as an 'unknown' token.
1837 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001838 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001839 return true;
1840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Chris Lattner31f0eca2008-10-12 04:19:49 +00001842 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001843 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Chris Lattner8146b682007-07-21 23:43:37 +00001846 // Check to see if the first character after the '/*' is another /. If so,
1847 // then this slash does not end the block comment, it is part of it.
1848 if (C == '/')
1849 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 while (1) {
1852 // Skip over all non-interesting characters until we find end of buffer or a
1853 // (probably ending) '/' character.
1854 if (CurPtr + 24 < BufferEnd) {
1855 // While not aligned to a 16-byte boundary.
1856 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1857 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 if (C == '/') goto FoundSlash;
1860
1861#ifdef __SSE2__
1862 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1863 '/', '/', '/', '/', '/', '/', '/', '/');
1864 while (CurPtr+16 <= BufferEnd &&
1865 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1866 CurPtr += 16;
1867#elif __ALTIVEC__
1868 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001869 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 '/', '/', '/', '/', '/', '/', '/', '/'
1871 };
1872 while (CurPtr+16 <= BufferEnd &&
1873 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1874 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001875#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 // Scan for '/' quickly. Many block comments are very large.
1877 while (CurPtr[0] != '/' &&
1878 CurPtr[1] != '/' &&
1879 CurPtr[2] != '/' &&
1880 CurPtr[3] != '/' &&
1881 CurPtr+4 < BufferEnd) {
1882 CurPtr += 4;
1883 }
1884#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 // It has to be one of the bytes scanned, increment to it and read one.
1887 C = *CurPtr++;
1888 }
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 // Loop to scan the remainder.
1891 while (C != '/' && C != '\0')
1892 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 FoundSlash:
1895 if (C == '/') {
1896 if (CurPtr[-2] == '*') // We found the final */. We're done!
1897 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1900 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1901 // We found the final */, though it had an escaped newline between the
1902 // * and /. We're done!
1903 break;
1904 }
1905 }
1906 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1907 // If this is a /* inside of the comment, emit a warning. Don't do this
1908 // if this is a /*/, which will end the comment. This misses cases with
1909 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001910 if (!isLexingRawMode())
1911 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 }
1913 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001914 if (PP && PP->isCodeCompletionFile(FileLoc))
1915 PP->CodeCompleteNaturalLanguage();
1916 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001917 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 // Note: the user probably forgot a */. We could continue immediately
1919 // after the /*, but this would involve lexing a lot of what really is the
1920 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001921 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Chris Lattner31f0eca2008-10-12 04:19:49 +00001923 // KeepWhitespaceMode should return this broken comment as a token. Since
1924 // it isn't a well formed comment, just return it as an 'unknown' token.
1925 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001926 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001927 return true;
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Chris Lattner31f0eca2008-10-12 04:19:49 +00001930 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001931 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 }
1933 C = *CurPtr++;
1934 }
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Chris Lattner3d0ad582010-02-03 21:06:21 +00001936 // Notify comment handlers about the comment unless we're in a #if 0 block.
1937 if (PP && !isLexingRawMode() &&
1938 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1939 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001940 BufferPtr = CurPtr;
1941 return true; // A token has to be returned.
1942 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001945 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001946 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001947 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 }
1949
1950 // It is common for the tokens immediately after a /**/ comment to be
1951 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001952 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1953 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001955 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001957 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 }
1959
1960 // Otherwise, just return so that the next character will be lexed as a token.
1961 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001962 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001963 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001964}
1965
1966//===----------------------------------------------------------------------===//
1967// Primary Lexing Entry Points
1968//===----------------------------------------------------------------------===//
1969
Reid Spencer5f016e22007-07-11 17:01:13 +00001970/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1971/// uninterpreted string. This switches the lexer out of directive mode.
1972std::string Lexer::ReadToEndOfLine() {
1973 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1974 "Must be in a preprocessing directive!");
1975 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001976 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001977
1978 // CurPtr - Cache BufferPtr in an automatic variable.
1979 const char *CurPtr = BufferPtr;
1980 while (1) {
1981 char Char = getAndAdvanceChar(CurPtr, Tmp);
1982 switch (Char) {
1983 default:
1984 Result += Char;
1985 break;
1986 case 0: // Null.
1987 // Found end of file?
1988 if (CurPtr-1 != BufferEnd) {
1989 // Nope, normal character, continue.
1990 Result += Char;
1991 break;
1992 }
1993 // FALL THROUGH.
1994 case '\r':
1995 case '\n':
1996 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1997 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1998 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Peter Collingbourne84021552011-02-28 02:37:51 +00002000 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002002 if (Tmp.is(tok::code_completion)) {
2003 if (PP && PP->getCodeCompletionHandler())
2004 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
2005 Lex(Tmp);
2006 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002007 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // Finally, we're done, return the string we found.
2010 return Result;
2011 }
2012 }
2013}
2014
2015/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2016/// condition, reporting diagnostics and handling other edge cases as required.
2017/// This returns true if Result contains a token, false if PP.Lex should be
2018/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002019bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00002020 // Check if we are performing code completion.
2021 if (PP && PP->isCodeCompletionFile(FileLoc)) {
2022 // We're at the end of the file, but we've been asked to consider the
2023 // end of the file to be a code-completion token. Return the
2024 // code-completion token.
2025 Result.startToken();
2026 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2027
2028 // Only do the eof -> code_completion translation once.
2029 PP->SetCodeCompletionPoint(0, 0, 0);
2030
2031 // Silence any diagnostics that occur once we hit the code-completion point.
2032 PP->getDiagnostics().setSuppressAllDiagnostics(true);
2033 return true;
2034 }
2035
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 // If we hit the end of the file while parsing a preprocessor directive,
2037 // end the preprocessor directive first. The next token returned will
2038 // then be the end of file.
2039 if (ParsingPreprocessorDirective) {
2040 // Done parsing the "line".
2041 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002043 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002046 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002048 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002049
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 // If we are in raw mode, return this event as an EOF token. Let the caller
2051 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002052 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 Result.startToken();
2054 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002055 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 return true;
2057 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002058
Douglas Gregorf44e8542010-08-24 19:08:16 +00002059 // Issue diagnostics for unterminated #if and missing newline.
2060
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 // If we are in a #if directive, emit an error.
2062 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002063 if (!PP->isCodeCompletionFile(FileLoc))
2064 PP->Diag(ConditionalStack.back().IfLoc,
2065 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 ConditionalStack.pop_back();
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002069 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2070 // a pedwarn.
2071 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002072 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002073 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 BufferPtr = CurPtr;
2076
2077 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002078 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002079}
2080
2081/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2082/// the specified lexer will return a tok::l_paren token, 0 if it is something
2083/// else and 2 if there are no more tokens in the buffer controlled by the
2084/// lexer.
2085unsigned Lexer::isNextPPTokenLParen() {
2086 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 // Switch to 'skipping' mode. This will ensure that we can lex a token
2089 // without emitting diagnostics, disables macro expansion, and will cause EOF
2090 // to return an EOF token instead of popping the include stack.
2091 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 // Save state that can be changed while lexing so that we can restore it.
2094 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002095 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Chris Lattnerd2177732007-07-20 16:59:19 +00002097 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 Tok.startToken();
2099 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 // Restore state that may have changed.
2102 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002103 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // Restore the lexer back to non-skipping mode.
2106 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002108 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002110 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111}
2112
Chris Lattner34f349d2009-12-14 06:16:57 +00002113/// FindConflictEnd - Find the end of a version control conflict marker.
2114static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002115 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002116 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002117 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002118 // Must occur at start of line.
2119 if (RestOfBuffer[Pos-1] != '\r' &&
2120 RestOfBuffer[Pos-1] != '\n') {
2121 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002122 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002123 continue;
2124 }
2125 return RestOfBuffer.data()+Pos;
2126 }
2127 return 0;
2128}
2129
2130/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2131/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2132/// and recover nicely. This returns true if it is a conflict marker and false
2133/// if not.
2134bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2135 // Only a conflict marker if it starts at the beginning of a line.
2136 if (CurPtr != BufferStart &&
2137 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2138 return false;
2139
2140 // Check to see if we have <<<<<<<.
2141 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002142 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002143 return false;
2144
2145 // If we have a situation where we don't care about conflict markers, ignore
2146 // it.
2147 if (IsInConflictMarker || isLexingRawMode())
2148 return false;
2149
2150 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2151 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002152 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002153 // We found a match. We are really in a conflict marker.
2154 // Diagnose this, and ignore to the end of line.
2155 Diag(CurPtr, diag::err_conflict_marker);
2156 IsInConflictMarker = true;
2157
2158 // Skip ahead to the end of line. We know this exists because the
2159 // end-of-conflict marker starts with \r or \n.
2160 while (*CurPtr != '\r' && *CurPtr != '\n') {
2161 assert(CurPtr != BufferEnd && "Didn't find end of line");
2162 ++CurPtr;
2163 }
2164 BufferPtr = CurPtr;
2165 return true;
2166 }
2167
2168 // No end of conflict marker found.
2169 return false;
2170}
2171
2172
2173/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2174/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2175/// until the end of the line. This returns true if it is a conflict marker and
2176/// false if not.
2177bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2178 // Only a conflict marker if it starts at the beginning of a line.
2179 if (CurPtr != BufferStart &&
2180 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2181 return false;
2182
2183 // If we have a situation where we don't care about conflict markers, ignore
2184 // it.
2185 if (!IsInConflictMarker || isLexingRawMode())
2186 return false;
2187
2188 // Check to see if we have the marker (7 characters in a row).
2189 for (unsigned i = 1; i != 7; ++i)
2190 if (CurPtr[i] != CurPtr[0])
2191 return false;
2192
2193 // If we do have it, search for the end of the conflict marker. This could
2194 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2195 // be the end of conflict marker.
2196 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2197 CurPtr = End;
2198
2199 // Skip ahead to the end of line.
2200 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2201 ++CurPtr;
2202
2203 BufferPtr = CurPtr;
2204
2205 // No longer in the conflict marker.
2206 IsInConflictMarker = false;
2207 return true;
2208 }
2209
2210 return false;
2211}
2212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213
2214/// LexTokenInternal - This implements a simple C family lexer. It is an
2215/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002216/// has a null character at the end of the file. This returns a preprocessing
2217/// token, not a normal token, as such, it is an internal interface. It assumes
2218/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002219void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002220LexNextToken:
2221 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002222 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // CurPtr - Cache BufferPtr in an automatic variable.
2226 const char *CurPtr = BufferPtr;
2227
2228 // Small amounts of horizontal whitespace is very common between tokens.
2229 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2230 ++CurPtr;
2231 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2232 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Chris Lattnerd88dc482008-10-12 04:05:48 +00002234 // If we are keeping whitespace and other tokens, just return what we just
2235 // skipped. The next lexer invocation will return the token after the
2236 // whitespace.
2237 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002238 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002239 return;
2240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002243 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // Read a character, advancing over it.
2249 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002250 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 switch (Char) {
2253 case 0: // Null.
2254 // Found end of file?
2255 if (CurPtr-1 == BufferEnd) {
2256 // Read the PP instance variable into an automatic variable, because
2257 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002258 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2260 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002261 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2262 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chris Lattner74d15df2008-11-22 02:02:22 +00002265 if (!isLexingRawMode())
2266 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002267 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002268 if (SkipWhitespace(Result, CurPtr))
2269 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002272
2273 case 26: // DOS & CP/M EOF: "^Z".
2274 // If we're in Microsoft extensions mode, treat this as end of file.
2275 if (Features.Microsoft) {
2276 // Read the PP instance variable into an automatic variable, because
2277 // LexEndOfFile will often delete 'this'.
2278 Preprocessor *PPCache = PP;
2279 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2280 return; // Got a token to return.
2281 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2282 return PPCache->Lex(Result);
2283 }
2284 // If Microsoft extensions are disabled, this is just random garbage.
2285 Kind = tok::unknown;
2286 break;
2287
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 case '\n':
2289 case '\r':
2290 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002291 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 if (ParsingPreprocessorDirective) {
2293 // Done parsing the "line".
2294 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002297 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Reid Spencer5f016e22007-07-11 17:01:13 +00002299 // Since we consumed a newline, we are back at the start of a line.
2300 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Peter Collingbourne84021552011-02-28 02:37:51 +00002302 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 break;
2304 }
2305 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002306 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002308 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Chris Lattnerd88dc482008-10-12 04:05:48 +00002310 if (SkipWhitespace(Result, CurPtr))
2311 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 goto LexNextToken; // GCC isn't tail call eliminating.
2313 case ' ':
2314 case '\t':
2315 case '\f':
2316 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002317 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002318 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002319 if (SkipWhitespace(Result, CurPtr))
2320 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002321
2322 SkipIgnoredUnits:
2323 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Chris Lattner8133cfc2007-07-22 06:29:05 +00002325 // If the next token is obviously a // or /* */ comment, skip it efficiently
2326 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002327 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002328 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002329 if (SkipBCPLComment(Result, CurPtr+2))
2330 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002331 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002332 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002333 if (SkipBlockComment(Result, CurPtr+2))
2334 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002335 goto SkipIgnoredUnits;
2336 } else if (isHorizontalWhitespace(*CurPtr)) {
2337 goto SkipHorizontalWhitespace;
2338 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002340
Chris Lattner3a570772008-01-03 17:58:54 +00002341 // C99 6.4.4.1: Integer Constants.
2342 // C99 6.4.4.2: Floating Constants.
2343 case '0': case '1': case '2': case '3': case '4':
2344 case '5': case '6': case '7': case '8': case '9':
2345 // Notify MIOpt that we read a non-whitespace/non-comment token.
2346 MIOpt.ReadToken();
2347 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Douglas Gregor5cee1192011-07-27 05:40:30 +00002349 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2350 // Notify MIOpt that we read a non-whitespace/non-comment token.
2351 MIOpt.ReadToken();
2352
2353 if (Features.CPlusPlus0x) {
2354 Char = getCharAndSize(CurPtr, SizeTmp);
2355
2356 // UTF-16 string literal
2357 if (Char == '"')
2358 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2359 tok::utf16_string_literal);
2360
2361 // UTF-16 character constant
2362 if (Char == '\'')
2363 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2364 tok::utf16_char_constant);
2365
Craig Topper2fa4e862011-08-11 04:06:15 +00002366 // UTF-16 raw string literal
2367 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2368 return LexRawStringLiteral(Result,
2369 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2370 SizeTmp2, Result),
2371 tok::utf16_string_literal);
2372
2373 if (Char == '8') {
2374 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2375
2376 // UTF-8 string literal
2377 if (Char2 == '"')
2378 return LexStringLiteral(Result,
2379 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2380 SizeTmp2, Result),
2381 tok::utf8_string_literal);
2382
2383 if (Char2 == 'R') {
2384 unsigned SizeTmp3;
2385 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2386 // UTF-8 raw string literal
2387 if (Char3 == '"') {
2388 return LexRawStringLiteral(Result,
2389 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2390 SizeTmp2, Result),
2391 SizeTmp3, Result),
2392 tok::utf8_string_literal);
2393 }
2394 }
2395 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002396 }
2397
2398 // treat u like the start of an identifier.
2399 return LexIdentifier(Result, CurPtr);
2400
2401 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2402 // Notify MIOpt that we read a non-whitespace/non-comment token.
2403 MIOpt.ReadToken();
2404
2405 if (Features.CPlusPlus0x) {
2406 Char = getCharAndSize(CurPtr, SizeTmp);
2407
2408 // UTF-32 string literal
2409 if (Char == '"')
2410 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2411 tok::utf32_string_literal);
2412
2413 // UTF-32 character constant
2414 if (Char == '\'')
2415 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2416 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002417
2418 // UTF-32 raw string literal
2419 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2420 return LexRawStringLiteral(Result,
2421 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2422 SizeTmp2, Result),
2423 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002424 }
2425
2426 // treat U like the start of an identifier.
2427 return LexIdentifier(Result, CurPtr);
2428
Craig Topper2fa4e862011-08-11 04:06:15 +00002429 case 'R': // Identifier or C++0x raw string literal
2430 // Notify MIOpt that we read a non-whitespace/non-comment token.
2431 MIOpt.ReadToken();
2432
2433 if (Features.CPlusPlus0x) {
2434 Char = getCharAndSize(CurPtr, SizeTmp);
2435
2436 if (Char == '"')
2437 return LexRawStringLiteral(Result,
2438 ConsumeChar(CurPtr, SizeTmp, Result),
2439 tok::string_literal);
2440 }
2441
2442 // treat R like the start of an identifier.
2443 return LexIdentifier(Result, CurPtr);
2444
Chris Lattner3a570772008-01-03 17:58:54 +00002445 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 // Notify MIOpt that we read a non-whitespace/non-comment token.
2447 MIOpt.ReadToken();
2448 Char = getCharAndSize(CurPtr, SizeTmp);
2449
2450 // Wide string literal.
2451 if (Char == '"')
2452 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002453 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002454
Craig Topper2fa4e862011-08-11 04:06:15 +00002455 // Wide raw string literal.
2456 if (Features.CPlusPlus0x && Char == 'R' &&
2457 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2458 return LexRawStringLiteral(Result,
2459 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2460 SizeTmp2, Result),
2461 tok::wide_string_literal);
2462
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 // Wide character constant.
2464 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002465 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2466 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002467 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 // C99 6.4.2: Identifiers.
2470 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2471 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002472 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002473 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2474 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2475 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002476 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 case 'v': case 'w': case 'x': case 'y': case 'z':
2478 case '_':
2479 // Notify MIOpt that we read a non-whitespace/non-comment token.
2480 MIOpt.ReadToken();
2481 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002482
2483 case '$': // $ in identifiers.
2484 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002485 if (!isLexingRawMode())
2486 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002487 // Notify MIOpt that we read a non-whitespace/non-comment token.
2488 MIOpt.ReadToken();
2489 return LexIdentifier(Result, CurPtr);
2490 }
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Chris Lattner9e6293d2008-10-12 04:51:35 +00002492 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002493 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 // C99 6.4.4: Character Constants.
2496 case '\'':
2497 // Notify MIOpt that we read a non-whitespace/non-comment token.
2498 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002499 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002500
2501 // C99 6.4.5: String Literals.
2502 case '"':
2503 // Notify MIOpt that we read a non-whitespace/non-comment token.
2504 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002505 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002506
2507 // C99 6.4.6: Punctuators.
2508 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002509 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 break;
2511 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002512 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002513 break;
2514 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002515 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 break;
2517 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002518 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 break;
2520 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002521 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002522 break;
2523 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002524 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 break;
2526 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002527 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 break;
2529 case '.':
2530 Char = getCharAndSize(CurPtr, SizeTmp);
2531 if (Char >= '0' && Char <= '9') {
2532 // Notify MIOpt that we read a non-whitespace/non-comment token.
2533 MIOpt.ReadToken();
2534
2535 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2536 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002537 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002538 CurPtr += SizeTmp;
2539 } else if (Char == '.' &&
2540 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002541 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2543 SizeTmp2, Result);
2544 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002545 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 }
2547 break;
2548 case '&':
2549 Char = getCharAndSize(CurPtr, SizeTmp);
2550 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002551 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2553 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002554 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2556 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002557 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002558 }
2559 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002560 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002562 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2564 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002565 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 }
2567 break;
2568 case '+':
2569 Char = getCharAndSize(CurPtr, SizeTmp);
2570 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002572 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002575 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002577 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 }
2579 break;
2580 case '-':
2581 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002582 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002584 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002586 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2588 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002589 Kind = tok::arrowstar;
2590 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002592 Kind = tok::arrow;
2593 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002595 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002597 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 }
2599 break;
2600 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002601 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 break;
2603 case '!':
2604 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002605 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2607 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002608 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002609 }
2610 break;
2611 case '/':
2612 // 6.4.9: Comments
2613 Char = getCharAndSize(CurPtr, SizeTmp);
2614 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002615 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2616 // want to lex this as a comment. There is one problem with this though,
2617 // that in one particular corner case, this can change the behavior of the
2618 // resultant program. For example, In "foo //**/ bar", C89 would lex
2619 // this as "foo / bar" and langauges with BCPL comments would lex it as
2620 // "foo". Check to see if the character after the second slash is a '*'.
2621 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002622 // However, we never do this in -traditional-cpp mode.
2623 if ((Features.BCPLComment ||
2624 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2625 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002626 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002627 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Chris Lattner8402c732009-01-16 22:39:25 +00002629 // It is common for the tokens immediately after a // comment to be
2630 // whitespace (indentation for the next line). Instead of going through
2631 // the big switch, handle it efficiently now.
2632 goto SkipIgnoredUnits;
2633 }
2634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Chris Lattner8402c732009-01-16 22:39:25 +00002636 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002638 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002639 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002640 }
Mike Stump1eb44332009-09-09 15:08:12 +00002641
Chris Lattner8402c732009-01-16 22:39:25 +00002642 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002644 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002646 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 }
2648 break;
2649 case '%':
2650 Char = getCharAndSize(CurPtr, SizeTmp);
2651 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002652 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2654 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002655 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2657 } else if (Features.Digraphs && Char == ':') {
2658 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2659 Char = getCharAndSize(CurPtr, SizeTmp);
2660 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002661 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2663 SizeTmp2, Result);
2664 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002666 if (!isLexingRawMode())
2667 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002668 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002669 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 // We parsed a # character. If this occurs at the start of the line,
2671 // it's actually the start of a preprocessing directive. Callback to
2672 // the preprocessor to handle it.
2673 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002674 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002675 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002676 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002677
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 // As an optimization, if the preprocessor didn't switch lexers, tail
2679 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002680 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 // Start a new token. If this is a #include or something, the PP may
2682 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002683 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002685 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002686 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 IsAtStartOfLine = false;
2688 }
2689 goto LexNextToken; // GCC isn't tail call eliminating.
2690 }
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Chris Lattner168ae2d2007-10-17 20:41:00 +00002692 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 }
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Chris Lattnere91e9322009-03-18 20:58:27 +00002695 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 }
2697 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002698 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
2700 break;
2701 case '<':
2702 Char = getCharAndSize(CurPtr, SizeTmp);
2703 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002704 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002706 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2707 if (After == '=') {
2708 Kind = tok::lesslessequal;
2709 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2710 SizeTmp2, Result);
2711 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2712 // If this is actually a '<<<<<<<' version control conflict marker,
2713 // recognize it as such and recover nicely.
2714 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002715 } else if (Features.CUDA && After == '<') {
2716 Kind = tok::lesslessless;
2717 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2718 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002719 } else {
2720 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2721 Kind = tok::lessless;
2722 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002725 Kind = tok::lessequal;
2726 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002727 if (Features.CPlusPlus0x &&
2728 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2729 // C++0x [lex.pptoken]p3:
2730 // Otherwise, if the next three characters are <:: and the subsequent
2731 // character is neither : nor >, the < is treated as a preprocessor
2732 // token by itself and not as the first character of the alternative
2733 // token <:.
2734 unsigned SizeTmp3;
2735 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2736 if (After != ':' && After != '>') {
2737 Kind = tok::less;
2738 break;
2739 }
2740 }
2741
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002743 Kind = tok::l_square;
2744 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002746 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002748 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 }
2750 break;
2751 case '>':
2752 Char = getCharAndSize(CurPtr, SizeTmp);
2753 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002755 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002756 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002757 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2758 if (After == '=') {
2759 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2760 SizeTmp2, Result);
2761 Kind = tok::greatergreaterequal;
2762 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2763 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2764 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002765 } else if (Features.CUDA && After == '>') {
2766 Kind = tok::greatergreatergreater;
2767 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2768 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002769 } else {
2770 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2771 Kind = tok::greatergreater;
2772 }
2773
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002775 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 }
2777 break;
2778 case '^':
2779 Char = getCharAndSize(CurPtr, SizeTmp);
2780 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002782 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002784 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 }
2786 break;
2787 case '|':
2788 Char = getCharAndSize(CurPtr, SizeTmp);
2789 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002790 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2792 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002793 // If this is '|||||||' and we're in a conflict marker, ignore it.
2794 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2795 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002796 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2798 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002799 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 }
2801 break;
2802 case ':':
2803 Char = getCharAndSize(CurPtr, SizeTmp);
2804 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002805 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2807 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002808 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002810 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002811 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 }
2813 break;
2814 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002815 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 break;
2817 case '=':
2818 Char = getCharAndSize(CurPtr, SizeTmp);
2819 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002820 // If this is '=======' and we're in a conflict marker, ignore it.
2821 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2822 goto LexNextToken;
2823
Chris Lattner9e6293d2008-10-12 04:51:35 +00002824 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002826 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002827 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002828 }
2829 break;
2830 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002831 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 break;
2833 case '#':
2834 Char = getCharAndSize(CurPtr, SizeTmp);
2835 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002836 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2838 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002839 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002840 if (!isLexingRawMode())
2841 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2843 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002844 // We parsed a # character. If this occurs at the start of the line,
2845 // it's actually the start of a preprocessing directive. Callback to
2846 // the preprocessor to handle it.
2847 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002848 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002849 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002850 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 // As an optimization, if the preprocessor didn't switch lexers, tail
2853 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002854 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 // Start a new token. If this is a #include or something, the PP may
2856 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002857 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002859 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002860 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002861 IsAtStartOfLine = false;
2862 }
2863 goto LexNextToken; // GCC isn't tail call eliminating.
2864 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002865 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 }
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Chris Lattnere91e9322009-03-18 20:58:27 +00002868 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 }
2870 break;
2871
Chris Lattner3a570772008-01-03 17:58:54 +00002872 case '@':
2873 // Objective C support.
2874 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002875 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002876 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002877 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002878 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 case '\\':
2881 // FIXME: UCN's.
2882 // FALL THROUGH.
2883 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002884 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 break;
2886 }
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 // Notify MIOpt that we read a non-whitespace/non-comment token.
2889 MIOpt.ReadToken();
2890
2891 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002892 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002893}