blob: 0c32c8d9bafa8d1f86436a1d261b73144c064df1 [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
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000419SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
420 const SourceManager &SM,
421 const LangOptions &LangOpts) {
422 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000423 if (LocInfo.first.isInvalid())
424 return Loc;
425
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000426 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000427 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000428 if (Invalid)
429 return Loc;
430
431 // Back up from the current location until we hit the beginning of a line
432 // (or the buffer). We'll relex from that point.
433 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000434 if (LocInfo.second >= Buffer.size())
435 return Loc;
436
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000437 const char *StrData = BufStart+LocInfo.second;
438 if (StrData[0] == '\n' || StrData[0] == '\r')
439 return Loc;
440
441 const char *LexStart = StrData;
442 while (LexStart != BufStart) {
443 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
444 ++LexStart;
445 break;
446 }
447
448 --LexStart;
449 }
450
451 // Create a lexer starting at the beginning of this token.
452 SourceLocation LexerStartLoc = Loc.getFileLocWithOffset(-LocInfo.second);
453 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
454 TheLexer.SetCommentRetentionState(true);
455
456 // Lex tokens until we find the token that contains the source location.
457 Token TheTok;
458 do {
459 TheLexer.LexFromRawLexer(TheTok);
460
461 if (TheLexer.getBufferLocation() > StrData) {
462 // Lexing this token has taken the lexer past the source location we're
463 // looking for. If the current token encompasses our source location,
464 // return the beginning of that token.
465 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
466 return TheTok.getLocation();
467
468 // We ended up skipping over the source location entirely, which means
469 // that it points into whitespace. We're done here.
470 break;
471 }
472 } while (TheTok.getKind() != tok::eof);
473
474 // We've passed our source location; just return the original source location.
475 return Loc;
476}
477
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000478namespace {
479 enum PreambleDirectiveKind {
480 PDK_Skipped,
481 PDK_StartIf,
482 PDK_EndIf,
483 PDK_Unknown
484 };
485}
486
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000487std::pair<unsigned, bool>
Douglas Gregordf95a132010-08-09 20:45:32 +0000488Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000489 // Create a lexer starting at the beginning of the file. Note that we use a
490 // "fake" file source location at offset 1 so that the lexer will track our
491 // position within the file.
492 const unsigned StartOffset = 1;
493 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
494 LangOptions LangOpts;
495 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
496 Buffer->getBufferStart(), Buffer->getBufferEnd());
497
498 bool InPreprocessorDirective = false;
499 Token TheTok;
500 Token IfStartTok;
501 unsigned IfCount = 0;
Douglas Gregordf95a132010-08-09 20:45:32 +0000502 unsigned Line = 0;
503
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000504 do {
505 TheLexer.LexFromRawLexer(TheTok);
506
507 if (InPreprocessorDirective) {
508 // If we've hit the end of the file, we're done.
509 if (TheTok.getKind() == tok::eof) {
510 InPreprocessorDirective = false;
511 break;
512 }
513
514 // If we haven't hit the end of the preprocessor directive, skip this
515 // token.
516 if (!TheTok.isAtStartOfLine())
517 continue;
518
519 // We've passed the end of the preprocessor directive, and will look
520 // at this token again below.
521 InPreprocessorDirective = false;
522 }
523
Douglas Gregordf95a132010-08-09 20:45:32 +0000524 // Keep track of the # of lines in the preamble.
525 if (TheTok.isAtStartOfLine()) {
526 ++Line;
527
528 // If we were asked to limit the number of lines in the preamble,
529 // and we're about to exceed that limit, we're done.
530 if (MaxLines && Line >= MaxLines)
531 break;
532 }
533
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000534 // Comments are okay; skip over them.
535 if (TheTok.getKind() == tok::comment)
536 continue;
537
538 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
539 // This is the start of a preprocessor directive.
540 Token HashTok = TheTok;
541 InPreprocessorDirective = true;
542
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000543 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000544 // we don't have an identifier table available. Instead, just look at
545 // the raw identifier to recognize and categorize preprocessor directives.
546 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000547 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000548 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000549 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000550 PreambleDirectiveKind PDK
551 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
552 .Case("include", PDK_Skipped)
553 .Case("__include_macros", PDK_Skipped)
554 .Case("define", PDK_Skipped)
555 .Case("undef", PDK_Skipped)
556 .Case("line", PDK_Skipped)
557 .Case("error", PDK_Skipped)
558 .Case("pragma", PDK_Skipped)
559 .Case("import", PDK_Skipped)
560 .Case("include_next", PDK_Skipped)
561 .Case("warning", PDK_Skipped)
562 .Case("ident", PDK_Skipped)
563 .Case("sccs", PDK_Skipped)
564 .Case("assert", PDK_Skipped)
565 .Case("unassert", PDK_Skipped)
566 .Case("if", PDK_StartIf)
567 .Case("ifdef", PDK_StartIf)
568 .Case("ifndef", PDK_StartIf)
569 .Case("elif", PDK_Skipped)
570 .Case("else", PDK_Skipped)
571 .Case("endif", PDK_EndIf)
572 .Default(PDK_Unknown);
573
574 switch (PDK) {
575 case PDK_Skipped:
576 continue;
577
578 case PDK_StartIf:
579 if (IfCount == 0)
580 IfStartTok = HashTok;
581
582 ++IfCount;
583 continue;
584
585 case PDK_EndIf:
586 // Mismatched #endif. The preamble ends here.
587 if (IfCount == 0)
588 break;
589
590 --IfCount;
591 continue;
592
593 case PDK_Unknown:
594 // We don't know what this directive is; stop at the '#'.
595 break;
596 }
597 }
598
599 // We only end up here if we didn't recognize the preprocessor
600 // directive or it was one that can't occur in the preamble at this
601 // point. Roll back the current token to the location of the '#'.
602 InPreprocessorDirective = false;
603 TheTok = HashTok;
604 }
605
Douglas Gregordf95a132010-08-09 20:45:32 +0000606 // We hit a token that we don't recognize as being in the
607 // "preprocessing only" part of the file, so we're no longer in
608 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000609 break;
610 } while (true);
611
612 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000613 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
614 IfCount? IfStartTok.isAtStartOfLine()
615 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000616}
617
Chris Lattner7ef5c272010-11-17 07:05:50 +0000618
619/// AdvanceToTokenCharacter - Given a location that specifies the start of a
620/// token, return a new location that specifies a character within the token.
621SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
622 unsigned CharNo,
623 const SourceManager &SM,
624 const LangOptions &Features) {
Chandler Carruth433db062011-07-14 08:20:40 +0000625 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000626 // character is. This needs to take into consideration newlines and
627 // trigraphs.
628 bool Invalid = false;
629 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
630
631 // If they request the first char of the token, we're trivially done.
632 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
633 return TokStart;
634
635 unsigned PhysOffset = 0;
636
637 // The usual case is that tokens don't contain anything interesting. Skip
638 // over the uninteresting characters. If a token only consists of simple
639 // chars, this method is extremely fast.
640 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
641 if (CharNo == 0)
642 return TokStart.getFileLocWithOffset(PhysOffset);
643 ++TokPtr, --CharNo, ++PhysOffset;
644 }
645
646 // If we have a character that may be a trigraph or escaped newline, use a
647 // lexer to parse it correctly.
648 for (; CharNo; --CharNo) {
649 unsigned Size;
650 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
651 TokPtr += Size;
652 PhysOffset += Size;
653 }
654
655 // Final detail: if we end up on an escaped newline, we want to return the
656 // location of the actual byte of the token. For example foo\<newline>bar
657 // advanced by 3 should return the location of b, not of \\. One compounding
658 // detail of this is that the escape may be made by a trigraph.
659 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
660 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
661
662 return TokStart.getFileLocWithOffset(PhysOffset);
663}
664
665/// \brief Computes the source location just past the end of the
666/// token at this source location.
667///
668/// This routine can be used to produce a source location that
669/// points just past the end of the token referenced by \p Loc, and
670/// is generally used when a diagnostic needs to point just after a
671/// token where it expected something different that it received. If
672/// the returned source location would not be meaningful (e.g., if
673/// it points into a macro), this routine returns an invalid
674/// source location.
675///
676/// \param Offset an offset from the end of the token, where the source
677/// location should refer to. The default offset (0) produces a source
678/// location pointing just past the end of the token; an offset of 1 produces
679/// a source location pointing to the last character in the token, etc.
680SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
681 const SourceManager &SM,
682 const LangOptions &Features) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000683 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000684 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000685
686 if (Loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000687 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
688 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000689
Chandler Carruth433db062011-07-14 08:20:40 +0000690 // Continue and find the location just after the macro expansion.
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000691 Loc = SM.getExpansionRange(Loc).second;
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000692 }
693
Chris Lattner7ef5c272010-11-17 07:05:50 +0000694 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features);
695 if (Len > Offset)
696 Len = Len - Offset;
697 else
698 return Loc;
699
John McCall77ebb382011-04-06 01:50:22 +0000700 return Loc.getFileLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000701}
702
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000703/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000704/// token of the macro expansion.
705bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000706 const SourceManager &SM,
707 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000708 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
709
710 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
711 // FIXME: If the token comes from the macro token paste operator ('##')
712 // this function will always return false;
713 if (infoLoc.second > 0)
714 return false; // Does not point at the start of token.
715
Chandler Carruth433db062011-07-14 08:20:40 +0000716 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000717 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Chandler Carruth433db062011-07-14 08:20:40 +0000718 if (expansionLoc.isFileID())
719 return true; // No other macro expansions, this is the first.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000720
Chandler Carruth433db062011-07-14 08:20:40 +0000721 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000722}
723
724/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000725/// token of the macro expansion.
726bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000727 const SourceManager &SM,
728 const LangOptions &LangOpts) {
729 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
730
731 SourceLocation spellLoc = SM.getSpellingLoc(loc);
732 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
733 if (tokLen == 0)
734 return false;
735
736 FileID FID = SM.getFileID(loc);
737 SourceLocation afterLoc = loc.getFileLocWithOffset(tokLen+1);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000738 if (!SM.isBeforeInSourceLocationOffset(afterLoc, SM.getNextLocalOffset()))
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000739 return true; // We got past the last FileID, this points to the last token.
740
741 // FIXME: If the token comes from the macro token paste operator ('##')
742 // or the stringify operator ('#') this function will always return false;
743 if (FID == SM.getFileID(afterLoc))
744 return false; // Still in the same FileID, does not point to the last token.
745
Chandler Carruth433db062011-07-14 08:20:40 +0000746 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000747 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Chandler Carruth433db062011-07-14 08:20:40 +0000748 if (expansionLoc.isFileID())
749 return true; // No other macro expansions.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000750
Chandler Carruth433db062011-07-14 08:20:40 +0000751 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000752}
753
Reid Spencer5f016e22007-07-11 17:01:13 +0000754//===----------------------------------------------------------------------===//
755// Character information.
756//===----------------------------------------------------------------------===//
757
Reid Spencer5f016e22007-07-11 17:01:13 +0000758enum {
759 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
760 CHAR_VERT_WS = 0x02, // '\r', '\n'
761 CHAR_LETTER = 0x04, // a-z,A-Z
762 CHAR_NUMBER = 0x08, // 0-9
763 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +0000764 CHAR_PERIOD = 0x20, // .
765 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +0000766};
767
Chris Lattner03b98662009-07-07 17:09:54 +0000768// Statically initialize CharInfo table based on ASCII character set
769// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +0000770static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +0000771{
772// 0 NUL 1 SOH 2 STX 3 ETX
773// 4 EOT 5 ENQ 6 ACK 7 BEL
774 0 , 0 , 0 , 0 ,
775 0 , 0 , 0 , 0 ,
776// 8 BS 9 HT 10 NL 11 VT
777//12 NP 13 CR 14 SO 15 SI
778 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
779 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
780//16 DLE 17 DC1 18 DC2 19 DC3
781//20 DC4 21 NAK 22 SYN 23 ETB
782 0 , 0 , 0 , 0 ,
783 0 , 0 , 0 , 0 ,
784//24 CAN 25 EM 26 SUB 27 ESC
785//28 FS 29 GS 30 RS 31 US
786 0 , 0 , 0 , 0 ,
787 0 , 0 , 0 , 0 ,
788//32 SP 33 ! 34 " 35 #
789//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +0000790 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
791 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000792//40 ( 41 ) 42 * 43 +
793//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +0000794 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
795 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000796//48 0 49 1 50 2 51 3
797//52 4 53 5 54 6 55 7
798 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
799 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
800//56 8 57 9 58 : 59 ;
801//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +0000802 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
803 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +0000804//64 @ 65 A 66 B 67 C
805//68 D 69 E 70 F 71 G
806 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
807 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
808//72 H 73 I 74 J 75 K
809//76 L 77 M 78 N 79 O
810 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
811 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
812//80 P 81 Q 82 R 83 S
813//84 T 85 U 86 V 87 W
814 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
815 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
816//88 X 89 Y 90 Z 91 [
817//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +0000818 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
819 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +0000820//96 ` 97 a 98 b 99 c
821//100 d 101 e 102 f 103 g
822 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
823 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
824//104 h 105 i 106 j 107 k
825//108 l 109 m 110 n 111 o
826 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
827 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
828//112 p 113 q 114 r 115 s
829//116 t 117 u 118 v 119 w
830 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
831 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
832//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +0000833//124 | 125 } 126 ~ 127 DEL
834 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
835 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +0000836};
837
Chris Lattnera2bf1052009-12-17 05:29:40 +0000838static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000839 static bool isInited = false;
840 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +0000841 // check the statically-initialized CharInfo table
842 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
843 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
844 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
845 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
846 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
847 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
848 assert(CHAR_UNDER == CharInfo[(int)'_']);
849 assert(CHAR_PERIOD == CharInfo[(int)'.']);
850 for (unsigned i = 'a'; i <= 'z'; ++i) {
851 assert(CHAR_LETTER == CharInfo[i]);
852 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
853 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +0000855 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +0000856
Chris Lattner03b98662009-07-07 17:09:54 +0000857 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000858}
859
Chris Lattner03b98662009-07-07 17:09:54 +0000860
Reid Spencer5f016e22007-07-11 17:01:13 +0000861/// isIdentifierBody - Return true if this is the body character of an
862/// identifier, which is [a-zA-Z0-9_].
863static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000864 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000865}
866
867/// isHorizontalWhitespace - Return true if this character is horizontal
868/// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
869static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000870 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000871}
872
Anna Zaksaca25bc2011-07-27 21:43:43 +0000873/// isVerticalWhitespace - Return true if this character is vertical
874/// whitespace: '\n', '\r'. Note that this returns false for '\0'.
875static inline bool isVerticalWhitespace(unsigned char c) {
876 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
877}
878
Reid Spencer5f016e22007-07-11 17:01:13 +0000879/// isWhitespace - Return true if this character is horizontal or vertical
880/// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
881/// for '\0'.
882static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000883 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000884}
885
886/// isNumberBody - Return true if this is the body character of an
887/// preprocessing number, which is [a-zA-Z0-9_.].
888static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +0000889 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +0000890 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
892
Craig Topper2fa4e862011-08-11 04:06:15 +0000893/// isRawStringDelimBody - Return true if this is the body character of a
894/// raw string delimiter.
895static inline bool isRawStringDelimBody(unsigned char c) {
896 return (CharInfo[c] &
897 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
898 true : false;
899}
900
Reid Spencer5f016e22007-07-11 17:01:13 +0000901
902//===----------------------------------------------------------------------===//
903// Diagnostics forwarding code.
904//===----------------------------------------------------------------------===//
905
Chris Lattner409a0362007-07-22 18:38:25 +0000906/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +0000907/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +0000908/// This is currently only used for _Pragma implementation, so it is the slow
909/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +0000910static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
911 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000912static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
913 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000914 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +0000915 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner409a0362007-07-22 18:38:25 +0000917 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +0000918 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000919 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000920 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chandler Carruth433db062011-07-14 08:20:40 +0000922 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000923 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000924 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000925 SpellingLoc = SpellingLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattnere7fb4842009-02-15 20:52:18 +0000927 // Figure out the expansion loc range, which is the range covered by the
928 // original _Pragma(...) sequence.
929 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +0000930 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Chandler Carruthbf340e42011-07-26 03:03:05 +0000932 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +0000933}
934
Reid Spencer5f016e22007-07-11 17:01:13 +0000935/// getSourceLocation - Return a source location identifier for the specified
936/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000937SourceLocation Lexer::getSourceLocation(const char *Loc,
938 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +0000939 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +0000941
942 // In the normal case, we're just lexing from a simple file buffer, return
943 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +0000944 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +0000945 if (FileLoc.isFileID())
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000946 return FileLoc.getFileLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner2b2453a2009-01-17 06:22:33 +0000948 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
949 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +0000950 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000951 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +0000952}
953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954/// Diag - Forwarding function for diagnostics. This translate a source
955/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +0000956DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +0000957 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000958}
Reid Spencer5f016e22007-07-11 17:01:13 +0000959
960//===----------------------------------------------------------------------===//
961// Trigraph and Escaped Newline Handling Code.
962//===----------------------------------------------------------------------===//
963
964/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
965/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
966static char GetTrigraphCharForLetter(char Letter) {
967 switch (Letter) {
968 default: return 0;
969 case '=': return '#';
970 case ')': return ']';
971 case '(': return '[';
972 case '!': return '|';
973 case '\'': return '^';
974 case '>': return '}';
975 case '/': return '\\';
976 case '<': return '{';
977 case '-': return '~';
978 }
979}
980
981/// DecodeTrigraphChar - If the specified character is a legal trigraph when
982/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
983/// return the result character. Finally, emit a warning about trigraph use
984/// whether trigraphs are enabled or not.
985static char DecodeTrigraphChar(const char *CP, Lexer *L) {
986 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +0000987 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner3692b092008-11-18 07:59:24 +0000989 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +0000990 if (!L->isLexingRawMode())
991 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +0000992 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner74d15df2008-11-22 02:02:22 +0000995 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000996 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 return Res;
998}
999
Chris Lattner24f0e482009-04-18 22:05:41 +00001000/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1001/// 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 +00001002/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001003unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1004 unsigned Size = 0;
1005 while (isWhitespace(Ptr[Size])) {
1006 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner24f0e482009-04-18 22:05:41 +00001008 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1009 continue;
1010
1011 // If this is a \r\n or \n\r, skip the other half.
1012 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1013 Ptr[Size-1] != Ptr[Size])
1014 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner24f0e482009-04-18 22:05:41 +00001016 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001017 }
1018
Chris Lattner24f0e482009-04-18 22:05:41 +00001019 // Not an escaped newline, must be a \t or something else.
1020 return 0;
1021}
1022
Chris Lattner03374952009-04-18 22:27:02 +00001023/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1024/// them), skip over them and return the first non-escaped-newline found,
1025/// otherwise return P.
1026const char *Lexer::SkipEscapedNewLines(const char *P) {
1027 while (1) {
1028 const char *AfterEscape;
1029 if (*P == '\\') {
1030 AfterEscape = P+1;
1031 } else if (*P == '?') {
1032 // If not a trigraph for escape, bail out.
1033 if (P[1] != '?' || P[2] != '/')
1034 return P;
1035 AfterEscape = P+3;
1036 } else {
1037 return P;
1038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Chris Lattner03374952009-04-18 22:27:02 +00001040 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1041 if (NewLineSize == 0) return P;
1042 P = AfterEscape+NewLineSize;
1043 }
1044}
1045
Anna Zaksaca25bc2011-07-27 21:43:43 +00001046/// \brief Checks that the given token is the first token that occurs after the
1047/// given location (this excludes comments and whitespace). Returns the location
1048/// immediately after the specified token. If the token is not found or the
1049/// location is inside a macro, the returned source location will be invalid.
1050SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1051 tok::TokenKind TKind,
1052 const SourceManager &SM,
1053 const LangOptions &LangOpts,
1054 bool SkipTrailingWhitespaceAndNewLine) {
1055 if (Loc.isMacroID()) {
1056 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
1057 return SourceLocation();
1058 Loc = SM.getExpansionRange(Loc).second;
1059 }
1060 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1061
1062 // Break down the source location.
1063 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1064
1065 // Try to load the file buffer.
1066 bool InvalidTemp = false;
1067 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1068 if (InvalidTemp)
1069 return SourceLocation();
1070
1071 const char *TokenBegin = File.data() + LocInfo.second;
1072
1073 // Lex from the start of the given location.
1074 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1075 TokenBegin, File.end());
1076 // Find the token.
1077 Token Tok;
1078 lexer.LexFromRawLexer(Tok);
1079 if (Tok.isNot(TKind))
1080 return SourceLocation();
1081 SourceLocation TokenLoc = Tok.getLocation();
1082
1083 // Calculate how much whitespace needs to be skipped if any.
1084 unsigned NumWhitespaceChars = 0;
1085 if (SkipTrailingWhitespaceAndNewLine) {
1086 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1087 Tok.getLength();
1088 unsigned char C = *TokenEnd;
1089 while (isHorizontalWhitespace(C)) {
1090 C = *(++TokenEnd);
1091 NumWhitespaceChars++;
1092 }
1093 if (isVerticalWhitespace(C))
1094 NumWhitespaceChars++;
1095 }
1096
1097 return TokenLoc.getFileLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1098}
Chris Lattner24f0e482009-04-18 22:05:41 +00001099
Reid Spencer5f016e22007-07-11 17:01:13 +00001100/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1101/// get its size, and return it. This is tricky in several cases:
1102/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1103/// then either return the trigraph (skipping 3 chars) or the '?',
1104/// depending on whether trigraphs are enabled or not.
1105/// 2. If this is an escaped newline (potentially with whitespace between
1106/// the backslash and newline), implicitly skip the newline and return
1107/// the char after it.
1108/// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1109///
1110/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1111/// know that we can accumulate into Size, and that we have already incremented
1112/// Ptr by Size bytes.
1113///
1114/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1115/// be updated to match.
1116///
1117char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001118 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 // If we have a slash, look for an escaped newline.
1120 if (Ptr[0] == '\\') {
1121 ++Size;
1122 ++Ptr;
1123Slash:
1124 // Common case, backslash-char where the char is not whitespace.
1125 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattner5636a3b2009-06-23 05:15:06 +00001127 // See if we have optional whitespace characters between the slash and
1128 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001129 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1130 // Remember that this token needs to be cleaned.
1131 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
Chris Lattner24f0e482009-04-18 22:05:41 +00001133 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001134 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001135 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner24f0e482009-04-18 22:05:41 +00001137 // Found backslash<whitespace><newline>. Parse the char after it.
1138 Size += EscapedNewLineSize;
1139 Ptr += EscapedNewLineSize;
1140 // Use slow version to accumulate a correct size field.
1141 return getCharAndSizeSlow(Ptr, Size, Tok);
1142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 // Otherwise, this is not an escaped newline, just return the slash.
1145 return '\\';
1146 }
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 // If this is a trigraph, process it.
1149 if (Ptr[0] == '?' && Ptr[1] == '?') {
1150 // If this is actually a legal trigraph (not something like "??x"), emit
1151 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1152 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1153 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001154 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156 Ptr += 3;
1157 Size += 3;
1158 if (C == '\\') goto Slash;
1159 return C;
1160 }
1161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 // If this is neither, return a single character.
1164 ++Size;
1165 return *Ptr;
1166}
1167
1168
1169/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1170/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1171/// and that we have already incremented Ptr by Size bytes.
1172///
1173/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1174/// be updated to match.
1175char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1176 const LangOptions &Features) {
1177 // If we have a slash, look for an escaped newline.
1178 if (Ptr[0] == '\\') {
1179 ++Size;
1180 ++Ptr;
1181Slash:
1182 // Common case, backslash-char where the char is not whitespace.
1183 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001186 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1187 // Found backslash<whitespace><newline>. Parse the char after it.
1188 Size += EscapedNewLineSize;
1189 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chris Lattner24f0e482009-04-18 22:05:41 +00001191 // Use slow version to accumulate a correct size field.
1192 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // Otherwise, this is not an escaped newline, just return the slash.
1196 return '\\';
1197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // If this is a trigraph, process it.
1200 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1201 // If this is actually a legal trigraph (not something like "??x"), return
1202 // it.
1203 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1204 Ptr += 3;
1205 Size += 3;
1206 if (C == '\\') goto Slash;
1207 return C;
1208 }
1209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 // If this is neither, return a single character.
1212 ++Size;
1213 return *Ptr;
1214}
1215
1216//===----------------------------------------------------------------------===//
1217// Helper methods for lexing.
1218//===----------------------------------------------------------------------===//
1219
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001220/// \brief Routine that indiscriminately skips bytes in the source file.
1221void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1222 BufferPtr += Bytes;
1223 if (BufferPtr > BufferEnd)
1224 BufferPtr = BufferEnd;
1225 IsAtStartOfLine = StartOfLine;
1226}
1227
Chris Lattnerd2177732007-07-20 16:59:19 +00001228void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1230 unsigned Size;
1231 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001232 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 --CurPtr; // Back up over the skipped character.
1236
1237 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1238 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1239 // FIXME: UCNs.
Chris Lattnercd991db2010-01-11 02:38:50 +00001240 //
1241 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1242 // cheaper
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) {
1244FinishIdentifier:
1245 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001246 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1247 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // If we are in raw mode, return this identifier raw. There is no need to
1250 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001251 if (LexingRawMode)
1252 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001254 // Fill in Result.IdentifierInfo and update the token kind,
1255 // looking up the identifier in the identifier table.
1256 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 // Finally, now that we know we have an identifier, pass this off to the
1259 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001260 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001261 PP->HandleIdentifier(Result);
1262 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 C = getCharAndSize(CurPtr, Size);
1268 while (1) {
1269 if (C == '$') {
1270 // If we hit a $ and they are not supported in identifiers, we are done.
1271 if (!Features.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001274 if (!isLexingRawMode())
1275 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 CurPtr = ConsumeChar(CurPtr, Size, Result);
1277 C = getCharAndSize(CurPtr, Size);
1278 continue;
1279 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1280 // Found end of identifier.
1281 goto FinishIdentifier;
1282 }
1283
1284 // Otherwise, this character is good, consume it.
1285 CurPtr = ConsumeChar(CurPtr, Size, Result);
1286
1287 C = getCharAndSize(CurPtr, Size);
1288 while (isIdentifierBody(C)) { // FIXME: UCNs.
1289 CurPtr = ConsumeChar(CurPtr, Size, Result);
1290 C = getCharAndSize(CurPtr, Size);
1291 }
1292 }
1293}
1294
Douglas Gregora75ec432010-08-30 14:50:47 +00001295/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001296/// in microsoft mode (where this is supposed to be several different tokens).
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001297static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
1298 unsigned Size;
1299 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features);
1300 if (C1 != '0')
1301 return false;
1302 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
1303 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001304}
Reid Spencer5f016e22007-07-11 17:01:13 +00001305
Nate Begeman5253c7f2008-04-14 02:26:39 +00001306/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001307/// constant. From[-1] is the first character lexed. Return the end of the
1308/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001309void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 unsigned Size;
1311 char C = getCharAndSize(CurPtr, Size);
1312 char PrevCh = 0;
1313 while (isNumberBody(C)) { // FIXME: UCNs?
1314 CurPtr = ConsumeChar(CurPtr, Size, Result);
1315 PrevCh = C;
1316 C = getCharAndSize(CurPtr, Size);
1317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001320 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1321 // If we are in Microsoft mode, don't continue if the constant is hex.
1322 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001323 if (!Features.Microsoft || !isHexaLiteral(BufferPtr, Features))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001324 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1325 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
1327 // If we have a hex FP constant, continue.
Sean Hunt8c723402010-01-10 23:37:56 +00001328 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p') &&
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001329 !Features.CPlusPlus0x)
Reid Spencer5f016e22007-07-11 17:01:13 +00001330 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001333 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001334 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001335 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001336}
1337
1338/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001339/// either " or L" or u8" or u" or U".
1340void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1341 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 char C = getAndAdvanceChar(CurPtr, Result);
1345 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001346 // Skip escaped characters. Escaped newlines will already be processed by
1347 // getAndAdvanceChar.
1348 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001350
Chris Lattner571339c2010-05-30 23:27:38 +00001351 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001352 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001353 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1354 PP->CodeCompleteNaturalLanguage();
1355 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001356 Diag(BufferPtr, diag::warn_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001357 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 }
Chris Lattner571339c2010-05-30 23:27:38 +00001360
1361 if (C == 0)
1362 NulCharacter = CurPtr-1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 C = getAndAdvanceChar(CurPtr, Result);
1364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001367 if (NulCharacter && !isLexingRawMode())
1368 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001371 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001372 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001373 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001374}
1375
Craig Topper2fa4e862011-08-11 04:06:15 +00001376/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1377/// having lexed R", LR", u8R", uR", or UR".
1378void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1379 tok::TokenKind Kind) {
1380 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1381 // Between the initial and final double quote characters of the raw string,
1382 // any transformations performed in phases 1 and 2 (trigraphs,
1383 // universal-character-names, and line splicing) are reverted.
1384
1385 unsigned PrefixLen = 0;
1386
1387 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1388 ++PrefixLen;
1389
1390 // If the last character was not a '(', then we didn't lex a valid delimiter.
1391 if (CurPtr[PrefixLen] != '(') {
1392 if (!isLexingRawMode()) {
1393 const char *PrefixEnd = &CurPtr[PrefixLen];
1394 if (PrefixLen == 16) {
1395 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1396 } else {
1397 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1398 << StringRef(PrefixEnd, 1);
1399 }
1400 }
1401
1402 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1403 // it's possible the '"' was intended to be part of the raw string, but
1404 // there's not much we can do about that.
1405 while (1) {
1406 char C = *CurPtr++;
1407
1408 if (C == '"')
1409 break;
1410 if (C == 0 && CurPtr-1 == BufferEnd) {
1411 --CurPtr;
1412 break;
1413 }
1414 }
1415
1416 FormTokenWithChars(Result, CurPtr, tok::unknown);
1417 return;
1418 }
1419
1420 // Save prefix and move CurPtr past it
1421 const char *Prefix = CurPtr;
1422 CurPtr += PrefixLen + 1; // skip over prefix and '('
1423
1424 while (1) {
1425 char C = *CurPtr++;
1426
1427 if (C == ')') {
1428 // Check for prefix match and closing quote.
1429 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1430 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1431 break;
1432 }
1433 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1434 if (!isLexingRawMode())
1435 Diag(BufferPtr, diag::err_unterminated_raw_string)
1436 << StringRef(Prefix, PrefixLen);
1437 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1438 return;
1439 }
1440 }
1441
1442 // Update the location of token as well as BufferPtr.
1443 const char *TokStart = BufferPtr;
1444 FormTokenWithChars(Result, CurPtr, Kind);
1445 Result.setLiteralData(TokStart);
1446}
1447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1449/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001450void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001452 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 char C = getAndAdvanceChar(CurPtr, Result);
1454 while (C != '>') {
1455 // Skip escaped characters.
1456 if (C == '\\') {
1457 // Skip the escaped character.
1458 C = getAndAdvanceChar(CurPtr, Result);
1459 } else if (C == '\n' || C == '\r' || // Newline.
1460 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001461 // If the filename is unterminated, then it must just be a lone <
1462 // character. Return this as such.
1463 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 return;
1465 } else if (C == 0) {
1466 NulCharacter = CurPtr-1;
1467 }
1468 C = getAndAdvanceChar(CurPtr, Result);
1469 }
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001472 if (NulCharacter && !isLexingRawMode())
1473 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001476 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001477 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001478 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001479}
1480
1481
1482/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001483/// lexed either ' or L' or u' or U'.
1484void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1485 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 const char *NulCharacter = 0; // Does this character contain the \0 character?
1487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 char C = getAndAdvanceChar(CurPtr, Result);
1489 if (C == '\'') {
Chris Lattner33ab3f62009-03-18 21:10:12 +00001490 if (!isLexingRawMode() && !Features.AsmPreprocessor)
Chris Lattner74d15df2008-11-22 02:02:22 +00001491 Diag(BufferPtr, diag::err_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001492 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001494 }
1495
1496 while (C != '\'') {
1497 // Skip escaped characters.
1498 if (C == '\\') {
1499 // Skip the escaped character.
1500 // FIXME: UCN's
1501 C = getAndAdvanceChar(CurPtr, Result);
1502 } else if (C == '\n' || C == '\r' || // Newline.
1503 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
Douglas Gregor55817af2010-08-25 17:04:25 +00001504 if (C == 0 && PP && PP->isCodeCompletionFile(FileLoc))
1505 PP->CodeCompleteNaturalLanguage();
1506 else if (!isLexingRawMode() && !Features.AsmPreprocessor)
Argyrios Kyrtzidisff1ed982011-02-15 23:45:31 +00001507 Diag(BufferPtr, diag::warn_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001508 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1509 return;
1510 } else if (C == 0) {
1511 NulCharacter = CurPtr-1;
1512 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 C = getAndAdvanceChar(CurPtr, Result);
1514 }
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Chris Lattnerd80f7862010-07-07 23:24:27 +00001516 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001517 if (NulCharacter && !isLexingRawMode())
1518 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001519
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001521 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001522 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001523 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001524}
1525
1526/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1527/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001528///
1529/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1530///
1531bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Whitespace - Skip it, then return the token after the whitespace.
1533 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1534 while (1) {
1535 // Skip horizontal whitespace very aggressively.
1536 while (isHorizontalWhitespace(Char))
1537 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001539 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 if (Char != '\n' && Char != '\r')
1541 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 if (ParsingPreprocessorDirective) {
1544 // End of preprocessor directive line, let LexTokenInternal handle this.
1545 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001546 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 }
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 // ok, but handle newline.
1550 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001551 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001553 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 Char = *++CurPtr;
1555 }
1556
1557 // If this isn't immediately after a newline, there is leading space.
1558 char PrevChar = CurPtr[-1];
1559 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001560 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561
Chris Lattnerd88dc482008-10-12 04:05:48 +00001562 // If the client wants us to return whitespace, return it now.
1563 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001564 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001565 return true;
1566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001569 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001570}
1571
1572// SkipBCPLComment - We have just read the // characters from input. Skip until
1573// we find the newline character thats terminate the comment. Then update
Chris Lattner046c2272010-01-18 22:35:47 +00001574/// BufferPtr and return.
1575///
1576/// If we're in KeepCommentMode or any CommentHandler has inserted
1577/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001578bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 // If BCPL comments aren't explicitly enabled for this language, emit an
1580 // extension warning.
Chris Lattner74d15df2008-11-22 02:02:22 +00001581 if (!Features.BCPLComment && !isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 Diag(BufferPtr, diag::ext_bcpl_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 // Mark them enabled so we only emit one warning for this translation
1585 // unit.
1586 Features.BCPLComment = true;
1587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // Scan over the body of the comment. The common case, when scanning, is that
1590 // the comment contains normal ascii characters with nothing interesting in
1591 // them. As such, optimize for this case with the inner loop.
1592 char C;
1593 do {
1594 C = *CurPtr;
1595 // FIXME: Speedup BCPL comment lexing. Just scan for a \n or \r character.
1596 // If we find a \n character, scan backwards, checking to see if it's an
1597 // escaped newline, like we do for block comments.
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 // Skip over characters in the fast loop.
1600 while (C != 0 && // Potentially EOF.
1601 C != '\\' && // Potentially escaped newline.
1602 C != '?' && // Potentially trigraph.
1603 C != '\n' && C != '\r') // Newline or DOS-style newline.
1604 C = *++CurPtr;
1605
1606 // If this is a newline, we're done.
1607 if (C == '\n' || C == '\r')
1608 break; // Found the newline? Break out!
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001611 // properly decode the character. Read it in raw mode to avoid emitting
1612 // diagnostics about things like trigraphs. If we see an escaped newline,
1613 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001615 bool OldRawMode = isLexingRawMode();
1616 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001618 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001619
1620 // If the char that we finally got was a \n, then we must have had something
1621 // like \<newline><newline>. We don't want to have consumed the second
1622 // newline, we want CurPtr, to end up pointing to it down below.
1623 if (C == '\n' || C == '\r') {
1624 --CurPtr;
1625 C = 'x'; // doesn't matter what this is.
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 // If we read multiple characters, and one of those characters was a \r or
1629 // \n, then we had an escaped newline within the comment. Emit diagnostic
1630 // unless the next line is also a // comment.
1631 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1632 for (; OldPtr != CurPtr; ++OldPtr)
1633 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1634 // Okay, we found a // comment that ends in a newline, if the next
1635 // line is also a // comment, but has spaces, don't emit a diagnostic.
1636 if (isspace(C)) {
1637 const char *ForwardPtr = CurPtr;
1638 while (isspace(*ForwardPtr)) // Skip whitespace.
1639 ++ForwardPtr;
1640 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1641 break;
1642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Chris Lattner74d15df2008-11-22 02:02:22 +00001644 if (!isLexingRawMode())
1645 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 break;
1647 }
1648 }
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Douglas Gregor55817af2010-08-25 17:04:25 +00001650 if (CurPtr == BufferEnd+1) {
1651 if (PP && PP->isCodeCompletionFile(FileLoc))
1652 PP->CodeCompleteNaturalLanguage();
1653
1654 --CurPtr;
1655 break;
1656 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 } while (C != '\n' && C != '\r');
1658
Chris Lattner3d0ad582010-02-03 21:06:21 +00001659 // Found but did not consume the newline. Notify comment handlers about the
1660 // comment unless we're in a #if 0 block.
1661 if (PP && !isLexingRawMode() &&
1662 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1663 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001664 BufferPtr = CurPtr;
1665 return true; // A token has to be returned.
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001669 if (inKeepCommentMode())
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 return SaveBCPLComment(Result, CurPtr);
1671
1672 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001673 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1675 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001676 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00001680 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00001681 // contribute to another token), it isn't needed for correctness. Note that
1682 // this is ok even in KeepWhitespaceMode, because we would have returned the
1683 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001687 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001689 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001691 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001692}
1693
1694/// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
1695/// an appropriate way and return it.
Chris Lattnerd2177732007-07-20 16:59:19 +00001696bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001697 // If we're not in a preprocessor directive, just return the // comment
1698 // directly.
1699 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Chris Lattner9e6293d2008-10-12 04:51:35 +00001701 if (!ParsingPreprocessorDirective)
1702 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Chris Lattner9e6293d2008-10-12 04:51:35 +00001704 // If this BCPL-style comment is in a macro definition, transmogrify it into
1705 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00001706 bool Invalid = false;
1707 std::string Spelling = PP->getSpelling(Result, &Invalid);
1708 if (Invalid)
1709 return true;
1710
Chris Lattner9e6293d2008-10-12 04:51:35 +00001711 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
1712 Spelling[1] = '*'; // Change prefix to "/*".
1713 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Chris Lattner9e6293d2008-10-12 04:51:35 +00001715 Result.setKind(tok::comment);
Chris Lattner47246be2009-01-26 19:29:26 +00001716 PP->CreateString(&Spelling[0], Spelling.size(), Result,
1717 Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00001718 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001719}
1720
1721/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
1722/// character (either \n or \r) is part of an escaped newline sequence. Issue a
Chris Lattner47a2b402008-12-12 07:14:34 +00001723/// diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00001724static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 Lexer *L) {
1726 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 // Back up off the newline.
1729 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 // If this is a two-character newline sequence, skip the other character.
1732 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
1733 // \n\n or \r\r -> not escaped newline.
1734 if (CurPtr[0] == CurPtr[1])
1735 return false;
1736 // \n\r or \r\n -> skip the newline.
1737 --CurPtr;
1738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 // If we have horizontal whitespace, skip over it. We allow whitespace
1741 // between the slash and newline.
1742 bool HasSpace = false;
1743 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
1744 --CurPtr;
1745 HasSpace = true;
1746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 // If we have a slash, we know this is an escaped newline.
1749 if (*CurPtr == '\\') {
1750 if (CurPtr[-1] != '*') return false;
1751 } else {
1752 // It isn't a slash, is it the ?? / trigraph?
1753 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
1754 CurPtr[-3] != '*')
1755 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 // This is the trigraph ending the comment. Emit a stern warning!
1758 CurPtr -= 2;
1759
1760 // If no trigraphs are enabled, warn that we ignored this trigraph and
1761 // ignore this * character.
1762 if (!L->getFeatures().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001763 if (!L->isLexingRawMode())
1764 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return false;
1766 }
Chris Lattner74d15df2008-11-22 02:02:22 +00001767 if (!L->isLexingRawMode())
1768 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00001772 if (!L->isLexingRawMode())
1773 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001776 if (HasSpace && !L->isLexingRawMode())
1777 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 return true;
1780}
1781
1782#ifdef __SSE2__
1783#include <emmintrin.h>
1784#elif __ALTIVEC__
1785#include <altivec.h>
1786#undef bool
1787#endif
1788
1789/// SkipBlockComment - We have just read the /* characters from input. Read
1790/// until we find the */ characters that terminate the comment. Note that we
1791/// don't bother decoding trigraphs or escaped newlines in block comments,
1792/// because they cannot cause the comment to end. The only thing that can
1793/// happen is the comment could end with an escaped newline between the */ end
1794/// of comment.
Chris Lattner2d381892008-10-12 04:15:42 +00001795///
Chris Lattner046c2272010-01-18 22:35:47 +00001796/// If we're in KeepCommentMode or any CommentHandler has inserted
1797/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00001798bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001800 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 // optimization helps people who like to put a lot of * characters in their
1802 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00001803
1804 // The first character we get with newlines and trigraphs skipped to handle
1805 // the degenerate /*/ case below correctly if the * has an escaped newline
1806 // after it.
1807 unsigned CharSize;
1808 unsigned char C = getCharAndSize(CurPtr, CharSize);
1809 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 if (C == 0 && CurPtr == BufferEnd+1) {
Chris Lattner150fcd52010-05-16 19:54:05 +00001811 if (!isLexingRawMode() &&
1812 !PP->isCodeCompletionFile(FileLoc))
Chris Lattner0af57422008-10-12 01:31:51 +00001813 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001814 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Chris Lattner31f0eca2008-10-12 04:19:49 +00001816 // KeepWhitespaceMode should return this broken comment as a token. Since
1817 // it isn't a well formed comment, just return it as an 'unknown' token.
1818 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001819 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001820 return true;
1821 }
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Chris Lattner31f0eca2008-10-12 04:19:49 +00001823 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001824 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 }
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Chris Lattner8146b682007-07-21 23:43:37 +00001827 // Check to see if the first character after the '/*' is another /. If so,
1828 // then this slash does not end the block comment, it is part of it.
1829 if (C == '/')
1830 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 while (1) {
1833 // Skip over all non-interesting characters until we find end of buffer or a
1834 // (probably ending) '/' character.
1835 if (CurPtr + 24 < BufferEnd) {
1836 // While not aligned to a 16-byte boundary.
1837 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
1838 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Reid Spencer5f016e22007-07-11 17:01:13 +00001840 if (C == '/') goto FoundSlash;
1841
1842#ifdef __SSE2__
1843 __m128i Slashes = _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', '/',
1844 '/', '/', '/', '/', '/', '/', '/', '/');
1845 while (CurPtr+16 <= BufferEnd &&
1846 _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)) == 0)
1847 CurPtr += 16;
1848#elif __ALTIVEC__
1849 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00001850 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 '/', '/', '/', '/', '/', '/', '/', '/'
1852 };
1853 while (CurPtr+16 <= BufferEnd &&
1854 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
1855 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001856#else
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 // Scan for '/' quickly. Many block comments are very large.
1858 while (CurPtr[0] != '/' &&
1859 CurPtr[1] != '/' &&
1860 CurPtr[2] != '/' &&
1861 CurPtr[3] != '/' &&
1862 CurPtr+4 < BufferEnd) {
1863 CurPtr += 4;
1864 }
1865#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Reid Spencer5f016e22007-07-11 17:01:13 +00001867 // It has to be one of the bytes scanned, increment to it and read one.
1868 C = *CurPtr++;
1869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 // Loop to scan the remainder.
1872 while (C != '/' && C != '\0')
1873 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Reid Spencer5f016e22007-07-11 17:01:13 +00001875 FoundSlash:
1876 if (C == '/') {
1877 if (CurPtr[-2] == '*') // We found the final */. We're done!
1878 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
1881 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
1882 // We found the final */, though it had an escaped newline between the
1883 // * and /. We're done!
1884 break;
1885 }
1886 }
1887 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
1888 // If this is a /* inside of the comment, emit a warning. Don't do this
1889 // if this is a /*/, which will end the comment. This misses cases with
1890 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00001891 if (!isLexingRawMode())
1892 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 }
1894 } else if (C == 0 && CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001895 if (PP && PP->isCodeCompletionFile(FileLoc))
1896 PP->CodeCompleteNaturalLanguage();
1897 else if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00001898 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // Note: the user probably forgot a */. We could continue immediately
1900 // after the /*, but this would involve lexing a lot of what really is the
1901 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00001902 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Chris Lattner31f0eca2008-10-12 04:19:49 +00001904 // KeepWhitespaceMode should return this broken comment as a token. Since
1905 // it isn't a well formed comment, just return it as an 'unknown' token.
1906 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001907 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00001908 return true;
1909 }
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Chris Lattner31f0eca2008-10-12 04:19:49 +00001911 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001912 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 }
1914 C = *CurPtr++;
1915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattner3d0ad582010-02-03 21:06:21 +00001917 // Notify comment handlers about the comment unless we're in a #if 0 block.
1918 if (PP && !isLexingRawMode() &&
1919 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1920 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001921 BufferPtr = CurPtr;
1922 return true; // A token has to be returned.
1923 }
Douglas Gregor2e222532009-07-02 17:08:52 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001926 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001927 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00001928 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 }
1930
1931 // It is common for the tokens immediately after a /**/ comment to be
1932 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00001933 // efficiently now. This is safe even in KeepWhitespaceMode because we would
1934 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00001936 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00001938 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 }
1940
1941 // Otherwise, just return so that the next character will be lexed as a token.
1942 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00001943 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00001944 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001945}
1946
1947//===----------------------------------------------------------------------===//
1948// Primary Lexing Entry Points
1949//===----------------------------------------------------------------------===//
1950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
1952/// uninterpreted string. This switches the lexer out of directive mode.
1953std::string Lexer::ReadToEndOfLine() {
1954 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
1955 "Must be in a preprocessing directive!");
1956 std::string Result;
Chris Lattnerd2177732007-07-20 16:59:19 +00001957 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00001958
1959 // CurPtr - Cache BufferPtr in an automatic variable.
1960 const char *CurPtr = BufferPtr;
1961 while (1) {
1962 char Char = getAndAdvanceChar(CurPtr, Tmp);
1963 switch (Char) {
1964 default:
1965 Result += Char;
1966 break;
1967 case 0: // Null.
1968 // Found end of file?
1969 if (CurPtr-1 != BufferEnd) {
1970 // Nope, normal character, continue.
1971 Result += Char;
1972 break;
1973 }
1974 // FALL THROUGH.
1975 case '\r':
1976 case '\n':
1977 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
1978 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
1979 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Peter Collingbourne84021552011-02-28 02:37:51 +00001981 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00001983 if (Tmp.is(tok::code_completion)) {
1984 if (PP && PP->getCodeCompletionHandler())
1985 PP->getCodeCompletionHandler()->CodeCompleteNaturalLanguage();
1986 Lex(Tmp);
1987 }
Peter Collingbourne84021552011-02-28 02:37:51 +00001988 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 // Finally, we're done, return the string we found.
1991 return Result;
1992 }
1993 }
1994}
1995
1996/// LexEndOfFile - CurPtr points to the end of this file. Handle this
1997/// condition, reporting diagnostics and handling other edge cases as required.
1998/// This returns true if Result contains a token, false if PP.Lex should be
1999/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002000bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Douglas Gregorf44e8542010-08-24 19:08:16 +00002001 // Check if we are performing code completion.
2002 if (PP && PP->isCodeCompletionFile(FileLoc)) {
2003 // We're at the end of the file, but we've been asked to consider the
2004 // end of the file to be a code-completion token. Return the
2005 // code-completion token.
2006 Result.startToken();
2007 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2008
2009 // Only do the eof -> code_completion translation once.
2010 PP->SetCodeCompletionPoint(0, 0, 0);
2011
2012 // Silence any diagnostics that occur once we hit the code-completion point.
2013 PP->getDiagnostics().setSuppressAllDiagnostics(true);
2014 return true;
2015 }
2016
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 // If we hit the end of the file while parsing a preprocessor directive,
2018 // end the preprocessor directive first. The next token returned will
2019 // then be the end of file.
2020 if (ParsingPreprocessorDirective) {
2021 // Done parsing the "line".
2022 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002024 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002027 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002029 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002030
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 // If we are in raw mode, return this event as an EOF token. Let the caller
2032 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002033 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 Result.startToken();
2035 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002036 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 return true;
2038 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002039
Douglas Gregorf44e8542010-08-24 19:08:16 +00002040 // Issue diagnostics for unterminated #if and missing newline.
2041
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // If we are in a #if directive, emit an error.
2043 while (!ConditionalStack.empty()) {
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002044 if (!PP->isCodeCompletionFile(FileLoc))
2045 PP->Diag(ConditionalStack.back().IfLoc,
2046 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 ConditionalStack.pop_back();
2048 }
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002050 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2051 // a pedwarn.
2052 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Mike Stump20d0ee52009-04-02 02:29:42 +00002053 Diag(BufferEnd, diag::ext_no_newline_eof)
Douglas Gregor849b2432010-03-31 17:46:05 +00002054 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 BufferPtr = CurPtr;
2057
2058 // Finally, let the preprocessor handle this.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002059 return PP->HandleEndOfFile(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002060}
2061
2062/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2063/// the specified lexer will return a tok::l_paren token, 0 if it is something
2064/// else and 2 if there are no more tokens in the buffer controlled by the
2065/// lexer.
2066unsigned Lexer::isNextPPTokenLParen() {
2067 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 // Switch to 'skipping' mode. This will ensure that we can lex a token
2070 // without emitting diagnostics, disables macro expansion, and will cause EOF
2071 // to return an EOF token instead of popping the include stack.
2072 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 // Save state that can be changed while lexing so that we can restore it.
2075 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002076 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Chris Lattnerd2177732007-07-20 16:59:19 +00002078 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 Tok.startToken();
2080 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 // Restore state that may have changed.
2083 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002084 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 // Restore the lexer back to non-skipping mode.
2087 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002089 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002091 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002092}
2093
Chris Lattner34f349d2009-12-14 06:16:57 +00002094/// FindConflictEnd - Find the end of a version control conflict marker.
2095static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002096 StringRef RestOfBuffer(CurPtr+7, BufferEnd-CurPtr-7);
Chris Lattner34f349d2009-12-14 06:16:57 +00002097 size_t Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002098 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002099 // Must occur at start of line.
2100 if (RestOfBuffer[Pos-1] != '\r' &&
2101 RestOfBuffer[Pos-1] != '\n') {
2102 RestOfBuffer = RestOfBuffer.substr(Pos+7);
Chris Lattner3d488992010-05-17 20:27:25 +00002103 Pos = RestOfBuffer.find(">>>>>>>");
Chris Lattner34f349d2009-12-14 06:16:57 +00002104 continue;
2105 }
2106 return RestOfBuffer.data()+Pos;
2107 }
2108 return 0;
2109}
2110
2111/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2112/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2113/// and recover nicely. This returns true if it is a conflict marker and false
2114/// if not.
2115bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2116 // Only a conflict marker if it starts at the beginning of a line.
2117 if (CurPtr != BufferStart &&
2118 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2119 return false;
2120
2121 // Check to see if we have <<<<<<<.
2122 if (BufferEnd-CurPtr < 8 ||
Chris Lattner5f9e2722011-07-23 10:55:15 +00002123 StringRef(CurPtr, 7) != "<<<<<<<")
Chris Lattner34f349d2009-12-14 06:16:57 +00002124 return false;
2125
2126 // If we have a situation where we don't care about conflict markers, ignore
2127 // it.
2128 if (IsInConflictMarker || isLexingRawMode())
2129 return false;
2130
2131 // Check to see if there is a >>>>>>> somewhere in the buffer at the start of
2132 // a line to terminate this conflict marker.
Chris Lattner3d488992010-05-17 20:27:25 +00002133 if (FindConflictEnd(CurPtr, BufferEnd)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002134 // We found a match. We are really in a conflict marker.
2135 // Diagnose this, and ignore to the end of line.
2136 Diag(CurPtr, diag::err_conflict_marker);
2137 IsInConflictMarker = true;
2138
2139 // Skip ahead to the end of line. We know this exists because the
2140 // end-of-conflict marker starts with \r or \n.
2141 while (*CurPtr != '\r' && *CurPtr != '\n') {
2142 assert(CurPtr != BufferEnd && "Didn't find end of line");
2143 ++CurPtr;
2144 }
2145 BufferPtr = CurPtr;
2146 return true;
2147 }
2148
2149 // No end of conflict marker found.
2150 return false;
2151}
2152
2153
2154/// HandleEndOfConflictMarker - If this is a '=======' or '|||||||' or '>>>>>>>'
2155/// marker, then it is the end of a conflict marker. Handle it by ignoring up
2156/// until the end of the line. This returns true if it is a conflict marker and
2157/// false if not.
2158bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2159 // Only a conflict marker if it starts at the beginning of a line.
2160 if (CurPtr != BufferStart &&
2161 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2162 return false;
2163
2164 // If we have a situation where we don't care about conflict markers, ignore
2165 // it.
2166 if (!IsInConflictMarker || isLexingRawMode())
2167 return false;
2168
2169 // Check to see if we have the marker (7 characters in a row).
2170 for (unsigned i = 1; i != 7; ++i)
2171 if (CurPtr[i] != CurPtr[0])
2172 return false;
2173
2174 // If we do have it, search for the end of the conflict marker. This could
2175 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2176 // be the end of conflict marker.
2177 if (const char *End = FindConflictEnd(CurPtr, BufferEnd)) {
2178 CurPtr = End;
2179
2180 // Skip ahead to the end of line.
2181 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2182 ++CurPtr;
2183
2184 BufferPtr = CurPtr;
2185
2186 // No longer in the conflict marker.
2187 IsInConflictMarker = false;
2188 return true;
2189 }
2190
2191 return false;
2192}
2193
Reid Spencer5f016e22007-07-11 17:01:13 +00002194
2195/// LexTokenInternal - This implements a simple C family lexer. It is an
2196/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002197/// has a null character at the end of the file. This returns a preprocessing
2198/// token, not a normal token, as such, it is an internal interface. It assumes
2199/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002200void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002201LexNextToken:
2202 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002203 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 // CurPtr - Cache BufferPtr in an automatic variable.
2207 const char *CurPtr = BufferPtr;
2208
2209 // Small amounts of horizontal whitespace is very common between tokens.
2210 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2211 ++CurPtr;
2212 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2213 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Chris Lattnerd88dc482008-10-12 04:05:48 +00002215 // If we are keeping whitespace and other tokens, just return what we just
2216 // skipped. The next lexer invocation will return the token after the
2217 // whitespace.
2218 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002219 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002220 return;
2221 }
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002224 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 }
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 // Read a character, advancing over it.
2230 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002231 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 switch (Char) {
2234 case 0: // Null.
2235 // Found end of file?
2236 if (CurPtr-1 == BufferEnd) {
2237 // Read the PP instance variable into an automatic variable, because
2238 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002239 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2241 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002242 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2243 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Chris Lattner74d15df2008-11-22 02:02:22 +00002246 if (!isLexingRawMode())
2247 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002248 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002249 if (SkipWhitespace(Result, CurPtr))
2250 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002253
2254 case 26: // DOS & CP/M EOF: "^Z".
2255 // If we're in Microsoft extensions mode, treat this as end of file.
2256 if (Features.Microsoft) {
2257 // Read the PP instance variable into an automatic variable, because
2258 // LexEndOfFile will often delete 'this'.
2259 Preprocessor *PPCache = PP;
2260 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2261 return; // Got a token to return.
2262 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2263 return PPCache->Lex(Result);
2264 }
2265 // If Microsoft extensions are disabled, this is just random garbage.
2266 Kind = tok::unknown;
2267 break;
2268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 case '\n':
2270 case '\r':
2271 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002272 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 if (ParsingPreprocessorDirective) {
2274 // Done parsing the "line".
2275 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Reid Spencer5f016e22007-07-11 17:01:13 +00002277 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002278 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 // Since we consumed a newline, we are back at the start of a line.
2281 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Peter Collingbourne84021552011-02-28 02:37:51 +00002283 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 break;
2285 }
2286 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002287 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002289 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Chris Lattnerd88dc482008-10-12 04:05:48 +00002291 if (SkipWhitespace(Result, CurPtr))
2292 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 goto LexNextToken; // GCC isn't tail call eliminating.
2294 case ' ':
2295 case '\t':
2296 case '\f':
2297 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002298 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002299 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002300 if (SkipWhitespace(Result, CurPtr))
2301 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002302
2303 SkipIgnoredUnits:
2304 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Chris Lattner8133cfc2007-07-22 06:29:05 +00002306 // If the next token is obviously a // or /* */ comment, skip it efficiently
2307 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002308 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002309 Features.BCPLComment && !Features.TraditionalCPP) {
Chris Lattner046c2272010-01-18 22:35:47 +00002310 if (SkipBCPLComment(Result, CurPtr+2))
2311 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002312 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002313 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002314 if (SkipBlockComment(Result, CurPtr+2))
2315 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002316 goto SkipIgnoredUnits;
2317 } else if (isHorizontalWhitespace(*CurPtr)) {
2318 goto SkipHorizontalWhitespace;
2319 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002321
Chris Lattner3a570772008-01-03 17:58:54 +00002322 // C99 6.4.4.1: Integer Constants.
2323 // C99 6.4.4.2: Floating Constants.
2324 case '0': case '1': case '2': case '3': case '4':
2325 case '5': case '6': case '7': case '8': case '9':
2326 // Notify MIOpt that we read a non-whitespace/non-comment token.
2327 MIOpt.ReadToken();
2328 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Douglas Gregor5cee1192011-07-27 05:40:30 +00002330 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2331 // Notify MIOpt that we read a non-whitespace/non-comment token.
2332 MIOpt.ReadToken();
2333
2334 if (Features.CPlusPlus0x) {
2335 Char = getCharAndSize(CurPtr, SizeTmp);
2336
2337 // UTF-16 string literal
2338 if (Char == '"')
2339 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2340 tok::utf16_string_literal);
2341
2342 // UTF-16 character constant
2343 if (Char == '\'')
2344 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2345 tok::utf16_char_constant);
2346
Craig Topper2fa4e862011-08-11 04:06:15 +00002347 // UTF-16 raw string literal
2348 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2349 return LexRawStringLiteral(Result,
2350 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2351 SizeTmp2, Result),
2352 tok::utf16_string_literal);
2353
2354 if (Char == '8') {
2355 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2356
2357 // UTF-8 string literal
2358 if (Char2 == '"')
2359 return LexStringLiteral(Result,
2360 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2361 SizeTmp2, Result),
2362 tok::utf8_string_literal);
2363
2364 if (Char2 == 'R') {
2365 unsigned SizeTmp3;
2366 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2367 // UTF-8 raw string literal
2368 if (Char3 == '"') {
2369 return LexRawStringLiteral(Result,
2370 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2371 SizeTmp2, Result),
2372 SizeTmp3, Result),
2373 tok::utf8_string_literal);
2374 }
2375 }
2376 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002377 }
2378
2379 // treat u like the start of an identifier.
2380 return LexIdentifier(Result, CurPtr);
2381
2382 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2383 // Notify MIOpt that we read a non-whitespace/non-comment token.
2384 MIOpt.ReadToken();
2385
2386 if (Features.CPlusPlus0x) {
2387 Char = getCharAndSize(CurPtr, SizeTmp);
2388
2389 // UTF-32 string literal
2390 if (Char == '"')
2391 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2392 tok::utf32_string_literal);
2393
2394 // UTF-32 character constant
2395 if (Char == '\'')
2396 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2397 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002398
2399 // UTF-32 raw string literal
2400 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2401 return LexRawStringLiteral(Result,
2402 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2403 SizeTmp2, Result),
2404 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002405 }
2406
2407 // treat U like the start of an identifier.
2408 return LexIdentifier(Result, CurPtr);
2409
Craig Topper2fa4e862011-08-11 04:06:15 +00002410 case 'R': // Identifier or C++0x raw string literal
2411 // Notify MIOpt that we read a non-whitespace/non-comment token.
2412 MIOpt.ReadToken();
2413
2414 if (Features.CPlusPlus0x) {
2415 Char = getCharAndSize(CurPtr, SizeTmp);
2416
2417 if (Char == '"')
2418 return LexRawStringLiteral(Result,
2419 ConsumeChar(CurPtr, SizeTmp, Result),
2420 tok::string_literal);
2421 }
2422
2423 // treat R like the start of an identifier.
2424 return LexIdentifier(Result, CurPtr);
2425
Chris Lattner3a570772008-01-03 17:58:54 +00002426 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // Notify MIOpt that we read a non-whitespace/non-comment token.
2428 MIOpt.ReadToken();
2429 Char = getCharAndSize(CurPtr, SizeTmp);
2430
2431 // Wide string literal.
2432 if (Char == '"')
2433 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002434 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002435
Craig Topper2fa4e862011-08-11 04:06:15 +00002436 // Wide raw string literal.
2437 if (Features.CPlusPlus0x && Char == 'R' &&
2438 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2439 return LexRawStringLiteral(Result,
2440 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2441 SizeTmp2, Result),
2442 tok::wide_string_literal);
2443
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 // Wide character constant.
2445 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002446 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2447 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002448 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 // C99 6.4.2: Identifiers.
2451 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2452 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002453 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002454 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2455 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2456 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002457 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002458 case 'v': case 'w': case 'x': case 'y': case 'z':
2459 case '_':
2460 // Notify MIOpt that we read a non-whitespace/non-comment token.
2461 MIOpt.ReadToken();
2462 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002463
2464 case '$': // $ in identifiers.
2465 if (Features.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002466 if (!isLexingRawMode())
2467 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002468 // Notify MIOpt that we read a non-whitespace/non-comment token.
2469 MIOpt.ReadToken();
2470 return LexIdentifier(Result, CurPtr);
2471 }
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Chris Lattner9e6293d2008-10-12 04:51:35 +00002473 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002474 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002475
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 // C99 6.4.4: Character Constants.
2477 case '\'':
2478 // Notify MIOpt that we read a non-whitespace/non-comment token.
2479 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002480 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002481
2482 // C99 6.4.5: String Literals.
2483 case '"':
2484 // Notify MIOpt that we read a non-whitespace/non-comment token.
2485 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002486 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002487
2488 // C99 6.4.6: Punctuators.
2489 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002490 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00002491 break;
2492 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002493 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 break;
2495 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002496 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 break;
2498 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002499 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 break;
2501 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002502 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 break;
2504 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002505 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 break;
2507 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002508 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 break;
2510 case '.':
2511 Char = getCharAndSize(CurPtr, SizeTmp);
2512 if (Char >= '0' && Char <= '9') {
2513 // Notify MIOpt that we read a non-whitespace/non-comment token.
2514 MIOpt.ReadToken();
2515
2516 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2517 } else if (Features.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002518 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 CurPtr += SizeTmp;
2520 } else if (Char == '.' &&
2521 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002522 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2524 SizeTmp2, Result);
2525 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002526 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 }
2528 break;
2529 case '&':
2530 Char = getCharAndSize(CurPtr, SizeTmp);
2531 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002532 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2534 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002535 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2537 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002538 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 }
2540 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002541 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002543 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2545 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002546 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00002547 }
2548 break;
2549 case '+':
2550 Char = getCharAndSize(CurPtr, SizeTmp);
2551 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002552 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002553 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002556 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002558 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 }
2560 break;
2561 case '-':
2562 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002563 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002565 Kind = tok::minusminus;
Mike Stump1eb44332009-09-09 15:08:12 +00002566 } else if (Char == '>' && Features.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00002567 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2569 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002570 Kind = tok::arrowstar;
2571 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002573 Kind = tok::arrow;
2574 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002576 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002577 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002578 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
2580 break;
2581 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002582 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 break;
2584 case '!':
2585 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002586 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002587 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2588 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002589 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 }
2591 break;
2592 case '/':
2593 // 6.4.9: Comments
2594 Char = getCharAndSize(CurPtr, SizeTmp);
2595 if (Char == '/') { // BCPL comment.
Chris Lattner8402c732009-01-16 22:39:25 +00002596 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2597 // want to lex this as a comment. There is one problem with this though,
2598 // that in one particular corner case, this can change the behavior of the
2599 // resultant program. For example, In "foo //**/ bar", C89 would lex
2600 // this as "foo / bar" and langauges with BCPL comments would lex it as
2601 // "foo". Check to see if the character after the second slash is a '*'.
2602 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00002603 // However, we never do this in -traditional-cpp mode.
2604 if ((Features.BCPLComment ||
2605 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2606 !Features.TraditionalCPP) {
Chris Lattner8402c732009-01-16 22:39:25 +00002607 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002608 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Chris Lattner8402c732009-01-16 22:39:25 +00002610 // It is common for the tokens immediately after a // comment to be
2611 // whitespace (indentation for the next line). Instead of going through
2612 // the big switch, handle it efficiently now.
2613 goto SkipIgnoredUnits;
2614 }
2615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Chris Lattner8402c732009-01-16 22:39:25 +00002617 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00002618 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00002619 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00002620 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00002621 }
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Chris Lattner8402c732009-01-16 22:39:25 +00002623 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002625 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002627 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002628 }
2629 break;
2630 case '%':
2631 Char = getCharAndSize(CurPtr, SizeTmp);
2632 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002633 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002634 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2635 } else if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002636 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00002637 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2638 } else if (Features.Digraphs && Char == ':') {
2639 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2640 Char = getCharAndSize(CurPtr, SizeTmp);
2641 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002642 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2644 SizeTmp2, Result);
2645 } else if (Char == '@' && Features.Microsoft) { // %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00002647 if (!isLexingRawMode())
2648 Diag(BufferPtr, diag::charize_microsoft_ext);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002649 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00002650 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // We parsed a # character. If this occurs at the start of the line,
2652 // it's actually the start of a preprocessing directive. Callback to
2653 // the preprocessor to handle it.
2654 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002655 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002656 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002657 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 // As an optimization, if the preprocessor didn't switch lexers, tail
2660 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002661 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 // Start a new token. If this is a #include or something, the PP may
2663 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002664 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002666 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002667 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 IsAtStartOfLine = false;
2669 }
2670 goto LexNextToken; // GCC isn't tail call eliminating.
2671 }
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Chris Lattner168ae2d2007-10-17 20:41:00 +00002673 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 }
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Chris Lattnere91e9322009-03-18 20:58:27 +00002676 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 }
2678 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002679 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 }
2681 break;
2682 case '<':
2683 Char = getCharAndSize(CurPtr, SizeTmp);
2684 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00002685 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002686 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002687 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2688 if (After == '=') {
2689 Kind = tok::lesslessequal;
2690 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2691 SizeTmp2, Result);
2692 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
2693 // If this is actually a '<<<<<<<' version control conflict marker,
2694 // recognize it as such and recover nicely.
2695 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002696 } else if (Features.CUDA && After == '<') {
2697 Kind = tok::lesslessless;
2698 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2699 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002700 } else {
2701 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2702 Kind = tok::lessless;
2703 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002706 Kind = tok::lessequal;
2707 } else if (Features.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith87a1e192011-04-14 18:36:27 +00002708 if (Features.CPlusPlus0x &&
2709 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
2710 // C++0x [lex.pptoken]p3:
2711 // Otherwise, if the next three characters are <:: and the subsequent
2712 // character is neither : nor >, the < is treated as a preprocessor
2713 // token by itself and not as the first character of the alternative
2714 // token <:.
2715 unsigned SizeTmp3;
2716 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2717 if (After != ':' && After != '>') {
2718 Kind = tok::less;
2719 break;
2720 }
2721 }
2722
Reid Spencer5f016e22007-07-11 17:01:13 +00002723 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002724 Kind = tok::l_square;
2725 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002727 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002729 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 }
2731 break;
2732 case '>':
2733 Char = getCharAndSize(CurPtr, SizeTmp);
2734 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002736 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002738 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
2739 if (After == '=') {
2740 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2741 SizeTmp2, Result);
2742 Kind = tok::greatergreaterequal;
2743 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
2744 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
2745 goto LexNextToken;
Peter Collingbourne1b791d62011-02-09 21:08:21 +00002746 } else if (Features.CUDA && After == '>') {
2747 Kind = tok::greatergreatergreater;
2748 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2749 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00002750 } else {
2751 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2752 Kind = tok::greatergreater;
2753 }
2754
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002756 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 }
2758 break;
2759 case '^':
2760 Char = getCharAndSize(CurPtr, SizeTmp);
2761 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002763 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002765 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00002766 }
2767 break;
2768 case '|':
2769 Char = getCharAndSize(CurPtr, SizeTmp);
2770 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002771 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2773 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002774 // If this is '|||||||' and we're in a conflict marker, ignore it.
2775 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
2776 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002777 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2779 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002780 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 }
2782 break;
2783 case ':':
2784 Char = getCharAndSize(CurPtr, SizeTmp);
2785 if (Features.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002786 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2788 } else if (Features.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002789 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002791 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002792 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 }
2794 break;
2795 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002796 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 break;
2798 case '=':
2799 Char = getCharAndSize(CurPtr, SizeTmp);
2800 if (Char == '=') {
Chris Lattner34f349d2009-12-14 06:16:57 +00002801 // If this is '=======' and we're in a conflict marker, ignore it.
2802 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
2803 goto LexNextToken;
2804
Chris Lattner9e6293d2008-10-12 04:51:35 +00002805 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002807 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002808 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00002809 }
2810 break;
2811 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00002812 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 break;
2814 case '#':
2815 Char = getCharAndSize(CurPtr, SizeTmp);
2816 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002817 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2819 } else if (Char == '@' && Features.Microsoft) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00002820 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00002821 if (!isLexingRawMode())
2822 Diag(BufferPtr, diag::charize_microsoft_ext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002823 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2824 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 // We parsed a # character. If this occurs at the start of the line,
2826 // it's actually the start of a preprocessing directive. Callback to
2827 // the preprocessor to handle it.
2828 // FIXME: -fpreprocessed mode??
Chris Lattner766703b2009-05-13 06:10:29 +00002829 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
Chris Lattnere91e9322009-03-18 20:58:27 +00002830 FormTokenWithChars(Result, CurPtr, tok::hash);
Chris Lattner168ae2d2007-10-17 20:41:00 +00002831 PP->HandleDirective(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 // As an optimization, if the preprocessor didn't switch lexers, tail
2834 // recurse.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002835 if (PP->isCurrentLexer(this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 // Start a new token. If this is a #include or something, the PP may
2837 // want us starting at the beginning of the line again. If so, set
Chris Lattner515f43f2010-04-12 23:04:41 +00002838 // the StartOfLine flag and clear LeadingSpace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 if (IsAtStartOfLine) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002840 Result.setFlag(Token::StartOfLine);
Chris Lattner515f43f2010-04-12 23:04:41 +00002841 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 IsAtStartOfLine = false;
2843 }
2844 goto LexNextToken; // GCC isn't tail call eliminating.
2845 }
Chris Lattner168ae2d2007-10-17 20:41:00 +00002846 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 }
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Chris Lattnere91e9322009-03-18 20:58:27 +00002849 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00002850 }
2851 break;
2852
Chris Lattner3a570772008-01-03 17:58:54 +00002853 case '@':
2854 // Objective C support.
2855 if (CurPtr[-1] == '@' && Features.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002856 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00002857 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00002858 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002859 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Reid Spencer5f016e22007-07-11 17:01:13 +00002861 case '\\':
2862 // FIXME: UCN's.
2863 // FALL THROUGH.
2864 default:
Chris Lattner9e6293d2008-10-12 04:51:35 +00002865 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00002866 break;
2867 }
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 // Notify MIOpt that we read a non-whitespace/non-comment token.
2870 MIOpt.ReadToken();
2871
2872 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00002873 FormTokenWithChars(Result, CurPtr, Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002874}