blob: 0590d9e114a7dc8862477785c1d34b3e3e662688 [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"
Jordan Rose98939022013-02-08 22:30:22 +000028#include "clang/Basic/CharInfo.h"
Chris Lattner9dc1f532007-07-20 16:37:10 +000029#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/CodeCompletionHandler.h"
31#include "clang/Lex/LexDiagnostic.h"
32#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Jordan Rosec7629d92013-01-24 20:50:46 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "llvm/ADT/StringSwitch.h"
Chris Lattner409a0362007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "llvm/Support/MemoryBuffer.h"
Jordan Roseed9c59f2013-02-09 01:10:25 +000039#include "UnicodeCharSets.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000040#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Chris Lattnerdbf388b2007-10-07 08:47:24 +000043//===----------------------------------------------------------------------===//
44// Token Class Implementation
45//===----------------------------------------------------------------------===//
46
Mike Stump1eb44332009-09-09 15:08:12 +000047/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattnerdbf388b2007-10-07 08:47:24 +000048bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregorbec1c9d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattnerdbf388b2007-10-07 08:47:24 +000052}
53
54/// getObjCKeywordID - Return the ObjC keyword kind.
55tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 IdentifierInfo *specId = getIdentifierInfo();
57 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
58}
59
Chris Lattner53702cd2007-12-13 01:59:49 +000060
Chris Lattnerdbf388b2007-10-07 08:47:24 +000061//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie99ba9e32011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump1eb44332009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattner22d91ca2009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattner22d91ca2009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner22d91ca2009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000076
Eric Christopher156119d2011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattner22d91ca2009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000093
Chris Lattner22d91ca2009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Chris Lattner22d91ca2009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +000099
Chris Lattner22d91ca2009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner22d91ca2009-01-17 06:55:17 +0000103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner22d91ca2009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner0770dab2009-01-17 07:56:59 +0000113/// Lexer constructor - Create a new lexer object for the specified buffer
114/// with the specified preprocessor managing the lexing process. This lexer
115/// assumes that the associated file buffer and Preprocessor objects will
116/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikie4e4d0842012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattner0770dab2009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Chris Lattner0770dab2009-01-17 07:56:59 +0000125 // Default to keeping comments if the preprocessor wants them.
126 SetCommentRetentionState(PP.getCommentRetentionState());
127}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000128
Chris Lattner168ae2d2007-10-17 20:41:00 +0000129/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000130/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner590f0cc2008-10-12 01:15:46 +0000131/// range will outlive it, so it doesn't take ownership of it.
David Blaikie4e4d0842012-03-11 07:00:24 +0000132Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000133 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikie4e4d0842012-03-11 07:00:24 +0000134 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000135
Chris Lattner22d91ca2009-01-17 06:55:17 +0000136 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner168ae2d2007-10-17 20:41:00 +0000138 // We *are* in raw mode.
139 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000140}
141
Chris Lattner025c3a62009-01-17 07:35:14 +0000142/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000143/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner025c3a62009-01-17 07:35:14 +0000144/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000145Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikie4e4d0842012-03-11 07:00:24 +0000146 const SourceManager &SM, const LangOptions &langOpts)
147 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000148
Mike Stump1eb44332009-09-09 15:08:12 +0000149 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000150 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner025c3a62009-01-17 07:35:14 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
154}
155
Chris Lattner42e00d12009-01-17 08:27:52 +0000156/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
157/// _Pragma expansion. This has a variety of magic semantics that this method
158/// sets up. It returns a new'd Lexer that must be delete'd when done.
159///
160/// On entrance to this routine, TokStartLoc is a macro location which has a
161/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000162/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000163/// "expanded from".
164///
165/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
166/// normal lexer that remaps tokens as they fly by. This would require making
167/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
168/// interface that could handle this stuff. This would pull GetMappedTokenLoc
169/// out of the critical path of the lexer!
170///
Mike Stump1eb44332009-09-09 15:08:12 +0000171Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000172 SourceLocation ExpansionLocStart,
173 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000174 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000175 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000176
177 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000178 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000179 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
180 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner42e00d12009-01-17 08:27:52 +0000182 // Now that the lexer is created, change the start/end locations so that we
183 // just lex the subsection of the file that we want. This is lexing from a
184 // scratch buffer.
185 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner42e00d12009-01-17 08:27:52 +0000187 L->BufferPtr = StrData;
188 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000189 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000190
191 // Set the SourceLocation with the remapping information. This ensures that
192 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000193 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
194 ExpansionLocStart,
195 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner42e00d12009-01-17 08:27:52 +0000197 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000198 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Chris Lattner42e00d12009-01-17 08:27:52 +0000201 // This lexer really is for _Pragma.
202 L->Is_PragmaLexer = true;
203 return L;
204}
205
Chris Lattner168ae2d2007-10-17 20:41:00 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207/// Stringify - Convert the specified string into a C string, with surrounding
208/// ""'s, and with escaped \ and " characters.
209std::string Lexer::Stringify(const std::string &Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
215 ++i; ++e;
216 }
217 }
218 return Result;
219}
220
Chris Lattnerd8e30832007-07-24 06:57:14 +0000221/// Stringify - Convert the specified string into a C string by escaping '\'
222/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000223void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
230}
231
Chris Lattnerb0607272010-11-17 07:26:20 +0000232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
Richard Smith30cddae2012-11-28 07:29:00 +0000236/// \brief Slow case of getSpelling. Extract the characters comprising the
237/// spelling of this token from the provided input buffer.
238static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
241
242 size_t Length = 0;
243 const char *BufEnd = BufPtr + Tok.getLength();
244
245 if (Tok.is(tok::string_literal)) {
246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
248 unsigned Size;
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
250 BufPtr += Size;
251
252 if (Spelling[Length - 1] == '"')
253 break;
254 }
255
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
258 // r-char-sequence.
259 if (Length >= 2 &&
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
262 // quote.
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
266
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
269 Length += RawLength;
270 BufPtr += RawLength;
271
272 // The rest of the token is lexed normally.
273 }
274 }
275
276 while (BufPtr < BufEnd) {
277 unsigned Size;
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
279 BufPtr += Size;
280 }
281
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
284 return Length;
285}
286
Chris Lattnerb0607272010-11-17 07:26:20 +0000287/// getSpelling() - Return the 'spelling' of this token. The spelling of a
288/// token are the characters used to represent the token in the source file
289/// after trigraph expansion and escaped-newline folding. In particular, this
290/// wants to get the true, uncanonicalized, spelling of things like digraphs
291/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith30cddae2012-11-28 07:29:00 +0000293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
296 bool *invalid) {
John McCall834e3f62011-03-08 07:59:04 +0000297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000303 if (invalidTemp) {
304 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000305 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000306 }
307
308 const char *tokenBegin = file.data() + locInfo.second;
309
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
313 Token token;
314 lexer.LexFromRawLexer(token);
315
316 unsigned length = token.getLength();
317
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000320 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000321
Richard Smith30cddae2012-11-28 07:29:00 +0000322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner5f9e2722011-07-23 10:55:15 +0000325 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000326}
327
328/// getSpelling() - Return the 'spelling' of this token. The spelling of a
329/// token are the characters used to represent the token in the source file
330/// after trigraph expansion and escaped-newline folding. In particular, this
331/// wants to get the true, uncanonicalized, spelling of things like digraphs
332/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000333std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith30cddae2012-11-28 07:29:00 +0000336
Chris Lattnerb0607272010-11-17 07:26:20 +0000337 bool CharDataInvalid = false;
Richard Smith30cddae2012-11-28 07:29:00 +0000338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 &CharDataInvalid);
340 if (Invalid)
341 *Invalid = CharDataInvalid;
342 if (CharDataInvalid)
343 return std::string();
Richard Smith30cddae2012-11-28 07:29:00 +0000344
345 // If this token contains nothing interesting, return it directly.
Chris Lattnerb0607272010-11-17 07:26:20 +0000346 if (!Tok.needsCleaning())
Richard Smith30cddae2012-11-28 07:29:00 +0000347 return std::string(TokStart, TokStart + Tok.getLength());
348
Chris Lattnerb0607272010-11-17 07:26:20 +0000349 std::string Result;
Richard Smith30cddae2012-11-28 07:29:00 +0000350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattnerb0607272010-11-17 07:26:20 +0000352 return Result;
353}
354
355/// getSpelling - This method is used to get the spelling of a token into a
356/// preallocated buffer, instead of as an std::string. The caller is required
357/// to allocate enough space for the token, which is guaranteed to be at least
358/// Tok.getLength() bytes long. The actual length of the token is returned.
359///
360/// Note that this method may do two possible things: it may either fill in
361/// the buffer specified with characters, or it may *change the input pointer*
362/// to point to a constant buffer with the data already in it (avoiding a
363/// copy). The caller is not allowed to modify the returned buffer pointer
364/// if an internal buffer is returned.
365unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000367 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000369
370 const char *TokStart = 0;
371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
373 TokStart = Tok.getRawIdentifierData();
Jordan Rosec7629d92013-01-24 20:50:46 +0000374 else if (!Tok.hasUCN()) {
375 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
376 // Just return the string from the identifier table, which is very quick.
377 Buffer = II->getNameStart();
378 return II->getLength();
379 }
Chris Lattnerb0607272010-11-17 07:26:20 +0000380 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000381
382 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000383 if (Tok.isLiteral())
384 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000385
Chris Lattnerb0607272010-11-17 07:26:20 +0000386 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000387 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000388 bool CharDataInvalid = false;
389 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
390 if (Invalid)
391 *Invalid = CharDataInvalid;
392 if (CharDataInvalid) {
393 Buffer = "";
394 return 0;
395 }
396 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000397
Chris Lattnerb0607272010-11-17 07:26:20 +0000398 // If this token contains nothing interesting, return it directly.
399 if (!Tok.needsCleaning()) {
400 Buffer = TokStart;
401 return Tok.getLength();
402 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000403
Chris Lattnerb0607272010-11-17 07:26:20 +0000404 // Otherwise, hard case, relex the characters into the string.
Richard Smith30cddae2012-11-28 07:29:00 +0000405 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattnerb0607272010-11-17 07:26:20 +0000406}
407
408
Chris Lattner9a611942007-10-17 21:18:47 +0000409/// MeasureTokenLength - Relex the token at the specified location and return
410/// its length in bytes in the input file. If the token needs cleaning (e.g.
411/// includes a trigraph or an escaped newline) then this count includes bytes
412/// that are part of that.
413unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000414 const SourceManager &SM,
415 const LangOptions &LangOpts) {
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000416 Token TheTok;
417 if (getRawToken(Loc, TheTok, SM, LangOpts))
418 return 0;
419 return TheTok.getLength();
420}
421
422/// \brief Relex the token at the specified location.
423/// \returns true if there was a failure, false on success.
424bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
425 const SourceManager &SM,
426 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000429 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
431 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000432
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000435 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000437 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000439 if (Invalid)
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000440 return true;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000441
442 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000443
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000444 if (isWhitespace(StrData[0]))
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000445 return true;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000446
Chris Lattner9a611942007-10-17 21:18:47 +0000447 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000450 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000451 TheLexer.LexFromRawLexer(Result);
452 return false;
Chris Lattner9a611942007-10-17 21:18:47 +0000453}
454
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000455static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
456 const SourceManager &SM,
457 const LangOptions &LangOpts) {
458 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000460 if (LocInfo.first.isInvalid())
461 return Loc;
462
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000463 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000465 if (Invalid)
466 return Loc;
467
468 // Back up from the current location until we hit the beginning of a line
469 // (or the buffer). We'll relex from that point.
470 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000471 if (LocInfo.second >= Buffer.size())
472 return Loc;
473
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000474 const char *StrData = BufStart+LocInfo.second;
475 if (StrData[0] == '\n' || StrData[0] == '\r')
476 return Loc;
477
478 const char *LexStart = StrData;
479 while (LexStart != BufStart) {
480 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
481 ++LexStart;
482 break;
483 }
484
485 --LexStart;
486 }
487
488 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000489 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000490 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
491 TheLexer.SetCommentRetentionState(true);
492
493 // Lex tokens until we find the token that contains the source location.
494 Token TheTok;
495 do {
496 TheLexer.LexFromRawLexer(TheTok);
497
498 if (TheLexer.getBufferLocation() > StrData) {
499 // Lexing this token has taken the lexer past the source location we're
500 // looking for. If the current token encompasses our source location,
501 // return the beginning of that token.
502 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
503 return TheTok.getLocation();
504
505 // We ended up skipping over the source location entirely, which means
506 // that it points into whitespace. We're done here.
507 break;
508 }
509 } while (TheTok.getKind() != tok::eof);
510
511 // We've passed our source location; just return the original source location.
512 return Loc;
513}
514
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000515SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
516 const SourceManager &SM,
517 const LangOptions &LangOpts) {
518 if (Loc.isFileID())
519 return getBeginningOfFileToken(Loc, SM, LangOpts);
520
521 if (!SM.isMacroArgExpansion(Loc))
522 return Loc;
523
524 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
525 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
526 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000527 std::pair<FileID, unsigned> BeginFileLocInfo
528 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000529 assert(FileLocInfo.first == BeginFileLocInfo.first &&
530 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000531 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000532}
533
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000534namespace {
535 enum PreambleDirectiveKind {
536 PDK_Skipped,
537 PDK_StartIf,
538 PDK_EndIf,
539 PDK_Unknown
540 };
541}
542
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000543std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000544Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000545 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000546 // Create a lexer starting at the beginning of the file. Note that we use a
547 // "fake" file source location at offset 1 so that the lexer will track our
548 // position within the file.
549 const unsigned StartOffset = 1;
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000550 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
551 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000552 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000553
554 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
555 SourceLocation StartLoc = TheLexer.getSourceLocation();
556
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000557 bool InPreprocessorDirective = false;
558 Token TheTok;
559 Token IfStartTok;
560 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000561
562 unsigned MaxLineOffset = 0;
563 if (MaxLines) {
564 const char *CurPtr = Buffer->getBufferStart();
565 unsigned CurLine = 0;
566 while (CurPtr != Buffer->getBufferEnd()) {
567 char ch = *CurPtr++;
568 if (ch == '\n') {
569 ++CurLine;
570 if (CurLine == MaxLines)
571 break;
572 }
573 }
574 if (CurPtr != Buffer->getBufferEnd())
575 MaxLineOffset = CurPtr - Buffer->getBufferStart();
576 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000577
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000578 do {
579 TheLexer.LexFromRawLexer(TheTok);
580
581 if (InPreprocessorDirective) {
582 // If we've hit the end of the file, we're done.
583 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000584 break;
585 }
586
587 // If we haven't hit the end of the preprocessor directive, skip this
588 // token.
589 if (!TheTok.isAtStartOfLine())
590 continue;
591
592 // We've passed the end of the preprocessor directive, and will look
593 // at this token again below.
594 InPreprocessorDirective = false;
595 }
596
Douglas Gregordf95a132010-08-09 20:45:32 +0000597 // Keep track of the # of lines in the preamble.
598 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000599 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000600
601 // If we were asked to limit the number of lines in the preamble,
602 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000603 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000604 break;
605 }
606
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000607 // Comments are okay; skip over them.
608 if (TheTok.getKind() == tok::comment)
609 continue;
610
611 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
612 // This is the start of a preprocessor directive.
613 Token HashTok = TheTok;
614 InPreprocessorDirective = true;
615
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000616 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000617 // we don't have an identifier table available. Instead, just look at
618 // the raw identifier to recognize and categorize preprocessor directives.
619 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000620 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000621 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000622 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000623 PreambleDirectiveKind PDK
624 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
625 .Case("include", PDK_Skipped)
626 .Case("__include_macros", PDK_Skipped)
627 .Case("define", PDK_Skipped)
628 .Case("undef", PDK_Skipped)
629 .Case("line", PDK_Skipped)
630 .Case("error", PDK_Skipped)
631 .Case("pragma", PDK_Skipped)
632 .Case("import", PDK_Skipped)
633 .Case("include_next", PDK_Skipped)
634 .Case("warning", PDK_Skipped)
635 .Case("ident", PDK_Skipped)
636 .Case("sccs", PDK_Skipped)
637 .Case("assert", PDK_Skipped)
638 .Case("unassert", PDK_Skipped)
639 .Case("if", PDK_StartIf)
640 .Case("ifdef", PDK_StartIf)
641 .Case("ifndef", PDK_StartIf)
642 .Case("elif", PDK_Skipped)
643 .Case("else", PDK_Skipped)
644 .Case("endif", PDK_EndIf)
645 .Default(PDK_Unknown);
646
647 switch (PDK) {
648 case PDK_Skipped:
649 continue;
650
651 case PDK_StartIf:
652 if (IfCount == 0)
653 IfStartTok = HashTok;
654
655 ++IfCount;
656 continue;
657
658 case PDK_EndIf:
659 // Mismatched #endif. The preamble ends here.
660 if (IfCount == 0)
661 break;
662
663 --IfCount;
664 continue;
665
666 case PDK_Unknown:
667 // We don't know what this directive is; stop at the '#'.
668 break;
669 }
670 }
671
672 // We only end up here if we didn't recognize the preprocessor
673 // directive or it was one that can't occur in the preamble at this
674 // point. Roll back the current token to the location of the '#'.
675 InPreprocessorDirective = false;
676 TheTok = HashTok;
677 }
678
Douglas Gregordf95a132010-08-09 20:45:32 +0000679 // We hit a token that we don't recognize as being in the
680 // "preprocessing only" part of the file, so we're no longer in
681 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000682 break;
683 } while (true);
684
685 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000686 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
687 IfCount? IfStartTok.isAtStartOfLine()
688 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000689}
690
Chris Lattner7ef5c272010-11-17 07:05:50 +0000691
692/// AdvanceToTokenCharacter - Given a location that specifies the start of a
693/// token, return a new location that specifies a character within the token.
694SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
695 unsigned CharNo,
696 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000697 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000698 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000699 // character is. This needs to take into consideration newlines and
700 // trigraphs.
701 bool Invalid = false;
702 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
703
704 // If they request the first char of the token, we're trivially done.
705 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
706 return TokStart;
707
708 unsigned PhysOffset = 0;
709
710 // The usual case is that tokens don't contain anything interesting. Skip
711 // over the uninteresting characters. If a token only consists of simple
712 // chars, this method is extremely fast.
713 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
714 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000715 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000716 ++TokPtr, --CharNo, ++PhysOffset;
717 }
718
719 // If we have a character that may be a trigraph or escaped newline, use a
720 // lexer to parse it correctly.
721 for (; CharNo; --CharNo) {
722 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000723 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000724 TokPtr += Size;
725 PhysOffset += Size;
726 }
727
728 // Final detail: if we end up on an escaped newline, we want to return the
729 // location of the actual byte of the token. For example foo\<newline>bar
730 // advanced by 3 should return the location of b, not of \\. One compounding
731 // detail of this is that the escape may be made by a trigraph.
732 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
733 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
734
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000735 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000736}
737
738/// \brief Computes the source location just past the end of the
739/// token at this source location.
740///
741/// This routine can be used to produce a source location that
742/// points just past the end of the token referenced by \p Loc, and
743/// is generally used when a diagnostic needs to point just after a
744/// token where it expected something different that it received. If
745/// the returned source location would not be meaningful (e.g., if
746/// it points into a macro), this routine returns an invalid
747/// source location.
748///
749/// \param Offset an offset from the end of the token, where the source
750/// location should refer to. The default offset (0) produces a source
751/// location pointing just past the end of the token; an offset of 1 produces
752/// a source location pointing to the last character in the token, etc.
753SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
754 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000755 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000756 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000757 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000758
759 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000760 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000761 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000762 }
763
David Blaikie4e4d0842012-03-11 07:00:24 +0000764 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000765 if (Len > Offset)
766 Len = Len - Offset;
767 else
768 return Loc;
769
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000770 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000771}
772
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000773/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000774/// token of the macro expansion.
775bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000776 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000777 const LangOptions &LangOpts,
778 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000779 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
780
781 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
782 // FIXME: If the token comes from the macro token paste operator ('##')
783 // this function will always return false;
784 if (infoLoc.second > 0)
785 return false; // Does not point at the start of token.
786
Chandler Carruth433db062011-07-14 08:20:40 +0000787 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000788 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000789 if (expansionLoc.isFileID()) {
790 // No other macro expansions, this is the first.
791 if (MacroBegin)
792 *MacroBegin = expansionLoc;
793 return true;
794 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000795
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000796 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000797}
798
799/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000800/// token of the macro expansion.
801bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000802 const SourceManager &SM,
803 const LangOptions &LangOpts,
804 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000805 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
806
807 SourceLocation spellLoc = SM.getSpellingLoc(loc);
808 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
809 if (tokLen == 0)
810 return false;
811
812 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000813 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000814 if (SM.isInFileID(afterLoc, FID))
815 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000816
817 // FIXME: If the token comes from the macro token paste operator ('##')
818 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000819
Chandler Carruth433db062011-07-14 08:20:40 +0000820 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000821 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000822 if (expansionLoc.isFileID()) {
823 // No other macro expansions.
824 if (MacroEnd)
825 *MacroEnd = expansionLoc;
826 return true;
827 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000828
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000829 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000830}
831
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000832static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000833 const SourceManager &SM,
834 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000835 SourceLocation Begin = Range.getBegin();
836 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000837 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000838 if (Range.isTokenRange()) {
839 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
840 if (End.isInvalid())
841 return CharSourceRange();
842 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000843
844 // Break down the source locations.
845 FileID FID;
846 unsigned BeginOffs;
847 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
848 if (FID.isInvalid())
849 return CharSourceRange();
850
851 unsigned EndOffs;
852 if (!SM.isInFileID(End, FID, &EndOffs) ||
853 BeginOffs > EndOffs)
854 return CharSourceRange();
855
856 return CharSourceRange::getCharRange(Begin, End);
857}
858
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000859CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000860 const SourceManager &SM,
861 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000862 SourceLocation Begin = Range.getBegin();
863 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000864 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000865 return CharSourceRange();
866
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000867 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000868 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000869
870 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000871 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
872 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000873 Range.setBegin(Begin);
874 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000875 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000876
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000877 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000878 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
879 &End)) ||
880 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
881 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000882 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000883 Range.setEnd(End);
884 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000885 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000886
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000887 assert(Begin.isMacroID() && End.isMacroID());
888 SourceLocation MacroBegin, MacroEnd;
889 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000890 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
891 &MacroEnd)) ||
892 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
893 &MacroEnd)))) {
894 Range.setBegin(MacroBegin);
895 Range.setEnd(MacroEnd);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
897 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000898
899 FileID FID;
900 unsigned BeginOffs;
901 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
902 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000903 return CharSourceRange();
904
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000905 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000906 if (!SM.isInFileID(End, FID, &EndOffs) ||
907 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000908 return CharSourceRange();
909
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000910 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
911 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
912 if (Expansion.isMacroArgExpansion() &&
913 Expansion.getSpellingLoc().isFileID()) {
914 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000915 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
916 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
917 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000918 }
919
920 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000921}
922
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000923StringRef Lexer::getSourceText(CharSourceRange Range,
924 const SourceManager &SM,
925 const LangOptions &LangOpts,
926 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000927 Range = makeFileCharRange(Range, SM, LangOpts);
928 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000929 if (Invalid) *Invalid = true;
930 return StringRef();
931 }
932
933 // Break down the source location.
934 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
935 if (beginInfo.first.isInvalid()) {
936 if (Invalid) *Invalid = true;
937 return StringRef();
938 }
939
940 unsigned EndOffs;
941 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
942 beginInfo.second > EndOffs) {
943 if (Invalid) *Invalid = true;
944 return StringRef();
945 }
946
947 // Try to the load the file buffer.
948 bool invalidTemp = false;
949 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
950 if (invalidTemp) {
951 if (Invalid) *Invalid = true;
952 return StringRef();
953 }
954
955 if (Invalid) *Invalid = false;
956 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
957}
958
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000959StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
960 const SourceManager &SM,
961 const LangOptions &LangOpts) {
962 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000963
964 // Find the location of the immediate macro expansion.
965 while (1) {
966 FileID FID = SM.getFileID(Loc);
967 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
968 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
969 Loc = Expansion.getExpansionLocStart();
970 if (!Expansion.isMacroArgExpansion())
971 break;
972
973 // For macro arguments we need to check that the argument did not come
974 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
975
976 // Loc points to the argument id of the macro definition, move to the
977 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000978 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000979 SourceLocation SpellLoc = Expansion.getSpellingLoc();
980 if (SpellLoc.isFileID())
981 break; // No inner macro.
982
983 // If spelling location resides in the same FileID as macro expansion
984 // location, it means there is no inner macro.
985 FileID MacroFID = SM.getFileID(Loc);
986 if (SM.isInFileID(SpellLoc, MacroFID))
987 break;
988
989 // Argument came from inner macro.
990 Loc = SpellLoc;
991 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000992
993 // Find the spelling location of the start of the non-argument expansion
994 // range. This is where the macro name was spelled in order to begin
995 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000996 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000997
998 // Dig out the buffer where the macro name was spelled and the extents of the
999 // name so that we can render it into the expansion note.
1000 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1001 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1002 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1003 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1004}
1005
Jordan Rosed880b3a2012-06-07 01:10:31 +00001006bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rose98939022013-02-08 22:30:22 +00001007 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rosed880b3a2012-06-07 01:10:31 +00001008}
1009
Reid Spencer5f016e22007-07-11 17:01:13 +00001010
1011//===----------------------------------------------------------------------===//
1012// Diagnostics forwarding code.
1013//===----------------------------------------------------------------------===//
1014
Chris Lattner409a0362007-07-22 18:38:25 +00001015/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001016/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001017/// This is currently only used for _Pragma implementation, so it is the slow
1018/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001019static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1020 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001021static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1022 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001023 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001024 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner409a0362007-07-22 18:38:25 +00001026 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001027 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001028 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001029 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chandler Carruth433db062011-07-14 08:20:40 +00001031 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001032 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001033 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001034 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattnere7fb4842009-02-15 20:52:18 +00001036 // Figure out the expansion loc range, which is the range covered by the
1037 // original _Pragma(...) sequence.
1038 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001039 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chandler Carruthbf340e42011-07-26 03:03:05 +00001041 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001042}
1043
Reid Spencer5f016e22007-07-11 17:01:13 +00001044/// getSourceLocation - Return a source location identifier for the specified
1045/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001046SourceLocation Lexer::getSourceLocation(const char *Loc,
1047 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001048 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001050
1051 // In the normal case, we're just lexing from a simple file buffer, return
1052 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001053 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001054 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001055 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Chris Lattner2b2453a2009-01-17 06:22:33 +00001057 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1058 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001059 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001060 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001061}
1062
Reid Spencer5f016e22007-07-11 17:01:13 +00001063/// Diag - Forwarding function for diagnostics. This translate a source
1064/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001065DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001066 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001067}
Reid Spencer5f016e22007-07-11 17:01:13 +00001068
1069//===----------------------------------------------------------------------===//
1070// Trigraph and Escaped Newline Handling Code.
1071//===----------------------------------------------------------------------===//
1072
1073/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1074/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1075static char GetTrigraphCharForLetter(char Letter) {
1076 switch (Letter) {
1077 default: return 0;
1078 case '=': return '#';
1079 case ')': return ']';
1080 case '(': return '[';
1081 case '!': return '|';
1082 case '\'': return '^';
1083 case '>': return '}';
1084 case '/': return '\\';
1085 case '<': return '{';
1086 case '-': return '~';
1087 }
1088}
1089
1090/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1091/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1092/// return the result character. Finally, emit a warning about trigraph use
1093/// whether trigraphs are enabled or not.
1094static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1095 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001096 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
David Blaikie4e4d0842012-03-11 07:00:24 +00001098 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001099 if (!L->isLexingRawMode())
1100 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001101 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 }
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Chris Lattner74d15df2008-11-22 02:02:22 +00001104 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001105 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 return Res;
1107}
1108
Chris Lattner24f0e482009-04-18 22:05:41 +00001109/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1110/// 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 +00001111/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001112unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1113 unsigned Size = 0;
1114 while (isWhitespace(Ptr[Size])) {
1115 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner24f0e482009-04-18 22:05:41 +00001117 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1118 continue;
1119
1120 // If this is a \r\n or \n\r, skip the other half.
1121 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1122 Ptr[Size-1] != Ptr[Size])
1123 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Chris Lattner24f0e482009-04-18 22:05:41 +00001125 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001126 }
1127
Chris Lattner24f0e482009-04-18 22:05:41 +00001128 // Not an escaped newline, must be a \t or something else.
1129 return 0;
1130}
1131
Chris Lattner03374952009-04-18 22:27:02 +00001132/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1133/// them), skip over them and return the first non-escaped-newline found,
1134/// otherwise return P.
1135const char *Lexer::SkipEscapedNewLines(const char *P) {
1136 while (1) {
1137 const char *AfterEscape;
1138 if (*P == '\\') {
1139 AfterEscape = P+1;
1140 } else if (*P == '?') {
1141 // If not a trigraph for escape, bail out.
1142 if (P[1] != '?' || P[2] != '/')
1143 return P;
1144 AfterEscape = P+3;
1145 } else {
1146 return P;
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner03374952009-04-18 22:27:02 +00001149 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1150 if (NewLineSize == 0) return P;
1151 P = AfterEscape+NewLineSize;
1152 }
1153}
1154
Anna Zaksaca25bc2011-07-27 21:43:43 +00001155/// \brief Checks that the given token is the first token that occurs after the
1156/// given location (this excludes comments and whitespace). Returns the location
1157/// immediately after the specified token. If the token is not found or the
1158/// location is inside a macro, the returned source location will be invalid.
1159SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1160 tok::TokenKind TKind,
1161 const SourceManager &SM,
1162 const LangOptions &LangOpts,
1163 bool SkipTrailingWhitespaceAndNewLine) {
1164 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001165 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001166 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001167 }
1168 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1169
1170 // Break down the source location.
1171 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1172
1173 // Try to load the file buffer.
1174 bool InvalidTemp = false;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001175 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001176 if (InvalidTemp)
1177 return SourceLocation();
1178
1179 const char *TokenBegin = File.data() + LocInfo.second;
1180
1181 // Lex from the start of the given location.
1182 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1183 TokenBegin, File.end());
1184 // Find the token.
1185 Token Tok;
1186 lexer.LexFromRawLexer(Tok);
1187 if (Tok.isNot(TKind))
1188 return SourceLocation();
1189 SourceLocation TokenLoc = Tok.getLocation();
1190
1191 // Calculate how much whitespace needs to be skipped if any.
1192 unsigned NumWhitespaceChars = 0;
1193 if (SkipTrailingWhitespaceAndNewLine) {
1194 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1195 Tok.getLength();
1196 unsigned char C = *TokenEnd;
1197 while (isHorizontalWhitespace(C)) {
1198 C = *(++TokenEnd);
1199 NumWhitespaceChars++;
1200 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001201
1202 // Skip \r, \n, \r\n, or \n\r
1203 if (C == '\n' || C == '\r') {
1204 char PrevC = C;
1205 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001206 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001207 if ((C == '\n' || C == '\r') && C != PrevC)
1208 NumWhitespaceChars++;
1209 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001210 }
1211
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001212 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001213}
Chris Lattner24f0e482009-04-18 22:05:41 +00001214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1216/// get its size, and return it. This is tricky in several cases:
1217/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1218/// then either return the trigraph (skipping 3 chars) or the '?',
1219/// depending on whether trigraphs are enabled or not.
1220/// 2. If this is an escaped newline (potentially with whitespace between
1221/// the backslash and newline), implicitly skip the newline and return
1222/// the char after it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001223///
1224/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1225/// know that we can accumulate into Size, and that we have already incremented
1226/// Ptr by Size bytes.
1227///
1228/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1229/// be updated to match.
1230///
1231char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001232 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // If we have a slash, look for an escaped newline.
1234 if (Ptr[0] == '\\') {
1235 ++Size;
1236 ++Ptr;
1237Slash:
1238 // Common case, backslash-char where the char is not whitespace.
1239 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Chris Lattner5636a3b2009-06-23 05:15:06 +00001241 // See if we have optional whitespace characters between the slash and
1242 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001243 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1244 // Remember that this token needs to be cleaned.
1245 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001246
Chris Lattner24f0e482009-04-18 22:05:41 +00001247 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001248 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001249 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Chris Lattner24f0e482009-04-18 22:05:41 +00001251 // Found backslash<whitespace><newline>. Parse the char after it.
1252 Size += EscapedNewLineSize;
1253 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001254
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001255 // If the char that we finally got was a \n, then we must have had
1256 // something like \<newline><newline>. We don't want to consume the
1257 // second newline.
1258 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1259 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001260
Chris Lattner24f0e482009-04-18 22:05:41 +00001261 // Use slow version to accumulate a correct size field.
1262 return getCharAndSizeSlow(Ptr, Size, Tok);
1263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // Otherwise, this is not an escaped newline, just return the slash.
1266 return '\\';
1267 }
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 // If this is a trigraph, process it.
1270 if (Ptr[0] == '?' && Ptr[1] == '?') {
1271 // If this is actually a legal trigraph (not something like "??x"), emit
1272 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1273 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1274 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001275 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001276
1277 Ptr += 3;
1278 Size += 3;
1279 if (C == '\\') goto Slash;
1280 return C;
1281 }
1282 }
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 // If this is neither, return a single character.
1285 ++Size;
1286 return *Ptr;
1287}
1288
1289
1290/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1291/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1292/// and that we have already incremented Ptr by Size bytes.
1293///
1294/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1295/// be updated to match.
1296char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001297 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If we have a slash, look for an escaped newline.
1299 if (Ptr[0] == '\\') {
1300 ++Size;
1301 ++Ptr;
1302Slash:
1303 // Common case, backslash-char where the char is not whitespace.
1304 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001307 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1308 // Found backslash<whitespace><newline>. Parse the char after it.
1309 Size += EscapedNewLineSize;
1310 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001311
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001312 // If the char that we finally got was a \n, then we must have had
1313 // something like \<newline><newline>. We don't want to consume the
1314 // second newline.
1315 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1316 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001317
Chris Lattner24f0e482009-04-18 22:05:41 +00001318 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001319 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001320 }
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 // Otherwise, this is not an escaped newline, just return the slash.
1323 return '\\';
1324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001327 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 // If this is actually a legal trigraph (not something like "??x"), return
1329 // it.
1330 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1331 Ptr += 3;
1332 Size += 3;
1333 if (C == '\\') goto Slash;
1334 return C;
1335 }
1336 }
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 // If this is neither, return a single character.
1339 ++Size;
1340 return *Ptr;
1341}
1342
1343//===----------------------------------------------------------------------===//
1344// Helper methods for lexing.
1345//===----------------------------------------------------------------------===//
1346
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001347/// \brief Routine that indiscriminately skips bytes in the source file.
1348void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1349 BufferPtr += Bytes;
1350 if (BufferPtr > BufferEnd)
1351 BufferPtr = BufferEnd;
1352 IsAtStartOfLine = StartOfLine;
1353}
1354
Jordan Roseed9c59f2013-02-09 01:10:25 +00001355static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1356 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1357 return isCharInSet(C, C11AllowedIDChars);
1358 else if (LangOpts.CPlusPlus)
1359 return isCharInSet(C, CXX03AllowedIDChars);
1360 else
1361 return isCharInSet(C, C99AllowedIDChars);
Jordan Rosec7629d92013-01-24 20:50:46 +00001362}
1363
Jordan Roseed9c59f2013-02-09 01:10:25 +00001364static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1365 assert(isAllowedIDChar(C, LangOpts));
1366 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1367 return !isCharInSet(C, C11DisallowedInitialIDChars);
1368 else if (LangOpts.CPlusPlus)
1369 return true;
1370 else
1371 return !isCharInSet(C, C99DisallowedInitialIDChars);
1372}
Jordan Rosec7629d92013-01-24 20:50:46 +00001373
Jordan Roseed9c59f2013-02-09 01:10:25 +00001374static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1375 const char *End) {
1376 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1377 L.getSourceLocation(End));
1378}
1379
1380static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1381 CharSourceRange Range, bool IsFirst) {
1382 // Check C99 compatibility.
1383 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1384 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1385 enum {
1386 CannotAppearInIdentifier = 0,
1387 CannotStartIdentifier
1388 };
1389
1390 if (!isCharInSet(C, C99AllowedIDChars)) {
1391 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1392 << Range
1393 << CannotAppearInIdentifier;
1394 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1395 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1396 << Range
1397 << CannotStartIdentifier;
1398 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001399 }
1400
Jordan Roseed9c59f2013-02-09 01:10:25 +00001401 // Check C++98 compatibility.
1402 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1403 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1404 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1405 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1406 << Range;
1407 }
1408 }
1409 }
Jordan Rosec7629d92013-01-24 20:50:46 +00001410
Chris Lattnerd2177732007-07-20 16:59:19 +00001411void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1413 unsigned Size;
1414 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001415 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 --CurPtr; // Back up over the skipped character.
1419
1420 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1421 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattnercd991db2010-01-11 02:38:50 +00001422 //
Jordan Rose98939022013-02-08 22:30:22 +00001423 // TODO: Could merge these checks into an InfoTable flag to make the
1424 // comparison cheaper
Jordan Rosec7629d92013-01-24 20:50:46 +00001425 if (isASCII(C) && C != '\\' && C != '?' &&
1426 (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001427FinishIdentifier:
1428 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001429 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1430 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 // If we are in raw mode, return this identifier raw. There is no need to
1433 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001434 if (LexingRawMode)
1435 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001437 // Fill in Result.IdentifierInfo and update the token kind,
1438 // looking up the identifier in the identifier table.
1439 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 // Finally, now that we know we have an identifier, pass this off to the
1442 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001443 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001444 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001445
Chris Lattner6a170eb2009-01-21 07:43:11 +00001446 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 C = getCharAndSize(CurPtr, Size);
1452 while (1) {
1453 if (C == '$') {
1454 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001455 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001458 if (!isLexingRawMode())
1459 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 CurPtr = ConsumeChar(CurPtr, Size, Result);
1461 C = getCharAndSize(CurPtr, Size);
1462 continue;
Jordan Rosec7629d92013-01-24 20:50:46 +00001463
1464 } else if (C == '\\') {
1465 const char *UCNPtr = CurPtr + Size;
1466 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Roseed9c59f2013-02-09 01:10:25 +00001467 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001468 goto FinishIdentifier;
1469
Jordan Roseed9c59f2013-02-09 01:10:25 +00001470 if (!isLexingRawMode()) {
1471 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1472 makeCharRange(*this, CurPtr, UCNPtr),
1473 /*IsFirst=*/false);
1474 }
1475
Jordan Rosec7629d92013-01-24 20:50:46 +00001476 Result.setFlag(Token::HasUCN);
1477 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1478 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1479 CurPtr = UCNPtr;
1480 else
1481 while (CurPtr != UCNPtr)
1482 (void)getAndAdvanceChar(CurPtr, Result);
1483
1484 C = getCharAndSize(CurPtr, Size);
1485 continue;
1486 } else if (!isASCII(C)) {
1487 const char *UnicodePtr = CurPtr;
1488 UTF32 CodePoint;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00001489 ConversionResult Result =
1490 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1491 (const UTF8 *)BufferEnd,
1492 &CodePoint,
1493 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00001494 if (Result != conversionOK ||
Jordan Roseed9c59f2013-02-09 01:10:25 +00001495 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rosec7629d92013-01-24 20:50:46 +00001496 goto FinishIdentifier;
1497
Jordan Roseed9c59f2013-02-09 01:10:25 +00001498 if (!isLexingRawMode()) {
1499 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1500 makeCharRange(*this, CurPtr, UnicodePtr),
1501 /*IsFirst=*/false);
1502 }
1503
Jordan Rosec7629d92013-01-24 20:50:46 +00001504 CurPtr = UnicodePtr;
1505 C = getCharAndSize(CurPtr, Size);
1506 continue;
1507 } else if (!isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 goto FinishIdentifier;
1509 }
1510
1511 // Otherwise, this character is good, consume it.
1512 CurPtr = ConsumeChar(CurPtr, Size, Result);
1513
1514 C = getCharAndSize(CurPtr, Size);
Jordan Rosec7629d92013-01-24 20:50:46 +00001515 while (isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 CurPtr = ConsumeChar(CurPtr, Size, Result);
1517 C = getCharAndSize(CurPtr, Size);
1518 }
1519 }
1520}
1521
Douglas Gregora75ec432010-08-30 14:50:47 +00001522/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001523/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001524bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001525 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001526 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001527 if (C1 != '0')
1528 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001529 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001530 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001531}
Reid Spencer5f016e22007-07-11 17:01:13 +00001532
Nate Begeman5253c7f2008-04-14 02:26:39 +00001533/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001534/// constant. From[-1] is the first character lexed. Return the end of the
1535/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001536void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 unsigned Size;
1538 char C = getCharAndSize(CurPtr, Size);
1539 char PrevCh = 0;
Jordan Rose98939022013-02-08 22:30:22 +00001540 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 CurPtr = ConsumeChar(CurPtr, Size, Result);
1542 PrevCh = C;
1543 C = getCharAndSize(CurPtr, Size);
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001547 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1548 // If we are in Microsoft mode, don't continue if the constant is hex.
1549 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001550 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001551 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1552 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
1554 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001555 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1556 // Outside C99, we accept hexadecimal floating point numbers as a
1557 // not-quite-conforming extension. Only do so if this looks like it's
1558 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1559 bool IsHexFloat = true;
1560 if (!LangOpts.C99) {
1561 if (!isHexaLiteral(BufferPtr, LangOpts))
1562 IsHexFloat = false;
1563 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1564 IsHexFloat = false;
1565 }
1566 if (IsHexFloat)
1567 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1568 }
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001571 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001572 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001573 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574}
1575
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001576/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001577/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001578const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001579 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001580
1581 // Maximally munch an identifier. FIXME: UCNs.
1582 unsigned Size;
1583 char C = getCharAndSize(CurPtr, Size);
1584 if (isIdentifierHead(C)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001585 if (!getLangOpts().CPlusPlus11) {
Richard Smithe816c712012-03-07 03:13:00 +00001586 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001587 Diag(CurPtr,
1588 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1589 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1590 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1591 return CurPtr;
1592 }
1593
1594 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1595 // that does not start with an underscore is ill-formed. As a conforming
1596 // extension, we treat all such suffixes as if they had whitespace before
1597 // them.
1598 if (C != '_') {
1599 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001600 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1601 diag::ext_ms_reserved_user_defined_literal :
1602 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001603 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1604 return CurPtr;
1605 }
1606
Richard Smith99831e42012-03-06 03:21:47 +00001607 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001608 do {
1609 CurPtr = ConsumeChar(CurPtr, Size, Result);
1610 C = getCharAndSize(CurPtr, Size);
1611 } while (isIdentifierBody(C));
1612 }
1613 return CurPtr;
1614}
1615
Reid Spencer5f016e22007-07-11 17:01:13 +00001616/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001617/// either " or L" or u8" or u" or U".
1618void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1619 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Richard Smith661a9962011-10-15 01:18:56 +00001622 if (!isLexingRawMode() &&
1623 (Kind == tok::utf8_string_literal ||
1624 Kind == tok::utf16_string_literal ||
1625 Kind == tok::utf32_string_literal))
1626 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 char C = getAndAdvanceChar(CurPtr, Result);
1629 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001630 // Skip escaped characters. Escaped newlines will already be processed by
1631 // getAndAdvanceChar.
1632 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001634
Chris Lattner571339c2010-05-30 23:27:38 +00001635 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001636 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001637 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001638 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001639 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 }
Chris Lattner571339c2010-05-30 23:27:38 +00001642
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001643 if (C == 0) {
1644 if (isCodeCompletionPoint(CurPtr-1)) {
1645 PP->CodeCompleteNaturalLanguage();
1646 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1647 return cutOffLexing();
1648 }
1649
Chris Lattner571339c2010-05-30 23:27:38 +00001650 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001651 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 C = getAndAdvanceChar(CurPtr, Result);
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001655 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001656 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001657 CurPtr = LexUDSuffix(Result, CurPtr);
1658
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001660 if (NulCharacter && !isLexingRawMode())
1661 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001664 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001665 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001666 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001667}
1668
Craig Topper2fa4e862011-08-11 04:06:15 +00001669/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1670/// having lexed R", LR", u8R", uR", or UR".
1671void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1672 tok::TokenKind Kind) {
1673 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1674 // Between the initial and final double quote characters of the raw string,
1675 // any transformations performed in phases 1 and 2 (trigraphs,
1676 // universal-character-names, and line splicing) are reverted.
1677
Richard Smith661a9962011-10-15 01:18:56 +00001678 if (!isLexingRawMode())
1679 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1680
Craig Topper2fa4e862011-08-11 04:06:15 +00001681 unsigned PrefixLen = 0;
1682
1683 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1684 ++PrefixLen;
1685
1686 // If the last character was not a '(', then we didn't lex a valid delimiter.
1687 if (CurPtr[PrefixLen] != '(') {
1688 if (!isLexingRawMode()) {
1689 const char *PrefixEnd = &CurPtr[PrefixLen];
1690 if (PrefixLen == 16) {
1691 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1692 } else {
1693 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1694 << StringRef(PrefixEnd, 1);
1695 }
1696 }
1697
1698 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1699 // it's possible the '"' was intended to be part of the raw string, but
1700 // there's not much we can do about that.
1701 while (1) {
1702 char C = *CurPtr++;
1703
1704 if (C == '"')
1705 break;
1706 if (C == 0 && CurPtr-1 == BufferEnd) {
1707 --CurPtr;
1708 break;
1709 }
1710 }
1711
1712 FormTokenWithChars(Result, CurPtr, tok::unknown);
1713 return;
1714 }
1715
1716 // Save prefix and move CurPtr past it
1717 const char *Prefix = CurPtr;
1718 CurPtr += PrefixLen + 1; // skip over prefix and '('
1719
1720 while (1) {
1721 char C = *CurPtr++;
1722
1723 if (C == ')') {
1724 // Check for prefix match and closing quote.
1725 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1726 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1727 break;
1728 }
1729 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1730 if (!isLexingRawMode())
1731 Diag(BufferPtr, diag::err_unterminated_raw_string)
1732 << StringRef(Prefix, PrefixLen);
1733 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1734 return;
1735 }
1736 }
1737
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001738 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001739 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001740 CurPtr = LexUDSuffix(Result, CurPtr);
1741
Craig Topper2fa4e862011-08-11 04:06:15 +00001742 // Update the location of token as well as BufferPtr.
1743 const char *TokStart = BufferPtr;
1744 FormTokenWithChars(Result, CurPtr, Kind);
1745 Result.setLiteralData(TokStart);
1746}
1747
Reid Spencer5f016e22007-07-11 17:01:13 +00001748/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1749/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001750void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001752 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001753 char C = getAndAdvanceChar(CurPtr, Result);
1754 while (C != '>') {
1755 // Skip escaped characters.
1756 if (C == '\\') {
1757 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001758 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001760 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1761 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001762 // If the filename is unterminated, then it must just be a lone <
1763 // character. Return this as such.
1764 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 return;
1766 } else if (C == 0) {
1767 NulCharacter = CurPtr-1;
1768 }
1769 C = getAndAdvanceChar(CurPtr, Result);
1770 }
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001773 if (NulCharacter && !isLexingRawMode())
1774 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001777 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001778 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001779 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001780}
1781
1782
1783/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001784/// lexed either ' or L' or u' or U'.
1785void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1786 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 const char *NulCharacter = 0; // Does this character contain the \0 character?
1788
Richard Smith661a9962011-10-15 01:18:56 +00001789 if (!isLexingRawMode() &&
1790 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1791 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1792
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 char C = getAndAdvanceChar(CurPtr, Result);
1794 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001795 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001796 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001797 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001799 }
1800
1801 while (C != '\'') {
1802 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001803 if (C == '\\')
1804 C = getAndAdvanceChar(CurPtr, Result);
1805
1806 if (C == '\n' || C == '\r' || // Newline.
1807 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001808 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001809 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001810 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1811 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001812 }
1813
1814 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001815 if (isCodeCompletionPoint(CurPtr-1)) {
1816 PP->CodeCompleteNaturalLanguage();
1817 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1818 return cutOffLexing();
1819 }
1820
Chris Lattnerd80f7862010-07-07 23:24:27 +00001821 NulCharacter = CurPtr-1;
1822 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 C = getAndAdvanceChar(CurPtr, Result);
1824 }
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001826 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001827 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001828 CurPtr = LexUDSuffix(Result, CurPtr);
1829
Chris Lattnerd80f7862010-07-07 23:24:27 +00001830 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001831 if (NulCharacter && !isLexingRawMode())
1832 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001835 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001836 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001837 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001838}
1839
1840/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1841/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00001842///
1843/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1844///
1845bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001846 // Whitespace - Skip it, then return the token after the whitespace.
1847 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1848 while (1) {
1849 // Skip horizontal whitespace very aggressively.
1850 while (isHorizontalWhitespace(Char))
1851 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00001853 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 if (Char != '\n' && Char != '\r')
1855 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 if (ParsingPreprocessorDirective) {
1858 // End of preprocessor directive line, let LexTokenInternal handle this.
1859 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001860 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 }
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 // ok, but handle newline.
1864 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00001865 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00001867 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 Char = *++CurPtr;
1869 }
1870
1871 // If this isn't immediately after a newline, there is leading space.
1872 char PrevChar = CurPtr[-1];
1873 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00001874 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00001875
Chris Lattnerd88dc482008-10-12 04:05:48 +00001876 // If the client wants us to return whitespace, return it now.
1877 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00001878 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00001879 return true;
1880 }
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00001883 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001884}
1885
Nico Weberbb236282012-11-11 07:02:14 +00001886/// We have just read the // characters from input. Skip until we find the
1887/// newline character thats terminate the comment. Then update BufferPtr and
1888/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00001889///
1890/// If we're in KeepCommentMode or any CommentHandler has inserted
1891/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00001892bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1893 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00001895 if (!LangOpts.LineComment && !isLexingRawMode()) {
1896 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 // Mark them enabled so we only emit one warning for this translation
1899 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00001900 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 // Scan over the body of the comment. The common case, when scanning, is that
1904 // the comment contains normal ascii characters with nothing interesting in
1905 // them. As such, optimize for this case with the inner loop.
1906 char C;
1907 do {
1908 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 // Skip over characters in the fast loop.
1910 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 C != '\n' && C != '\r') // Newline or DOS-style newline.
1912 C = *++CurPtr;
1913
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001914 const char *NextLine = CurPtr;
1915 if (C != 0) {
1916 // We found a newline, see if it's escaped.
1917 const char *EscapePtr = CurPtr-1;
1918 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1919 --EscapePtr;
1920
1921 if (*EscapePtr == '\\') // Escaped newline.
1922 CurPtr = EscapePtr;
1923 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1924 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1925 CurPtr = EscapePtr-2;
1926 else
1927 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001931 // properly decode the character. Read it in raw mode to avoid emitting
1932 // diagnostics about things like trigraphs. If we see an escaped newline,
1933 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001935 bool OldRawMode = isLexingRawMode();
1936 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001937 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00001938 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00001939
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00001940 // If we only read only one character, then no special handling is needed.
1941 // We're done and can skip forward to the newline.
1942 if (C != 0 && CurPtr == OldPtr+1) {
1943 CurPtr = NextLine;
1944 break;
1945 }
1946
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // If we read multiple characters, and one of those characters was a \r or
1948 // \n, then we had an escaped newline within the comment. Emit diagnostic
1949 // unless the next line is also a // comment.
1950 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1951 for (; OldPtr != CurPtr; ++OldPtr)
1952 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1953 // Okay, we found a // comment that ends in a newline, if the next
1954 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001955 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00001957 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 ++ForwardPtr;
1959 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1960 break;
1961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Chris Lattner74d15df2008-11-22 02:02:22 +00001963 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00001964 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 break;
1966 }
1967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor55817af2010-08-25 17:04:25 +00001969 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00001970 --CurPtr;
1971 break;
1972 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001973
1974 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1975 PP->CodeCompleteNaturalLanguage();
1976 cutOffLexing();
1977 return false;
1978 }
1979
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 } while (C != '\n' && C != '\r');
1981
Chris Lattner3d0ad582010-02-03 21:06:21 +00001982 // Found but did not consume the newline. Notify comment handlers about the
1983 // comment unless we're in a #if 0 block.
1984 if (PP && !isLexingRawMode() &&
1985 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1986 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00001987 BufferPtr = CurPtr;
1988 return true; // A token has to be returned.
1989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00001992 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00001993 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994
1995 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00001996 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
1998 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00001999 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002003 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002004 // contribute to another token), it isn't needed for correctness. Note that
2005 // this is ok even in KeepWhitespaceMode, because we would have returned the
2006 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002010 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002012 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002014 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002015}
2016
Nico Weberbb236282012-11-11 07:02:14 +00002017/// If in save-comment mode, package up this Line comment in an appropriate
2018/// way and return it.
2019bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002020 // If we're not in a preprocessor directive, just return the // comment
2021 // directly.
2022 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002023
David Blaikie8c0b3782012-06-06 18:52:13 +00002024 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002025 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Nico Weberbb236282012-11-11 07:02:14 +00002027 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002028 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002029 bool Invalid = false;
2030 std::string Spelling = PP->getSpelling(Result, &Invalid);
2031 if (Invalid)
2032 return true;
2033
Nico Weberbb236282012-11-11 07:02:14 +00002034 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002035 Spelling[1] = '*'; // Change prefix to "/*".
2036 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Chris Lattner9e6293d2008-10-12 04:51:35 +00002038 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002039 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002040 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002041 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002042}
2043
2044/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002045/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2046/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002047static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 Lexer *L) {
2049 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Reid Spencer5f016e22007-07-11 17:01:13 +00002051 // Back up off the newline.
2052 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // If this is a two-character newline sequence, skip the other character.
2055 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2056 // \n\n or \r\r -> not escaped newline.
2057 if (CurPtr[0] == CurPtr[1])
2058 return false;
2059 // \n\r or \r\n -> skip the newline.
2060 --CurPtr;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 // If we have horizontal whitespace, skip over it. We allow whitespace
2064 // between the slash and newline.
2065 bool HasSpace = false;
2066 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2067 --CurPtr;
2068 HasSpace = true;
2069 }
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 // If we have a slash, we know this is an escaped newline.
2072 if (*CurPtr == '\\') {
2073 if (CurPtr[-1] != '*') return false;
2074 } else {
2075 // It isn't a slash, is it the ?? / trigraph?
2076 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2077 CurPtr[-3] != '*')
2078 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 // This is the trigraph ending the comment. Emit a stern warning!
2081 CurPtr -= 2;
2082
2083 // If no trigraphs are enabled, warn that we ignored this trigraph and
2084 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002085 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002086 if (!L->isLexingRawMode())
2087 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 return false;
2089 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002090 if (!L->isLexingRawMode())
2091 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002095 if (!L->isLexingRawMode())
2096 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002099 if (HasSpace && !L->isLexingRawMode())
2100 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 return true;
2103}
2104
2105#ifdef __SSE2__
2106#include <emmintrin.h>
2107#elif __ALTIVEC__
2108#include <altivec.h>
2109#undef bool
2110#endif
2111
James Dennettec769932012-06-17 03:40:43 +00002112/// We have just read from input the / and * characters that started a comment.
2113/// Read until we find the * and / characters that terminate the comment.
2114/// Note that we don't bother decoding trigraphs or escaped newlines in block
2115/// comments, because they cannot cause the comment to end. The only thing
2116/// that can happen is the comment could end with an escaped newline between
2117/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002118///
Chris Lattner046c2272010-01-18 22:35:47 +00002119/// If we're in KeepCommentMode or any CommentHandler has inserted
2120/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002121bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002123 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 // optimization helps people who like to put a lot of * characters in their
2125 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002126
2127 // The first character we get with newlines and trigraphs skipped to handle
2128 // the degenerate /*/ case below correctly if the * has an escaped newline
2129 // after it.
2130 unsigned CharSize;
2131 unsigned char C = getCharAndSize(CurPtr, CharSize);
2132 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002134 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002135 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002136 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Chris Lattner31f0eca2008-10-12 04:19:49 +00002138 // KeepWhitespaceMode should return this broken comment as a token. Since
2139 // it isn't a well formed comment, just return it as an 'unknown' token.
2140 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002141 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002142 return true;
2143 }
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Chris Lattner31f0eca2008-10-12 04:19:49 +00002145 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002146 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Chris Lattner8146b682007-07-21 23:43:37 +00002149 // Check to see if the first character after the '/*' is another /. If so,
2150 // then this slash does not end the block comment, it is part of it.
2151 if (C == '/')
2152 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 while (1) {
2155 // Skip over all non-interesting characters until we find end of buffer or a
2156 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002157 if (CurPtr + 24 < BufferEnd &&
2158 // If there is a code-completion point avoid the fast scan because it
2159 // doesn't check for '\0'.
2160 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 // While not aligned to a 16-byte boundary.
2162 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2163 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 if (C == '/') goto FoundSlash;
2166
2167#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002168 __m128i Slashes = _mm_set1_epi8('/');
2169 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002170 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2171 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002172 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002173 // Adjust the pointer to point directly after the first slash. It's
2174 // not necessary to set C here, it will be overwritten at the end of
2175 // the outer loop.
2176 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002177 goto FoundSlash;
2178 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002180 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002181#elif __ALTIVEC__
2182 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002183 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 '/', '/', '/', '/', '/', '/', '/', '/'
2185 };
2186 while (CurPtr+16 <= BufferEnd &&
2187 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2188 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002189#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 // Scan for '/' quickly. Many block comments are very large.
2191 while (CurPtr[0] != '/' &&
2192 CurPtr[1] != '/' &&
2193 CurPtr[2] != '/' &&
2194 CurPtr[3] != '/' &&
2195 CurPtr+4 < BufferEnd) {
2196 CurPtr += 4;
2197 }
2198#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 // It has to be one of the bytes scanned, increment to it and read one.
2201 C = *CurPtr++;
2202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 // Loop to scan the remainder.
2205 while (C != '/' && C != '\0')
2206 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002209 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 if (CurPtr[-2] == '*') // We found the final */. We're done!
2211 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2214 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2215 // We found the final */, though it had an escaped newline between the
2216 // * and /. We're done!
2217 break;
2218 }
2219 }
2220 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2221 // If this is a /* inside of the comment, emit a warning. Don't do this
2222 // if this is a /*/, which will end the comment. This misses cases with
2223 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002224 if (!isLexingRawMode())
2225 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 }
2227 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002228 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002229 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 // Note: the user probably forgot a */. We could continue immediately
2231 // after the /*, but this would involve lexing a lot of what really is the
2232 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002233 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Chris Lattner31f0eca2008-10-12 04:19:49 +00002235 // KeepWhitespaceMode should return this broken comment as a token. Since
2236 // it isn't a well formed comment, just return it as an 'unknown' token.
2237 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002238 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002239 return true;
2240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Chris Lattner31f0eca2008-10-12 04:19:49 +00002242 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002243 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002244 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2245 PP->CodeCompleteNaturalLanguage();
2246 cutOffLexing();
2247 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002249
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 C = *CurPtr++;
2251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Chris Lattner3d0ad582010-02-03 21:06:21 +00002253 // Notify comment handlers about the comment unless we're in a #if 0 block.
2254 if (PP && !isLexingRawMode() &&
2255 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2256 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002257 BufferPtr = CurPtr;
2258 return true; // A token has to be returned.
2259 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002260
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002262 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002263 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002264 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002265 }
2266
2267 // It is common for the tokens immediately after a /**/ comment to be
2268 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002269 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2270 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002272 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002274 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 }
2276
2277 // Otherwise, just return so that the next character will be lexed as a token.
2278 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002279 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002280 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002281}
2282
2283//===----------------------------------------------------------------------===//
2284// Primary Lexing Entry Points
2285//===----------------------------------------------------------------------===//
2286
Reid Spencer5f016e22007-07-11 17:01:13 +00002287/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2288/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002289void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2291 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002292 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002293
2294 // CurPtr - Cache BufferPtr in an automatic variable.
2295 const char *CurPtr = BufferPtr;
2296 while (1) {
2297 char Char = getAndAdvanceChar(CurPtr, Tmp);
2298 switch (Char) {
2299 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002300 if (Result)
2301 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 break;
2303 case 0: // Null.
2304 // Found end of file?
2305 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002306 if (isCodeCompletionPoint(CurPtr-1)) {
2307 PP->CodeCompleteNaturalLanguage();
2308 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002309 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002310 }
2311
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002313 if (Result)
2314 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 break;
2316 }
2317 // FALL THROUGH.
2318 case '\r':
2319 case '\n':
2320 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2321 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2322 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Peter Collingbourne84021552011-02-28 02:37:51 +00002324 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002326 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002327 if (PP)
2328 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002329 Lex(Tmp);
2330 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002331 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Benjamin Kramer3093b202012-05-18 19:32:16 +00002333 // Finally, we're done;
2334 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 }
2336 }
2337}
2338
2339/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2340/// condition, reporting diagnostics and handling other edge cases as required.
2341/// This returns true if Result contains a token, false if PP.Lex should be
2342/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002343bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 // If we hit the end of the file while parsing a preprocessor directive,
2345 // end the preprocessor directive first. The next token returned will
2346 // then be the end of file.
2347 if (ParsingPreprocessorDirective) {
2348 // Done parsing the "line".
2349 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002351 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002354 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002356 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002357
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 // If we are in raw mode, return this event as an EOF token. Let the caller
2359 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002360 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 Result.startToken();
2362 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002363 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 return true;
2365 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002366
Douglas Gregorf44e8542010-08-24 19:08:16 +00002367 // Issue diagnostics for unterminated #if and missing newline.
2368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 // If we are in a #if directive, emit an error.
2370 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002371 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002372 PP->Diag(ConditionalStack.back().IfLoc,
2373 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 ConditionalStack.pop_back();
2375 }
Mike Stump1eb44332009-09-09 15:08:12 +00002376
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002377 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2378 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002379 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith80ad52f2013-01-02 11:42:31 +00002380 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002381 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2382 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Reid Spencer5f016e22007-07-11 17:01:13 +00002384 BufferPtr = CurPtr;
2385
2386 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002387 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002388}
2389
2390/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2391/// the specified lexer will return a tok::l_paren token, 0 if it is something
2392/// else and 2 if there are no more tokens in the buffer controlled by the
2393/// lexer.
2394unsigned Lexer::isNextPPTokenLParen() {
2395 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 // Switch to 'skipping' mode. This will ensure that we can lex a token
2398 // without emitting diagnostics, disables macro expansion, and will cause EOF
2399 // to return an EOF token instead of popping the include stack.
2400 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 // Save state that can be changed while lexing so that we can restore it.
2403 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002404 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Chris Lattnerd2177732007-07-20 16:59:19 +00002406 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002407 Tok.startToken();
2408 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 // Restore state that may have changed.
2411 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002412 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 // Restore the lexer back to non-skipping mode.
2415 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002417 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002418 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002419 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002420}
2421
James Dennettec769932012-06-17 03:40:43 +00002422/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002423static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2424 ConflictMarkerKind CMK) {
2425 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2426 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2427 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2428 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002429 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002430 // Must occur at start of line.
2431 if (RestOfBuffer[Pos-1] != '\r' &&
2432 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002433 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2434 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002435 continue;
2436 }
2437 return RestOfBuffer.data()+Pos;
2438 }
2439 return 0;
2440}
2441
2442/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2443/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2444/// and recover nicely. This returns true if it is a conflict marker and false
2445/// if not.
2446bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2447 // Only a conflict marker if it starts at the beginning of a line.
2448 if (CurPtr != BufferStart &&
2449 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2450 return false;
2451
Richard Smithd5e1d602011-10-12 00:37:51 +00002452 // Check to see if we have <<<<<<< or >>>>.
2453 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2454 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002455 return false;
2456
2457 // If we have a situation where we don't care about conflict markers, ignore
2458 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002459 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002460 return false;
2461
Richard Smithd5e1d602011-10-12 00:37:51 +00002462 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2463
2464 // Check to see if there is an ending marker somewhere in the buffer at the
2465 // start of a line to terminate this conflict marker.
2466 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002467 // We found a match. We are really in a conflict marker.
2468 // Diagnose this, and ignore to the end of line.
2469 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002470 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002471
2472 // Skip ahead to the end of line. We know this exists because the
2473 // end-of-conflict marker starts with \r or \n.
2474 while (*CurPtr != '\r' && *CurPtr != '\n') {
2475 assert(CurPtr != BufferEnd && "Didn't find end of line");
2476 ++CurPtr;
2477 }
2478 BufferPtr = CurPtr;
2479 return true;
2480 }
2481
2482 // No end of conflict marker found.
2483 return false;
2484}
2485
2486
Richard Smithd5e1d602011-10-12 00:37:51 +00002487/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2488/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2489/// is the end of a conflict marker. Handle it by ignoring up until the end of
2490/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002491bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2492 // Only a conflict marker if it starts at the beginning of a line.
2493 if (CurPtr != BufferStart &&
2494 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2495 return false;
2496
2497 // If we have a situation where we don't care about conflict markers, ignore
2498 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002499 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002500 return false;
2501
Richard Smithd5e1d602011-10-12 00:37:51 +00002502 // Check to see if we have the marker (4 characters in a row).
2503 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002504 if (CurPtr[i] != CurPtr[0])
2505 return false;
2506
2507 // If we do have it, search for the end of the conflict marker. This could
2508 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2509 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002510 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2511 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002512 CurPtr = End;
2513
2514 // Skip ahead to the end of line.
2515 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2516 ++CurPtr;
2517
2518 BufferPtr = CurPtr;
2519
2520 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002521 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002522 return true;
2523 }
2524
2525 return false;
2526}
2527
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002528bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2529 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002530 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002531 return Loc == PP->getCodeCompletionLoc();
2532 }
2533
2534 return false;
2535}
2536
Jordan Rosec7629d92013-01-24 20:50:46 +00002537uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2538 Token *Result) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002539 unsigned CharSize;
2540 char Kind = getCharAndSize(StartPtr, CharSize);
2541
2542 unsigned NumHexDigits;
2543 if (Kind == 'u')
2544 NumHexDigits = 4;
2545 else if (Kind == 'U')
2546 NumHexDigits = 8;
2547 else
2548 return 0;
2549
Jordan Rosebfec9162013-01-27 20:12:04 +00002550 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rose8094bac2013-01-28 17:49:02 +00002551 if (Result && !isLexingRawMode())
2552 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosebfec9162013-01-27 20:12:04 +00002553 return 0;
2554 }
2555
Jordan Rosec7629d92013-01-24 20:50:46 +00002556 const char *CurPtr = StartPtr + CharSize;
2557 const char *KindLoc = &CurPtr[-1];
2558
2559 uint32_t CodePoint = 0;
2560 for (unsigned i = 0; i < NumHexDigits; ++i) {
2561 char C = getCharAndSize(CurPtr, CharSize);
2562
2563 unsigned Value = llvm::hexDigitValue(C);
2564 if (Value == -1U) {
2565 if (Result && !isLexingRawMode()) {
2566 if (i == 0) {
2567 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2568 << StringRef(KindLoc, 1);
2569 } else {
Jordan Rosec7629d92013-01-24 20:50:46 +00002570 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Roseb87672b2013-01-24 20:50:52 +00002571
2572 // If the user wrote \U1234, suggest a fixit to \u.
2573 if (i == 4 && NumHexDigits == 8) {
Jordan Roseed9c59f2013-02-09 01:10:25 +00002574 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Roseb87672b2013-01-24 20:50:52 +00002575 Diag(KindLoc, diag::note_ucn_four_not_eight)
2576 << FixItHint::CreateReplacement(URange, "u");
2577 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002578 }
2579 }
Jordan Rosebfec9162013-01-27 20:12:04 +00002580
Jordan Rosec7629d92013-01-24 20:50:46 +00002581 return 0;
2582 }
2583
2584 CodePoint <<= 4;
2585 CodePoint += Value;
2586
2587 CurPtr += CharSize;
2588 }
2589
2590 if (Result) {
2591 Result->setFlag(Token::HasUCN);
NAKAMURA Takumib6c08a62013-01-25 14:57:21 +00002592 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rosec7629d92013-01-24 20:50:46 +00002593 StartPtr = CurPtr;
2594 else
2595 while (StartPtr != CurPtr)
2596 (void)getAndAdvanceChar(StartPtr, *Result);
2597 } else {
2598 StartPtr = CurPtr;
2599 }
2600
2601 // C99 6.4.3p2: A universal character name shall not specify a character whose
2602 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2603 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2604 // C++11 [lex.charset]p2: If the hexadecimal value for a
2605 // universal-character-name corresponds to a surrogate code point (in the
2606 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2607 // if the hexadecimal value for a universal-character-name outside the
2608 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2609 // string literal corresponds to a control character (in either of the
2610 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2611 // basic source character set, the program is ill-formed.
2612 if (CodePoint < 0xA0) {
2613 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2614 return CodePoint;
2615
2616 // We don't use isLexingRawMode() here because we need to warn about bad
2617 // UCNs even when skipping preprocessing tokens in a #if block.
2618 if (Result && PP) {
2619 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2620 Diag(BufferPtr, diag::err_ucn_control_character);
2621 else {
2622 char C = static_cast<char>(CodePoint);
2623 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2624 }
2625 }
2626
2627 return 0;
Jordan Roseed9c59f2013-02-09 01:10:25 +00002628
2629 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002630 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002631 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rosec7629d92013-01-24 20:50:46 +00002632 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Roseed9c59f2013-02-09 01:10:25 +00002633 if (Result && PP) {
2634 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2635 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2636 else
2637 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2638 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002639 return 0;
2640 }
2641
2642 return CodePoint;
2643}
2644
2645void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose74c24982013-01-30 01:52:57 +00002646 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002647 isCharInSet(C, UnicodeWhitespaceChars)) {
Jordan Rose74c24982013-01-30 01:52:57 +00002648 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002649 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rosefc120602013-01-24 20:50:50 +00002650
2651 Result.setFlag(Token::LeadingSpace);
2652 if (SkipWhitespace(Result, CurPtr))
2653 return; // KeepWhitespaceMode
2654
2655 return LexTokenInternal(Result);
2656 }
2657
Jordan Roseed9c59f2013-02-09 01:10:25 +00002658 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2659 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2660 !PP->isPreprocessedOutput()) {
2661 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2662 makeCharRange(*this, BufferPtr, CurPtr),
2663 /*IsFirst=*/true);
2664 }
2665
Jordan Rosec7629d92013-01-24 20:50:46 +00002666 MIOpt.ReadToken();
2667 return LexIdentifier(Result, CurPtr);
2668 }
2669
Jordan Rose0ed43942013-01-31 19:48:48 +00002670 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2671 !PP->isPreprocessedOutput() &&
Jordan Roseed9c59f2013-02-09 01:10:25 +00002672 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rosec7629d92013-01-24 20:50:46 +00002673 // Non-ASCII characters tend to creep into source code unintentionally.
2674 // Instead of letting the parser complain about the unknown token,
2675 // just drop the character.
2676 // Note that we can /only/ do this when the non-ASCII character is actually
2677 // spelled as Unicode, not written as a UCN. The standard requires that
2678 // we not throw away any possible preprocessor tokens, but there's a
2679 // loophole in the mapping of Unicode characters to basic character set
2680 // characters that allows us to map these particular characters to, say,
2681 // whitespace.
Jordan Rose74c24982013-01-30 01:52:57 +00002682 Diag(BufferPtr, diag::err_non_ascii)
Jordan Roseed9c59f2013-02-09 01:10:25 +00002683 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rosec7629d92013-01-24 20:50:46 +00002684
2685 BufferPtr = CurPtr;
2686 return LexTokenInternal(Result);
2687 }
2688
2689 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2690 // up by accident.
2691 MIOpt.ReadToken();
2692 FormTokenWithChars(Result, CurPtr, tok::unknown);
2693}
2694
Reid Spencer5f016e22007-07-11 17:01:13 +00002695
2696/// LexTokenInternal - This implements a simple C family lexer. It is an
2697/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002698/// has a null character at the end of the file. This returns a preprocessing
2699/// token, not a normal token, as such, it is an internal interface. It assumes
2700/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002701void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002702LexNextToken:
2703 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002704 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 // CurPtr - Cache BufferPtr in an automatic variable.
2708 const char *CurPtr = BufferPtr;
2709
2710 // Small amounts of horizontal whitespace is very common between tokens.
2711 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2712 ++CurPtr;
2713 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2714 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattnerd88dc482008-10-12 04:05:48 +00002716 // If we are keeping whitespace and other tokens, just return what we just
2717 // skipped. The next lexer invocation will return the token after the
2718 // whitespace.
2719 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002720 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002721 return;
2722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002725 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 }
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 // Read a character, advancing over it.
2731 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002732 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 switch (Char) {
2735 case 0: // Null.
2736 // Found end of file?
2737 if (CurPtr-1 == BufferEnd) {
2738 // Read the PP instance variable into an automatic variable, because
2739 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002740 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2742 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002743 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2744 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002747 // Check if we are performing code completion.
2748 if (isCodeCompletionPoint(CurPtr-1)) {
2749 // Return the code-completion token.
2750 Result.startToken();
2751 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2752 return;
2753 }
2754
Chris Lattner74d15df2008-11-22 02:02:22 +00002755 if (!isLexingRawMode())
2756 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002757 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002758 if (SkipWhitespace(Result, CurPtr))
2759 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002762
2763 case 26: // DOS & CP/M EOF: "^Z".
2764 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002765 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002766 // Read the PP instance variable into an automatic variable, because
2767 // LexEndOfFile will often delete 'this'.
2768 Preprocessor *PPCache = PP;
2769 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2770 return; // Got a token to return.
2771 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2772 return PPCache->Lex(Result);
2773 }
2774 // If Microsoft extensions are disabled, this is just random garbage.
2775 Kind = tok::unknown;
2776 break;
2777
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 case '\n':
2779 case '\r':
2780 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002781 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002782 if (ParsingPreprocessorDirective) {
2783 // Done parsing the "line".
2784 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002787 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002788 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 // Since we consumed a newline, we are back at the start of a line.
2791 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Peter Collingbourne84021552011-02-28 02:37:51 +00002793 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 break;
2795 }
2796 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002797 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002799 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Chris Lattnerd88dc482008-10-12 04:05:48 +00002801 if (SkipWhitespace(Result, CurPtr))
2802 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 goto LexNextToken; // GCC isn't tail call eliminating.
2804 case ' ':
2805 case '\t':
2806 case '\f':
2807 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002808 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002809 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002810 if (SkipWhitespace(Result, CurPtr))
2811 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002812
2813 SkipIgnoredUnits:
2814 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Chris Lattner8133cfc2007-07-22 06:29:05 +00002816 // If the next token is obviously a // or /* */ comment, skip it efficiently
2817 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002818 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002819 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2820 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002821 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002822 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002823 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002824 if (SkipBlockComment(Result, CurPtr+2))
2825 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002826 goto SkipIgnoredUnits;
2827 } else if (isHorizontalWhitespace(*CurPtr)) {
2828 goto SkipHorizontalWhitespace;
2829 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002831
Chris Lattner3a570772008-01-03 17:58:54 +00002832 // C99 6.4.4.1: Integer Constants.
2833 // C99 6.4.4.2: Floating Constants.
2834 case '0': case '1': case '2': case '3': case '4':
2835 case '5': case '6': case '7': case '8': case '9':
2836 // Notify MIOpt that we read a non-whitespace/non-comment token.
2837 MIOpt.ReadToken();
2838 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Douglas Gregor5cee1192011-07-27 05:40:30 +00002840 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2841 // Notify MIOpt that we read a non-whitespace/non-comment token.
2842 MIOpt.ReadToken();
2843
Richard Smith80ad52f2013-01-02 11:42:31 +00002844 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002845 Char = getCharAndSize(CurPtr, SizeTmp);
2846
2847 // UTF-16 string literal
2848 if (Char == '"')
2849 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2850 tok::utf16_string_literal);
2851
2852 // UTF-16 character constant
2853 if (Char == '\'')
2854 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2855 tok::utf16_char_constant);
2856
Craig Topper2fa4e862011-08-11 04:06:15 +00002857 // UTF-16 raw string literal
2858 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2859 return LexRawStringLiteral(Result,
2860 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2861 SizeTmp2, Result),
2862 tok::utf16_string_literal);
2863
2864 if (Char == '8') {
2865 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2866
2867 // UTF-8 string literal
2868 if (Char2 == '"')
2869 return LexStringLiteral(Result,
2870 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2871 SizeTmp2, Result),
2872 tok::utf8_string_literal);
2873
2874 if (Char2 == 'R') {
2875 unsigned SizeTmp3;
2876 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2877 // UTF-8 raw string literal
2878 if (Char3 == '"') {
2879 return LexRawStringLiteral(Result,
2880 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2881 SizeTmp2, Result),
2882 SizeTmp3, Result),
2883 tok::utf8_string_literal);
2884 }
2885 }
2886 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00002887 }
2888
2889 // treat u like the start of an identifier.
2890 return LexIdentifier(Result, CurPtr);
2891
2892 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2893 // Notify MIOpt that we read a non-whitespace/non-comment token.
2894 MIOpt.ReadToken();
2895
Richard Smith80ad52f2013-01-02 11:42:31 +00002896 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00002897 Char = getCharAndSize(CurPtr, SizeTmp);
2898
2899 // UTF-32 string literal
2900 if (Char == '"')
2901 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2902 tok::utf32_string_literal);
2903
2904 // UTF-32 character constant
2905 if (Char == '\'')
2906 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2907 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00002908
2909 // UTF-32 raw string literal
2910 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2911 return LexRawStringLiteral(Result,
2912 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2913 SizeTmp2, Result),
2914 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00002915 }
2916
2917 // treat U like the start of an identifier.
2918 return LexIdentifier(Result, CurPtr);
2919
Craig Topper2fa4e862011-08-11 04:06:15 +00002920 case 'R': // Identifier or C++0x raw string literal
2921 // Notify MIOpt that we read a non-whitespace/non-comment token.
2922 MIOpt.ReadToken();
2923
Richard Smith80ad52f2013-01-02 11:42:31 +00002924 if (LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00002925 Char = getCharAndSize(CurPtr, SizeTmp);
2926
2927 if (Char == '"')
2928 return LexRawStringLiteral(Result,
2929 ConsumeChar(CurPtr, SizeTmp, Result),
2930 tok::string_literal);
2931 }
2932
2933 // treat R like the start of an identifier.
2934 return LexIdentifier(Result, CurPtr);
2935
Chris Lattner3a570772008-01-03 17:58:54 +00002936 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 // Notify MIOpt that we read a non-whitespace/non-comment token.
2938 MIOpt.ReadToken();
2939 Char = getCharAndSize(CurPtr, SizeTmp);
2940
2941 // Wide string literal.
2942 if (Char == '"')
2943 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002944 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002945
Craig Topper2fa4e862011-08-11 04:06:15 +00002946 // Wide raw string literal.
Richard Smith80ad52f2013-01-02 11:42:31 +00002947 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00002948 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2949 return LexRawStringLiteral(Result,
2950 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2951 SizeTmp2, Result),
2952 tok::wide_string_literal);
2953
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 // Wide character constant.
2955 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00002956 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2957 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 // C99 6.4.2: Identifiers.
2961 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2962 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00002963 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2965 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2966 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00002967 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 case 'v': case 'w': case 'x': case 'y': case 'z':
2969 case '_':
2970 // Notify MIOpt that we read a non-whitespace/non-comment token.
2971 MIOpt.ReadToken();
2972 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00002973
2974 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00002975 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002976 if (!isLexingRawMode())
2977 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00002978 // Notify MIOpt that we read a non-whitespace/non-comment token.
2979 MIOpt.ReadToken();
2980 return LexIdentifier(Result, CurPtr);
2981 }
Mike Stump1eb44332009-09-09 15:08:12 +00002982
Chris Lattner9e6293d2008-10-12 04:51:35 +00002983 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00002984 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002985
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 // C99 6.4.4: Character Constants.
2987 case '\'':
2988 // Notify MIOpt that we read a non-whitespace/non-comment token.
2989 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002990 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00002991
2992 // C99 6.4.5: String Literals.
2993 case '"':
2994 // Notify MIOpt that we read a non-whitespace/non-comment token.
2995 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00002996 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00002997
2998 // C99 6.4.6: Punctuators.
2999 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003000 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 break;
3002 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003003 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 break;
3005 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003006 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 break;
3008 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003009 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 break;
3011 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003012 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003013 break;
3014 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003015 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 break;
3017 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003018 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 break;
3020 case '.':
3021 Char = getCharAndSize(CurPtr, SizeTmp);
3022 if (Char >= '0' && Char <= '9') {
3023 // Notify MIOpt that we read a non-whitespace/non-comment token.
3024 MIOpt.ReadToken();
3025
3026 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00003027 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003028 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 CurPtr += SizeTmp;
3030 } else if (Char == '.' &&
3031 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003032 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00003033 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3034 SizeTmp2, Result);
3035 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003036 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 }
3038 break;
3039 case '&':
3040 Char = getCharAndSize(CurPtr, SizeTmp);
3041 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003042 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3044 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003045 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003046 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3047 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003048 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003049 }
3050 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003051 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00003052 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003053 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3055 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003056 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 }
3058 break;
3059 case '+':
3060 Char = getCharAndSize(CurPtr, SizeTmp);
3061 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003063 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003064 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003065 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003066 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003067 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003068 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 }
3070 break;
3071 case '-':
3072 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003073 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00003074 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003075 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00003076 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00003077 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3079 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003080 Kind = tok::arrowstar;
3081 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00003082 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003083 Kind = tok::arrow;
3084 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00003085 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003086 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003087 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003088 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003089 }
3090 break;
3091 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003092 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00003093 break;
3094 case '!':
3095 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003096 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3098 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003099 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 }
3101 break;
3102 case '/':
3103 // 6.4.9: Comments
3104 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00003105 if (Char == '/') { // Line comment.
3106 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00003107 // want to lex this as a comment. There is one problem with this though,
3108 // that in one particular corner case, this can change the behavior of the
3109 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003110 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003111 // "foo". Check to see if the character after the second slash is a '*'.
3112 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003113 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00003114 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003115 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003116 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00003117 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003118 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Chris Lattner8402c732009-01-16 22:39:25 +00003120 // It is common for the tokens immediately after a // comment to be
3121 // whitespace (indentation for the next line). Instead of going through
3122 // the big switch, handle it efficiently now.
3123 goto SkipIgnoredUnits;
3124 }
3125 }
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Chris Lattner8402c732009-01-16 22:39:25 +00003127 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003128 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003129 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003130 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003131 }
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Chris Lattner8402c732009-01-16 22:39:25 +00003133 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003135 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003136 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003137 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 }
3139 break;
3140 case '%':
3141 Char = getCharAndSize(CurPtr, SizeTmp);
3142 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003143 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003144 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003145 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003146 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003148 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3150 Char = getCharAndSize(CurPtr, SizeTmp);
3151 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003152 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003153 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3154 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003155 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003156 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003157 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003158 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003159 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003160 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003161 // We parsed a # character. If this occurs at the start of the line,
3162 // it's actually the start of a preprocessing directive. Callback to
3163 // the preprocessor to handle it.
3164 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003165 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3166 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003167
Chris Lattnere91e9322009-03-18 20:58:27 +00003168 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003169 }
3170 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003171 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003172 }
3173 break;
3174 case '<':
3175 Char = getCharAndSize(CurPtr, SizeTmp);
3176 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003177 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003178 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003179 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3180 if (After == '=') {
3181 Kind = tok::lesslessequal;
3182 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3183 SizeTmp2, Result);
3184 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3185 // If this is actually a '<<<<<<<' version control conflict marker,
3186 // recognize it as such and recover nicely.
3187 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003188 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3189 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3190 // ignore it.
3191 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003192 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003193 Kind = tok::lesslessless;
3194 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3195 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003196 } else {
3197 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3198 Kind = tok::lessless;
3199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003201 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003202 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003203 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith80ad52f2013-01-02 11:42:31 +00003204 if (LangOpts.CPlusPlus11 &&
Richard Smith87a1e192011-04-14 18:36:27 +00003205 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3206 // C++0x [lex.pptoken]p3:
3207 // Otherwise, if the next three characters are <:: and the subsequent
3208 // character is neither : nor >, the < is treated as a preprocessor
3209 // token by itself and not as the first character of the alternative
3210 // token <:.
3211 unsigned SizeTmp3;
3212 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3213 if (After != ':' && After != '>') {
3214 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003215 if (!isLexingRawMode())
3216 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003217 break;
3218 }
3219 }
3220
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003222 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003223 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003224 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003225 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003226 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003227 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 }
3229 break;
3230 case '>':
3231 Char = getCharAndSize(CurPtr, SizeTmp);
3232 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003233 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003234 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003235 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003236 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3237 if (After == '=') {
3238 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3239 SizeTmp2, Result);
3240 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003241 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3242 // If this is actually a '>>>>' conflict marker, recognize it as such
3243 // and recover nicely.
3244 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003245 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3246 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3247 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003248 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003249 Kind = tok::greatergreatergreater;
3250 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3251 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003252 } else {
3253 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3254 Kind = tok::greatergreater;
3255 }
3256
Reid Spencer5f016e22007-07-11 17:01:13 +00003257 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003258 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003259 }
3260 break;
3261 case '^':
3262 Char = getCharAndSize(CurPtr, SizeTmp);
3263 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003265 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003266 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003267 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003268 }
3269 break;
3270 case '|':
3271 Char = getCharAndSize(CurPtr, SizeTmp);
3272 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003273 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003274 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3275 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003276 // If this is '|||||||' and we're in a conflict marker, ignore it.
3277 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3278 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003279 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003280 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3281 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003282 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003283 }
3284 break;
3285 case ':':
3286 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003287 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003288 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003289 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003290 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003291 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003292 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003293 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003294 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003295 }
3296 break;
3297 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003298 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003299 break;
3300 case '=':
3301 Char = getCharAndSize(CurPtr, SizeTmp);
3302 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003303 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003304 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3305 goto LexNextToken;
3306
Chris Lattner9e6293d2008-10-12 04:51:35 +00003307 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003308 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003309 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003310 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003311 }
3312 break;
3313 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003314 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003315 break;
3316 case '#':
3317 Char = getCharAndSize(CurPtr, SizeTmp);
3318 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003319 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003320 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003321 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003322 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003323 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003324 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3326 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003327 // We parsed a # character. If this occurs at the start of the line,
3328 // it's actually the start of a preprocessing directive. Callback to
3329 // the preprocessor to handle it.
3330 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003331 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3332 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Chris Lattnere91e9322009-03-18 20:58:27 +00003334 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003335 }
3336 break;
3337
Chris Lattner3a570772008-01-03 17:58:54 +00003338 case '@':
3339 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003340 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003341 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003342 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003343 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003344 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Jordan Rosec7629d92013-01-24 20:50:46 +00003346 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Reid Spencer5f016e22007-07-11 17:01:13 +00003347 case '\\':
Jordan Rosec7629d92013-01-24 20:50:46 +00003348 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3349 return LexUnicode(Result, CodePoint, CurPtr);
3350
Chris Lattner9e6293d2008-10-12 04:51:35 +00003351 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003352 break;
Jordan Rosec7629d92013-01-24 20:50:46 +00003353
3354 default: {
3355 if (isASCII(Char)) {
3356 Kind = tok::unknown;
3357 break;
3358 }
3359
3360 UTF32 CodePoint;
3361
3362 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3363 // an escaped newline.
3364 --CurPtr;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +00003365 ConversionResult Status =
3366 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3367 (const UTF8 *)BufferEnd,
3368 &CodePoint,
3369 strictConversion);
Jordan Rosec7629d92013-01-24 20:50:46 +00003370 if (Status == conversionOK)
3371 return LexUnicode(Result, CodePoint, CurPtr);
3372
Jordan Rose0ed43942013-01-31 19:48:48 +00003373 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3374 PP->isPreprocessedOutput()) {
Jordan Rose20afc292013-01-30 19:21:12 +00003375 ++CurPtr;
Jordan Rose74c24982013-01-30 01:52:57 +00003376 Kind = tok::unknown;
3377 break;
3378 }
3379
Jordan Rosec7629d92013-01-24 20:50:46 +00003380 // Non-ASCII characters tend to creep into source code unintentionally.
3381 // Instead of letting the parser complain about the unknown token,
Jordan Roseae82c2b2013-01-25 00:20:28 +00003382 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose74c24982013-01-30 01:52:57 +00003383 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rosec7629d92013-01-24 20:50:46 +00003384
3385 BufferPtr = CurPtr+1;
3386 goto LexNextToken;
3387 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Reid Spencer5f016e22007-07-11 17:01:13 +00003390 // Notify MIOpt that we read a non-whitespace/non-comment token.
3391 MIOpt.ReadToken();
3392
3393 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003394 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003395 return;
3396
3397HandleDirective:
3398 // We parsed a # character and it's the start of a preprocessing directive.
3399
3400 FormTokenWithChars(Result, CurPtr, tok::hash);
3401 PP->HandleDirective(Result);
3402
3403 // As an optimization, if the preprocessor didn't switch lexers, tail
3404 // recurse.
3405 if (PP->isCurrentLexer(this)) {
3406 // Start a new token. If this is a #include or something, the PP may
3407 // want us starting at the beginning of the line again. If so, set
3408 // the StartOfLine flag and clear LeadingSpace.
3409 if (IsAtStartOfLine) {
3410 Result.setFlag(Token::StartOfLine);
3411 Result.clearFlag(Token::LeadingSpace);
3412 IsAtStartOfLine = false;
3413 }
3414 goto LexNextToken; // GCC isn't tail call eliminating.
3415 }
3416 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003417}