blob: 4de6ce7ad5cf775accaae699e68de180d6bf9e3e [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;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000522
523 unsigned MaxLineOffset = 0;
524 if (MaxLines) {
525 const char *CurPtr = Buffer->getBufferStart();
526 unsigned CurLine = 0;
527 while (CurPtr != Buffer->getBufferEnd()) {
528 char ch = *CurPtr++;
529 if (ch == '\n') {
530 ++CurLine;
531 if (CurLine == MaxLines)
532 break;
533 }
534 }
535 if (CurPtr != Buffer->getBufferEnd())
536 MaxLineOffset = CurPtr - Buffer->getBufferStart();
537 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000538
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000539 do {
540 TheLexer.LexFromRawLexer(TheTok);
541
542 if (InPreprocessorDirective) {
543 // If we've hit the end of the file, we're done.
544 if (TheTok.getKind() == tok::eof) {
545 InPreprocessorDirective = false;
546 break;
547 }
548
549 // If we haven't hit the end of the preprocessor directive, skip this
550 // token.
551 if (!TheTok.isAtStartOfLine())
552 continue;
553
554 // We've passed the end of the preprocessor directive, and will look
555 // at this token again below.
556 InPreprocessorDirective = false;
557 }
558
Douglas Gregordf95a132010-08-09 20:45:32 +0000559 // Keep track of the # of lines in the preamble.
560 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000561 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000562
563 // If we were asked to limit the number of lines in the preamble,
564 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000565 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000566 break;
567 }
568
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000569 // Comments are okay; skip over them.
570 if (TheTok.getKind() == tok::comment)
571 continue;
572
573 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
574 // This is the start of a preprocessor directive.
575 Token HashTok = TheTok;
576 InPreprocessorDirective = true;
577
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000578 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000579 // we don't have an identifier table available. Instead, just look at
580 // the raw identifier to recognize and categorize preprocessor directives.
581 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000582 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000584 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000585 PreambleDirectiveKind PDK
586 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
587 .Case("include", PDK_Skipped)
588 .Case("__include_macros", PDK_Skipped)
589 .Case("define", PDK_Skipped)
590 .Case("undef", PDK_Skipped)
591 .Case("line", PDK_Skipped)
592 .Case("error", PDK_Skipped)
593 .Case("pragma", PDK_Skipped)
594 .Case("import", PDK_Skipped)
595 .Case("include_next", PDK_Skipped)
596 .Case("warning", PDK_Skipped)
597 .Case("ident", PDK_Skipped)
598 .Case("sccs", PDK_Skipped)
599 .Case("assert", PDK_Skipped)
600 .Case("unassert", PDK_Skipped)
601 .Case("if", PDK_StartIf)
602 .Case("ifdef", PDK_StartIf)
603 .Case("ifndef", PDK_StartIf)
604 .Case("elif", PDK_Skipped)
605 .Case("else", PDK_Skipped)
606 .Case("endif", PDK_EndIf)
607 .Default(PDK_Unknown);
608
609 switch (PDK) {
610 case PDK_Skipped:
611 continue;
612
613 case PDK_StartIf:
614 if (IfCount == 0)
615 IfStartTok = HashTok;
616
617 ++IfCount;
618 continue;
619
620 case PDK_EndIf:
621 // Mismatched #endif. The preamble ends here.
622 if (IfCount == 0)
623 break;
624
625 --IfCount;
626 continue;
627
628 case PDK_Unknown:
629 // We don't know what this directive is; stop at the '#'.
630 break;
631 }
632 }
633
634 // We only end up here if we didn't recognize the preprocessor
635 // directive or it was one that can't occur in the preamble at this
636 // point. Roll back the current token to the location of the '#'.
637 InPreprocessorDirective = false;
638 TheTok = HashTok;
639 }
640
Douglas Gregordf95a132010-08-09 20:45:32 +0000641 // We hit a token that we don't recognize as being in the
642 // "preprocessing only" part of the file, so we're no longer in
643 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000644 break;
645 } while (true);
646
647 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000648 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
649 IfCount? IfStartTok.isAtStartOfLine()
650 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000651}
652
Chris Lattner7ef5c272010-11-17 07:05:50 +0000653
654/// AdvanceToTokenCharacter - Given a location that specifies the start of a
655/// token, return a new location that specifies a character within the token.
656SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
657 unsigned CharNo,
658 const SourceManager &SM,
659 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000660 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000661 // character is. This needs to take into consideration newlines and
662 // trigraphs.
663 bool Invalid = false;
664 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
665
666 // If they request the first char of the token, we're trivially done.
667 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
668 return TokStart;
669
670 unsigned PhysOffset = 0;
671
672 // The usual case is that tokens don't contain anything interesting. Skip
673 // over the uninteresting characters. If a token only consists of simple
674 // chars, this method is extremely fast.
675 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
676 if (CharNo == 0)
677 return TokStart.getFileLocWithOffset(PhysOffset);
678 ++TokPtr, --CharNo, ++PhysOffset;
679 }
680
681 // If we have a character that may be a trigraph or escaped newline, use a
682 // lexer to parse it correctly.
683 for (; CharNo; --CharNo) {
684 unsigned Size;
685 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
686 TokPtr += Size;
687 PhysOffset += Size;
688 }
689
690 // Final detail: if we end up on an escaped newline, we want to return the
691 // location of the actual byte of the token. For example foo\<newline>bar
692 // advanced by 3 should return the location of b, not of \\. One compounding
693 // detail of this is that the escape may be made by a trigraph.
694 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
695 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
696
697 return TokStart.getFileLocWithOffset(PhysOffset);
698}
699
700/// \brief Computes the source location just past the end of the
701/// token at this source location.
702///
703/// This routine can be used to produce a source location that
704/// points just past the end of the token referenced by \p Loc, and
705/// is generally used when a diagnostic needs to point just after a
706/// token where it expected something different that it received. If
707/// the returned source location would not be meaningful (e.g., if
708/// it points into a macro), this routine returns an invalid
709/// source location.
710///
711/// \param Offset an offset from the end of the token, where the source
712/// location should refer to. The default offset (0) produces a source
713/// location pointing just past the end of the token; an offset of 1 produces
714/// a source location pointing to the last character in the token, etc.
715SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
716 const SourceManager &SM,
717 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000718 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000719 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000720
721 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000722 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
723 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000724
Chandler Carruth433db062011-07-14 08:20:40 +0000725 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000726 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000727 }
728
Chris Lattner7ef5c272010-11-17 07:05:50 +0000729 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
730 if (Len > Offset)
731 Len = Len - Offset;
732 else
733 return Loc;
734
John McCall77ebb382011-04-06 01:50:22 +0000735 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000736}
737
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000738/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000739/// token of the macro expansion.
740bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000741 const SourceManager &SM,
742 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000743 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
744
745 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
746 // FIXME: If the token comes from the macro token paste operator ('##')
747 // this function will always return false;
748 if (infoLoc.second > 0)
749 return false; // Does not point at the start of token.
750
Chandler Carruth433db062011-07-14 08:20:40 +0000751 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000752 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000753 if (expansionLoc.isFileID())
754 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000755
Chandler Carruth433db062011-07-14 08:20:40 +0000756 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000757}
758
759/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000760/// token of the macro expansion.
761bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000762 const SourceManager &SM,
763 const LangOptions &LangOpts) {
764 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
765
766 SourceLocation spellLoc = SM.getSpellingLoc(loc);
767 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
768 if (tokLen == 0)
769 return false;
770
771 FileID FID = SM.getFileID(loc);
772 SourceLocation afterLoc = loc.getFileLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000773 if (SM.isInFileID(afterLoc, FID))
774 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000775
776 // FIXME: If the token comes from the macro token paste operator ('##')
777 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000778
Chandler Carruth433db062011-07-14 08:20:40 +0000779 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000780 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000781 if (expansionLoc.isFileID())
782 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000783
Chandler Carruth433db062011-07-14 08:20:40 +0000784 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000785}
786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787//===----------------------------------------------------------------------===//
788// Character information.
789//===----------------------------------------------------------------------===//
790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791enum {
792 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
793 CHAR_VERT_WS = 0x02, // '\r', '\n'
794 CHAR_LETTER = 0x04, // a-z,A-Z
795 CHAR_NUMBER = 0x08, // 0-9
796 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000797 CHAR_PERIOD = 0x20, // .
798 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000799};
800
Chris Lattner03b98662009-07-07 17:09:54 +0000801// Statically initialize CharInfo table based on ASCII character set
802// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000803static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000804{
805// 0 NUL 1 SOH 2 STX 3 ETX
806// 4 EOT 5 ENQ 6 ACK 7 BEL
807 0 , 0 , 0 , 0 ,
808 0 , 0 , 0 , 0 ,
809// 8 BS 9 HT 10 NL 11 VT
810//12 NP 13 CR 14 SO 15 SI
811 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
812 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
813//16 DLE 17 DC1 18 DC2 19 DC3
814//20 DC4 21 NAK 22 SYN 23 ETB
815 0 , 0 , 0 , 0 ,
816 0 , 0 , 0 , 0 ,
817//24 CAN 25 EM 26 SUB 27 ESC
818//28 FS 29 GS 30 RS 31 US
819 0 , 0 , 0 , 0 ,
820 0 , 0 , 0 , 0 ,
821//32 SP 33 ! 34 " 35 #
822//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000823 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
824 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000825//40 ( 41 ) 42 * 43 +
826//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000827 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
828 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000829//48 0 49 1 50 2 51 3
830//52 4 53 5 54 6 55 7
831 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
832 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
833//56 8 57 9 58 : 59 ;
834//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000835 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
836 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000837//64 @ 65 A 66 B 67 C
838//68 D 69 E 70 F 71 G
839 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
840 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
841//72 H 73 I 74 J 75 K
842//76 L 77 M 78 N 79 O
843 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
844 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
845//80 P 81 Q 82 R 83 S
846//84 T 85 U 86 V 87 W
847 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
848 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
849//88 X 89 Y 90 Z 91 [
850//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000851 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
852 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000853//96 ` 97 a 98 b 99 c
854//100 d 101 e 102 f 103 g
855 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
856 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
857//104 h 105 i 106 j 107 k
858//108 l 109 m 110 n 111 o
859 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
860 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
861//112 p 113 q 114 r 115 s
862//116 t 117 u 118 v 119 w
863 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
864 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
865//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000866//124 | 125 } 126 ~ 127 DEL
867 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
868 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000869};
870
Chris Lattnera2bf1052009-12-17 05:29:40 +0000871static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 static bool isInited = false;
873 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000874 // check the statically-initialized CharInfo table
875 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
876 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
877 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
878 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
879 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
880 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
881 assert(CHAR_UNDER == CharInfo[(int)'_']);
882 assert(CHAR_PERIOD == CharInfo[(int)'.']);
883 for (unsigned i = 'a'; i <= 'z'; ++i) {
884 assert(CHAR_LETTER == CharInfo[i]);
885 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
886 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000887 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000888 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000889
Chris Lattner03b98662009-07-07 17:09:54 +0000890 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
892
Chris Lattner03b98662009-07-07 17:09:54 +0000893
Reid Spencer5f016e22007-07-11 17:01:13 +0000894/// isIdentifierBody - Return true if this is the body character of an
895/// identifier, which is [a-zA-Z0-9_].
896static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000897 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000898}
899
900/// isHorizontalWhitespace - Return true if this character is horizontal
901/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
902static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000903 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000904}
905
Anna Zaksaca25bc2011-07-27 21:43:43 +0000906/// isVerticalWhitespace - Return true if this character is vertical
907/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
908static inline bool isVerticalWhitespace(unsigned char c) {
909 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
910}
911
Reid Spencer5f016e22007-07-11 17:01:13 +0000912/// isWhitespace - Return true if this character is horizontal or vertical
913/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
914/// for '\0'.
915static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000916 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000917}
918
919/// isNumberBody - Return true if this is the body character of an
920/// preprocessing number, which is [a-zA-Z0-9_.].
921static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000922 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000923 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000924}
925
Craig Topper2fa4e862011-08-11 04:06:15 +0000926/// isRawStringDelimBody - Return true if this is the body character of a
927/// raw string delimiter.
928static inline bool isRawStringDelimBody(unsigned char c) {
929 return (CharInfo[c] &
930 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
931 true : false;
932}
933
Reid Spencer5f016e22007-07-11 17:01:13 +0000934
935//===----------------------------------------------------------------------===//
936// Diagnostics forwarding code.
937//===----------------------------------------------------------------------===//
938
Chris Lattner409a0362007-07-22 18:38:25 +0000939/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000940/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000941/// This is currently only used for _Pragma implementation, so it is the slow
942/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000943static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
944 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000945static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
946 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000947 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000948 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chris Lattner409a0362007-07-22 18:38:25 +0000950 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000951 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000952 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000953 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chandler Carruth433db062011-07-14 08:20:40 +0000955 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000956 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000957 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000958 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattnere7fb4842009-02-15 20:52:18 +0000960 // Figure out the expansion loc range, which is the range covered by the
961 // original _Pragma(...) sequence.
962 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000963 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chandler Carruthbf340e42011-07-26 03:03:05 +0000965 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000966}
967
Reid Spencer5f016e22007-07-11 17:01:13 +0000968/// getSourceLocation - Return a source location identifier for the specified
969/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000970SourceLocation Lexer::getSourceLocation(const char *Loc,
971 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000972 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000974
975 // In the normal case, we're just lexing from a simple file buffer, return
976 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000977 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000978 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000979 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner2b2453a2009-01-17 06:22:33 +0000981 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
982 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000983 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000984 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000985}
986
Reid Spencer5f016e22007-07-11 17:01:13 +0000987/// Diag - Forwarding function for diagnostics. This translate a source
988/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000989DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000990 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000991}
Reid Spencer5f016e22007-07-11 17:01:13 +0000992
993//===----------------------------------------------------------------------===//
994// Trigraph and Escaped Newline Handling Code.
995//===----------------------------------------------------------------------===//
996
997/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
998/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
999static char GetTrigraphCharForLetter(char Letter) {
1000 switch (Letter) {
1001 default: return 0;
1002 case '=': return '#';
1003 case ')': return ']';
1004 case '(': return '[';
1005 case '!': return '|';
1006 case '\'': return '^';
1007 case '>': return '}';
1008 case '/': return '\\';
1009 case '<': return '{';
1010 case '-': return '~';
1011 }
1012}
1013
1014/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1015/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1016/// return the result character. Finally, emit a warning about trigraph use
1017/// whether trigraphs are enabled or not.
1018static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1019 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001020 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Chris Lattner3692b092008-11-18 07:59:24 +00001022 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001023 if (!L->isLexingRawMode())
1024 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001025 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner74d15df2008-11-22 02:02:22 +00001028 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001029 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 return Res;
1031}
1032
Chris Lattner24f0e482009-04-18 22:05:41 +00001033/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1034/// 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 +00001035/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001036unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1037 unsigned Size = 0;
1038 while (isWhitespace(Ptr[Size])) {
1039 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattner24f0e482009-04-18 22:05:41 +00001041 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1042 continue;
1043
1044 // If this is a \r\n or \n\r, skip the other half.
1045 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1046 Ptr[Size-1] != Ptr[Size])
1047 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattner24f0e482009-04-18 22:05:41 +00001049 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001050 }
1051
Chris Lattner24f0e482009-04-18 22:05:41 +00001052 // Not an escaped newline, must be a \t or something else.
1053 return 0;
1054}
1055
Chris Lattner03374952009-04-18 22:27:02 +00001056/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1057/// them), skip over them and return the first non-escaped-newline found,
1058/// otherwise return P.
1059const char *Lexer::SkipEscapedNewLines(const char *P) {
1060 while (1) {
1061 const char *AfterEscape;
1062 if (*P == '\\') {
1063 AfterEscape = P+1;
1064 } else if (*P == '?') {
1065 // If not a trigraph for escape, bail out.
1066 if (P[1] != '?' || P[2] != '/')
1067 return P;
1068 AfterEscape = P+3;
1069 } else {
1070 return P;
1071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Chris Lattner03374952009-04-18 22:27:02 +00001073 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1074 if (NewLineSize == 0) return P;
1075 P = AfterEscape+NewLineSize;
1076 }
1077}
1078
Anna Zaksaca25bc2011-07-27 21:43:43 +00001079/// \brief Checks that the given token is the first token that occurs after the
1080/// given location (this excludes comments and whitespace). Returns the location
1081/// immediately after the specified token. If the token is not found or the
1082/// location is inside a macro, the returned source location will be invalid.
1083SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1084 tok::TokenKind TKind,
1085 const SourceManager &SM,
1086 const LangOptions &LangOpts,
1087 bool SkipTrailingWhitespaceAndNewLine) {
1088 if (Loc.isMacroID()) {
1089 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1090 return SourceLocation();
1091 Loc = SM.getExpansionRange(Loc).second;
1092 }
1093 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1094
1095 // Break down the source location.
1096 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1097
1098 // Try to load the file buffer.
1099 bool InvalidTemp = false;
1100 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1101 if (InvalidTemp)
1102 return SourceLocation();
1103
1104 const char *TokenBegin = File.data() + LocInfo.second;
1105
1106 // Lex from the start of the given location.
1107 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1108 TokenBegin, File.end());
1109 // Find the token.
1110 Token Tok;
1111 lexer.LexFromRawLexer(Tok);
1112 if (Tok.isNot(TKind))
1113 return SourceLocation();
1114 SourceLocation TokenLoc = Tok.getLocation();
1115
1116 // Calculate how much whitespace needs to be skipped if any.
1117 unsigned NumWhitespaceChars = 0;
1118 if (SkipTrailingWhitespaceAndNewLine) {
1119 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1120 Tok.getLength();
1121 unsigned char C = *TokenEnd;
1122 while (isHorizontalWhitespace(C)) {
1123 C = *(++TokenEnd);
1124 NumWhitespaceChars++;
1125 }
1126 if (isVerticalWhitespace(C))
1127 NumWhitespaceChars++;
1128 }
1129
1130 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1131}
Chris Lattner24f0e482009-04-18 22:05:41 +00001132
Reid Spencer5f016e22007-07-11 17:01:13 +00001133/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1134/// get its size, and return it. This is tricky in several cases:
1135/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1136/// then either return the trigraph (skipping 3 chars) or the '?',
1137/// depending on whether trigraphs are enabled or not.
1138/// 2. If this is an escaped newline (potentially with whitespace between
1139/// the backslash and newline), implicitly skip the newline and return
1140/// the char after it.
1141/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1142///
1143/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1144/// know that we can accumulate into Size, and that we have already incremented
1145/// Ptr by Size bytes.
1146///
1147/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1148/// be updated to match.
1149///
1150char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001151 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 // If we have a slash, look for an escaped newline.
1153 if (Ptr[0] == '\\') {
1154 ++Size;
1155 ++Ptr;
1156Slash:
1157 // Common case, backslash-char where the char is not whitespace.
1158 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Chris Lattner5636a3b2009-06-23 05:15:06 +00001160 // See if we have optional whitespace characters between the slash and
1161 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001162 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1163 // Remember that this token needs to be cleaned.
1164 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001165
Chris Lattner24f0e482009-04-18 22:05:41 +00001166 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001167 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001168 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattner24f0e482009-04-18 22:05:41 +00001170 // Found backslash<whitespace><newline>. Parse the char after it.
1171 Size += EscapedNewLineSize;
1172 Ptr += EscapedNewLineSize;
1173 // Use slow version to accumulate a correct size field.
1174 return getCharAndSizeSlow(Ptr, Size, Tok);
1175 }
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 // Otherwise, this is not an escaped newline, just return the slash.
1178 return '\\';
1179 }
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // If this is a trigraph, process it.
1182 if (Ptr[0] == '?' && Ptr[1] == '?') {
1183 // If this is actually a legal trigraph (not something like "??x"), emit
1184 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1185 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1186 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001187 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001188
1189 Ptr += 3;
1190 Size += 3;
1191 if (C == '\\') goto Slash;
1192 return C;
1193 }
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 // If this is neither, return a single character.
1197 ++Size;
1198 return *Ptr;
1199}
1200
1201
1202/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1203/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1204/// and that we have already incremented Ptr by Size bytes.
1205///
1206/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1207/// be updated to match.
1208char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1209 const LangOptions &Features) {
1210 // If we have a slash, look for an escaped newline.
1211 if (Ptr[0] == '\\') {
1212 ++Size;
1213 ++Ptr;
1214Slash:
1215 // Common case, backslash-char where the char is not whitespace.
1216 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001219 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1220 // Found backslash<whitespace><newline>. Parse the char after it.
1221 Size += EscapedNewLineSize;
1222 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner24f0e482009-04-18 22:05:41 +00001224 // Use slow version to accumulate a correct size field.
1225 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 // Otherwise, this is not an escaped newline, just return the slash.
1229 return '\\';
1230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 // If this is a trigraph, process it.
1233 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1234 // If this is actually a legal trigraph (not something like "??x"), return
1235 // it.
1236 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1237 Ptr += 3;
1238 Size += 3;
1239 if (C == '\\') goto Slash;
1240 return C;
1241 }
1242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 // If this is neither, return a single character.
1245 ++Size;
1246 return *Ptr;
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// Helper methods for lexing.
1251//===----------------------------------------------------------------------===//
1252
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001253/// \brief Routine that indiscriminately skips bytes in the source file.
1254void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1255 BufferPtr += Bytes;
1256 if (BufferPtr > BufferEnd)
1257 BufferPtr = BufferEnd;
1258 IsAtStartOfLine = StartOfLine;
1259}
1260
Chris Lattnerd2177732007-07-20 16:59:19 +00001261void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1263 unsigned Size;
1264 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001265 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001267
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 --CurPtr; // Back up over the skipped character.
1269
1270 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1271 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1272 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001273 //
1274 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1275 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1277FinishIdentifier:
1278 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001279 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1280 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // If we are in raw mode, return this identifier raw. There is no need to
1283 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001284 if (LexingRawMode)
1285 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001287 // Fill in Result.IdentifierInfo and update the token kind,
1288 // looking up the identifier in the identifier table.
1289 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Finally, now that we know we have an identifier, pass this off to the
1292 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001293 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001294 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001295
Chris Lattner6a170eb2009-01-21 07:43:11 +00001296 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 C = getCharAndSize(CurPtr, Size);
1302 while (1) {
1303 if (C == '$') {
1304 // If we hit a $ and they are not supported in identifiers, we are done.
1305 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001308 if (!isLexingRawMode())
1309 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 CurPtr = ConsumeChar(CurPtr, Size, Result);
1311 C = getCharAndSize(CurPtr, Size);
1312 continue;
1313 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1314 // Found end of identifier.
1315 goto FinishIdentifier;
1316 }
1317
1318 // Otherwise, this character is good, consume it.
1319 CurPtr = ConsumeChar(CurPtr, Size, Result);
1320
1321 C = getCharAndSize(CurPtr, Size);
1322 while (isIdentifierBody(C)) { // FIXME: UCNs.
1323 CurPtr = ConsumeChar(CurPtr, Size, Result);
1324 C = getCharAndSize(CurPtr, Size);
1325 }
1326 }
1327}
1328
Douglas Gregora75ec432010-08-30 14:50:47 +00001329/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001330/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001331static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1332 unsigned Size;
1333 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1334 if (C1 != '0')
1335 return false;
1336 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1337 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001338}
Reid Spencer5f016e22007-07-11 17:01:13 +00001339
Nate Begeman5253c7f2008-04-14 02:26:39 +00001340/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001341/// constant. From[-1] is the first character lexed. Return the end of the
1342/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001343void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 unsigned Size;
1345 char C = getCharAndSize(CurPtr, Size);
1346 char PrevCh = 0;
1347 while (isNumberBody(C)) { // FIXME: UCNs?
1348 CurPtr = ConsumeChar(CurPtr, Size, Result);
1349 PrevCh = C;
1350 C = getCharAndSize(CurPtr, Size);
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001354 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1355 // If we are in Microsoft mode, don't continue if the constant is hex.
1356 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001357 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001358 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1359 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001360
1361 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001362 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001363 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001367 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001368 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001369 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001370}
1371
1372/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001373/// either " or L" or u8" or u" or U".
1374void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1375 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 char C = getAndAdvanceChar(CurPtr, Result);
1379 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001380 // Skip escaped characters. Escaped newlines will already be processed by
1381 // getAndAdvanceChar.
1382 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001384
Chris Lattner571339c2010-05-30 23:27:38 +00001385 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001386 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001387 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001388 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001389 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
Chris Lattner571339c2010-05-30 23:27:38 +00001392
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001393 if (C == 0) {
1394 if (isCodeCompletionPoint(CurPtr-1)) {
1395 PP->CodeCompleteNaturalLanguage();
1396 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1397 return cutOffLexing();
1398 }
1399
Chris Lattner571339c2010-05-30 23:27:38 +00001400 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 C = getAndAdvanceChar(CurPtr, Result);
1403 }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001406 if (NulCharacter && !isLexingRawMode())
1407 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001410 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001411 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001412 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413}
1414
Craig Topper2fa4e862011-08-11 04:06:15 +00001415/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1416/// having lexed R", LR", u8R", uR", or UR".
1417void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1418 tok::TokenKind Kind) {
1419 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1420 // Between the initial and final double quote characters of the raw string,
1421 // any transformations performed in phases 1 and 2 (trigraphs,
1422 // universal-character-names, and line splicing) are reverted.
1423
1424 unsigned PrefixLen = 0;
1425
1426 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1427 ++PrefixLen;
1428
1429 // If the last character was not a '(', then we didn't lex a valid delimiter.
1430 if (CurPtr[PrefixLen] != '(') {
1431 if (!isLexingRawMode()) {
1432 const char *PrefixEnd = &CurPtr[PrefixLen];
1433 if (PrefixLen == 16) {
1434 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1435 } else {
1436 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1437 << StringRef(PrefixEnd, 1);
1438 }
1439 }
1440
1441 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1442 // it's possible the '"' was intended to be part of the raw string, but
1443 // there's not much we can do about that.
1444 while (1) {
1445 char C = *CurPtr++;
1446
1447 if (C == '"')
1448 break;
1449 if (C == 0 && CurPtr-1 == BufferEnd) {
1450 --CurPtr;
1451 break;
1452 }
1453 }
1454
1455 FormTokenWithChars(Result, CurPtr, tok::unknown);
1456 return;
1457 }
1458
1459 // Save prefix and move CurPtr past it
1460 const char *Prefix = CurPtr;
1461 CurPtr += PrefixLen + 1; // skip over prefix and '('
1462
1463 while (1) {
1464 char C = *CurPtr++;
1465
1466 if (C == ')') {
1467 // Check for prefix match and closing quote.
1468 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1469 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1470 break;
1471 }
1472 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1473 if (!isLexingRawMode())
1474 Diag(BufferPtr, diag::err_unterminated_raw_string)
1475 << StringRef(Prefix, PrefixLen);
1476 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1477 return;
1478 }
1479 }
1480
1481 // Update the location of token as well as BufferPtr.
1482 const char *TokStart = BufferPtr;
1483 FormTokenWithChars(Result, CurPtr, Kind);
1484 Result.setLiteralData(TokStart);
1485}
1486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1488/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001489void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001491 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 char C = getAndAdvanceChar(CurPtr, Result);
1493 while (C != '>') {
1494 // Skip escaped characters.
1495 if (C == '\\') {
1496 // Skip the escaped character.
1497 C = getAndAdvanceChar(CurPtr, Result);
1498 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001499 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1500 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001501 // If the filename is unterminated, then it must just be a lone <
1502 // character. Return this as such.
1503 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 return;
1505 } else if (C == 0) {
1506 NulCharacter = CurPtr-1;
1507 }
1508 C = getAndAdvanceChar(CurPtr, Result);
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001512 if (NulCharacter && !isLexingRawMode())
1513 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001516 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001517 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001518 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001519}
1520
1521
1522/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001523/// lexed either ' or L' or u' or U'.
1524void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1525 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 const char *NulCharacter = 0; // Does this character contain the \0 character?
1527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 char C = getAndAdvanceChar(CurPtr, Result);
1529 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001530 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001531 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001532 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001534 }
1535
1536 while (C != '\'') {
1537 // Skip escaped characters.
1538 if (C == '\\') {
1539 // Skip the escaped character.
1540 // FIXME: UCN's
1541 C = getAndAdvanceChar(CurPtr, Result);
1542 } else if (C == '\n' || C == '\r' || // Newline.
1543 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001544 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001545 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001546 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1547 return;
1548 } else if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001549 if (isCodeCompletionPoint(CurPtr-1)) {
1550 PP->CodeCompleteNaturalLanguage();
1551 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1552 return cutOffLexing();
1553 }
1554
Chris Lattnerd80f7862010-07-07 23:24:27 +00001555 NulCharacter = CurPtr-1;
1556 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 C = getAndAdvanceChar(CurPtr, Result);
1558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Chris Lattnerd80f7862010-07-07 23:24:27 +00001560 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001561 if (NulCharacter && !isLexingRawMode())
1562 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001563
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001565 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001566 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001567 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568}
1569
1570/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1571/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001572///
1573/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1574///
1575bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // Whitespace - Skip it, then return the token after the whitespace.
1577 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1578 while (1) {
1579 // Skip horizontal whitespace very aggressively.
1580 while (isHorizontalWhitespace(Char))
1581 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001583 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 if (Char != '\n' && Char != '\r')
1585 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 if (ParsingPreprocessorDirective) {
1588 // End of preprocessor directive line, let LexTokenInternal handle this.
1589 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001590 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // ok, but handle newline.
1594 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001595 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001597 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001598 Char = *++CurPtr;
1599 }
1600
1601 // If this isn't immediately after a newline, there is leading space.
1602 char PrevChar = CurPtr[-1];
1603 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001604 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001605
Chris Lattnerd88dc482008-10-12 04:05:48 +00001606 // If the client wants us to return whitespace, return it now.
1607 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001608 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001609 return true;
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001613 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001614}
1615
1616// SkipBCPLComment - We have just read the // characters from input. Skip until
1617// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001618/// BufferPtr and return.
1619///
1620/// If we're in KeepCommentMode or any CommentHandler has inserted
1621/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001622bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 // If BCPL comments aren't explicitly enabled for this language, emit an
1624 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001625 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // Mark them enabled so we only emit one warning for this translation
1629 // unit.
1630 Features.BCPLComment = true;
1631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 // Scan over the body of the comment. The common case, when scanning, is that
1634 // the comment contains normal ascii characters with nothing interesting in
1635 // them. As such, optimize for this case with the inner loop.
1636 char C;
1637 do {
1638 C = *CurPtr;
1639 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1640 // If we find a \n character, scan backwards, checking to see if it's an
1641 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // Skip over characters in the fast loop.
1644 while (C != 0 && // Potentially EOF.
1645 C != '\\' && // Potentially escaped newline.
1646 C != '?' && // Potentially trigraph.
1647 C != '\n' && C != '\r') // Newline or DOS-style newline.
1648 C = *++CurPtr;
1649
1650 // If this is a newline, we're done.
1651 if (C == '\n' || C == '\r')
1652 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001655 // properly decode the character. Read it in raw mode to avoid emitting
1656 // diagnostics about things like trigraphs. If we see an escaped newline,
1657 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001659 bool OldRawMode = isLexingRawMode();
1660 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001662 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001663
1664 // If the char that we finally got was a \n, then we must have had something
1665 // like \<newline><newline>. We don't want to have consumed the second
1666 // newline, we want CurPtr, to end up pointing to it down below.
1667 if (C == '\n' || C == '\r') {
1668 --CurPtr;
1669 C = 'x'; // doesn't matter what this is.
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 // If we read multiple characters, and one of those characters was a \r or
1673 // \n, then we had an escaped newline within the comment. Emit diagnostic
1674 // unless the next line is also a // comment.
1675 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1676 for (; OldPtr != CurPtr; ++OldPtr)
1677 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1678 // Okay, we found a // comment that ends in a newline, if the next
1679 // line is also a // comment, but has spaces, don't emit a diagnostic.
1680 if (isspace(C)) {
1681 const char *ForwardPtr = CurPtr;
1682 while (isspace(*ForwardPtr)) // Skip whitespace.
1683 ++ForwardPtr;
1684 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1685 break;
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner74d15df2008-11-22 02:02:22 +00001688 if (!isLexingRawMode())
1689 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 break;
1691 }
1692 }
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregor55817af2010-08-25 17:04:25 +00001694 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001695 --CurPtr;
1696 break;
1697 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001698
1699 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1700 PP->CodeCompleteNaturalLanguage();
1701 cutOffLexing();
1702 return false;
1703 }
1704
Reid Spencer5f016e22007-07-11 17:01:13 +00001705 } while (C != '\n' && C != '\r');
1706
Chris Lattner3d0ad582010-02-03 21:06:21 +00001707 // Found but did not consume the newline. Notify comment handlers about the
1708 // comment unless we're in a #if 0 block.
1709 if (PP && !isLexingRawMode() &&
1710 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1711 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001712 BufferPtr = CurPtr;
1713 return true; // A token has to be returned.
1714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001717 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 return SaveBCPLComment(Result, CurPtr);
1719
1720 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001721 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1723 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001724 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001728 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001729 // contribute to another token), it isn't needed for correctness. Note that
1730 // this is ok even in KeepWhitespaceMode, because we would have returned the
1731 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001735 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001737 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001738 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001739 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001740}
1741
1742/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1743/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001744bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001745 // If we're not in a preprocessor directive, just return the // comment
1746 // directly.
1747 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner9e6293d2008-10-12 04:51:35 +00001749 if (!ParsingPreprocessorDirective)
1750 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Chris Lattner9e6293d2008-10-12 04:51:35 +00001752 // If this BCPL-style comment is in a macro definition, transmogrify it into
1753 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001754 bool Invalid = false;
1755 std::string Spelling = PP->getSpelling(Result, &Invalid);
1756 if (Invalid)
1757 return true;
1758
Chris Lattner9e6293d2008-10-12 04:51:35 +00001759 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1760 Spelling[1] = '*'; // Change prefix to "/*".
1761 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Chris Lattner9e6293d2008-10-12 04:51:35 +00001763 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001764 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1765 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001766 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767}
1768
1769/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1770/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001771/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001772static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 Lexer *L) {
1774 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Back up off the newline.
1777 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // If this is a two-character newline sequence, skip the other character.
1780 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1781 // \n\n or \r\r -> not escaped newline.
1782 if (CurPtr[0] == CurPtr[1])
1783 return false;
1784 // \n\r or \r\n -> skip the newline.
1785 --CurPtr;
1786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 // If we have horizontal whitespace, skip over it. We allow whitespace
1789 // between the slash and newline.
1790 bool HasSpace = false;
1791 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1792 --CurPtr;
1793 HasSpace = true;
1794 }
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 // If we have a slash, we know this is an escaped newline.
1797 if (*CurPtr == '\\') {
1798 if (CurPtr[-1] != '*') return false;
1799 } else {
1800 // It isn't a slash, is it the ?? / trigraph?
1801 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1802 CurPtr[-3] != '*')
1803 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // This is the trigraph ending the comment. Emit a stern warning!
1806 CurPtr -= 2;
1807
1808 // If no trigraphs are enabled, warn that we ignored this trigraph and
1809 // ignore this * character.
1810 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001811 if (!L->isLexingRawMode())
1812 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 return false;
1814 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001815 if (!L->isLexingRawMode())
1816 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Reid Spencer5f016e22007-07-11 17:01:13 +00001819 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001820 if (!L->isLexingRawMode())
1821 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001824 if (HasSpace && !L->isLexingRawMode())
1825 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 return true;
1828}
1829
1830#ifdef __SSE2__
1831#include <emmintrin.h>
1832#elif __ALTIVEC__
1833#include <altivec.h>
1834#undef bool
1835#endif
1836
1837/// SkipBlockComment - We have just read the /* characters from input. Read
1838/// until we find the */ characters that terminate the comment. Note that we
1839/// don't bother decoding trigraphs or escaped newlines in block comments,
1840/// because they cannot cause the comment to end. The only thing that can
1841/// happen is the comment could end with an escaped newline between the */ end
1842/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001843///
Chris Lattner046c2272010-01-18 22:35:47 +00001844/// If we're in KeepCommentMode or any CommentHandler has inserted
1845/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001846bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001848 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // optimization helps people who like to put a lot of * characters in their
1850 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001851
1852 // The first character we get with newlines and trigraphs skipped to handle
1853 // the degenerate /*/ case below correctly if the * has an escaped newline
1854 // after it.
1855 unsigned CharSize;
1856 unsigned char C = getCharAndSize(CurPtr, CharSize);
1857 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001859 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00001860 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001861 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Chris Lattner31f0eca2008-10-12 04:19:49 +00001863 // KeepWhitespaceMode should return this broken comment as a token. Since
1864 // it isn't a well formed comment, just return it as an 'unknown' token.
1865 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001866 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001867 return true;
1868 }
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Chris Lattner31f0eca2008-10-12 04:19:49 +00001870 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001871 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Chris Lattner8146b682007-07-21 23:43:37 +00001874 // Check to see if the first character after the '/*' is another /. If so,
1875 // then this slash does not end the block comment, it is part of it.
1876 if (C == '/')
1877 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 while (1) {
1880 // Skip over all non-interesting characters until we find end of buffer or a
1881 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001882 if (CurPtr + 24 < BufferEnd &&
1883 // If there is a code-completion point avoid the fast scan because it
1884 // doesn't check for '\0'.
1885 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001886 // While not aligned to a 16-byte boundary.
1887 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1888 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 if (C == '/') goto FoundSlash;
1891
1892#ifdef __SSE2__
1893 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1894 '/', '/', '/', '/', '/', '/', '/', '/');
1895 while (CurPtr+16 <= BufferEnd &&
1896 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1897 CurPtr += 16;
1898#elif __ALTIVEC__
1899 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001900 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 '/', '/', '/', '/', '/', '/', '/', '/'
1902 };
1903 while (CurPtr+16 <= BufferEnd &&
1904 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1905 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001906#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 // Scan for '/' quickly. Many block comments are very large.
1908 while (CurPtr[0] != '/' &&
1909 CurPtr[1] != '/' &&
1910 CurPtr[2] != '/' &&
1911 CurPtr[3] != '/' &&
1912 CurPtr+4 < BufferEnd) {
1913 CurPtr += 4;
1914 }
1915#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // It has to be one of the bytes scanned, increment to it and read one.
1918 C = *CurPtr++;
1919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // Loop to scan the remainder.
1922 while (C != '/' && C != '\0')
1923 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 FoundSlash:
1926 if (C == '/') {
1927 if (CurPtr[-2] == '*') // We found the final */. We're done!
1928 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1931 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1932 // We found the final */, though it had an escaped newline between the
1933 // * and /. We're done!
1934 break;
1935 }
1936 }
1937 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1938 // If this is a /* inside of the comment, emit a warning. Don't do this
1939 // if this is a /*/, which will end the comment. This misses cases with
1940 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001941 if (!isLexingRawMode())
1942 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 }
1944 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001945 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001946 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // Note: the user probably forgot a */. We could continue immediately
1948 // after the /*, but this would involve lexing a lot of what really is the
1949 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001950 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattner31f0eca2008-10-12 04:19:49 +00001952 // KeepWhitespaceMode should return this broken comment as a token. Since
1953 // it isn't a well formed comment, just return it as an 'unknown' token.
1954 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001955 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001956 return true;
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Chris Lattner31f0eca2008-10-12 04:19:49 +00001959 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001960 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001961 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1962 PP->CodeCompleteNaturalLanguage();
1963 cutOffLexing();
1964 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 C = *CurPtr++;
1968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Chris Lattner3d0ad582010-02-03 21:06:21 +00001970 // Notify comment handlers about the comment unless we're in a #if 0 block.
1971 if (PP && !isLexingRawMode() &&
1972 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1973 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001974 BufferPtr = CurPtr;
1975 return true; // A token has to be returned.
1976 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001979 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001980 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001981 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 }
1983
1984 // It is common for the tokens immediately after a /**/ comment to be
1985 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001986 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1987 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001989 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001991 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 }
1993
1994 // Otherwise, just return so that the next character will be lexed as a token.
1995 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001996 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001997 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001998}
1999
2000//===----------------------------------------------------------------------===//
2001// Primary Lexing Entry Points
2002//===----------------------------------------------------------------------===//
2003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2005/// uninterpreted string. This switches the lexer out of directive mode.
2006std::string Lexer::ReadToEndOfLine() {
2007 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2008 "Must be in a preprocessing directive!");
2009 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00002010 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002011
2012 // CurPtr - Cache BufferPtr in an automatic variable.
2013 const char *CurPtr = BufferPtr;
2014 while (1) {
2015 char Char = getAndAdvanceChar(CurPtr, Tmp);
2016 switch (Char) {
2017 default:
2018 Result += Char;
2019 break;
2020 case 0: // Null.
2021 // Found end of file?
2022 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002023 if (isCodeCompletionPoint(CurPtr-1)) {
2024 PP->CodeCompleteNaturalLanguage();
2025 cutOffLexing();
2026 return Result;
2027 }
2028
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 // Nope, normal character, continue.
2030 Result += Char;
2031 break;
2032 }
2033 // FALL THROUGH.
2034 case '\r':
2035 case '\n':
2036 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2037 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2038 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Peter Collingbourne84021552011-02-28 02:37:51 +00002040 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002042 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002043 if (PP)
2044 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002045 Lex(Tmp);
2046 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002047 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // Finally, we're done, return the string we found.
2050 return Result;
2051 }
2052 }
2053}
2054
2055/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2056/// condition, reporting diagnostics and handling other edge cases as required.
2057/// This returns true if Result contains a token, false if PP.Lex should be
2058/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002059bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // If we hit the end of the file while parsing a preprocessor directive,
2061 // end the preprocessor directive first. The next token returned will
2062 // then be the end of file.
2063 if (ParsingPreprocessorDirective) {
2064 // Done parsing the "line".
2065 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002067 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002070 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002072 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002073
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 // If we are in raw mode, return this event as an EOF token. Let the caller
2075 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002076 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 Result.startToken();
2078 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002079 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 return true;
2081 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002082
Douglas Gregorf44e8542010-08-24 19:08:16 +00002083 // Issue diagnostics for unterminated #if and missing newline.
2084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // If we are in a #if directive, emit an error.
2086 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002087 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002088 PP->Diag(ConditionalStack.back().IfLoc,
2089 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 ConditionalStack.pop_back();
2091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002093 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2094 // a pedwarn.
2095 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002096 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002097 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 BufferPtr = CurPtr;
2100
2101 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002102 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002103}
2104
2105/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2106/// the specified lexer will return a tok::l_paren token, 0 if it is something
2107/// else and 2 if there are no more tokens in the buffer controlled by the
2108/// lexer.
2109unsigned Lexer::isNextPPTokenLParen() {
2110 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // Switch to 'skipping' mode. This will ensure that we can lex a token
2113 // without emitting diagnostics, disables macro expansion, and will cause EOF
2114 // to return an EOF token instead of popping the include stack.
2115 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 // Save state that can be changed while lexing so that we can restore it.
2118 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002119 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Chris Lattnerd2177732007-07-20 16:59:19 +00002121 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 Tok.startToken();
2123 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // Restore state that may have changed.
2126 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002127 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // Restore the lexer back to non-skipping mode.
2130 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002132 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002134 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002135}
2136
Chris Lattner34f349d2009-12-14 06:16:57 +00002137/// FindConflictEnd - Find the end of a version control conflict marker.
2138static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002139 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002140 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002141 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002142 // Must occur at start of line.
2143 if (RestOfBuffer[Pos-1] != '\r' &&
2144 RestOfBuffer[Pos-1] != '\n') {
2145 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002146 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002147 continue;
2148 }
2149 return RestOfBuffer.data()+Pos;
2150 }
2151 return 0;
2152}
2153
2154/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2155/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2156/// and recover nicely. This returns true if it is a conflict marker and false
2157/// if not.
2158bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2159 // Only a conflict marker if it starts at the beginning of a line.
2160 if (CurPtr != BufferStart &&
2161 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2162 return false;
2163
2164 // Check to see if we have <<<<<<<.
2165 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002166 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002167 return false;
2168
2169 // If we have a situation where we don't care about conflict markers, ignore
2170 // it.
2171 if (IsInConflictMarker || isLexingRawMode())
2172 return false;
2173
2174 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2175 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002176 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002177 // We found a match. We are really in a conflict marker.
2178 // Diagnose this, and ignore to the end of line.
2179 Diag(CurPtr, diag::err_conflict_marker);
2180 IsInConflictMarker = true;
2181
2182 // Skip ahead to the end of line. We know this exists because the
2183 // end-of-conflict marker starts with \r or \n.
2184 while (*CurPtr != '\r' && *CurPtr != '\n') {
2185 assert(CurPtr != BufferEnd && "Didn't find end of line");
2186 ++CurPtr;
2187 }
2188 BufferPtr = CurPtr;
2189 return true;
2190 }
2191
2192 // No end of conflict marker found.
2193 return false;
2194}
2195
2196
2197/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2198/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2199/// until the end of the line. This returns true if it is a conflict marker and
2200/// false if not.
2201bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2202 // Only a conflict marker if it starts at the beginning of a line.
2203 if (CurPtr != BufferStart &&
2204 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2205 return false;
2206
2207 // If we have a situation where we don't care about conflict markers, ignore
2208 // it.
2209 if (!IsInConflictMarker || isLexingRawMode())
2210 return false;
2211
2212 // Check to see if we have the marker (7 characters in a row).
2213 for (unsigned i = 1; i != 7; ++i)
2214 if (CurPtr[i] != CurPtr[0])
2215 return false;
2216
2217 // If we do have it, search for the end of the conflict marker. This could
2218 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2219 // be the end of conflict marker.
2220 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2221 CurPtr = End;
2222
2223 // Skip ahead to the end of line.
2224 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2225 ++CurPtr;
2226
2227 BufferPtr = CurPtr;
2228
2229 // No longer in the conflict marker.
2230 IsInConflictMarker = false;
2231 return true;
2232 }
2233
2234 return false;
2235}
2236
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002237bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2238 if (PP && PP->isCodeCompletionEnabled()) {
2239 SourceLocation Loc = FileLoc.getFileLocWithOffset(CurPtr-BufferStart);
2240 return Loc == PP->getCodeCompletionLoc();
2241 }
2242
2243 return false;
2244}
2245
Reid Spencer5f016e22007-07-11 17:01:13 +00002246
2247/// LexTokenInternal - This implements a simple C family lexer. It is an
2248/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002249/// has a null character at the end of the file. This returns a preprocessing
2250/// token, not a normal token, as such, it is an internal interface. It assumes
2251/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002252void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002253LexNextToken:
2254 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002255 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 // CurPtr - Cache BufferPtr in an automatic variable.
2259 const char *CurPtr = BufferPtr;
2260
2261 // Small amounts of horizontal whitespace is very common between tokens.
2262 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2263 ++CurPtr;
2264 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2265 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Chris Lattnerd88dc482008-10-12 04:05:48 +00002267 // If we are keeping whitespace and other tokens, just return what we just
2268 // skipped. The next lexer invocation will return the token after the
2269 // whitespace.
2270 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002271 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002272 return;
2273 }
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002276 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 }
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Reid Spencer5f016e22007-07-11 17:01:13 +00002279 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 // Read a character, advancing over it.
2282 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002283 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 switch (Char) {
2286 case 0: // Null.
2287 // Found end of file?
2288 if (CurPtr-1 == BufferEnd) {
2289 // Read the PP instance variable into an automatic variable, because
2290 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002291 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002292 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2293 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002294 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2295 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002296 }
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002298 // Check if we are performing code completion.
2299 if (isCodeCompletionPoint(CurPtr-1)) {
2300 // Return the code-completion token.
2301 Result.startToken();
2302 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2303 return;
2304 }
2305
Chris Lattner74d15df2008-11-22 02:02:22 +00002306 if (!isLexingRawMode())
2307 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002308 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002309 if (SkipWhitespace(Result, CurPtr))
2310 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002313
2314 case 26: // DOS & CP/M EOF: "^Z".
2315 // If we're in Microsoft extensions mode, treat this as end of file.
2316 if (Features.Microsoft) {
2317 // Read the PP instance variable into an automatic variable, because
2318 // LexEndOfFile will often delete 'this'.
2319 Preprocessor *PPCache = PP;
2320 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2321 return; // Got a token to return.
2322 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2323 return PPCache->Lex(Result);
2324 }
2325 // If Microsoft extensions are disabled, this is just random garbage.
2326 Kind = tok::unknown;
2327 break;
2328
Reid Spencer5f016e22007-07-11 17:01:13 +00002329 case '\n':
2330 case '\r':
2331 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002332 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 if (ParsingPreprocessorDirective) {
2334 // Done parsing the "line".
2335 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002338 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 // Since we consumed a newline, we are back at the start of a line.
2341 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Peter Collingbourne84021552011-02-28 02:37:51 +00002343 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 break;
2345 }
2346 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002347 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002349 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Chris Lattnerd88dc482008-10-12 04:05:48 +00002351 if (SkipWhitespace(Result, CurPtr))
2352 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 goto LexNextToken; // GCC isn't tail call eliminating.
2354 case ' ':
2355 case '\t':
2356 case '\f':
2357 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002358 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002359 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002360 if (SkipWhitespace(Result, CurPtr))
2361 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002362
2363 SkipIgnoredUnits:
2364 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Chris Lattner8133cfc2007-07-22 06:29:05 +00002366 // If the next token is obviously a // or /* */ comment, skip it efficiently
2367 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002368 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002369 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002370 if (SkipBCPLComment(Result, CurPtr+2))
2371 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002372 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002373 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002374 if (SkipBlockComment(Result, CurPtr+2))
2375 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002376 goto SkipIgnoredUnits;
2377 } else if (isHorizontalWhitespace(*CurPtr)) {
2378 goto SkipHorizontalWhitespace;
2379 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002381
Chris Lattner3a570772008-01-03 17:58:54 +00002382 // C99 6.4.4.1: Integer Constants.
2383 // C99 6.4.4.2: Floating Constants.
2384 case '0': case '1': case '2': case '3': case '4':
2385 case '5': case '6': case '7': case '8': case '9':
2386 // Notify MIOpt that we read a non-whitespace/non-comment token.
2387 MIOpt.ReadToken();
2388 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor5cee1192011-07-27 05:40:30 +00002390 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2391 // Notify MIOpt that we read a non-whitespace/non-comment token.
2392 MIOpt.ReadToken();
2393
2394 if (Features.CPlusPlus0x) {
2395 Char = getCharAndSize(CurPtr, SizeTmp);
2396
2397 // UTF-16 string literal
2398 if (Char == '"')
2399 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2400 tok::utf16_string_literal);
2401
2402 // UTF-16 character constant
2403 if (Char == '\'')
2404 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2405 tok::utf16_char_constant);
2406
Craig Topper2fa4e862011-08-11 04:06:15 +00002407 // UTF-16 raw string literal
2408 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2409 return LexRawStringLiteral(Result,
2410 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2411 SizeTmp2, Result),
2412 tok::utf16_string_literal);
2413
2414 if (Char == '8') {
2415 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2416
2417 // UTF-8 string literal
2418 if (Char2 == '"')
2419 return LexStringLiteral(Result,
2420 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2421 SizeTmp2, Result),
2422 tok::utf8_string_literal);
2423
2424 if (Char2 == 'R') {
2425 unsigned SizeTmp3;
2426 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2427 // UTF-8 raw string literal
2428 if (Char3 == '"') {
2429 return LexRawStringLiteral(Result,
2430 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2431 SizeTmp2, Result),
2432 SizeTmp3, Result),
2433 tok::utf8_string_literal);
2434 }
2435 }
2436 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002437 }
2438
2439 // treat u like the start of an identifier.
2440 return LexIdentifier(Result, CurPtr);
2441
2442 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2443 // Notify MIOpt that we read a non-whitespace/non-comment token.
2444 MIOpt.ReadToken();
2445
2446 if (Features.CPlusPlus0x) {
2447 Char = getCharAndSize(CurPtr, SizeTmp);
2448
2449 // UTF-32 string literal
2450 if (Char == '"')
2451 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2452 tok::utf32_string_literal);
2453
2454 // UTF-32 character constant
2455 if (Char == '\'')
2456 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2457 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002458
2459 // UTF-32 raw string literal
2460 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2461 return LexRawStringLiteral(Result,
2462 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2463 SizeTmp2, Result),
2464 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002465 }
2466
2467 // treat U like the start of an identifier.
2468 return LexIdentifier(Result, CurPtr);
2469
Craig Topper2fa4e862011-08-11 04:06:15 +00002470 case 'R': // Identifier or C++0x raw string literal
2471 // Notify MIOpt that we read a non-whitespace/non-comment token.
2472 MIOpt.ReadToken();
2473
2474 if (Features.CPlusPlus0x) {
2475 Char = getCharAndSize(CurPtr, SizeTmp);
2476
2477 if (Char == '"')
2478 return LexRawStringLiteral(Result,
2479 ConsumeChar(CurPtr, SizeTmp, Result),
2480 tok::string_literal);
2481 }
2482
2483 // treat R like the start of an identifier.
2484 return LexIdentifier(Result, CurPtr);
2485
Chris Lattner3a570772008-01-03 17:58:54 +00002486 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 // Notify MIOpt that we read a non-whitespace/non-comment token.
2488 MIOpt.ReadToken();
2489 Char = getCharAndSize(CurPtr, SizeTmp);
2490
2491 // Wide string literal.
2492 if (Char == '"')
2493 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002494 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002495
Craig Topper2fa4e862011-08-11 04:06:15 +00002496 // Wide raw string literal.
2497 if (Features.CPlusPlus0x && Char == 'R' &&
2498 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2499 return LexRawStringLiteral(Result,
2500 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2501 SizeTmp2, Result),
2502 tok::wide_string_literal);
2503
Reid Spencer5f016e22007-07-11 17:01:13 +00002504 // Wide character constant.
2505 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002506 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2507 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002508 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 // C99 6.4.2: Identifiers.
2511 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2512 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002513 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2515 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2516 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002517 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 case 'v': case 'w': case 'x': case 'y': case 'z':
2519 case '_':
2520 // Notify MIOpt that we read a non-whitespace/non-comment token.
2521 MIOpt.ReadToken();
2522 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002523
2524 case '$': // $ in identifiers.
2525 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002526 if (!isLexingRawMode())
2527 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002528 // Notify MIOpt that we read a non-whitespace/non-comment token.
2529 MIOpt.ReadToken();
2530 return LexIdentifier(Result, CurPtr);
2531 }
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Chris Lattner9e6293d2008-10-12 04:51:35 +00002533 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002534 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 // C99 6.4.4: Character Constants.
2537 case '\'':
2538 // Notify MIOpt that we read a non-whitespace/non-comment token.
2539 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002540 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002541
2542 // C99 6.4.5: String Literals.
2543 case '"':
2544 // Notify MIOpt that we read a non-whitespace/non-comment token.
2545 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002546 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002547
2548 // C99 6.4.6: Punctuators.
2549 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002550 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 break;
2552 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002553 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 break;
2555 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002556 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 break;
2558 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002559 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002560 break;
2561 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002562 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 break;
2564 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002565 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002566 break;
2567 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002568 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 break;
2570 case '.':
2571 Char = getCharAndSize(CurPtr, SizeTmp);
2572 if (Char >= '0' && Char <= '9') {
2573 // Notify MIOpt that we read a non-whitespace/non-comment token.
2574 MIOpt.ReadToken();
2575
2576 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2577 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002578 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 CurPtr += SizeTmp;
2580 } else if (Char == '.' &&
2581 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002582 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2584 SizeTmp2, Result);
2585 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002586 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 }
2588 break;
2589 case '&':
2590 Char = getCharAndSize(CurPtr, SizeTmp);
2591 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002592 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2594 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002595 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2597 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002598 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 }
2600 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002601 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002603 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2605 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002606 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 }
2608 break;
2609 case '+':
2610 Char = getCharAndSize(CurPtr, SizeTmp);
2611 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002613 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002616 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002618 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002619 }
2620 break;
2621 case '-':
2622 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002623 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002625 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002626 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002627 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2629 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002630 Kind = tok::arrowstar;
2631 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002633 Kind = tok::arrow;
2634 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002636 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002638 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
2640 break;
2641 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002642 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 break;
2644 case '!':
2645 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002646 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2648 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002649 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 }
2651 break;
2652 case '/':
2653 // 6.4.9: Comments
2654 Char = getCharAndSize(CurPtr, SizeTmp);
2655 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002656 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2657 // want to lex this as a comment. There is one problem with this though,
2658 // that in one particular corner case, this can change the behavior of the
2659 // resultant program. For example, In "foo //**/ bar", C89 would lex
2660 // this as "foo / bar" and langauges with BCPL comments would lex it as
2661 // "foo". Check to see if the character after the second slash is a '*'.
2662 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002663 // However, we never do this in -traditional-cpp mode.
2664 if ((Features.BCPLComment ||
2665 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2666 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002667 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002668 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Chris Lattner8402c732009-01-16 22:39:25 +00002670 // It is common for the tokens immediately after a // comment to be
2671 // whitespace (indentation for the next line). Instead of going through
2672 // the big switch, handle it efficiently now.
2673 goto SkipIgnoredUnits;
2674 }
2675 }
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Chris Lattner8402c732009-01-16 22:39:25 +00002677 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002678 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002679 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002680 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002681 }
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Chris Lattner8402c732009-01-16 22:39:25 +00002683 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002685 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002687 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 }
2689 break;
2690 case '%':
2691 Char = getCharAndSize(CurPtr, SizeTmp);
2692 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002693 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002694 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2695 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002696 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2698 } else if (Features.Digraphs && Char == ':') {
2699 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2700 Char = getCharAndSize(CurPtr, SizeTmp);
2701 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002702 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002703 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2704 SizeTmp2, Result);
2705 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002707 if (!isLexingRawMode())
2708 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002709 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002710 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 // We parsed a # character. If this occurs at the start of the line,
2712 // it's actually the start of a preprocessing directive. Callback to
2713 // the preprocessor to handle it.
2714 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002715 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002716 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002717 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Reid Spencer5f016e22007-07-11 17:01:13 +00002719 // As an optimization, if the preprocessor didn't switch lexers, tail
2720 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002721 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 // Start a new token. If this is a #include or something, the PP may
2723 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002724 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002725 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002726 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002727 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 IsAtStartOfLine = false;
2729 }
2730 goto LexNextToken; // GCC isn't tail call eliminating.
2731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Chris Lattner168ae2d2007-10-17 20:41:00 +00002733 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 }
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Chris Lattnere91e9322009-03-18 20:58:27 +00002736 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 }
2738 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002739 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 }
2741 break;
2742 case '<':
2743 Char = getCharAndSize(CurPtr, SizeTmp);
2744 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002745 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002747 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2748 if (After == '=') {
2749 Kind = tok::lesslessequal;
2750 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2751 SizeTmp2, Result);
2752 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2753 // If this is actually a '<<<<<<<' version control conflict marker,
2754 // recognize it as such and recover nicely.
2755 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002756 } else if (Features.CUDA && After == '<') {
2757 Kind = tok::lesslessless;
2758 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2759 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002760 } else {
2761 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2762 Kind = tok::lessless;
2763 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002766 Kind = tok::lessequal;
2767 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002768 if (Features.CPlusPlus0x &&
2769 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2770 // C++0x [lex.pptoken]p3:
2771 // Otherwise, if the next three characters are <:: and the subsequent
2772 // character is neither : nor >, the < is treated as a preprocessor
2773 // token by itself and not as the first character of the alternative
2774 // token <:.
2775 unsigned SizeTmp3;
2776 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2777 if (After != ':' && After != '>') {
2778 Kind = tok::less;
2779 break;
2780 }
2781 }
2782
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002784 Kind = tok::l_square;
2785 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002787 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 }
2791 break;
2792 case '>':
2793 Char = getCharAndSize(CurPtr, SizeTmp);
2794 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002796 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002798 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2799 if (After == '=') {
2800 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2801 SizeTmp2, Result);
2802 Kind = tok::greatergreaterequal;
2803 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2804 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2805 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002806 } else if (Features.CUDA && After == '>') {
2807 Kind = tok::greatergreatergreater;
2808 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2809 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002810 } else {
2811 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2812 Kind = tok::greatergreater;
2813 }
2814
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002816 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 }
2818 break;
2819 case '^':
2820 Char = getCharAndSize(CurPtr, SizeTmp);
2821 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002823 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002825 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 }
2827 break;
2828 case '|':
2829 Char = getCharAndSize(CurPtr, SizeTmp);
2830 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002831 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2833 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002834 // If this is '|||||||' and we're in a conflict marker, ignore it.
2835 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2836 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002837 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2839 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002840 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 }
2842 break;
2843 case ':':
2844 Char = getCharAndSize(CurPtr, SizeTmp);
2845 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002846 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2848 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002849 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002851 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002852 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 }
2854 break;
2855 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002856 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 break;
2858 case '=':
2859 Char = getCharAndSize(CurPtr, SizeTmp);
2860 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002861 // If this is '=======' and we're in a conflict marker, ignore it.
2862 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2863 goto LexNextToken;
2864
Chris Lattner9e6293d2008-10-12 04:51:35 +00002865 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002867 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002868 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 }
2870 break;
2871 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002872 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 break;
2874 case '#':
2875 Char = getCharAndSize(CurPtr, SizeTmp);
2876 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002877 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2879 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002880 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002881 if (!isLexingRawMode())
2882 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002883 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2884 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 // We parsed a # character. If this occurs at the start of the line,
2886 // it's actually the start of a preprocessing directive. Callback to
2887 // the preprocessor to handle it.
2888 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002889 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002890 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002891 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Reid Spencer5f016e22007-07-11 17:01:13 +00002893 // As an optimization, if the preprocessor didn't switch lexers, tail
2894 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002895 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 // Start a new token. If this is a #include or something, the PP may
2897 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002898 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002900 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002901 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002902 IsAtStartOfLine = false;
2903 }
2904 goto LexNextToken; // GCC isn't tail call eliminating.
2905 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002906 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002907 }
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Chris Lattnere91e9322009-03-18 20:58:27 +00002909 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 }
2911 break;
2912
Chris Lattner3a570772008-01-03 17:58:54 +00002913 case '@':
2914 // Objective C support.
2915 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002916 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002917 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002918 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002919 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Reid Spencer5f016e22007-07-11 17:01:13 +00002921 case '\\':
2922 // FIXME: UCN's.
2923 // FALL THROUGH.
2924 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002925 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002926 break;
2927 }
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 // Notify MIOpt that we read a non-whitespace/non-comment token.
2930 MIOpt.ReadToken();
2931
2932 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002933 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002934}