blob: e9db93ee436d83406814b4e08e717ff37d78a52f [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.
Douglas Gregor55817af2010-08-25 17:04:25 +00001387 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1388 PP->CodeCompleteNaturalLanguage();
1389 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001390 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001391 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 }
Chris Lattner571339c2010-05-30 23:27:38 +00001394
1395 if (C == 0)
1396 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 C = getAndAdvanceChar(CurPtr, Result);
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001401 if (NulCharacter && !isLexingRawMode())
1402 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001405 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001406 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001407 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408}
1409
Craig Topper2fa4e862011-08-11 04:06:15 +00001410/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1411/// having lexed R", LR", u8R", uR", or UR".
1412void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1413 tok::TokenKind Kind) {
1414 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1415 // Between the initial and final double quote characters of the raw string,
1416 // any transformations performed in phases 1 and 2 (trigraphs,
1417 // universal-character-names, and line splicing) are reverted.
1418
1419 unsigned PrefixLen = 0;
1420
1421 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1422 ++PrefixLen;
1423
1424 // If the last character was not a '(', then we didn't lex a valid delimiter.
1425 if (CurPtr[PrefixLen] != '(') {
1426 if (!isLexingRawMode()) {
1427 const char *PrefixEnd = &CurPtr[PrefixLen];
1428 if (PrefixLen == 16) {
1429 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1430 } else {
1431 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1432 << StringRef(PrefixEnd, 1);
1433 }
1434 }
1435
1436 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1437 // it's possible the '"' was intended to be part of the raw string, but
1438 // there's not much we can do about that.
1439 while (1) {
1440 char C = *CurPtr++;
1441
1442 if (C == '"')
1443 break;
1444 if (C == 0 && CurPtr-1 == BufferEnd) {
1445 --CurPtr;
1446 break;
1447 }
1448 }
1449
1450 FormTokenWithChars(Result, CurPtr, tok::unknown);
1451 return;
1452 }
1453
1454 // Save prefix and move CurPtr past it
1455 const char *Prefix = CurPtr;
1456 CurPtr += PrefixLen + 1; // skip over prefix and '('
1457
1458 while (1) {
1459 char C = *CurPtr++;
1460
1461 if (C == ')') {
1462 // Check for prefix match and closing quote.
1463 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1464 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1465 break;
1466 }
1467 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1468 if (!isLexingRawMode())
1469 Diag(BufferPtr, diag::err_unterminated_raw_string)
1470 << StringRef(Prefix, PrefixLen);
1471 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1472 return;
1473 }
1474 }
1475
1476 // Update the location of token as well as BufferPtr.
1477 const char *TokStart = BufferPtr;
1478 FormTokenWithChars(Result, CurPtr, Kind);
1479 Result.setLiteralData(TokStart);
1480}
1481
Reid Spencer5f016e22007-07-11 17:01:13 +00001482/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1483/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001484void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001486 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 char C = getAndAdvanceChar(CurPtr, Result);
1488 while (C != '>') {
1489 // Skip escaped characters.
1490 if (C == '\\') {
1491 // Skip the escaped character.
1492 C = getAndAdvanceChar(CurPtr, Result);
1493 } else if (C == '\n' || C == '\r' || // Newline.
1494 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001495 // If the filename is unterminated, then it must just be a lone <
1496 // character. Return this as such.
1497 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 return;
1499 } else if (C == 0) {
1500 NulCharacter = CurPtr-1;
1501 }
1502 C = getAndAdvanceChar(CurPtr, Result);
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001506 if (NulCharacter && !isLexingRawMode())
1507 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001510 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001511 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001512 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001513}
1514
1515
1516/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001517/// lexed either ' or L' or u' or U'.
1518void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1519 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 const char *NulCharacter = 0; // Does this character contain the \0 character?
1521
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 char C = getAndAdvanceChar(CurPtr, Result);
1523 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001524 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001525 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001526 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001528 }
1529
1530 while (C != '\'') {
1531 // Skip escaped characters.
1532 if (C == '\\') {
1533 // Skip the escaped character.
1534 // FIXME: UCN's
1535 C = getAndAdvanceChar(CurPtr, Result);
1536 } else if (C == '\n' || C == '\r' || // Newline.
1537 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001538 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1539 PP->CodeCompleteNaturalLanguage();
1540 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001541 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001542 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1543 return;
1544 } else if (C == 0) {
1545 NulCharacter = CurPtr-1;
1546 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 C = getAndAdvanceChar(CurPtr, Result);
1548 }
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattnerd80f7862010-07-07 23:24:27 +00001550 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001551 if (NulCharacter && !isLexingRawMode())
1552 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001555 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001556 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001557 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558}
1559
1560/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1561/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001562///
1563/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1564///
1565bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Whitespace - Skip it, then return the token after the whitespace.
1567 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1568 while (1) {
1569 // Skip horizontal whitespace very aggressively.
1570 while (isHorizontalWhitespace(Char))
1571 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001573 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 if (Char != '\n' && Char != '\r')
1575 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 if (ParsingPreprocessorDirective) {
1578 // End of preprocessor directive line, let LexTokenInternal handle this.
1579 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001580 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 }
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // ok, but handle newline.
1584 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001585 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001587 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001588 Char = *++CurPtr;
1589 }
1590
1591 // If this isn't immediately after a newline, there is leading space.
1592 char PrevChar = CurPtr[-1];
1593 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001594 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001595
Chris Lattnerd88dc482008-10-12 04:05:48 +00001596 // If the client wants us to return whitespace, return it now.
1597 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001598 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001599 return true;
1600 }
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001603 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604}
1605
1606// SkipBCPLComment - We have just read the // characters from input. Skip until
1607// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001608/// BufferPtr and return.
1609///
1610/// If we're in KeepCommentMode or any CommentHandler has inserted
1611/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001612bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 // If BCPL comments aren't explicitly enabled for this language, emit an
1614 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001615 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001616 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 // Mark them enabled so we only emit one warning for this translation
1619 // unit.
1620 Features.BCPLComment = true;
1621 }
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 // Scan over the body of the comment. The common case, when scanning, is that
1624 // the comment contains normal ascii characters with nothing interesting in
1625 // them. As such, optimize for this case with the inner loop.
1626 char C;
1627 do {
1628 C = *CurPtr;
1629 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1630 // If we find a \n character, scan backwards, checking to see if it's an
1631 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 // Skip over characters in the fast loop.
1634 while (C != 0 && // Potentially EOF.
1635 C != '\\' && // Potentially escaped newline.
1636 C != '?' && // Potentially trigraph.
1637 C != '\n' && C != '\r') // Newline or DOS-style newline.
1638 C = *++CurPtr;
1639
1640 // If this is a newline, we're done.
1641 if (C == '\n' || C == '\r')
1642 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001645 // properly decode the character. Read it in raw mode to avoid emitting
1646 // diagnostics about things like trigraphs. If we see an escaped newline,
1647 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001648 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001649 bool OldRawMode = isLexingRawMode();
1650 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001652 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001653
1654 // If the char that we finally got was a \n, then we must have had something
1655 // like \<newline><newline>. We don't want to have consumed the second
1656 // newline, we want CurPtr, to end up pointing to it down below.
1657 if (C == '\n' || C == '\r') {
1658 --CurPtr;
1659 C = 'x'; // doesn't matter what this is.
1660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 // If we read multiple characters, and one of those characters was a \r or
1663 // \n, then we had an escaped newline within the comment. Emit diagnostic
1664 // unless the next line is also a // comment.
1665 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1666 for (; OldPtr != CurPtr; ++OldPtr)
1667 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1668 // Okay, we found a // comment that ends in a newline, if the next
1669 // line is also a // comment, but has spaces, don't emit a diagnostic.
1670 if (isspace(C)) {
1671 const char *ForwardPtr = CurPtr;
1672 while (isspace(*ForwardPtr)) // Skip whitespace.
1673 ++ForwardPtr;
1674 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1675 break;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Chris Lattner74d15df2008-11-22 02:02:22 +00001678 if (!isLexingRawMode())
1679 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 break;
1681 }
1682 }
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Douglas Gregor55817af2010-08-25 17:04:25 +00001684 if (CurPtr == BufferEnd+1) {
1685 if (PP && PP->isCodeCompletionFile(FileLoc))
1686 PP->CodeCompleteNaturalLanguage();
1687
1688 --CurPtr;
1689 break;
1690 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 } while (C != '\n' && C != '\r');
1692
Chris Lattner3d0ad582010-02-03 21:06:21 +00001693 // Found but did not consume the newline. Notify comment handlers about the
1694 // comment unless we're in a #if 0 block.
1695 if (PP && !isLexingRawMode() &&
1696 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1697 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001698 BufferPtr = CurPtr;
1699 return true; // A token has to be returned.
1700 }
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001703 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 return SaveBCPLComment(Result, CurPtr);
1705
1706 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001707 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1709 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001710 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001714 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001715 // contribute to another token), it isn't needed for correctness. Note that
1716 // this is ok even in KeepWhitespaceMode, because we would have returned the
1717 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001721 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001723 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001725 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001726}
1727
1728/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1729/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001730bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001731 // If we're not in a preprocessor directive, just return the // comment
1732 // directly.
1733 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Chris Lattner9e6293d2008-10-12 04:51:35 +00001735 if (!ParsingPreprocessorDirective)
1736 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Chris Lattner9e6293d2008-10-12 04:51:35 +00001738 // If this BCPL-style comment is in a macro definition, transmogrify it into
1739 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001740 bool Invalid = false;
1741 std::string Spelling = PP->getSpelling(Result, &Invalid);
1742 if (Invalid)
1743 return true;
1744
Chris Lattner9e6293d2008-10-12 04:51:35 +00001745 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1746 Spelling[1] = '*'; // Change prefix to "/*".
1747 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Chris Lattner9e6293d2008-10-12 04:51:35 +00001749 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001750 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1751 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001752 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753}
1754
1755/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1756/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001757/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001758static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 Lexer *L) {
1760 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // Back up off the newline.
1763 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 // If this is a two-character newline sequence, skip the other character.
1766 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1767 // \n\n or \r\r -> not escaped newline.
1768 if (CurPtr[0] == CurPtr[1])
1769 return false;
1770 // \n\r or \r\n -> skip the newline.
1771 --CurPtr;
1772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 // If we have horizontal whitespace, skip over it. We allow whitespace
1775 // between the slash and newline.
1776 bool HasSpace = false;
1777 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1778 --CurPtr;
1779 HasSpace = true;
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 // If we have a slash, we know this is an escaped newline.
1783 if (*CurPtr == '\\') {
1784 if (CurPtr[-1] != '*') return false;
1785 } else {
1786 // It isn't a slash, is it the ?? / trigraph?
1787 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1788 CurPtr[-3] != '*')
1789 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 // This is the trigraph ending the comment. Emit a stern warning!
1792 CurPtr -= 2;
1793
1794 // If no trigraphs are enabled, warn that we ignored this trigraph and
1795 // ignore this * character.
1796 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001797 if (!L->isLexingRawMode())
1798 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 return false;
1800 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001801 if (!L->isLexingRawMode())
1802 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001806 if (!L->isLexingRawMode())
1807 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001810 if (HasSpace && !L->isLexingRawMode())
1811 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 return true;
1814}
1815
1816#ifdef __SSE2__
1817#include <emmintrin.h>
1818#elif __ALTIVEC__
1819#include <altivec.h>
1820#undef bool
1821#endif
1822
1823/// SkipBlockComment - We have just read the /* characters from input. Read
1824/// until we find the */ characters that terminate the comment. Note that we
1825/// don't bother decoding trigraphs or escaped newlines in block comments,
1826/// because they cannot cause the comment to end. The only thing that can
1827/// happen is the comment could end with an escaped newline between the */ end
1828/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001829///
Chris Lattner046c2272010-01-18 22:35:47 +00001830/// If we're in KeepCommentMode or any CommentHandler has inserted
1831/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001832bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001834 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 // optimization helps people who like to put a lot of * characters in their
1836 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001837
1838 // The first character we get with newlines and trigraphs skipped to handle
1839 // the degenerate /*/ case below correctly if the * has an escaped newline
1840 // after it.
1841 unsigned CharSize;
1842 unsigned char C = getCharAndSize(CurPtr, CharSize);
1843 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001845 if (!isLexingRawMode() &&
1846 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001847 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001848 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Chris Lattner31f0eca2008-10-12 04:19:49 +00001850 // KeepWhitespaceMode should return this broken comment as a token. Since
1851 // it isn't a well formed comment, just return it as an 'unknown' token.
1852 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001853 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001854 return true;
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Chris Lattner31f0eca2008-10-12 04:19:49 +00001857 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001858 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Chris Lattner8146b682007-07-21 23:43:37 +00001861 // Check to see if the first character after the '/*' is another /. If so,
1862 // then this slash does not end the block comment, it is part of it.
1863 if (C == '/')
1864 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 while (1) {
1867 // Skip over all non-interesting characters until we find end of buffer or a
1868 // (probably ending) '/' character.
1869 if (CurPtr + 24 < BufferEnd) {
1870 // While not aligned to a 16-byte boundary.
1871 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1872 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 if (C == '/') goto FoundSlash;
1875
1876#ifdef __SSE2__
1877 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1878 '/', '/', '/', '/', '/', '/', '/', '/');
1879 while (CurPtr+16 <= BufferEnd &&
1880 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1881 CurPtr += 16;
1882#elif __ALTIVEC__
1883 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001884 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 '/', '/', '/', '/', '/', '/', '/', '/'
1886 };
1887 while (CurPtr+16 <= BufferEnd &&
1888 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1889 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001890#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // Scan for '/' quickly. Many block comments are very large.
1892 while (CurPtr[0] != '/' &&
1893 CurPtr[1] != '/' &&
1894 CurPtr[2] != '/' &&
1895 CurPtr[3] != '/' &&
1896 CurPtr+4 < BufferEnd) {
1897 CurPtr += 4;
1898 }
1899#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 // It has to be one of the bytes scanned, increment to it and read one.
1902 C = *CurPtr++;
1903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 // Loop to scan the remainder.
1906 while (C != '/' && C != '\0')
1907 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 FoundSlash:
1910 if (C == '/') {
1911 if (CurPtr[-2] == '*') // We found the final */. We're done!
1912 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1915 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1916 // We found the final */, though it had an escaped newline between the
1917 // * and /. We're done!
1918 break;
1919 }
1920 }
1921 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1922 // If this is a /* inside of the comment, emit a warning. Don't do this
1923 // if this is a /*/, which will end the comment. This misses cases with
1924 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001925 if (!isLexingRawMode())
1926 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 }
1928 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001929 if (PP && PP->isCodeCompletionFile(FileLoc))
1930 PP->CodeCompleteNaturalLanguage();
1931 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001932 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 // Note: the user probably forgot a */. We could continue immediately
1934 // after the /*, but this would involve lexing a lot of what really is the
1935 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001936 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Chris Lattner31f0eca2008-10-12 04:19:49 +00001938 // KeepWhitespaceMode should return this broken comment as a token. Since
1939 // it isn't a well formed comment, just return it as an 'unknown' token.
1940 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001941 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001942 return true;
1943 }
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Chris Lattner31f0eca2008-10-12 04:19:49 +00001945 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001946 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 }
1948 C = *CurPtr++;
1949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Chris Lattner3d0ad582010-02-03 21:06:21 +00001951 // Notify comment handlers about the comment unless we're in a #if 0 block.
1952 if (PP && !isLexingRawMode() &&
1953 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1954 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001955 BufferPtr = CurPtr;
1956 return true; // A token has to be returned.
1957 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001960 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001961 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001962 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 }
1964
1965 // It is common for the tokens immediately after a /**/ comment to be
1966 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001967 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1968 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001970 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001972 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 }
1974
1975 // Otherwise, just return so that the next character will be lexed as a token.
1976 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001977 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001978 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001979}
1980
1981//===----------------------------------------------------------------------===//
1982// Primary Lexing Entry Points
1983//===----------------------------------------------------------------------===//
1984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1986/// uninterpreted string. This switches the lexer out of directive mode.
1987std::string Lexer::ReadToEndOfLine() {
1988 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1989 "Must be in a preprocessing directive!");
1990 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001991 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001992
1993 // CurPtr - Cache BufferPtr in an automatic variable.
1994 const char *CurPtr = BufferPtr;
1995 while (1) {
1996 char Char = getAndAdvanceChar(CurPtr, Tmp);
1997 switch (Char) {
1998 default:
1999 Result += Char;
2000 break;
2001 case 0: // Null.
2002 // Found end of file?
2003 if (CurPtr-1 != BufferEnd) {
2004 // Nope, normal character, continue.
2005 Result += Char;
2006 break;
2007 }
2008 // FALL THROUGH.
2009 case '\r':
2010 case '\n':
2011 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2012 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2013 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Peter Collingbourne84021552011-02-28 02:37:51 +00002015 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002017 if (Tmp.is(tok::code_completion)) {
2018 if (PP && PP->getCodeCompletionHandler())
2019 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
2020 Lex(Tmp);
2021 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002022 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 // Finally, we're done, return the string we found.
2025 return Result;
2026 }
2027 }
2028}
2029
2030/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2031/// condition, reporting diagnostics and handling other edge cases as required.
2032/// This returns true if Result contains a token, false if PP.Lex should be
2033/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002034bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00002035 // Check if we are performing code completion.
2036 if (PP && PP->isCodeCompletionFile(FileLoc)) {
2037 // We're at the end of the file, but we've been asked to consider the
2038 // end of the file to be a code-completion token. Return the
2039 // code-completion token.
2040 Result.startToken();
2041 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2042
2043 // Only do the eof -> code_completion translation once.
2044 PP->SetCodeCompletionPoint(0, 0, 0);
2045
2046 // Silence any diagnostics that occur once we hit the code-completion point.
2047 PP->getDiagnostics().setSuppressAllDiagnostics(true);
2048 return true;
2049 }
2050
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 // If we hit the end of the file while parsing a preprocessor directive,
2052 // end the preprocessor directive first. The next token returned will
2053 // then be the end of file.
2054 if (ParsingPreprocessorDirective) {
2055 // Done parsing the "line".
2056 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002058 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002061 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002063 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002064
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 // If we are in raw mode, return this event as an EOF token. Let the caller
2066 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002067 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 Result.startToken();
2069 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002070 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 return true;
2072 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002073
Douglas Gregorf44e8542010-08-24 19:08:16 +00002074 // Issue diagnostics for unterminated #if and missing newline.
2075
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 // If we are in a #if directive, emit an error.
2077 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002078 if (!PP->isCodeCompletionFile(FileLoc))
2079 PP->Diag(ConditionalStack.back().IfLoc,
2080 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 ConditionalStack.pop_back();
2082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002084 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2085 // a pedwarn.
2086 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002087 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002088 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 BufferPtr = CurPtr;
2091
2092 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002093 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002094}
2095
2096/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2097/// the specified lexer will return a tok::l_paren token, 0 if it is something
2098/// else and 2 if there are no more tokens in the buffer controlled by the
2099/// lexer.
2100unsigned Lexer::isNextPPTokenLParen() {
2101 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // Switch to 'skipping' mode. This will ensure that we can lex a token
2104 // without emitting diagnostics, disables macro expansion, and will cause EOF
2105 // to return an EOF token instead of popping the include stack.
2106 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 // Save state that can be changed while lexing so that we can restore it.
2109 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002110 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Chris Lattnerd2177732007-07-20 16:59:19 +00002112 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 Tok.startToken();
2114 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 // Restore state that may have changed.
2117 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002118 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 // Restore the lexer back to non-skipping mode.
2121 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002123 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002125 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002126}
2127
Chris Lattner34f349d2009-12-14 06:16:57 +00002128/// FindConflictEnd - Find the end of a version control conflict marker.
2129static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002130 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002131 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002132 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002133 // Must occur at start of line.
2134 if (RestOfBuffer[Pos-1] != '\r' &&
2135 RestOfBuffer[Pos-1] != '\n') {
2136 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002137 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002138 continue;
2139 }
2140 return RestOfBuffer.data()+Pos;
2141 }
2142 return 0;
2143}
2144
2145/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2146/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2147/// and recover nicely. This returns true if it is a conflict marker and false
2148/// if not.
2149bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2150 // Only a conflict marker if it starts at the beginning of a line.
2151 if (CurPtr != BufferStart &&
2152 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2153 return false;
2154
2155 // Check to see if we have <<<<<<<.
2156 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002157 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002158 return false;
2159
2160 // If we have a situation where we don't care about conflict markers, ignore
2161 // it.
2162 if (IsInConflictMarker || isLexingRawMode())
2163 return false;
2164
2165 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2166 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002167 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002168 // We found a match. We are really in a conflict marker.
2169 // Diagnose this, and ignore to the end of line.
2170 Diag(CurPtr, diag::err_conflict_marker);
2171 IsInConflictMarker = true;
2172
2173 // Skip ahead to the end of line. We know this exists because the
2174 // end-of-conflict marker starts with \r or \n.
2175 while (*CurPtr != '\r' && *CurPtr != '\n') {
2176 assert(CurPtr != BufferEnd && "Didn't find end of line");
2177 ++CurPtr;
2178 }
2179 BufferPtr = CurPtr;
2180 return true;
2181 }
2182
2183 // No end of conflict marker found.
2184 return false;
2185}
2186
2187
2188/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2189/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2190/// until the end of the line. This returns true if it is a conflict marker and
2191/// false if not.
2192bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2193 // Only a conflict marker if it starts at the beginning of a line.
2194 if (CurPtr != BufferStart &&
2195 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2196 return false;
2197
2198 // If we have a situation where we don't care about conflict markers, ignore
2199 // it.
2200 if (!IsInConflictMarker || isLexingRawMode())
2201 return false;
2202
2203 // Check to see if we have the marker (7 characters in a row).
2204 for (unsigned i = 1; i != 7; ++i)
2205 if (CurPtr[i] != CurPtr[0])
2206 return false;
2207
2208 // If we do have it, search for the end of the conflict marker. This could
2209 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2210 // be the end of conflict marker.
2211 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2212 CurPtr = End;
2213
2214 // Skip ahead to the end of line.
2215 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2216 ++CurPtr;
2217
2218 BufferPtr = CurPtr;
2219
2220 // No longer in the conflict marker.
2221 IsInConflictMarker = false;
2222 return true;
2223 }
2224
2225 return false;
2226}
2227
Reid Spencer5f016e22007-07-11 17:01:13 +00002228
2229/// LexTokenInternal - This implements a simple C family lexer. It is an
2230/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002231/// has a null character at the end of the file. This returns a preprocessing
2232/// token, not a normal token, as such, it is an internal interface. It assumes
2233/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002234void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002235LexNextToken:
2236 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002237 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 // CurPtr - Cache BufferPtr in an automatic variable.
2241 const char *CurPtr = BufferPtr;
2242
2243 // Small amounts of horizontal whitespace is very common between tokens.
2244 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2245 ++CurPtr;
2246 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2247 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Chris Lattnerd88dc482008-10-12 04:05:48 +00002249 // If we are keeping whitespace and other tokens, just return what we just
2250 // skipped. The next lexer invocation will return the token after the
2251 // whitespace.
2252 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002253 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002254 return;
2255 }
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Reid Spencer5f016e22007-07-11 17:01:13 +00002257 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002258 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 }
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 // Read a character, advancing over it.
2264 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002265 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 switch (Char) {
2268 case 0: // Null.
2269 // Found end of file?
2270 if (CurPtr-1 == BufferEnd) {
2271 // Read the PP instance variable into an automatic variable, because
2272 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002273 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002274 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2275 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002276 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2277 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 }
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Chris Lattner74d15df2008-11-22 02:02:22 +00002280 if (!isLexingRawMode())
2281 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002282 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002283 if (SkipWhitespace(Result, CurPtr))
2284 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002287
2288 case 26: // DOS & CP/M EOF: "^Z".
2289 // If we're in Microsoft extensions mode, treat this as end of file.
2290 if (Features.Microsoft) {
2291 // Read the PP instance variable into an automatic variable, because
2292 // LexEndOfFile will often delete 'this'.
2293 Preprocessor *PPCache = PP;
2294 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2295 return; // Got a token to return.
2296 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2297 return PPCache->Lex(Result);
2298 }
2299 // If Microsoft extensions are disabled, this is just random garbage.
2300 Kind = tok::unknown;
2301 break;
2302
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 case '\n':
2304 case '\r':
2305 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002306 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 if (ParsingPreprocessorDirective) {
2308 // Done parsing the "line".
2309 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Reid Spencer5f016e22007-07-11 17:01:13 +00002311 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002312 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Reid Spencer5f016e22007-07-11 17:01:13 +00002314 // Since we consumed a newline, we are back at the start of a line.
2315 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Peter Collingbourne84021552011-02-28 02:37:51 +00002317 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 break;
2319 }
2320 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002321 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002322 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002323 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Chris Lattnerd88dc482008-10-12 04:05:48 +00002325 if (SkipWhitespace(Result, CurPtr))
2326 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 goto LexNextToken; // GCC isn't tail call eliminating.
2328 case ' ':
2329 case '\t':
2330 case '\f':
2331 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002332 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002333 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002334 if (SkipWhitespace(Result, CurPtr))
2335 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002336
2337 SkipIgnoredUnits:
2338 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Chris Lattner8133cfc2007-07-22 06:29:05 +00002340 // If the next token is obviously a // or /* */ comment, skip it efficiently
2341 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002342 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002343 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002344 if (SkipBCPLComment(Result, CurPtr+2))
2345 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002346 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002347 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002348 if (SkipBlockComment(Result, CurPtr+2))
2349 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002350 goto SkipIgnoredUnits;
2351 } else if (isHorizontalWhitespace(*CurPtr)) {
2352 goto SkipHorizontalWhitespace;
2353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002355
Chris Lattner3a570772008-01-03 17:58:54 +00002356 // C99 6.4.4.1: Integer Constants.
2357 // C99 6.4.4.2: Floating Constants.
2358 case '0': case '1': case '2': case '3': case '4':
2359 case '5': case '6': case '7': case '8': case '9':
2360 // Notify MIOpt that we read a non-whitespace/non-comment token.
2361 MIOpt.ReadToken();
2362 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor5cee1192011-07-27 05:40:30 +00002364 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2365 // Notify MIOpt that we read a non-whitespace/non-comment token.
2366 MIOpt.ReadToken();
2367
2368 if (Features.CPlusPlus0x) {
2369 Char = getCharAndSize(CurPtr, SizeTmp);
2370
2371 // UTF-16 string literal
2372 if (Char == '"')
2373 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2374 tok::utf16_string_literal);
2375
2376 // UTF-16 character constant
2377 if (Char == '\'')
2378 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2379 tok::utf16_char_constant);
2380
Craig Topper2fa4e862011-08-11 04:06:15 +00002381 // UTF-16 raw string literal
2382 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2383 return LexRawStringLiteral(Result,
2384 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2385 SizeTmp2, Result),
2386 tok::utf16_string_literal);
2387
2388 if (Char == '8') {
2389 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2390
2391 // UTF-8 string literal
2392 if (Char2 == '"')
2393 return LexStringLiteral(Result,
2394 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2395 SizeTmp2, Result),
2396 tok::utf8_string_literal);
2397
2398 if (Char2 == 'R') {
2399 unsigned SizeTmp3;
2400 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2401 // UTF-8 raw string literal
2402 if (Char3 == '"') {
2403 return LexRawStringLiteral(Result,
2404 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2405 SizeTmp2, Result),
2406 SizeTmp3, Result),
2407 tok::utf8_string_literal);
2408 }
2409 }
2410 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002411 }
2412
2413 // treat u like the start of an identifier.
2414 return LexIdentifier(Result, CurPtr);
2415
2416 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2417 // Notify MIOpt that we read a non-whitespace/non-comment token.
2418 MIOpt.ReadToken();
2419
2420 if (Features.CPlusPlus0x) {
2421 Char = getCharAndSize(CurPtr, SizeTmp);
2422
2423 // UTF-32 string literal
2424 if (Char == '"')
2425 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2426 tok::utf32_string_literal);
2427
2428 // UTF-32 character constant
2429 if (Char == '\'')
2430 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2431 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002432
2433 // UTF-32 raw string literal
2434 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2435 return LexRawStringLiteral(Result,
2436 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2437 SizeTmp2, Result),
2438 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002439 }
2440
2441 // treat U like the start of an identifier.
2442 return LexIdentifier(Result, CurPtr);
2443
Craig Topper2fa4e862011-08-11 04:06:15 +00002444 case 'R': // Identifier or C++0x raw string literal
2445 // Notify MIOpt that we read a non-whitespace/non-comment token.
2446 MIOpt.ReadToken();
2447
2448 if (Features.CPlusPlus0x) {
2449 Char = getCharAndSize(CurPtr, SizeTmp);
2450
2451 if (Char == '"')
2452 return LexRawStringLiteral(Result,
2453 ConsumeChar(CurPtr, SizeTmp, Result),
2454 tok::string_literal);
2455 }
2456
2457 // treat R like the start of an identifier.
2458 return LexIdentifier(Result, CurPtr);
2459
Chris Lattner3a570772008-01-03 17:58:54 +00002460 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002461 // Notify MIOpt that we read a non-whitespace/non-comment token.
2462 MIOpt.ReadToken();
2463 Char = getCharAndSize(CurPtr, SizeTmp);
2464
2465 // Wide string literal.
2466 if (Char == '"')
2467 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002468 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002469
Craig Topper2fa4e862011-08-11 04:06:15 +00002470 // Wide raw string literal.
2471 if (Features.CPlusPlus0x && Char == 'R' &&
2472 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2473 return LexRawStringLiteral(Result,
2474 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2475 SizeTmp2, Result),
2476 tok::wide_string_literal);
2477
Reid Spencer5f016e22007-07-11 17:01:13 +00002478 // Wide character constant.
2479 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002480 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2481 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002483
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 // C99 6.4.2: Identifiers.
2485 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2486 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002487 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2489 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2490 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002491 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002492 case 'v': case 'w': case 'x': case 'y': case 'z':
2493 case '_':
2494 // Notify MIOpt that we read a non-whitespace/non-comment token.
2495 MIOpt.ReadToken();
2496 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002497
2498 case '$': // $ in identifiers.
2499 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002500 if (!isLexingRawMode())
2501 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002502 // Notify MIOpt that we read a non-whitespace/non-comment token.
2503 MIOpt.ReadToken();
2504 return LexIdentifier(Result, CurPtr);
2505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Chris Lattner9e6293d2008-10-12 04:51:35 +00002507 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002508 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 // C99 6.4.4: Character Constants.
2511 case '\'':
2512 // Notify MIOpt that we read a non-whitespace/non-comment token.
2513 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002514 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002515
2516 // C99 6.4.5: String Literals.
2517 case '"':
2518 // Notify MIOpt that we read a non-whitespace/non-comment token.
2519 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002520 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002521
2522 // C99 6.4.6: Punctuators.
2523 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002524 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002525 break;
2526 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002527 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 break;
2529 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002530 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 break;
2532 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002533 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 break;
2535 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002536 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002537 break;
2538 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002539 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002540 break;
2541 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002542 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002543 break;
2544 case '.':
2545 Char = getCharAndSize(CurPtr, SizeTmp);
2546 if (Char >= '0' && Char <= '9') {
2547 // Notify MIOpt that we read a non-whitespace/non-comment token.
2548 MIOpt.ReadToken();
2549
2550 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2551 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002552 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 CurPtr += SizeTmp;
2554 } else if (Char == '.' &&
2555 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002556 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2558 SizeTmp2, Result);
2559 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002560 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 }
2562 break;
2563 case '&':
2564 Char = getCharAndSize(CurPtr, SizeTmp);
2565 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002566 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2568 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002569 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2571 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002572 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 }
2574 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002575 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002577 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2579 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002580 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002581 }
2582 break;
2583 case '+':
2584 Char = getCharAndSize(CurPtr, SizeTmp);
2585 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002587 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002590 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002591 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002592 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 }
2594 break;
2595 case '-':
2596 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002597 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002599 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002600 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002601 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2603 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002604 Kind = tok::arrowstar;
2605 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002607 Kind = tok::arrow;
2608 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002609 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002610 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002612 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 }
2614 break;
2615 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002616 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 break;
2618 case '!':
2619 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002620 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2622 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002623 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 }
2625 break;
2626 case '/':
2627 // 6.4.9: Comments
2628 Char = getCharAndSize(CurPtr, SizeTmp);
2629 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002630 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2631 // want to lex this as a comment. There is one problem with this though,
2632 // that in one particular corner case, this can change the behavior of the
2633 // resultant program. For example, In "foo //**/ bar", C89 would lex
2634 // this as "foo / bar" and langauges with BCPL comments would lex it as
2635 // "foo". Check to see if the character after the second slash is a '*'.
2636 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002637 // However, we never do this in -traditional-cpp mode.
2638 if ((Features.BCPLComment ||
2639 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2640 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002641 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002642 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Chris Lattner8402c732009-01-16 22:39:25 +00002644 // It is common for the tokens immediately after a // comment to be
2645 // whitespace (indentation for the next line). Instead of going through
2646 // the big switch, handle it efficiently now.
2647 goto SkipIgnoredUnits;
2648 }
2649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Chris Lattner8402c732009-01-16 22:39:25 +00002651 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002653 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002654 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002655 }
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Chris Lattner8402c732009-01-16 22:39:25 +00002657 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002658 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002659 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002661 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 }
2663 break;
2664 case '%':
2665 Char = getCharAndSize(CurPtr, SizeTmp);
2666 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002667 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2669 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002670 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2672 } else if (Features.Digraphs && Char == ':') {
2673 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2674 Char = getCharAndSize(CurPtr, SizeTmp);
2675 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002676 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2678 SizeTmp2, Result);
2679 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002681 if (!isLexingRawMode())
2682 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002683 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002684 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 // We parsed a # character. If this occurs at the start of the line,
2686 // it's actually the start of a preprocessing directive. Callback to
2687 // the preprocessor to handle it.
2688 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002689 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002690 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002691 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 // As an optimization, if the preprocessor didn't switch lexers, tail
2694 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002695 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 // Start a new token. If this is a #include or something, the PP may
2697 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002698 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002700 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002701 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 IsAtStartOfLine = false;
2703 }
2704 goto LexNextToken; // GCC isn't tail call eliminating.
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattner168ae2d2007-10-17 20:41:00 +00002707 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 }
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Chris Lattnere91e9322009-03-18 20:58:27 +00002710 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 }
2712 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002713 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 }
2715 break;
2716 case '<':
2717 Char = getCharAndSize(CurPtr, SizeTmp);
2718 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002719 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002721 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2722 if (After == '=') {
2723 Kind = tok::lesslessequal;
2724 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2725 SizeTmp2, Result);
2726 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2727 // If this is actually a '<<<<<<<' version control conflict marker,
2728 // recognize it as such and recover nicely.
2729 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002730 } else if (Features.CUDA && After == '<') {
2731 Kind = tok::lesslessless;
2732 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2733 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002734 } else {
2735 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2736 Kind = tok::lessless;
2737 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002739 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002740 Kind = tok::lessequal;
2741 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002742 if (Features.CPlusPlus0x &&
2743 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2744 // C++0x [lex.pptoken]p3:
2745 // Otherwise, if the next three characters are <:: and the subsequent
2746 // character is neither : nor >, the < is treated as a preprocessor
2747 // token by itself and not as the first character of the alternative
2748 // token <:.
2749 unsigned SizeTmp3;
2750 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2751 if (After != ':' && After != '>') {
2752 Kind = tok::less;
2753 break;
2754 }
2755 }
2756
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002758 Kind = tok::l_square;
2759 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002761 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002763 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 }
2765 break;
2766 case '>':
2767 Char = getCharAndSize(CurPtr, SizeTmp);
2768 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002770 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002772 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2773 if (After == '=') {
2774 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2775 SizeTmp2, Result);
2776 Kind = tok::greatergreaterequal;
2777 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2778 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2779 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002780 } else if (Features.CUDA && After == '>') {
2781 Kind = tok::greatergreatergreater;
2782 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2783 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002784 } else {
2785 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2786 Kind = tok::greatergreater;
2787 }
2788
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002790 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 }
2792 break;
2793 case '^':
2794 Char = getCharAndSize(CurPtr, SizeTmp);
2795 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002797 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002799 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 }
2801 break;
2802 case '|':
2803 Char = getCharAndSize(CurPtr, SizeTmp);
2804 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002805 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2807 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002808 // If this is '|||||||' and we're in a conflict marker, ignore it.
2809 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2810 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002811 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2813 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002814 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002815 }
2816 break;
2817 case ':':
2818 Char = getCharAndSize(CurPtr, SizeTmp);
2819 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002820 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2822 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002823 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002825 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002826 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
2828 break;
2829 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002830 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 break;
2832 case '=':
2833 Char = getCharAndSize(CurPtr, SizeTmp);
2834 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002835 // If this is '=======' and we're in a conflict marker, ignore it.
2836 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2837 goto LexNextToken;
2838
Chris Lattner9e6293d2008-10-12 04:51:35 +00002839 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002841 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002842 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 }
2844 break;
2845 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002846 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 break;
2848 case '#':
2849 Char = getCharAndSize(CurPtr, SizeTmp);
2850 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002851 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002852 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2853 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002854 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002855 if (!isLexingRawMode())
2856 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2858 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 // We parsed a # character. If this occurs at the start of the line,
2860 // it's actually the start of a preprocessing directive. Callback to
2861 // the preprocessor to handle it.
2862 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002863 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002864 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002865 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 // As an optimization, if the preprocessor didn't switch lexers, tail
2868 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002869 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 // Start a new token. If this is a #include or something, the PP may
2871 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002872 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002874 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002875 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 IsAtStartOfLine = false;
2877 }
2878 goto LexNextToken; // GCC isn't tail call eliminating.
2879 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002880 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Chris Lattnere91e9322009-03-18 20:58:27 +00002883 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002884 }
2885 break;
2886
Chris Lattner3a570772008-01-03 17:58:54 +00002887 case '@':
2888 // Objective C support.
2889 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002890 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002891 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002892 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002893 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Reid Spencer5f016e22007-07-11 17:01:13 +00002895 case '\\':
2896 // FIXME: UCN's.
2897 // FALL THROUGH.
2898 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002899 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 break;
2901 }
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Reid Spencer5f016e22007-07-11 17:01:13 +00002903 // Notify MIOpt that we read a non-whitespace/non-comment token.
2904 MIOpt.ReadToken();
2905
2906 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002907 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002908}