blob: a4d6a2e8f7592d8a09999792bdeeb97f81e194c2 [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 Rosec7629d92013-01-24 20:50:46 +000028#include "clang/Basic/ConvertUTF.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/Support/MemoryBuffer.h"
Craig Topper2fa4e862011-08-11 04:06:15 +000038#include <cstring>
Reid Spencer5f016e22007-07-11 17:01:13 +000039using namespace clang;
40
Chris Lattnera2bf1052009-12-17 05:29:40 +000041static void InitCharacterInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +000042
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 Lattnera2bf1052009-12-17 05:29:40 +000069 InitCharacterInfo();
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner22d91ca2009-01-17 06:55:17 +000071 BufferStart = BufStart;
72 BufferPtr = BufPtr;
73 BufferEnd = BufEnd;
Mike Stump1eb44332009-09-09 15:08:12 +000074
Chris Lattner22d91ca2009-01-17 06:55:17 +000075 assert(BufEnd[0] == 0 &&
76 "We assume that the input buffer has a null character at the end"
77 " to simplify lexing!");
Mike Stump1eb44332009-09-09 15:08:12 +000078
Eric Christopher156119d2011-04-09 00:01:04 +000079 // Check whether we have a BOM in the beginning of the buffer. If yes - act
80 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
81 // skip the UTF-8 BOM if it's present.
82 if (BufferStart == BufferPtr) {
83 // Determine the size of the BOM.
Chris Lattner5f9e2722011-07-23 10:55:15 +000084 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman969f9d42011-05-10 17:11:21 +000085 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher156119d2011-04-09 00:01:04 +000086 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
87 .Default(0);
88
89 // Skip the BOM.
90 BufferPtr += BOMLength;
91 }
92
Chris Lattner22d91ca2009-01-17 06:55:17 +000093 Is_PragmaLexer = false;
Richard Smithd5e1d602011-10-12 00:37:51 +000094 CurrentConflictMarkerState = CMK_None;
Eric Christopher156119d2011-04-09 00:01:04 +000095
Chris Lattner22d91ca2009-01-17 06:55:17 +000096 // Start of the file is a start of line.
97 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner22d91ca2009-01-17 06:55:17 +000099 // We are not after parsing a #.
100 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner22d91ca2009-01-17 06:55:17 +0000102 // We are not after parsing #include.
103 ParsingFilename = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Chris Lattner22d91ca2009-01-17 06:55:17 +0000105 // We are not in raw mode. Raw mode disables diagnostics and interpretation
106 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
107 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
108 // or otherwise skipping over tokens.
109 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Chris Lattner22d91ca2009-01-17 06:55:17 +0000111 // Default to not keeping comments.
112 ExtendedTokenMode = 0;
113}
114
Chris Lattner0770dab2009-01-17 07:56:59 +0000115/// Lexer constructor - Create a new lexer object for the specified buffer
116/// with the specified preprocessor managing the lexing process. This lexer
117/// assumes that the associated file buffer and Preprocessor objects will
118/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner6e290142009-11-30 04:18:44 +0000119Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattner88d3ac12009-01-17 08:03:42 +0000120 : PreprocessorLexer(&PP, FID),
121 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikie4e4d0842012-03-11 07:00:24 +0000122 LangOpts(PP.getLangOpts()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Chris Lattner0770dab2009-01-17 07:56:59 +0000124 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
125 InputFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Chris Lattner0770dab2009-01-17 07:56:59 +0000127 // Default to keeping comments if the preprocessor wants them.
128 SetCommentRetentionState(PP.getCommentRetentionState());
129}
Chris Lattnerdbf388b2007-10-07 08:47:24 +0000130
Chris Lattner168ae2d2007-10-17 20:41:00 +0000131/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000132/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner590f0cc2008-10-12 01:15:46 +0000133/// range will outlive it, so it doesn't take ownership of it.
David Blaikie4e4d0842012-03-11 07:00:24 +0000134Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerde96c0f2009-01-17 07:42:27 +0000135 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikie4e4d0842012-03-11 07:00:24 +0000136 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattner22d91ca2009-01-17 06:55:17 +0000137
Chris Lattner22d91ca2009-01-17 06:55:17 +0000138 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattner168ae2d2007-10-17 20:41:00 +0000140 // We *are* in raw mode.
141 LexingRawMode = true;
Chris Lattner168ae2d2007-10-17 20:41:00 +0000142}
143
Chris Lattner025c3a62009-01-17 07:35:14 +0000144/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko092bf672012-06-08 23:19:37 +0000145/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner025c3a62009-01-17 07:35:14 +0000146/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner6e290142009-11-30 04:18:44 +0000147Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikie4e4d0842012-03-11 07:00:24 +0000148 const SourceManager &SM, const LangOptions &langOpts)
149 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner025c3a62009-01-17 07:35:14 +0000150
Mike Stump1eb44332009-09-09 15:08:12 +0000151 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner025c3a62009-01-17 07:35:14 +0000152 FromFile->getBufferEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Chris Lattner025c3a62009-01-17 07:35:14 +0000154 // We *are* in raw mode.
155 LexingRawMode = true;
156}
157
Chris Lattner42e00d12009-01-17 08:27:52 +0000158/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
159/// _Pragma expansion. This has a variety of magic semantics that this method
160/// sets up. It returns a new'd Lexer that must be delete'd when done.
161///
162/// On entrance to this routine, TokStartLoc is a macro location which has a
163/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruth433db062011-07-14 08:20:40 +0000164/// expansion location that indicates where all lexed tokens should be
Chris Lattner42e00d12009-01-17 08:27:52 +0000165/// "expanded from".
166///
167/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
168/// normal lexer that remaps tokens as they fly by. This would require making
169/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
170/// interface that could handle this stuff. This would pull GetMappedTokenLoc
171/// out of the critical path of the lexer!
172///
Mike Stump1eb44332009-09-09 15:08:12 +0000173Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruth433db062011-07-14 08:20:40 +0000174 SourceLocation ExpansionLocStart,
175 SourceLocation ExpansionLocEnd,
Chris Lattnerbcc2a672009-01-19 06:46:35 +0000176 unsigned TokLen, Preprocessor &PP) {
Chris Lattner42e00d12009-01-17 08:27:52 +0000177 SourceManager &SM = PP.getSourceManager();
Chris Lattner42e00d12009-01-17 08:27:52 +0000178
179 // Create the lexer as if we were going to lex the file normally.
Chris Lattnera11d6172009-01-19 07:46:45 +0000180 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner6e290142009-11-30 04:18:44 +0000181 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
182 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner42e00d12009-01-17 08:27:52 +0000184 // Now that the lexer is created, change the start/end locations so that we
185 // just lex the subsection of the file that we want. This is lexing from a
186 // scratch buffer.
187 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattner42e00d12009-01-17 08:27:52 +0000189 L->BufferPtr = StrData;
190 L->BufferEnd = StrData+TokLen;
Chris Lattner1fa49532009-03-08 08:08:45 +0000191 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner42e00d12009-01-17 08:27:52 +0000192
193 // Set the SourceLocation with the remapping information. This ensures that
194 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruthbf340e42011-07-26 03:03:05 +0000195 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
196 ExpansionLocStart,
197 ExpansionLocEnd, TokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner42e00d12009-01-17 08:27:52 +0000199 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne84021552011-02-28 02:37:51 +0000200 // return an EOD token.
Chris Lattner42e00d12009-01-17 08:27:52 +0000201 L->ParsingPreprocessorDirective = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattner42e00d12009-01-17 08:27:52 +0000203 // This lexer really is for _Pragma.
204 L->Is_PragmaLexer = true;
205 return L;
206}
207
Chris Lattner168ae2d2007-10-17 20:41:00 +0000208
Reid Spencer5f016e22007-07-11 17:01:13 +0000209/// Stringify - Convert the specified string into a C string, with surrounding
210/// ""'s, and with escaped \ and " characters.
211std::string Lexer::Stringify(const std::string &Str, bool Charify) {
212 std::string Result = Str;
213 char Quote = Charify ? '\'' : '"';
214 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
215 if (Result[i] == '\\' || Result[i] == Quote) {
216 Result.insert(Result.begin()+i, '\\');
217 ++i; ++e;
218 }
219 }
220 return Result;
221}
222
Chris Lattnerd8e30832007-07-24 06:57:14 +0000223/// Stringify - Convert the specified string into a C string by escaping '\'
224/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000225void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattnerd8e30832007-07-24 06:57:14 +0000226 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
227 if (Str[i] == '\\' || Str[i] == '"') {
228 Str.insert(Str.begin()+i, '\\');
229 ++i; ++e;
230 }
231 }
232}
233
Chris Lattnerb0607272010-11-17 07:26:20 +0000234//===----------------------------------------------------------------------===//
235// Token Spelling
236//===----------------------------------------------------------------------===//
237
Richard Smith30cddae2012-11-28 07:29:00 +0000238/// \brief Slow case of getSpelling. Extract the characters comprising the
239/// spelling of this token from the provided input buffer.
240static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
241 const LangOptions &LangOpts, char *Spelling) {
242 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
243
244 size_t Length = 0;
245 const char *BufEnd = BufPtr + Tok.getLength();
246
247 if (Tok.is(tok::string_literal)) {
248 // Munch the encoding-prefix and opening double-quote.
249 while (BufPtr < BufEnd) {
250 unsigned Size;
251 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
252 BufPtr += Size;
253
254 if (Spelling[Length - 1] == '"')
255 break;
256 }
257
258 // Raw string literals need special handling; trigraph expansion and line
259 // splicing do not occur within their d-char-sequence nor within their
260 // r-char-sequence.
261 if (Length >= 2 &&
262 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
263 // Search backwards from the end of the token to find the matching closing
264 // quote.
265 const char *RawEnd = BufEnd;
266 do --RawEnd; while (*RawEnd != '"');
267 size_t RawLength = RawEnd - BufPtr + 1;
268
269 // Everything between the quotes is included verbatim in the spelling.
270 memcpy(Spelling + Length, BufPtr, RawLength);
271 Length += RawLength;
272 BufPtr += RawLength;
273
274 // The rest of the token is lexed normally.
275 }
276 }
277
278 while (BufPtr < BufEnd) {
279 unsigned Size;
280 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
281 BufPtr += Size;
282 }
283
284 assert(Length < Tok.getLength() &&
285 "NeedsCleaning flag set on token that didn't need cleaning!");
286 return Length;
287}
288
Chris Lattnerb0607272010-11-17 07:26:20 +0000289/// getSpelling() - Return the 'spelling' of this token. The spelling of a
290/// token are the characters used to represent the token in the source file
291/// after trigraph expansion and escaped-newline folding. In particular, this
292/// wants to get the true, uncanonicalized, spelling of things like digraphs
293/// UCNs, etc.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith30cddae2012-11-28 07:29:00 +0000295 SmallVectorImpl<char> &buffer,
296 const SourceManager &SM,
297 const LangOptions &options,
298 bool *invalid) {
John McCall834e3f62011-03-08 07:59:04 +0000299 // Break down the source location.
300 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
301
302 // Try to the load the file buffer.
303 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000304 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall834e3f62011-03-08 07:59:04 +0000305 if (invalidTemp) {
306 if (invalid) *invalid = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000307 return StringRef();
John McCall834e3f62011-03-08 07:59:04 +0000308 }
309
310 const char *tokenBegin = file.data() + locInfo.second;
311
312 // Lex from the start of the given location.
313 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
314 file.begin(), tokenBegin, file.end());
315 Token token;
316 lexer.LexFromRawLexer(token);
317
318 unsigned length = token.getLength();
319
320 // Common case: no need for cleaning.
321 if (!token.needsCleaning())
Chris Lattner5f9e2722011-07-23 10:55:15 +0000322 return StringRef(tokenBegin, length);
John McCall834e3f62011-03-08 07:59:04 +0000323
Richard Smith30cddae2012-11-28 07:29:00 +0000324 // Hard case, we need to relex the characters into the string.
325 buffer.resize(length);
326 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner5f9e2722011-07-23 10:55:15 +0000327 return StringRef(buffer.data(), buffer.size());
John McCall834e3f62011-03-08 07:59:04 +0000328}
329
330/// getSpelling() - Return the 'spelling' of this token. The spelling of a
331/// token are the characters used to represent the token in the source file
332/// after trigraph expansion and escaped-newline folding. In particular, this
333/// wants to get the true, uncanonicalized, spelling of things like digraphs
334/// UCNs, etc.
Chris Lattnerb0607272010-11-17 07:26:20 +0000335std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000336 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000337 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith30cddae2012-11-28 07:29:00 +0000338
Chris Lattnerb0607272010-11-17 07:26:20 +0000339 bool CharDataInvalid = false;
Richard Smith30cddae2012-11-28 07:29:00 +0000340 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattnerb0607272010-11-17 07:26:20 +0000341 &CharDataInvalid);
342 if (Invalid)
343 *Invalid = CharDataInvalid;
344 if (CharDataInvalid)
345 return std::string();
Richard Smith30cddae2012-11-28 07:29:00 +0000346
347 // If this token contains nothing interesting, return it directly.
Chris Lattnerb0607272010-11-17 07:26:20 +0000348 if (!Tok.needsCleaning())
Richard Smith30cddae2012-11-28 07:29:00 +0000349 return std::string(TokStart, TokStart + Tok.getLength());
350
Chris Lattnerb0607272010-11-17 07:26:20 +0000351 std::string Result;
Richard Smith30cddae2012-11-28 07:29:00 +0000352 Result.resize(Tok.getLength());
353 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattnerb0607272010-11-17 07:26:20 +0000354 return Result;
355}
356
357/// getSpelling - This method is used to get the spelling of a token into a
358/// preallocated buffer, instead of as an std::string. The caller is required
359/// to allocate enough space for the token, which is guaranteed to be at least
360/// Tok.getLength() bytes long. The actual length of the token is returned.
361///
362/// Note that this method may do two possible things: it may either fill in
363/// the buffer specified with characters, or it may *change the input pointer*
364/// to point to a constant buffer with the data already in it (avoiding a
365/// copy). The caller is not allowed to modify the returned buffer pointer
366/// if an internal buffer is returned.
367unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
368 const SourceManager &SourceMgr,
David Blaikie4e4d0842012-03-11 07:00:24 +0000369 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattnerb0607272010-11-17 07:26:20 +0000370 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000371
372 const char *TokStart = 0;
373 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
374 if (Tok.is(tok::raw_identifier))
375 TokStart = Tok.getRawIdentifierData();
Jordan Rosec7629d92013-01-24 20:50:46 +0000376 else if (!Tok.hasUCN()) {
377 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
378 // Just return the string from the identifier table, which is very quick.
379 Buffer = II->getNameStart();
380 return II->getLength();
381 }
Chris Lattnerb0607272010-11-17 07:26:20 +0000382 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000383
384 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattnerb0607272010-11-17 07:26:20 +0000385 if (Tok.isLiteral())
386 TokStart = Tok.getLiteralData();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000387
Chris Lattnerb0607272010-11-17 07:26:20 +0000388 if (TokStart == 0) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000389 // Compute the start of the token in the input lexer buffer.
Chris Lattnerb0607272010-11-17 07:26:20 +0000390 bool CharDataInvalid = false;
391 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
392 if (Invalid)
393 *Invalid = CharDataInvalid;
394 if (CharDataInvalid) {
395 Buffer = "";
396 return 0;
397 }
398 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000399
Chris Lattnerb0607272010-11-17 07:26:20 +0000400 // If this token contains nothing interesting, return it directly.
401 if (!Tok.needsCleaning()) {
402 Buffer = TokStart;
403 return Tok.getLength();
404 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000405
Chris Lattnerb0607272010-11-17 07:26:20 +0000406 // Otherwise, hard case, relex the characters into the string.
Richard Smith30cddae2012-11-28 07:29:00 +0000407 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattnerb0607272010-11-17 07:26:20 +0000408}
409
410
411
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000412static bool isWhitespace(unsigned char c);
Reid Spencer5f016e22007-07-11 17:01:13 +0000413
Chris Lattner9a611942007-10-17 21:18:47 +0000414/// MeasureTokenLength - Relex the token at the specified location and return
415/// its length in bytes in the input file. If the token needs cleaning (e.g.
416/// includes a trigraph or an escaped newline) then this count includes bytes
417/// that are part of that.
418unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner2c78b872009-04-14 23:22:57 +0000419 const SourceManager &SM,
420 const LangOptions &LangOpts) {
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000421 Token TheTok;
422 if (getRawToken(Loc, TheTok, SM, LangOpts))
423 return 0;
424 return TheTok.getLength();
425}
426
427/// \brief Relex the token at the specified location.
428/// \returns true if there was a failure, false on success.
429bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
430 const SourceManager &SM,
431 const LangOptions &LangOpts) {
Chris Lattner9a611942007-10-17 21:18:47 +0000432 // TODO: this could be special cased for common tokens like identifiers, ')',
433 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump1eb44332009-09-09 15:08:12 +0000434 // all obviously single-char tokens. This could use
Chris Lattner9a611942007-10-17 21:18:47 +0000435 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
436 // something.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000437
438 // If this comes from a macro expansion, we really do want the macro name, not
439 // the token this macro expanded to.
Chandler Carruth40278532011-07-25 16:49:02 +0000440 Loc = SM.getExpansionLoc(Loc);
Chris Lattner363fdc22009-01-26 22:24:27 +0000441 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000442 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000443 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000444 if (Invalid)
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000445 return true;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000446
447 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner83503942009-01-17 08:30:10 +0000448
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000449 if (isWhitespace(StrData[0]))
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000450 return true;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000451
Chris Lattner9a611942007-10-17 21:18:47 +0000452 // Create a lexer starting at the beginning of this token.
Sebastian Redlc3526d82010-09-30 01:03:03 +0000453 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
454 Buffer.begin(), StrData, Buffer.end());
Chris Lattner39de7402009-10-14 15:04:18 +0000455 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd93335c2013-01-07 19:16:18 +0000456 TheLexer.LexFromRawLexer(Result);
457 return false;
Chris Lattner9a611942007-10-17 21:18:47 +0000458}
459
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000460static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
461 const SourceManager &SM,
462 const LangOptions &LangOpts) {
463 assert(Loc.isFileID());
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000464 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor3de84242011-01-31 22:42:36 +0000465 if (LocInfo.first.isInvalid())
466 return Loc;
467
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000468 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000469 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000470 if (Invalid)
471 return Loc;
472
473 // Back up from the current location until we hit the beginning of a line
474 // (or the buffer). We'll relex from that point.
475 const char *BufStart = Buffer.data();
Douglas Gregor3de84242011-01-31 22:42:36 +0000476 if (LocInfo.second >= Buffer.size())
477 return Loc;
478
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000479 const char *StrData = BufStart+LocInfo.second;
480 if (StrData[0] == '\n' || StrData[0] == '\r')
481 return Loc;
482
483 const char *LexStart = StrData;
484 while (LexStart != BufStart) {
485 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
486 ++LexStart;
487 break;
488 }
489
490 --LexStart;
491 }
492
493 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000494 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000495 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
496 TheLexer.SetCommentRetentionState(true);
497
498 // Lex tokens until we find the token that contains the source location.
499 Token TheTok;
500 do {
501 TheLexer.LexFromRawLexer(TheTok);
502
503 if (TheLexer.getBufferLocation() > StrData) {
504 // Lexing this token has taken the lexer past the source location we're
505 // looking for. If the current token encompasses our source location,
506 // return the beginning of that token.
507 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
508 return TheTok.getLocation();
509
510 // We ended up skipping over the source location entirely, which means
511 // that it points into whitespace. We're done here.
512 break;
513 }
514 } while (TheTok.getKind() != tok::eof);
515
516 // We've passed our source location; just return the original source location.
517 return Loc;
518}
519
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000520SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
521 const SourceManager &SM,
522 const LangOptions &LangOpts) {
523 if (Loc.isFileID())
524 return getBeginningOfFileToken(Loc, SM, LangOpts);
525
526 if (!SM.isMacroArgExpansion(Loc))
527 return Loc;
528
529 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
530 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
531 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000532 std::pair<FileID, unsigned> BeginFileLocInfo
533 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000534 assert(FileLocInfo.first == BeginFileLocInfo.first &&
535 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruthae9f85b2012-01-15 09:03:45 +0000536 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis0e870622011-08-17 00:31:23 +0000537}
538
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000539namespace {
540 enum PreambleDirectiveKind {
541 PDK_Skipped,
542 PDK_StartIf,
543 PDK_EndIf,
544 PDK_Unknown
545 };
546}
547
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000548std::pair<unsigned, bool>
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000549Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikie4e4d0842012-03-11 07:00:24 +0000550 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000551 // Create a lexer starting at the beginning of the file. Note that we use a
552 // "fake" file source location at offset 1 so that the lexer will track our
553 // position within the file.
554 const unsigned StartOffset = 1;
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000555 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
556 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000557 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis1cb71422012-10-25 01:51:45 +0000558
559 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
560 SourceLocation StartLoc = TheLexer.getSourceLocation();
561
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000562 bool InPreprocessorDirective = false;
563 Token TheTok;
564 Token IfStartTok;
565 unsigned IfCount = 0;
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000566
567 unsigned MaxLineOffset = 0;
568 if (MaxLines) {
569 const char *CurPtr = Buffer->getBufferStart();
570 unsigned CurLine = 0;
571 while (CurPtr != Buffer->getBufferEnd()) {
572 char ch = *CurPtr++;
573 if (ch == '\n') {
574 ++CurLine;
575 if (CurLine == MaxLines)
576 break;
577 }
578 }
579 if (CurPtr != Buffer->getBufferEnd())
580 MaxLineOffset = CurPtr - Buffer->getBufferStart();
581 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000582
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000583 do {
584 TheLexer.LexFromRawLexer(TheTok);
585
586 if (InPreprocessorDirective) {
587 // If we've hit the end of the file, we're done.
588 if (TheTok.getKind() == tok::eof) {
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000589 break;
590 }
591
592 // If we haven't hit the end of the preprocessor directive, skip this
593 // token.
594 if (!TheTok.isAtStartOfLine())
595 continue;
596
597 // We've passed the end of the preprocessor directive, and will look
598 // at this token again below.
599 InPreprocessorDirective = false;
600 }
601
Douglas Gregordf95a132010-08-09 20:45:32 +0000602 // Keep track of the # of lines in the preamble.
603 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000604 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregordf95a132010-08-09 20:45:32 +0000605
606 // If we were asked to limit the number of lines in the preamble,
607 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +0000608 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregordf95a132010-08-09 20:45:32 +0000609 break;
610 }
611
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000612 // Comments are okay; skip over them.
613 if (TheTok.getKind() == tok::comment)
614 continue;
615
616 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
617 // This is the start of a preprocessor directive.
618 Token HashTok = TheTok;
619 InPreprocessorDirective = true;
620
Joerg Sonnenberger19207f12011-07-20 00:14:37 +0000621 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000622 // we don't have an identifier table available. Instead, just look at
623 // the raw identifier to recognize and categorize preprocessor directives.
624 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000625 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000626 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000627 TheTok.getLength());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000628 PreambleDirectiveKind PDK
629 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
630 .Case("include", PDK_Skipped)
631 .Case("__include_macros", PDK_Skipped)
632 .Case("define", PDK_Skipped)
633 .Case("undef", PDK_Skipped)
634 .Case("line", PDK_Skipped)
635 .Case("error", PDK_Skipped)
636 .Case("pragma", PDK_Skipped)
637 .Case("import", PDK_Skipped)
638 .Case("include_next", PDK_Skipped)
639 .Case("warning", PDK_Skipped)
640 .Case("ident", PDK_Skipped)
641 .Case("sccs", PDK_Skipped)
642 .Case("assert", PDK_Skipped)
643 .Case("unassert", PDK_Skipped)
644 .Case("if", PDK_StartIf)
645 .Case("ifdef", PDK_StartIf)
646 .Case("ifndef", PDK_StartIf)
647 .Case("elif", PDK_Skipped)
648 .Case("else", PDK_Skipped)
649 .Case("endif", PDK_EndIf)
650 .Default(PDK_Unknown);
651
652 switch (PDK) {
653 case PDK_Skipped:
654 continue;
655
656 case PDK_StartIf:
657 if (IfCount == 0)
658 IfStartTok = HashTok;
659
660 ++IfCount;
661 continue;
662
663 case PDK_EndIf:
664 // Mismatched #endif. The preamble ends here.
665 if (IfCount == 0)
666 break;
667
668 --IfCount;
669 continue;
670
671 case PDK_Unknown:
672 // We don't know what this directive is; stop at the '#'.
673 break;
674 }
675 }
676
677 // We only end up here if we didn't recognize the preprocessor
678 // directive or it was one that can't occur in the preamble at this
679 // point. Roll back the current token to the location of the '#'.
680 InPreprocessorDirective = false;
681 TheTok = HashTok;
682 }
683
Douglas Gregordf95a132010-08-09 20:45:32 +0000684 // We hit a token that we don't recognize as being in the
685 // "preprocessing only" part of the file, so we're no longer in
686 // the preamble.
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000687 break;
688 } while (true);
689
690 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000691 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
692 IfCount? IfStartTok.isAtStartOfLine()
693 : TheTok.isAtStartOfLine());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000694}
695
Chris Lattner7ef5c272010-11-17 07:05:50 +0000696
697/// AdvanceToTokenCharacter - Given a location that specifies the start of a
698/// token, return a new location that specifies a character within the token.
699SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
700 unsigned CharNo,
701 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000702 const LangOptions &LangOpts) {
Chandler Carruth433db062011-07-14 08:20:40 +0000703 // Figure out how many physical characters away the specified expansion
Chris Lattner7ef5c272010-11-17 07:05:50 +0000704 // character is. This needs to take into consideration newlines and
705 // trigraphs.
706 bool Invalid = false;
707 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
708
709 // If they request the first char of the token, we're trivially done.
710 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
711 return TokStart;
712
713 unsigned PhysOffset = 0;
714
715 // The usual case is that tokens don't contain anything interesting. Skip
716 // over the uninteresting characters. If a token only consists of simple
717 // chars, this method is extremely fast.
718 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
719 if (CharNo == 0)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000720 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000721 ++TokPtr, --CharNo, ++PhysOffset;
722 }
723
724 // If we have a character that may be a trigraph or escaped newline, use a
725 // lexer to parse it correctly.
726 for (; CharNo; --CharNo) {
727 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +0000728 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000729 TokPtr += Size;
730 PhysOffset += Size;
731 }
732
733 // Final detail: if we end up on an escaped newline, we want to return the
734 // location of the actual byte of the token. For example foo\<newline>bar
735 // advanced by 3 should return the location of b, not of \\. One compounding
736 // detail of this is that the escape may be made by a trigraph.
737 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
738 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
739
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000740 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000741}
742
743/// \brief Computes the source location just past the end of the
744/// token at this source location.
745///
746/// This routine can be used to produce a source location that
747/// points just past the end of the token referenced by \p Loc, and
748/// is generally used when a diagnostic needs to point just after a
749/// token where it expected something different that it received. If
750/// the returned source location would not be meaningful (e.g., if
751/// it points into a macro), this routine returns an invalid
752/// source location.
753///
754/// \param Offset an offset from the end of the token, where the source
755/// location should refer to. The default offset (0) produces a source
756/// location pointing just past the end of the token; an offset of 1 produces
757/// a source location pointing to the last character in the token, etc.
758SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
759 const SourceManager &SM,
David Blaikie4e4d0842012-03-11 07:00:24 +0000760 const LangOptions &LangOpts) {
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000761 if (Loc.isInvalid())
Chris Lattner7ef5c272010-11-17 07:05:50 +0000762 return SourceLocation();
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000763
764 if (Loc.isMacroID()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000765 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruth433db062011-07-14 08:20:40 +0000766 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis7ddf6b22011-06-24 17:58:59 +0000767 }
768
David Blaikie4e4d0842012-03-11 07:00:24 +0000769 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000770 if (Len > Offset)
771 Len = Len - Offset;
772 else
773 return Loc;
774
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000775 return Loc.getLocWithOffset(Len);
Chris Lattner7ef5c272010-11-17 07:05:50 +0000776}
777
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000778/// \brief Returns true if the given MacroID location points at the first
Chandler Carruth433db062011-07-14 08:20:40 +0000779/// token of the macro expansion.
780bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000781 const SourceManager &SM,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000782 const LangOptions &LangOpts,
783 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000784 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
785
786 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
787 // FIXME: If the token comes from the macro token paste operator ('##')
788 // this function will always return false;
789 if (infoLoc.second > 0)
790 return false; // Does not point at the start of token.
791
Chandler Carruth433db062011-07-14 08:20:40 +0000792 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000793 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000794 if (expansionLoc.isFileID()) {
795 // No other macro expansions, this is the first.
796 if (MacroBegin)
797 *MacroBegin = expansionLoc;
798 return true;
799 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000800
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000801 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000802}
803
804/// \brief Returns true if the given MacroID location points at the last
Chandler Carruth433db062011-07-14 08:20:40 +0000805/// token of the macro expansion.
806bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000807 const SourceManager &SM,
808 const LangOptions &LangOpts,
809 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000810 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
811
812 SourceLocation spellLoc = SM.getSpellingLoc(loc);
813 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
814 if (tokLen == 0)
815 return false;
816
817 FileID FID = SM.getFileID(loc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000818 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000819 if (SM.isInFileID(afterLoc, FID))
820 return false; // Still in the same FileID, does not point to the last token.
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000821
822 // FIXME: If the token comes from the macro token paste operator ('##')
823 // or the stringify operator ('#') this function will always return false;
Argyrios Kyrtzidisf8c50652011-08-23 21:02:30 +0000824
Chandler Carruth433db062011-07-14 08:20:40 +0000825 SourceLocation expansionLoc =
Chandler Carruth17287622011-07-26 04:56:51 +0000826 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000827 if (expansionLoc.isFileID()) {
828 // No other macro expansions.
829 if (MacroEnd)
830 *MacroEnd = expansionLoc;
831 return true;
832 }
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000833
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +0000834 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis7a759602011-07-07 21:54:45 +0000835}
836
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000837static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000838 const SourceManager &SM,
839 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000840 SourceLocation Begin = Range.getBegin();
841 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000842 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000843 if (Range.isTokenRange()) {
844 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
845 if (End.isInvalid())
846 return CharSourceRange();
847 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000848
849 // Break down the source locations.
850 FileID FID;
851 unsigned BeginOffs;
852 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
853 if (FID.isInvalid())
854 return CharSourceRange();
855
856 unsigned EndOffs;
857 if (!SM.isInFileID(End, FID, &EndOffs) ||
858 BeginOffs > EndOffs)
859 return CharSourceRange();
860
861 return CharSourceRange::getCharRange(Begin, End);
862}
863
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000864CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000865 const SourceManager &SM,
866 const LangOptions &LangOpts) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000867 SourceLocation Begin = Range.getBegin();
868 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000869 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000870 return CharSourceRange();
871
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000872 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000873 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000874
875 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000876 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
877 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000878 Range.setBegin(Begin);
879 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000880 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000881
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000882 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000883 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
884 &End)) ||
885 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
886 &End)))
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000887 return CharSourceRange();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000888 Range.setEnd(End);
889 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000890 }
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000891
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000892 assert(Begin.isMacroID() && End.isMacroID());
893 SourceLocation MacroBegin, MacroEnd;
894 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000895 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
896 &MacroEnd)) ||
897 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
898 &MacroEnd)))) {
899 Range.setBegin(MacroBegin);
900 Range.setEnd(MacroEnd);
901 return makeRangeFromFileLocs(Range, SM, LangOpts);
902 }
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000903
904 FileID FID;
905 unsigned BeginOffs;
906 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
907 if (FID.isInvalid())
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000908 return CharSourceRange();
909
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000910 unsigned EndOffs;
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000911 if (!SM.isInFileID(End, FID, &EndOffs) ||
912 BeginOffs > EndOffs)
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000913 return CharSourceRange();
914
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000915 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
916 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
917 if (Expansion.isMacroArgExpansion() &&
918 Expansion.getSpellingLoc().isFileID()) {
919 SourceLocation SpellLoc = Expansion.getSpellingLoc();
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000920 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
921 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
922 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidisd9806c92012-01-20 16:52:43 +0000923 }
924
925 return CharSourceRange();
Argyrios Kyrtzidis11b652d2012-01-19 15:59:14 +0000926}
927
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000928StringRef Lexer::getSourceText(CharSourceRange Range,
929 const SourceManager &SM,
930 const LangOptions &LangOpts,
931 bool *Invalid) {
Argyrios Kyrtzidisa83f4d22012-02-03 05:58:29 +0000932 Range = makeFileCharRange(Range, SM, LangOpts);
933 if (Range.isInvalid()) {
Argyrios Kyrtzidise64d9032012-01-19 15:59:19 +0000934 if (Invalid) *Invalid = true;
935 return StringRef();
936 }
937
938 // Break down the source location.
939 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
940 if (beginInfo.first.isInvalid()) {
941 if (Invalid) *Invalid = true;
942 return StringRef();
943 }
944
945 unsigned EndOffs;
946 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
947 beginInfo.second > EndOffs) {
948 if (Invalid) *Invalid = true;
949 return StringRef();
950 }
951
952 // Try to the load the file buffer.
953 bool invalidTemp = false;
954 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
955 if (invalidTemp) {
956 if (Invalid) *Invalid = true;
957 return StringRef();
958 }
959
960 if (Invalid) *Invalid = false;
961 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
962}
963
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000964StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
965 const SourceManager &SM,
966 const LangOptions &LangOpts) {
967 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000968
969 // Find the location of the immediate macro expansion.
970 while (1) {
971 FileID FID = SM.getFileID(Loc);
972 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
973 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
974 Loc = Expansion.getExpansionLocStart();
975 if (!Expansion.isMacroArgExpansion())
976 break;
977
978 // For macro arguments we need to check that the argument did not come
979 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
980
981 // Loc points to the argument id of the macro definition, move to the
982 // macro expansion.
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000983 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000984 SourceLocation SpellLoc = Expansion.getSpellingLoc();
985 if (SpellLoc.isFileID())
986 break; // No inner macro.
987
988 // If spelling location resides in the same FileID as macro expansion
989 // location, it means there is no inner macro.
990 FileID MacroFID = SM.getFileID(Loc);
991 if (SM.isInFileID(SpellLoc, MacroFID))
992 break;
993
994 // Argument came from inner macro.
995 Loc = SpellLoc;
996 }
Anna Zaksc2a8d6c2012-01-18 20:17:16 +0000997
998 // Find the spelling location of the start of the non-argument expansion
999 // range. This is where the macro name was spelled in order to begin
1000 // expanding this macro.
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +00001001 Loc = SM.getSpellingLoc(Loc);
Anna Zaksc2a8d6c2012-01-18 20:17:16 +00001002
1003 // Dig out the buffer where the macro name was spelled and the extents of the
1004 // name so that we can render it into the expansion note.
1005 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1006 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1007 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1008 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1009}
1010
Reid Spencer5f016e22007-07-11 17:01:13 +00001011//===----------------------------------------------------------------------===//
1012// Character information.
1013//===----------------------------------------------------------------------===//
1014
Reid Spencer5f016e22007-07-11 17:01:13 +00001015enum {
1016 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
1017 CHAR_VERT_WS = 0x02, // '\r', '\n'
1018 CHAR_LETTER = 0x04, // a-z,A-Z
1019 CHAR_NUMBER = 0x08, // 0-9
1020 CHAR_UNDER = 0x10, // _
Craig Topper2fa4e862011-08-11 04:06:15 +00001021 CHAR_PERIOD = 0x20, // .
1022 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
Reid Spencer5f016e22007-07-11 17:01:13 +00001023};
1024
Chris Lattner03b98662009-07-07 17:09:54 +00001025// Statically initialize CharInfo table based on ASCII character set
1026// Reference: FreeBSD 7.2 /usr/share/misc/ascii
Chris Lattnera2bf1052009-12-17 05:29:40 +00001027static const unsigned char CharInfo[256] =
Chris Lattner03b98662009-07-07 17:09:54 +00001028{
1029// 0 NUL 1 SOH 2 STX 3 ETX
1030// 4 EOT 5 ENQ 6 ACK 7 BEL
1031 0 , 0 , 0 , 0 ,
1032 0 , 0 , 0 , 0 ,
1033// 8 BS 9 HT 10 NL 11 VT
1034//12 NP 13 CR 14 SO 15 SI
1035 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
1036 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
1037//16 DLE 17 DC1 18 DC2 19 DC3
1038//20 DC4 21 NAK 22 SYN 23 ETB
1039 0 , 0 , 0 , 0 ,
1040 0 , 0 , 0 , 0 ,
1041//24 CAN 25 EM 26 SUB 27 ESC
1042//28 FS 29 GS 30 RS 31 US
1043 0 , 0 , 0 , 0 ,
1044 0 , 0 , 0 , 0 ,
1045//32 SP 33 ! 34 " 35 #
1046//36 $ 37 % 38 & 39 '
Craig Topper2fa4e862011-08-11 04:06:15 +00001047 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1048 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001049//40 ( 41 ) 42 * 43 +
1050//44 , 45 - 46 . 47 /
Craig Topper2fa4e862011-08-11 04:06:15 +00001051 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1052 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001053//48 0 49 1 50 2 51 3
1054//52 4 53 5 54 6 55 7
1055 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1056 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1057//56 8 57 9 58 : 59 ;
1058//60 < 61 = 62 > 63 ?
Craig Topper2fa4e862011-08-11 04:06:15 +00001059 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1060 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
Chris Lattner03b98662009-07-07 17:09:54 +00001061//64 @ 65 A 66 B 67 C
1062//68 D 69 E 70 F 71 G
1063 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1064 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1065//72 H 73 I 74 J 75 K
1066//76 L 77 M 78 N 79 O
1067 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1068 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1069//80 P 81 Q 82 R 83 S
1070//84 T 85 U 86 V 87 W
1071 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1072 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1073//88 X 89 Y 90 Z 91 [
1074//92 \ 93 ] 94 ^ 95 _
Craig Topper2fa4e862011-08-11 04:06:15 +00001075 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1076 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
Chris Lattner03b98662009-07-07 17:09:54 +00001077//96 ` 97 a 98 b 99 c
1078//100 d 101 e 102 f 103 g
1079 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1080 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1081//104 h 105 i 106 j 107 k
1082//108 l 109 m 110 n 111 o
1083 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1084 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1085//112 p 113 q 114 r 115 s
1086//116 t 117 u 118 v 119 w
1087 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1088 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1089//120 x 121 y 122 z 123 {
Craig Topper2fa4e862011-08-11 04:06:15 +00001090//124 | 125 } 126 ~ 127 DEL
1091 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1092 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
Chris Lattner03b98662009-07-07 17:09:54 +00001093};
1094
Chris Lattnera2bf1052009-12-17 05:29:40 +00001095static void InitCharacterInfo() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 static bool isInited = false;
1097 if (isInited) return;
Chris Lattner03b98662009-07-07 17:09:54 +00001098 // check the statically-initialized CharInfo table
1099 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1100 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1101 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1102 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1103 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1104 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1105 assert(CHAR_UNDER == CharInfo[(int)'_']);
1106 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1107 for (unsigned i = 'a'; i <= 'z'; ++i) {
1108 assert(CHAR_LETTER == CharInfo[i]);
1109 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1110 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 for (unsigned i = '0'; i <= '9'; ++i)
Chris Lattner03b98662009-07-07 17:09:54 +00001112 assert(CHAR_NUMBER == CharInfo[i]);
Steve Naroff7b682652009-12-08 16:38:12 +00001113
Chris Lattner03b98662009-07-07 17:09:54 +00001114 isInited = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001115}
1116
Chris Lattner03b98662009-07-07 17:09:54 +00001117
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001118/// isIdentifierHead - Return true if this is the first character of an
1119/// identifier, which is [a-zA-Z_].
1120static inline bool isIdentifierHead(unsigned char c) {
1121 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1122}
1123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124/// isIdentifierBody - Return true if this is the body character of an
1125/// identifier, which is [a-zA-Z0-9_].
1126static inline bool isIdentifierBody(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001127 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
1129
1130/// isHorizontalWhitespace - Return true if this character is horizontal
James Dennetta05369f2012-06-15 21:36:54 +00001131/// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1132/// '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001133static inline bool isHorizontalWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001134 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001135}
1136
Anna Zaksaca25bc2011-07-27 21:43:43 +00001137/// isVerticalWhitespace - Return true if this character is vertical
James Dennetta05369f2012-06-15 21:36:54 +00001138/// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
Anna Zaksaca25bc2011-07-27 21:43:43 +00001139static inline bool isVerticalWhitespace(unsigned char c) {
1140 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1141}
1142
Reid Spencer5f016e22007-07-11 17:01:13 +00001143/// isWhitespace - Return true if this character is horizontal or vertical
James Dennetta05369f2012-06-15 21:36:54 +00001144/// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1145/// false for '\\0'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001146static inline bool isWhitespace(unsigned char c) {
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001147 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001148}
1149
1150/// isNumberBody - Return true if this is the body character of an
1151/// preprocessing number, which is [a-zA-Z0-9_.].
1152static inline bool isNumberBody(unsigned char c) {
Mike Stump1eb44332009-09-09 15:08:12 +00001153 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
Hartmut Kaiser95c062b2007-10-18 12:47:01 +00001154 true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001155}
1156
Craig Topper2fa4e862011-08-11 04:06:15 +00001157/// isRawStringDelimBody - Return true if this is the body character of a
1158/// raw string delimiter.
1159static inline bool isRawStringDelimBody(unsigned char c) {
1160 return (CharInfo[c] &
1161 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1162 true : false;
1163}
1164
Jordan Rosed880b3a2012-06-07 01:10:31 +00001165// Allow external clients to make use of CharInfo.
1166bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1167 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1168}
1169
Reid Spencer5f016e22007-07-11 17:01:13 +00001170
1171//===----------------------------------------------------------------------===//
1172// Diagnostics forwarding code.
1173//===----------------------------------------------------------------------===//
1174
Chris Lattner409a0362007-07-22 18:38:25 +00001175/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruth433db062011-07-14 08:20:40 +00001176/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner409a0362007-07-22 18:38:25 +00001177/// This is currently only used for _Pragma implementation, so it is the slow
1178/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruth14bd9652010-10-23 08:44:57 +00001179static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1180 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001181static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1182 SourceLocation FileLoc,
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001183 unsigned CharNo, unsigned TokLen) {
Chandler Carruth433db062011-07-14 08:20:40 +00001184 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattner409a0362007-07-22 18:38:25 +00001186 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruth433db062011-07-14 08:20:40 +00001187 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001188 // spelling location.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001189 SourceManager &SM = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Chandler Carruth433db062011-07-14 08:20:40 +00001191 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001192 // characters come from spelling(FileLoc)+Offset.
Chris Lattnere7fb4842009-02-15 20:52:18 +00001193 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001194 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Chris Lattnere7fb4842009-02-15 20:52:18 +00001196 // Figure out the expansion loc range, which is the range covered by the
1197 // original _Pragma(...) sequence.
1198 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruth999f7392011-07-25 20:52:21 +00001199 SM.getImmediateExpansionRange(FileLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Chandler Carruthbf340e42011-07-26 03:03:05 +00001201 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner409a0362007-07-22 18:38:25 +00001202}
1203
Reid Spencer5f016e22007-07-11 17:01:13 +00001204/// getSourceLocation - Return a source location identifier for the specified
1205/// offset in the current file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001206SourceLocation Lexer::getSourceLocation(const char *Loc,
1207 unsigned TokLen) const {
Chris Lattner448cec42007-07-22 18:44:36 +00001208 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 "Location out of range for this buffer!");
Chris Lattner9dc1f532007-07-20 16:37:10 +00001210
1211 // In the normal case, we're just lexing from a simple file buffer, return
1212 // the file id from FileLoc with the offset specified.
Chris Lattner448cec42007-07-22 18:44:36 +00001213 unsigned CharNo = Loc-BufferStart;
Chris Lattner9dc1f532007-07-20 16:37:10 +00001214 if (FileLoc.isFileID())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001215 return FileLoc.getLocWithOffset(CharNo);
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner2b2453a2009-01-17 06:22:33 +00001217 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1218 // tokens are lexed from where the _Pragma was defined.
Chris Lattner168ae2d2007-10-17 20:41:00 +00001219 assert(PP && "This doesn't work on raw lexers");
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001220 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221}
1222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223/// Diag - Forwarding function for diagnostics. This translate a source
1224/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner3cbfe2c2008-11-22 00:59:29 +00001225DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner3692b092008-11-18 07:59:24 +00001226 return PP->Diag(getSourceLocation(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00001227}
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
1229//===----------------------------------------------------------------------===//
1230// Trigraph and Escaped Newline Handling Code.
1231//===----------------------------------------------------------------------===//
1232
1233/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1234/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1235static char GetTrigraphCharForLetter(char Letter) {
1236 switch (Letter) {
1237 default: return 0;
1238 case '=': return '#';
1239 case ')': return ']';
1240 case '(': return '[';
1241 case '!': return '|';
1242 case '\'': return '^';
1243 case '>': return '}';
1244 case '/': return '\\';
1245 case '<': return '{';
1246 case '-': return '~';
1247 }
1248}
1249
1250/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1251/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1252/// return the result character. Finally, emit a warning about trigraph use
1253/// whether trigraphs are enabled or not.
1254static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1255 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner3692b092008-11-18 07:59:24 +00001256 if (!Res || !L) return Res;
Mike Stump1eb44332009-09-09 15:08:12 +00001257
David Blaikie4e4d0842012-03-11 07:00:24 +00001258 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00001259 if (!L->isLexingRawMode())
1260 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner3692b092008-11-18 07:59:24 +00001261 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattner74d15df2008-11-22 02:02:22 +00001264 if (!L->isLexingRawMode())
Chris Lattner5f9e2722011-07-23 10:55:15 +00001265 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 return Res;
1267}
1268
Chris Lattner24f0e482009-04-18 22:05:41 +00001269/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1270/// 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 +00001271/// trigraph equivalent on entry to this function.
Chris Lattner24f0e482009-04-18 22:05:41 +00001272unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1273 unsigned Size = 0;
1274 while (isWhitespace(Ptr[Size])) {
1275 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Chris Lattner24f0e482009-04-18 22:05:41 +00001277 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1278 continue;
1279
1280 // If this is a \r\n or \n\r, skip the other half.
1281 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1282 Ptr[Size-1] != Ptr[Size])
1283 ++Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner24f0e482009-04-18 22:05:41 +00001285 return Size;
Mike Stump1eb44332009-09-09 15:08:12 +00001286 }
1287
Chris Lattner24f0e482009-04-18 22:05:41 +00001288 // Not an escaped newline, must be a \t or something else.
1289 return 0;
1290}
1291
Chris Lattner03374952009-04-18 22:27:02 +00001292/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1293/// them), skip over them and return the first non-escaped-newline found,
1294/// otherwise return P.
1295const char *Lexer::SkipEscapedNewLines(const char *P) {
1296 while (1) {
1297 const char *AfterEscape;
1298 if (*P == '\\') {
1299 AfterEscape = P+1;
1300 } else if (*P == '?') {
1301 // If not a trigraph for escape, bail out.
1302 if (P[1] != '?' || P[2] != '/')
1303 return P;
1304 AfterEscape = P+3;
1305 } else {
1306 return P;
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Chris Lattner03374952009-04-18 22:27:02 +00001309 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1310 if (NewLineSize == 0) return P;
1311 P = AfterEscape+NewLineSize;
1312 }
1313}
1314
Anna Zaksaca25bc2011-07-27 21:43:43 +00001315/// \brief Checks that the given token is the first token that occurs after the
1316/// given location (this excludes comments and whitespace). Returns the location
1317/// immediately after the specified token. If the token is not found or the
1318/// location is inside a macro, the returned source location will be invalid.
1319SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1320 tok::TokenKind TKind,
1321 const SourceManager &SM,
1322 const LangOptions &LangOpts,
1323 bool SkipTrailingWhitespaceAndNewLine) {
1324 if (Loc.isMacroID()) {
Argyrios Kyrtzidis69bda4c2012-01-19 15:59:08 +00001325 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaksaca25bc2011-07-27 21:43:43 +00001326 return SourceLocation();
Anna Zaksaca25bc2011-07-27 21:43:43 +00001327 }
1328 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1329
1330 // Break down the source location.
1331 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1332
1333 // Try to load the file buffer.
1334 bool InvalidTemp = false;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001335 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001336 if (InvalidTemp)
1337 return SourceLocation();
1338
1339 const char *TokenBegin = File.data() + LocInfo.second;
1340
1341 // Lex from the start of the given location.
1342 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1343 TokenBegin, File.end());
1344 // Find the token.
1345 Token Tok;
1346 lexer.LexFromRawLexer(Tok);
1347 if (Tok.isNot(TKind))
1348 return SourceLocation();
1349 SourceLocation TokenLoc = Tok.getLocation();
1350
1351 // Calculate how much whitespace needs to be skipped if any.
1352 unsigned NumWhitespaceChars = 0;
1353 if (SkipTrailingWhitespaceAndNewLine) {
1354 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1355 Tok.getLength();
1356 unsigned char C = *TokenEnd;
1357 while (isHorizontalWhitespace(C)) {
1358 C = *(++TokenEnd);
1359 NumWhitespaceChars++;
1360 }
Eli Friedman35a2b792012-11-14 01:28:38 +00001361
1362 // Skip \r, \n, \r\n, or \n\r
1363 if (C == '\n' || C == '\r') {
1364 char PrevC = C;
1365 C = *(++TokenEnd);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001366 NumWhitespaceChars++;
Eli Friedman35a2b792012-11-14 01:28:38 +00001367 if ((C == '\n' || C == '\r') && C != PrevC)
1368 NumWhitespaceChars++;
1369 }
Anna Zaksaca25bc2011-07-27 21:43:43 +00001370 }
1371
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001372 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaksaca25bc2011-07-27 21:43:43 +00001373}
Chris Lattner24f0e482009-04-18 22:05:41 +00001374
Reid Spencer5f016e22007-07-11 17:01:13 +00001375/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1376/// get its size, and return it. This is tricky in several cases:
1377/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1378/// then either return the trigraph (skipping 3 chars) or the '?',
1379/// depending on whether trigraphs are enabled or not.
1380/// 2. If this is an escaped newline (potentially with whitespace between
1381/// the backslash and newline), implicitly skip the newline and return
1382/// the char after it.
Reid Spencer5f016e22007-07-11 17:01:13 +00001383///
1384/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1385/// know that we can accumulate into Size, and that we have already incremented
1386/// Ptr by Size bytes.
1387///
1388/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1389/// be updated to match.
1390///
1391char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattnerd2177732007-07-20 16:59:19 +00001392 Token *Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 // If we have a slash, look for an escaped newline.
1394 if (Ptr[0] == '\\') {
1395 ++Size;
1396 ++Ptr;
1397Slash:
1398 // Common case, backslash-char where the char is not whitespace.
1399 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Chris Lattner5636a3b2009-06-23 05:15:06 +00001401 // See if we have optional whitespace characters between the slash and
1402 // newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001403 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1404 // Remember that this token needs to be cleaned.
1405 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001406
Chris Lattner24f0e482009-04-18 22:05:41 +00001407 // Warn if there was whitespace between the backslash and newline.
Chris Lattner5636a3b2009-06-23 05:15:06 +00001408 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattner24f0e482009-04-18 22:05:41 +00001409 Diag(Ptr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Chris Lattner24f0e482009-04-18 22:05:41 +00001411 // Found backslash<whitespace><newline>. Parse the char after it.
1412 Size += EscapedNewLineSize;
1413 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001414
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001415 // If the char that we finally got was a \n, then we must have had
1416 // something like \<newline><newline>. We don't want to consume the
1417 // second newline.
1418 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1419 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001420
Chris Lattner24f0e482009-04-18 22:05:41 +00001421 // Use slow version to accumulate a correct size field.
1422 return getCharAndSizeSlow(Ptr, Size, Tok);
1423 }
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // Otherwise, this is not an escaped newline, just return the slash.
1426 return '\\';
1427 }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 // If this is a trigraph, process it.
1430 if (Ptr[0] == '?' && Ptr[1] == '?') {
1431 // If this is actually a legal trigraph (not something like "??x"), emit
1432 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1433 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1434 // Remember that this token needs to be cleaned.
Chris Lattnerd2177732007-07-20 16:59:19 +00001435 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00001436
1437 Ptr += 3;
1438 Size += 3;
1439 if (C == '\\') goto Slash;
1440 return C;
1441 }
1442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // If this is neither, return a single character.
1445 ++Size;
1446 return *Ptr;
1447}
1448
1449
1450/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1451/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1452/// and that we have already incremented Ptr by Size bytes.
1453///
1454/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1455/// be updated to match.
1456char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikie4e4d0842012-03-11 07:00:24 +00001457 const LangOptions &LangOpts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 // If we have a slash, look for an escaped newline.
1459 if (Ptr[0] == '\\') {
1460 ++Size;
1461 ++Ptr;
1462Slash:
1463 // Common case, backslash-char where the char is not whitespace.
1464 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 // See if we have optional whitespace characters followed by a newline.
Chris Lattner24f0e482009-04-18 22:05:41 +00001467 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1468 // Found backslash<whitespace><newline>. Parse the char after it.
1469 Size += EscapedNewLineSize;
1470 Ptr += EscapedNewLineSize;
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Argyrios Kyrtzidis04a94bc2011-12-22 04:38:07 +00001472 // If the char that we finally got was a \n, then we must have had
1473 // something like \<newline><newline>. We don't want to consume the
1474 // second newline.
1475 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1476 return ' ';
Argyrios Kyrtzidisf132dca2011-12-21 20:19:55 +00001477
Chris Lattner24f0e482009-04-18 22:05:41 +00001478 // Use slow version to accumulate a correct size field.
David Blaikie4e4d0842012-03-11 07:00:24 +00001479 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattner24f0e482009-04-18 22:05:41 +00001480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 // Otherwise, this is not an escaped newline, just return the slash.
1483 return '\\';
1484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 // If this is a trigraph, process it.
David Blaikie4e4d0842012-03-11 07:00:24 +00001487 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 // If this is actually a legal trigraph (not something like "??x"), return
1489 // it.
1490 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1491 Ptr += 3;
1492 Size += 3;
1493 if (C == '\\') goto Slash;
1494 return C;
1495 }
1496 }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // If this is neither, return a single character.
1499 ++Size;
1500 return *Ptr;
1501}
1502
1503//===----------------------------------------------------------------------===//
1504// Helper methods for lexing.
1505//===----------------------------------------------------------------------===//
1506
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001507/// \brief Routine that indiscriminately skips bytes in the source file.
1508void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1509 BufferPtr += Bytes;
1510 if (BufferPtr > BufferEnd)
1511 BufferPtr = BufferEnd;
1512 IsAtStartOfLine = StartOfLine;
1513}
1514
Jordan Rosec7629d92013-01-24 20:50:46 +00001515namespace {
1516 struct UCNCharRange {
1517 uint32_t Lower;
1518 uint32_t Upper;
1519 };
1520
1521 // C11 D.1, C++11 [charname.allowed]
1522 // FIXME: C99 and C++03 each have a different set of allowed UCNs.
1523 const UCNCharRange UCNAllowedCharRanges[] = {
1524 // 1
1525 { 0x00A8, 0x00A8 }, { 0x00AA, 0x00AA }, { 0x00AD, 0x00AD },
1526 { 0x00AF, 0x00AF }, { 0x00B2, 0x00B5 }, { 0x00B7, 0x00BA },
1527 { 0x00BC, 0x00BE }, { 0x00C0, 0x00D6 }, { 0x00D8, 0x00F6 },
1528 { 0x00F8, 0x00FF },
1529 // 2
1530 { 0x0100, 0x167F }, { 0x1681, 0x180D }, { 0x180F, 0x1FFF },
1531 // 3
1532 { 0x200B, 0x200D }, { 0x202A, 0x202E }, { 0x203F, 0x2040 },
1533 { 0x2054, 0x2054 }, { 0x2060, 0x206F },
1534 // 4
1535 { 0x2070, 0x218F }, { 0x2460, 0x24FF }, { 0x2776, 0x2793 },
1536 { 0x2C00, 0x2DFF }, { 0x2E80, 0x2FFF },
1537 // 5
1538 { 0x3004, 0x3007 }, { 0x3021, 0x302F }, { 0x3031, 0x303F },
1539 // 6
1540 { 0x3040, 0xD7FF },
1541 // 7
1542 { 0xF900, 0xFD3D }, { 0xFD40, 0xFDCF }, { 0xFDF0, 0xFE44 },
1543 { 0xFE47, 0xFFFD },
1544 // 8
1545 { 0x10000, 0x1FFFD }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD },
1546 { 0x40000, 0x4FFFD }, { 0x50000, 0x5FFFD }, { 0x60000, 0x6FFFD },
1547 { 0x70000, 0x7FFFD }, { 0x80000, 0x8FFFD }, { 0x90000, 0x9FFFD },
1548 { 0xA0000, 0xAFFFD }, { 0xB0000, 0xBFFFD }, { 0xC0000, 0xCFFFD },
1549 { 0xD0000, 0xDFFFD }, { 0xE0000, 0xEFFFD }
1550 };
1551}
1552
1553static bool isAllowedIDChar(uint32_t c) {
1554 unsigned LowPoint = 0;
1555 unsigned HighPoint = llvm::array_lengthof(UCNAllowedCharRanges);
1556
1557 // Binary search the UCNAllowedCharRanges set.
1558 while (HighPoint != LowPoint) {
1559 unsigned MidPoint = (HighPoint + LowPoint) / 2;
1560 if (c < UCNAllowedCharRanges[MidPoint].Lower)
1561 HighPoint = MidPoint;
1562 else if (c > UCNAllowedCharRanges[MidPoint].Upper)
1563 LowPoint = MidPoint + 1;
1564 else
1565 return true;
1566 }
1567
1568 return false;
1569}
1570
1571static bool isAllowedInitiallyIDChar(uint32_t c) {
1572 // C11 D.2, C++11 [charname.disallowed]
1573 // FIXME: C99 only forbids "digits", presumably as described in C99 Annex D.
1574 // FIXME: C++03 does not forbid any initial characters.
1575 return !(0x0300 <= c && c <= 0x036F) &&
1576 !(0x1DC0 <= c && c <= 0x1DFF) &&
1577 !(0x20D0 <= c && c <= 0x20FF) &&
1578 !(0xFE20 <= c && c <= 0xFE2F);
1579}
1580
1581static inline bool isASCII(char C) {
1582 return static_cast<signed char>(C) >= 0;
1583}
1584
1585
Chris Lattnerd2177732007-07-20 16:59:19 +00001586void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1588 unsigned Size;
1589 unsigned char C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001590 while (isIdentifierBody(C))
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 C = *CurPtr++;
Chris Lattnercd991db2010-01-11 02:38:50 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 --CurPtr; // Back up over the skipped character.
1594
1595 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1596 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattnercd991db2010-01-11 02:38:50 +00001597 //
1598 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1599 // cheaper
Jordan Rosec7629d92013-01-24 20:50:46 +00001600 if (isASCII(C) && C != '\\' && C != '?' &&
1601 (C != '$' || !LangOpts.DollarIdents)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001602FinishIdentifier:
1603 const char *IdStart = BufferPtr;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001604 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1605 Result.setRawIdentifierData(IdStart);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // If we are in raw mode, return this identifier raw. There is no need to
1608 // look up identifier information or attempt to macro expand it.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001609 if (LexingRawMode)
1610 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +00001612 // Fill in Result.IdentifierInfo and update the token kind,
1613 // looking up the identifier in the identifier table.
1614 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Reid Spencer5f016e22007-07-11 17:01:13 +00001616 // Finally, now that we know we have an identifier, pass this off to the
1617 // preprocessor, which may macro expand it or something.
Chris Lattnerd1186fa2009-01-21 07:45:14 +00001618 if (II->isHandleIdentifierCase())
Chris Lattner6a170eb2009-01-21 07:43:11 +00001619 PP->HandleIdentifier(Result);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001620
Chris Lattner6a170eb2009-01-21 07:43:11 +00001621 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 }
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 C = getCharAndSize(CurPtr, Size);
1627 while (1) {
1628 if (C == '$') {
1629 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikie4e4d0842012-03-11 07:00:24 +00001630 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 // Otherwise, emit a diagnostic and continue.
Chris Lattner74d15df2008-11-22 02:02:22 +00001633 if (!isLexingRawMode())
1634 Diag(CurPtr, diag::ext_dollar_in_identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 CurPtr = ConsumeChar(CurPtr, Size, Result);
1636 C = getCharAndSize(CurPtr, Size);
1637 continue;
Jordan Rosec7629d92013-01-24 20:50:46 +00001638
1639 } else if (C == '\\') {
1640 const char *UCNPtr = CurPtr + Size;
1641 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
1642 if (CodePoint == 0 || !isAllowedIDChar(CodePoint))
1643 goto FinishIdentifier;
1644
1645 Result.setFlag(Token::HasUCN);
1646 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1647 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1648 CurPtr = UCNPtr;
1649 else
1650 while (CurPtr != UCNPtr)
1651 (void)getAndAdvanceChar(CurPtr, Result);
1652
1653 C = getCharAndSize(CurPtr, Size);
1654 continue;
1655 } else if (!isASCII(C)) {
1656 const char *UnicodePtr = CurPtr;
1657 UTF32 CodePoint;
1658 ConversionResult Result = convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1659 (const UTF8 *)BufferEnd,
1660 &CodePoint,
1661 strictConversion);
1662 if (Result != conversionOK ||
1663 !isAllowedIDChar(static_cast<uint32_t>(CodePoint)))
1664 goto FinishIdentifier;
1665
1666 CurPtr = UnicodePtr;
1667 C = getCharAndSize(CurPtr, Size);
1668 continue;
1669 } else if (!isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 goto FinishIdentifier;
1671 }
1672
1673 // Otherwise, this character is good, consume it.
1674 CurPtr = ConsumeChar(CurPtr, Size, Result);
1675
1676 C = getCharAndSize(CurPtr, Size);
Jordan Rosec7629d92013-01-24 20:50:46 +00001677 while (isIdentifierBody(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 CurPtr = ConsumeChar(CurPtr, Size, Result);
1679 C = getCharAndSize(CurPtr, Size);
1680 }
1681 }
1682}
1683
Douglas Gregora75ec432010-08-30 14:50:47 +00001684/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner4a551002010-08-30 17:11:14 +00001685/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedmane506f8a2012-08-31 02:29:37 +00001686bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001687 unsigned Size;
David Blaikie4e4d0842012-03-11 07:00:24 +00001688 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001689 if (C1 != '0')
1690 return false;
David Blaikie4e4d0842012-03-11 07:00:24 +00001691 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner6ab55eb2010-08-31 16:42:00 +00001692 return (C2 == 'x' || C2 == 'X');
Douglas Gregora75ec432010-08-30 14:50:47 +00001693}
Reid Spencer5f016e22007-07-11 17:01:13 +00001694
Nate Begeman5253c7f2008-04-14 02:26:39 +00001695/// LexNumericConstant - Lex the remainder of a integer or floating point
Reid Spencer5f016e22007-07-11 17:01:13 +00001696/// constant. From[-1] is the first character lexed. Return the end of the
1697/// constant.
Chris Lattnerd2177732007-07-20 16:59:19 +00001698void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 unsigned Size;
1700 char C = getCharAndSize(CurPtr, Size);
1701 char PrevCh = 0;
Nico Weberdd817312012-11-13 06:25:15 +00001702 while (isNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 CurPtr = ConsumeChar(CurPtr, Size, Result);
1704 PrevCh = C;
1705 C = getCharAndSize(CurPtr, Size);
1706 }
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001709 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1710 // If we are in Microsoft mode, don't continue if the constant is hex.
1711 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikie4e4d0842012-03-11 07:00:24 +00001712 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattnerb2f4a202010-08-30 17:09:08 +00001713 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1714 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001715
1716 // If we have a hex FP constant, continue.
Richard Smithd2e95d12012-06-15 05:07:49 +00001717 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1718 // Outside C99, we accept hexadecimal floating point numbers as a
1719 // not-quite-conforming extension. Only do so if this looks like it's
1720 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1721 bool IsHexFloat = true;
1722 if (!LangOpts.C99) {
1723 if (!isHexaLiteral(BufferPtr, LangOpts))
1724 IsHexFloat = false;
1725 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1726 IsHexFloat = false;
1727 }
1728 if (IsHexFloat)
1729 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001733 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001734 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner47246be2009-01-26 19:29:26 +00001735 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001736}
1737
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001738/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smithe816c712012-03-07 03:13:00 +00001739/// in C++11, or warn on a ud-suffix in C++98.
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001740const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001741 assert(getLangOpts().CPlusPlus);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001742
1743 // Maximally munch an identifier. FIXME: UCNs.
1744 unsigned Size;
1745 char C = getCharAndSize(CurPtr, Size);
1746 if (isIdentifierHead(C)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001747 if (!getLangOpts().CPlusPlus11) {
Richard Smithe816c712012-03-07 03:13:00 +00001748 if (!isLexingRawMode())
Richard Smith2fb4ae32012-03-08 02:39:21 +00001749 Diag(CurPtr,
1750 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1751 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1752 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1753 return CurPtr;
1754 }
1755
1756 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1757 // that does not start with an underscore is ill-formed. As a conforming
1758 // extension, we treat all such suffixes as if they had whitespace before
1759 // them.
1760 if (C != '_') {
1761 if (!isLexingRawMode())
Francois Pichetb0afd5d2012-04-07 23:09:23 +00001762 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1763 diag::ext_ms_reserved_user_defined_literal :
1764 diag::ext_reserved_user_defined_literal)
Richard Smithe816c712012-03-07 03:13:00 +00001765 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1766 return CurPtr;
1767 }
1768
Richard Smith99831e42012-03-06 03:21:47 +00001769 Result.setFlag(Token::HasUDSuffix);
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001770 do {
1771 CurPtr = ConsumeChar(CurPtr, Size, Result);
1772 C = getCharAndSize(CurPtr, Size);
1773 } while (isIdentifierBody(C));
1774 }
1775 return CurPtr;
1776}
1777
Reid Spencer5f016e22007-07-11 17:01:13 +00001778/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregor5cee1192011-07-27 05:40:30 +00001779/// either " or L" or u8" or u" or U".
1780void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1781 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Richard Smith661a9962011-10-15 01:18:56 +00001784 if (!isLexingRawMode() &&
1785 (Kind == tok::utf8_string_literal ||
1786 Kind == tok::utf16_string_literal ||
1787 Kind == tok::utf32_string_literal))
1788 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1789
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 char C = getAndAdvanceChar(CurPtr, Result);
1791 while (C != '"') {
Chris Lattner571339c2010-05-30 23:27:38 +00001792 // Skip escaped characters. Escaped newlines will already be processed by
1793 // getAndAdvanceChar.
1794 if (C == '\\')
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregor33611e02010-05-30 22:59:50 +00001796
Chris Lattner571339c2010-05-30 23:27:38 +00001797 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregor33611e02010-05-30 22:59:50 +00001798 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001799 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001800 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001801 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00001803 }
Chris Lattner571339c2010-05-30 23:27:38 +00001804
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001805 if (C == 0) {
1806 if (isCodeCompletionPoint(CurPtr-1)) {
1807 PP->CodeCompleteNaturalLanguage();
1808 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1809 return cutOffLexing();
1810 }
1811
Chris Lattner571339c2010-05-30 23:27:38 +00001812 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001813 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001814 C = getAndAdvanceChar(CurPtr, Result);
1815 }
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001817 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001818 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001819 CurPtr = LexUDSuffix(Result, CurPtr);
1820
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001822 if (NulCharacter && !isLexingRawMode())
1823 Diag(NulCharacter, diag::null_in_string);
Reid Spencer5f016e22007-07-11 17:01:13 +00001824
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner47246be2009-01-26 19:29:26 +00001826 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001827 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001828 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001829}
1830
Craig Topper2fa4e862011-08-11 04:06:15 +00001831/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1832/// having lexed R", LR", u8R", uR", or UR".
1833void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1834 tok::TokenKind Kind) {
1835 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1836 // Between the initial and final double quote characters of the raw string,
1837 // any transformations performed in phases 1 and 2 (trigraphs,
1838 // universal-character-names, and line splicing) are reverted.
1839
Richard Smith661a9962011-10-15 01:18:56 +00001840 if (!isLexingRawMode())
1841 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1842
Craig Topper2fa4e862011-08-11 04:06:15 +00001843 unsigned PrefixLen = 0;
1844
1845 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1846 ++PrefixLen;
1847
1848 // If the last character was not a '(', then we didn't lex a valid delimiter.
1849 if (CurPtr[PrefixLen] != '(') {
1850 if (!isLexingRawMode()) {
1851 const char *PrefixEnd = &CurPtr[PrefixLen];
1852 if (PrefixLen == 16) {
1853 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1854 } else {
1855 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1856 << StringRef(PrefixEnd, 1);
1857 }
1858 }
1859
1860 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1861 // it's possible the '"' was intended to be part of the raw string, but
1862 // there's not much we can do about that.
1863 while (1) {
1864 char C = *CurPtr++;
1865
1866 if (C == '"')
1867 break;
1868 if (C == 0 && CurPtr-1 == BufferEnd) {
1869 --CurPtr;
1870 break;
1871 }
1872 }
1873
1874 FormTokenWithChars(Result, CurPtr, tok::unknown);
1875 return;
1876 }
1877
1878 // Save prefix and move CurPtr past it
1879 const char *Prefix = CurPtr;
1880 CurPtr += PrefixLen + 1; // skip over prefix and '('
1881
1882 while (1) {
1883 char C = *CurPtr++;
1884
1885 if (C == ')') {
1886 // Check for prefix match and closing quote.
1887 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1888 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1889 break;
1890 }
1891 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1892 if (!isLexingRawMode())
1893 Diag(BufferPtr, diag::err_unterminated_raw_string)
1894 << StringRef(Prefix, PrefixLen);
1895 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1896 return;
1897 }
1898 }
1899
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001900 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001901 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001902 CurPtr = LexUDSuffix(Result, CurPtr);
1903
Craig Topper2fa4e862011-08-11 04:06:15 +00001904 // Update the location of token as well as BufferPtr.
1905 const char *TokStart = BufferPtr;
1906 FormTokenWithChars(Result, CurPtr, Kind);
1907 Result.setLiteralData(TokStart);
1908}
1909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1911/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattnerd2177732007-07-20 16:59:19 +00001912void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001914 const char *AfterLessPos = CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 char C = getAndAdvanceChar(CurPtr, Result);
1916 while (C != '>') {
1917 // Skip escaped characters.
1918 if (C == '\\') {
1919 // Skip the escaped character.
Dmitri Gribenko60b202c2012-07-30 17:59:40 +00001920 getAndAdvanceChar(CurPtr, Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001922 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1923 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00001924 // If the filename is unterminated, then it must just be a lone <
1925 // character. Return this as such.
1926 FormTokenWithChars(Result, AfterLessPos, tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 return;
1928 } else if (C == 0) {
1929 NulCharacter = CurPtr-1;
1930 }
1931 C = getAndAdvanceChar(CurPtr, Result);
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Reid Spencer5f016e22007-07-11 17:01:13 +00001934 // If a nul character existed in the string, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001935 if (NulCharacter && !isLexingRawMode())
1936 Diag(NulCharacter, diag::null_in_string);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001939 const char *TokStart = BufferPtr;
Chris Lattner9e6293d2008-10-12 04:51:35 +00001940 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner47246be2009-01-26 19:29:26 +00001941 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00001942}
1943
1944
1945/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregor5cee1192011-07-27 05:40:30 +00001946/// lexed either ' or L' or u' or U'.
1947void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1948 tok::TokenKind Kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 const char *NulCharacter = 0; // Does this character contain the \0 character?
1950
Richard Smith661a9962011-10-15 01:18:56 +00001951 if (!isLexingRawMode() &&
1952 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1953 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 char C = getAndAdvanceChar(CurPtr, Result);
1956 if (C == '\'') {
David Blaikie4e4d0842012-03-11 07:00:24 +00001957 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001958 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattner9e6293d2008-10-12 04:51:35 +00001959 FormTokenWithChars(Result, CurPtr, tok::unknown);
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 return;
Chris Lattnerd80f7862010-07-07 23:24:27 +00001961 }
1962
1963 while (C != '\'') {
1964 // Skip escaped characters.
Nico Weber6d926ae2012-11-17 20:25:54 +00001965 if (C == '\\')
1966 C = getAndAdvanceChar(CurPtr, Result);
1967
1968 if (C == '\n' || C == '\r' || // Newline.
1969 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001970 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smithb6ebd442012-06-28 07:51:56 +00001971 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattnerd80f7862010-07-07 23:24:27 +00001972 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1973 return;
Nico Weber6d926ae2012-11-17 20:25:54 +00001974 }
1975
1976 if (C == 0) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001977 if (isCodeCompletionPoint(CurPtr-1)) {
1978 PP->CodeCompleteNaturalLanguage();
1979 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1980 return cutOffLexing();
1981 }
1982
Chris Lattnerd80f7862010-07-07 23:24:27 +00001983 NulCharacter = CurPtr-1;
1984 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 C = getAndAdvanceChar(CurPtr, Result);
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001988 // If we are in C++11, lex the optional ud-suffix.
David Blaikie4e4d0842012-03-11 07:00:24 +00001989 if (getLangOpts().CPlusPlus)
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001990 CurPtr = LexUDSuffix(Result, CurPtr);
1991
Chris Lattnerd80f7862010-07-07 23:24:27 +00001992 // If a nul character existed in the character, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00001993 if (NulCharacter && !isLexingRawMode())
1994 Diag(NulCharacter, diag::null_in_char);
Reid Spencer5f016e22007-07-11 17:01:13 +00001995
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 // Update the location of token as well as BufferPtr.
Chris Lattner47246be2009-01-26 19:29:26 +00001997 const char *TokStart = BufferPtr;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001998 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner47246be2009-01-26 19:29:26 +00001999 Result.setLiteralData(TokStart);
Reid Spencer5f016e22007-07-11 17:01:13 +00002000}
2001
2002/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2003/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattnerd88dc482008-10-12 04:05:48 +00002004///
2005/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2006///
2007bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 // Whitespace - Skip it, then return the token after the whitespace.
2009 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
2010 while (1) {
2011 // Skip horizontal whitespace very aggressively.
2012 while (isHorizontalWhitespace(Char))
2013 Char = *++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Daniel Dunbarddd3e8b2008-11-25 00:20:22 +00002015 // Otherwise if we have something other than whitespace, we're done.
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 if (Char != '\n' && Char != '\r')
2017 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 if (ParsingPreprocessorDirective) {
2020 // End of preprocessor directive line, let LexTokenInternal handle this.
2021 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00002022 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 // ok, but handle newline.
2026 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002027 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002029 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 Char = *++CurPtr;
2031 }
2032
2033 // If this isn't immediately after a newline, there is leading space.
2034 char PrevChar = CurPtr[-1];
2035 if (PrevChar != '\n' && PrevChar != '\r')
Chris Lattnerd2177732007-07-20 16:59:19 +00002036 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002037
Chris Lattnerd88dc482008-10-12 04:05:48 +00002038 // If the client wants us to return whitespace, return it now.
2039 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002040 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002041 return true;
2042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 BufferPtr = CurPtr;
Chris Lattnerd88dc482008-10-12 04:05:48 +00002045 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002046}
2047
Nico Weberbb236282012-11-11 07:02:14 +00002048/// We have just read the // characters from input. Skip until we find the
2049/// newline character thats terminate the comment. Then update BufferPtr and
2050/// return.
Chris Lattner046c2272010-01-18 22:35:47 +00002051///
2052/// If we're in KeepCommentMode or any CommentHandler has inserted
2053/// some tokens, this will store the first token and return true.
Nico Weberbb236282012-11-11 07:02:14 +00002054bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
2055 // If Line comments aren't explicitly enabled for this language, emit an
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 // extension warning.
Nico Weberbb236282012-11-11 07:02:14 +00002057 if (!LangOpts.LineComment && !isLexingRawMode()) {
2058 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 // Mark them enabled so we only emit one warning for this translation
2061 // unit.
Nico Weberbb236282012-11-11 07:02:14 +00002062 LangOpts.LineComment = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 // Scan over the body of the comment. The common case, when scanning, is that
2066 // the comment contains normal ascii characters with nothing interesting in
2067 // them. As such, optimize for this case with the inner loop.
2068 char C;
2069 do {
2070 C = *CurPtr;
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 // Skip over characters in the fast loop.
2072 while (C != 0 && // Potentially EOF.
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 C != '\n' && C != '\r') // Newline or DOS-style newline.
2074 C = *++CurPtr;
2075
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00002076 const char *NextLine = CurPtr;
2077 if (C != 0) {
2078 // We found a newline, see if it's escaped.
2079 const char *EscapePtr = CurPtr-1;
2080 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
2081 --EscapePtr;
2082
2083 if (*EscapePtr == '\\') // Escaped newline.
2084 CurPtr = EscapePtr;
2085 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2086 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2087 CurPtr = EscapePtr-2;
2088 else
2089 break; // This is a newline, we're done.
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00002090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnerbc3e9842008-12-12 07:34:39 +00002093 // properly decode the character. Read it in raw mode to avoid emitting
2094 // diagnostics about things like trigraphs. If we see an escaped newline,
2095 // we'll handle it below.
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 const char *OldPtr = CurPtr;
Chris Lattnerbc3e9842008-12-12 07:34:39 +00002097 bool OldRawMode = isLexingRawMode();
2098 LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerbc3e9842008-12-12 07:34:39 +00002100 LexingRawMode = OldRawMode;
Chris Lattneread616c2009-04-05 00:26:41 +00002101
Benjamin Kramer1daa58e2011-09-05 07:19:39 +00002102 // If we only read only one character, then no special handling is needed.
2103 // We're done and can skip forward to the newline.
2104 if (C != 0 && CurPtr == OldPtr+1) {
2105 CurPtr = NextLine;
2106 break;
2107 }
2108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 // If we read multiple characters, and one of those characters was a \r or
2110 // \n, then we had an escaped newline within the comment. Emit diagnostic
2111 // unless the next line is also a // comment.
2112 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2113 for (; OldPtr != CurPtr; ++OldPtr)
2114 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2115 // Okay, we found a // comment that ends in a newline, if the next
2116 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002117 if (isWhitespace(C)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 const char *ForwardPtr = CurPtr;
Benjamin Kramer5d6ae282011-09-05 07:19:35 +00002119 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 ++ForwardPtr;
2121 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2122 break;
2123 }
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Chris Lattner74d15df2008-11-22 02:02:22 +00002125 if (!isLexingRawMode())
Nico Weberbb236282012-11-11 07:02:14 +00002126 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 break;
2128 }
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregor55817af2010-08-25 17:04:25 +00002131 if (CurPtr == BufferEnd+1) {
Douglas Gregor55817af2010-08-25 17:04:25 +00002132 --CurPtr;
2133 break;
2134 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002135
2136 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2137 PP->CodeCompleteNaturalLanguage();
2138 cutOffLexing();
2139 return false;
2140 }
2141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 } while (C != '\n' && C != '\r');
2143
Chris Lattner3d0ad582010-02-03 21:06:21 +00002144 // Found but did not consume the newline. Notify comment handlers about the
2145 // comment unless we're in a #if 0 block.
2146 if (PP && !isLexingRawMode() &&
2147 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2148 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002149 BufferPtr = CurPtr;
2150 return true; // A token has to be returned.
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002154 if (inKeepCommentMode())
Nico Weberbb236282012-11-11 07:02:14 +00002155 return SaveLineComment(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002156
2157 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002158 // return immediately, so that the lexer can return this as an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2160 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002161 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner7a4f0042008-10-12 00:23:07 +00002165 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattnerd88dc482008-10-12 04:05:48 +00002166 // contribute to another token), it isn't needed for correctness. Note that
2167 // this is ok even in KeepWhitespaceMode, because we would have returned the
2168 /// comment above in that mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 // The next returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002172 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002174 Result.clearFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002176 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002177}
2178
Nico Weberbb236282012-11-11 07:02:14 +00002179/// If in save-comment mode, package up this Line comment in an appropriate
2180/// way and return it.
2181bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002182 // If we're not in a preprocessor directive, just return the // comment
2183 // directly.
2184 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump1eb44332009-09-09 15:08:12 +00002185
David Blaikie8c0b3782012-06-06 18:52:13 +00002186 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattner9e6293d2008-10-12 04:51:35 +00002187 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Nico Weberbb236282012-11-11 07:02:14 +00002189 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattner9e6293d2008-10-12 04:51:35 +00002190 // a C-style block comment.
Douglas Gregor453091c2010-03-16 22:30:13 +00002191 bool Invalid = false;
2192 std::string Spelling = PP->getSpelling(Result, &Invalid);
2193 if (Invalid)
2194 return true;
2195
Nico Weberbb236282012-11-11 07:02:14 +00002196 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattner9e6293d2008-10-12 04:51:35 +00002197 Spelling[1] = '*'; // Change prefix to "/*".
2198 Spelling += "*/"; // add suffix.
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Chris Lattner9e6293d2008-10-12 04:51:35 +00002200 Result.setKind(tok::comment);
Dmitri Gribenko374b3832012-09-24 21:07:17 +00002201 PP->CreateString(Spelling, Result,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +00002202 Result.getLocation(), Result.getLocation());
Chris Lattner2d381892008-10-12 04:15:42 +00002203 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002204}
2205
2206/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie80d7c522012-06-06 18:43:20 +00002207/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2208/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump1eb44332009-09-09 15:08:12 +00002209static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 Lexer *L) {
2211 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 // Back up off the newline.
2214 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 // If this is a two-character newline sequence, skip the other character.
2217 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2218 // \n\n or \r\r -> not escaped newline.
2219 if (CurPtr[0] == CurPtr[1])
2220 return false;
2221 // \n\r or \r\n -> skip the newline.
2222 --CurPtr;
2223 }
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // If we have horizontal whitespace, skip over it. We allow whitespace
2226 // between the slash and newline.
2227 bool HasSpace = false;
2228 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2229 --CurPtr;
2230 HasSpace = true;
2231 }
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 // If we have a slash, we know this is an escaped newline.
2234 if (*CurPtr == '\\') {
2235 if (CurPtr[-1] != '*') return false;
2236 } else {
2237 // It isn't a slash, is it the ?? / trigraph?
2238 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2239 CurPtr[-3] != '*')
2240 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 // This is the trigraph ending the comment. Emit a stern warning!
2243 CurPtr -= 2;
2244
2245 // If no trigraphs are enabled, warn that we ignored this trigraph and
2246 // ignore this * character.
David Blaikie4e4d0842012-03-11 07:00:24 +00002247 if (!L->getLangOpts().Trigraphs) {
Chris Lattner74d15df2008-11-22 02:02:22 +00002248 if (!L->isLexingRawMode())
2249 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 return false;
2251 }
Chris Lattner74d15df2008-11-22 02:02:22 +00002252 if (!L->isLexingRawMode())
2253 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 }
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Reid Spencer5f016e22007-07-11 17:01:13 +00002256 // Warn about having an escaped newline between the */ characters.
Chris Lattner74d15df2008-11-22 02:02:22 +00002257 if (!L->isLexingRawMode())
2258 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 // If there was space between the backslash and newline, warn about it.
Chris Lattner74d15df2008-11-22 02:02:22 +00002261 if (HasSpace && !L->isLexingRawMode())
2262 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Reid Spencer5f016e22007-07-11 17:01:13 +00002264 return true;
2265}
2266
2267#ifdef __SSE2__
2268#include <emmintrin.h>
2269#elif __ALTIVEC__
2270#include <altivec.h>
2271#undef bool
2272#endif
2273
James Dennettec769932012-06-17 03:40:43 +00002274/// We have just read from input the / and * characters that started a comment.
2275/// Read until we find the * and / characters that terminate the comment.
2276/// Note that we don't bother decoding trigraphs or escaped newlines in block
2277/// comments, because they cannot cause the comment to end. The only thing
2278/// that can happen is the comment could end with an escaped newline between
2279/// the terminating * and /.
Chris Lattner2d381892008-10-12 04:15:42 +00002280///
Chris Lattner046c2272010-01-18 22:35:47 +00002281/// If we're in KeepCommentMode or any CommentHandler has inserted
2282/// some tokens, this will store the first token and return true.
Chris Lattnerd2177732007-07-20 16:59:19 +00002283bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002285 // we find it, check to see if it was preceded by a *. This common
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 // optimization helps people who like to put a lot of * characters in their
2287 // comments.
Chris Lattner8146b682007-07-21 23:43:37 +00002288
2289 // The first character we get with newlines and trigraphs skipped to handle
2290 // the degenerate /*/ case below correctly if the * has an escaped newline
2291 // after it.
2292 unsigned CharSize;
2293 unsigned char C = getCharAndSize(CurPtr, CharSize);
2294 CurPtr += CharSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002296 if (!isLexingRawMode())
Chris Lattner0af57422008-10-12 01:31:51 +00002297 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002298 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattner31f0eca2008-10-12 04:19:49 +00002300 // KeepWhitespaceMode should return this broken comment as a token. Since
2301 // it isn't a well formed comment, just return it as an 'unknown' token.
2302 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002303 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002304 return true;
2305 }
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Chris Lattner31f0eca2008-10-12 04:19:49 +00002307 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002308 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 }
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Chris Lattner8146b682007-07-21 23:43:37 +00002311 // Check to see if the first character after the '/*' is another /. If so,
2312 // then this slash does not end the block comment, it is part of it.
2313 if (C == '/')
2314 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 while (1) {
2317 // Skip over all non-interesting characters until we find end of buffer or a
2318 // (probably ending) '/' character.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002319 if (CurPtr + 24 < BufferEnd &&
2320 // If there is a code-completion point avoid the fast scan because it
2321 // doesn't check for '\0'.
2322 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 // While not aligned to a 16-byte boundary.
2324 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2325 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Reid Spencer5f016e22007-07-11 17:01:13 +00002327 if (C == '/') goto FoundSlash;
2328
2329#ifdef __SSE2__
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002330 __m128i Slashes = _mm_set1_epi8('/');
2331 while (CurPtr+16 <= BufferEnd) {
Roman Divacky31ba6132012-09-06 15:59:27 +00002332 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2333 Slashes));
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002334 if (cmp != 0) {
Benjamin Kramer6300f5b2011-11-22 20:39:31 +00002335 // Adjust the pointer to point directly after the first slash. It's
2336 // not necessary to set C here, it will be overwritten at the end of
2337 // the outer loop.
2338 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002339 goto FoundSlash;
2340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 CurPtr += 16;
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002342 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002343#elif __ALTIVEC__
2344 __vector unsigned char Slashes = {
Mike Stump1eb44332009-09-09 15:08:12 +00002345 '/', '/', '/', '/', '/', '/', '/', '/',
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 '/', '/', '/', '/', '/', '/', '/', '/'
2347 };
2348 while (CurPtr+16 <= BufferEnd &&
2349 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2350 CurPtr += 16;
Mike Stump1eb44332009-09-09 15:08:12 +00002351#else
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 // Scan for '/' quickly. Many block comments are very large.
2353 while (CurPtr[0] != '/' &&
2354 CurPtr[1] != '/' &&
2355 CurPtr[2] != '/' &&
2356 CurPtr[3] != '/' &&
2357 CurPtr+4 < BufferEnd) {
2358 CurPtr += 4;
2359 }
2360#endif
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Reid Spencer5f016e22007-07-11 17:01:13 +00002362 // It has to be one of the bytes scanned, increment to it and read one.
2363 C = *CurPtr++;
2364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 // Loop to scan the remainder.
2367 while (C != '/' && C != '\0')
2368 C = *CurPtr++;
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 if (C == '/') {
Benjamin Kramer3f6f4e62011-11-22 18:56:46 +00002371 FoundSlash:
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 if (CurPtr[-2] == '*') // We found the final */. We're done!
2373 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2376 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2377 // We found the final */, though it had an escaped newline between the
2378 // * and /. We're done!
2379 break;
2380 }
2381 }
2382 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2383 // If this is a /* inside of the comment, emit a warning. Don't do this
2384 // if this is a /*/, which will end the comment. This misses cases with
2385 // embedded escaped newlines, but oh well.
Chris Lattner74d15df2008-11-22 02:02:22 +00002386 if (!isLexingRawMode())
2387 Diag(CurPtr-1, diag::warn_nested_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002388 }
2389 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002390 if (!isLexingRawMode())
Chris Lattner74d15df2008-11-22 02:02:22 +00002391 Diag(BufferPtr, diag::err_unterminated_block_comment);
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 // Note: the user probably forgot a */. We could continue immediately
2393 // after the /*, but this would involve lexing a lot of what really is the
2394 // comment, which surely would confuse the parser.
Chris Lattner31f0eca2008-10-12 04:19:49 +00002395 --CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Chris Lattner31f0eca2008-10-12 04:19:49 +00002397 // KeepWhitespaceMode should return this broken comment as a token. Since
2398 // it isn't a well formed comment, just return it as an 'unknown' token.
2399 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002400 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner31f0eca2008-10-12 04:19:49 +00002401 return true;
2402 }
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Chris Lattner31f0eca2008-10-12 04:19:49 +00002404 BufferPtr = CurPtr;
Chris Lattner2d381892008-10-12 04:15:42 +00002405 return false;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002406 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2407 PP->CodeCompleteNaturalLanguage();
2408 cutOffLexing();
2409 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002411
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 C = *CurPtr++;
2413 }
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Chris Lattner3d0ad582010-02-03 21:06:21 +00002415 // Notify comment handlers about the comment unless we're in a #if 0 block.
2416 if (PP && !isLexingRawMode() &&
2417 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2418 getSourceLocation(CurPtr)))) {
Chris Lattner046c2272010-01-18 22:35:47 +00002419 BufferPtr = CurPtr;
2420 return true; // A token has to be returned.
2421 }
Douglas Gregor2e222532009-07-02 17:08:52 +00002422
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 // If we are returning comments as tokens, return this comment as a token.
Chris Lattnerfa95a012008-10-12 03:22:02 +00002424 if (inKeepCommentMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002425 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattner2d381892008-10-12 04:15:42 +00002426 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 }
2428
2429 // It is common for the tokens immediately after a /**/ comment to be
2430 // whitespace. Instead of going through the big switch, handle it
Chris Lattnerd88dc482008-10-12 04:05:48 +00002431 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2432 // have already returned above with the comment as a token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002433 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattnerd2177732007-07-20 16:59:19 +00002434 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002435 SkipWhitespace(Result, CurPtr+1);
Chris Lattner2d381892008-10-12 04:15:42 +00002436 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002437 }
2438
2439 // Otherwise, just return so that the next character will be lexed as a token.
2440 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002441 Result.setFlag(Token::LeadingSpace);
Chris Lattner2d381892008-10-12 04:15:42 +00002442 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002443}
2444
2445//===----------------------------------------------------------------------===//
2446// Primary Lexing Entry Points
2447//===----------------------------------------------------------------------===//
2448
Reid Spencer5f016e22007-07-11 17:01:13 +00002449/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2450/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002451void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002452 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2453 "Must be in a preprocessing directive!");
Chris Lattnerd2177732007-07-20 16:59:19 +00002454 Token Tmp;
Reid Spencer5f016e22007-07-11 17:01:13 +00002455
2456 // CurPtr - Cache BufferPtr in an automatic variable.
2457 const char *CurPtr = BufferPtr;
2458 while (1) {
2459 char Char = getAndAdvanceChar(CurPtr, Tmp);
2460 switch (Char) {
2461 default:
Benjamin Kramer3093b202012-05-18 19:32:16 +00002462 if (Result)
2463 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 break;
2465 case 0: // Null.
2466 // Found end of file?
2467 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002468 if (isCodeCompletionPoint(CurPtr-1)) {
2469 PP->CodeCompleteNaturalLanguage();
2470 cutOffLexing();
Benjamin Kramer3093b202012-05-18 19:32:16 +00002471 return;
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002472 }
2473
Reid Spencer5f016e22007-07-11 17:01:13 +00002474 // Nope, normal character, continue.
Benjamin Kramer3093b202012-05-18 19:32:16 +00002475 if (Result)
2476 Result->push_back(Char);
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 break;
2478 }
2479 // FALL THROUGH.
2480 case '\r':
2481 case '\n':
2482 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2483 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2484 BufferPtr = CurPtr-1;
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Peter Collingbourne84021552011-02-28 02:37:51 +00002486 // Next, lex the character, which should handle the EOD transition.
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 Lex(Tmp);
Douglas Gregor55817af2010-08-25 17:04:25 +00002488 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002489 if (PP)
2490 PP->CodeCompleteNaturalLanguage();
Douglas Gregor55817af2010-08-25 17:04:25 +00002491 Lex(Tmp);
2492 }
Peter Collingbourne84021552011-02-28 02:37:51 +00002493 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Benjamin Kramer3093b202012-05-18 19:32:16 +00002495 // Finally, we're done;
2496 return;
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 }
2498 }
2499}
2500
2501/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2502/// condition, reporting diagnostics and handling other edge cases as required.
2503/// This returns true if Result contains a token, false if PP.Lex should be
2504/// called again.
Chris Lattnerd2177732007-07-20 16:59:19 +00002505bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 // If we hit the end of the file while parsing a preprocessor directive,
2507 // end the preprocessor directive first. The next token returned will
2508 // then be the end of file.
2509 if (ParsingPreprocessorDirective) {
2510 // Done parsing the "line".
2511 ParsingPreprocessorDirective = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002512 // Update the location of token as well as BufferPtr.
Peter Collingbourne84021552011-02-28 02:37:51 +00002513 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 // Restore comment saving mode, in case it was disabled for directive.
Chris Lattnerf744d132008-10-12 03:27:19 +00002516 SetCommentRetentionState(PP->getCommentRetentionState());
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 return true; // Have a token.
Mike Stump1eb44332009-09-09 15:08:12 +00002518 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002519
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 // If we are in raw mode, return this event as an EOF token. Let the caller
2521 // that put us in raw mode handle the event.
Chris Lattner74d15df2008-11-22 02:02:22 +00002522 if (isLexingRawMode()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 Result.startToken();
2524 BufferPtr = BufferEnd;
Chris Lattner9e6293d2008-10-12 04:51:35 +00002525 FormTokenWithChars(Result, BufferEnd, tok::eof);
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 return true;
2527 }
Douglas Gregor86d9a522009-09-21 16:56:56 +00002528
Douglas Gregorf44e8542010-08-24 19:08:16 +00002529 // Issue diagnostics for unterminated #if and missing newline.
2530
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 // If we are in a #if directive, emit an error.
2532 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002533 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor2d474ba2010-08-12 17:04:55 +00002534 PP->Diag(ConditionalStack.back().IfLoc,
2535 diag::err_pp_unterminated_conditional);
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 ConditionalStack.pop_back();
2537 }
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Chris Lattnerb25e5d72008-04-12 05:54:25 +00002539 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2540 // a pedwarn.
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002541 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith80ad52f2013-01-02 11:42:31 +00002542 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrell5e6c3f02012-04-13 03:43:23 +00002543 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2544 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 BufferPtr = CurPtr;
2547
2548 // Finally, let the preprocessor handle this.
Jordan Rose0cdd1fe2012-06-15 23:33:51 +00002549 return PP->HandleEndOfFile(Result, isPragmaLexer());
Reid Spencer5f016e22007-07-11 17:01:13 +00002550}
2551
2552/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2553/// the specified lexer will return a tok::l_paren token, 0 if it is something
2554/// else and 2 if there are no more tokens in the buffer controlled by the
2555/// lexer.
2556unsigned Lexer::isNextPPTokenLParen() {
2557 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 // Switch to 'skipping' mode. This will ensure that we can lex a token
2560 // without emitting diagnostics, disables macro expansion, and will cause EOF
2561 // to return an EOF token instead of popping the include stack.
2562 LexingRawMode = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002563
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 // Save state that can be changed while lexing so that we can restore it.
2565 const char *TmpBufferPtr = BufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002566 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Chris Lattnerd2177732007-07-20 16:59:19 +00002568 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 Tok.startToken();
2570 LexTokenInternal(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Reid Spencer5f016e22007-07-11 17:01:13 +00002572 // Restore state that may have changed.
2573 BufferPtr = TmpBufferPtr;
Chris Lattnera864cf72009-04-24 07:15:46 +00002574 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 // Restore the lexer back to non-skipping mode.
2577 LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002579 if (Tok.is(tok::eof))
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 return 2;
Chris Lattner22f6bbc2007-10-09 18:02:16 +00002581 return Tok.is(tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00002582}
2583
James Dennettec769932012-06-17 03:40:43 +00002584/// \brief Find the end of a version control conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002585static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2586 ConflictMarkerKind CMK) {
2587 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2588 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2589 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2590 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002591 while (Pos != StringRef::npos) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002592 // Must occur at start of line.
2593 if (RestOfBuffer[Pos-1] != '\r' &&
2594 RestOfBuffer[Pos-1] != '\n') {
Richard Smithd5e1d602011-10-12 00:37:51 +00002595 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2596 Pos = RestOfBuffer.find(Terminator);
Chris Lattner34f349d2009-12-14 06:16:57 +00002597 continue;
2598 }
2599 return RestOfBuffer.data()+Pos;
2600 }
2601 return 0;
2602}
2603
2604/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2605/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2606/// and recover nicely. This returns true if it is a conflict marker and false
2607/// if not.
2608bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2609 // Only a conflict marker if it starts at the beginning of a line.
2610 if (CurPtr != BufferStart &&
2611 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2612 return false;
2613
Richard Smithd5e1d602011-10-12 00:37:51 +00002614 // Check to see if we have <<<<<<< or >>>>.
2615 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2616 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner34f349d2009-12-14 06:16:57 +00002617 return false;
2618
2619 // If we have a situation where we don't care about conflict markers, ignore
2620 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002621 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002622 return false;
2623
Richard Smithd5e1d602011-10-12 00:37:51 +00002624 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2625
2626 // Check to see if there is an ending marker somewhere in the buffer at the
2627 // start of a line to terminate this conflict marker.
2628 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002629 // We found a match. We are really in a conflict marker.
2630 // Diagnose this, and ignore to the end of line.
2631 Diag(CurPtr, diag::err_conflict_marker);
Richard Smithd5e1d602011-10-12 00:37:51 +00002632 CurrentConflictMarkerState = Kind;
Chris Lattner34f349d2009-12-14 06:16:57 +00002633
2634 // Skip ahead to the end of line. We know this exists because the
2635 // end-of-conflict marker starts with \r or \n.
2636 while (*CurPtr != '\r' && *CurPtr != '\n') {
2637 assert(CurPtr != BufferEnd && "Didn't find end of line");
2638 ++CurPtr;
2639 }
2640 BufferPtr = CurPtr;
2641 return true;
2642 }
2643
2644 // No end of conflict marker found.
2645 return false;
2646}
2647
2648
Richard Smithd5e1d602011-10-12 00:37:51 +00002649/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2650/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2651/// is the end of a conflict marker. Handle it by ignoring up until the end of
2652/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner34f349d2009-12-14 06:16:57 +00002653bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2654 // Only a conflict marker if it starts at the beginning of a line.
2655 if (CurPtr != BufferStart &&
2656 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2657 return false;
2658
2659 // If we have a situation where we don't care about conflict markers, ignore
2660 // it.
Richard Smithd5e1d602011-10-12 00:37:51 +00002661 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner34f349d2009-12-14 06:16:57 +00002662 return false;
2663
Richard Smithd5e1d602011-10-12 00:37:51 +00002664 // Check to see if we have the marker (4 characters in a row).
2665 for (unsigned i = 1; i != 4; ++i)
Chris Lattner34f349d2009-12-14 06:16:57 +00002666 if (CurPtr[i] != CurPtr[0])
2667 return false;
2668
2669 // If we do have it, search for the end of the conflict marker. This could
2670 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2671 // be the end of conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002672 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2673 CurrentConflictMarkerState)) {
Chris Lattner34f349d2009-12-14 06:16:57 +00002674 CurPtr = End;
2675
2676 // Skip ahead to the end of line.
2677 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2678 ++CurPtr;
2679
2680 BufferPtr = CurPtr;
2681
2682 // No longer in the conflict marker.
Richard Smithd5e1d602011-10-12 00:37:51 +00002683 CurrentConflictMarkerState = CMK_None;
Chris Lattner34f349d2009-12-14 06:16:57 +00002684 return true;
2685 }
2686
2687 return false;
2688}
2689
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002690bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2691 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002692 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002693 return Loc == PP->getCodeCompletionLoc();
2694 }
2695
2696 return false;
2697}
2698
Jordan Rosec7629d92013-01-24 20:50:46 +00002699uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2700 Token *Result) {
2701 assert(LangOpts.CPlusPlus || LangOpts.C99);
2702
2703 unsigned CharSize;
2704 char Kind = getCharAndSize(StartPtr, CharSize);
2705
2706 unsigned NumHexDigits;
2707 if (Kind == 'u')
2708 NumHexDigits = 4;
2709 else if (Kind == 'U')
2710 NumHexDigits = 8;
2711 else
2712 return 0;
2713
2714 const char *CurPtr = StartPtr + CharSize;
2715 const char *KindLoc = &CurPtr[-1];
2716
2717 uint32_t CodePoint = 0;
2718 for (unsigned i = 0; i < NumHexDigits; ++i) {
2719 char C = getCharAndSize(CurPtr, CharSize);
2720
2721 unsigned Value = llvm::hexDigitValue(C);
2722 if (Value == -1U) {
2723 if (Result && !isLexingRawMode()) {
2724 if (i == 0) {
2725 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2726 << StringRef(KindLoc, 1);
2727 } else {
Jordan Rosec7629d92013-01-24 20:50:46 +00002728 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Roseb87672b2013-01-24 20:50:52 +00002729
2730 // If the user wrote \U1234, suggest a fixit to \u.
2731 if (i == 4 && NumHexDigits == 8) {
2732 CharSourceRange URange =
2733 CharSourceRange::getCharRange(getSourceLocation(KindLoc),
2734 getSourceLocation(KindLoc + 1));
2735 Diag(KindLoc, diag::note_ucn_four_not_eight)
2736 << FixItHint::CreateReplacement(URange, "u");
2737 }
Jordan Rosec7629d92013-01-24 20:50:46 +00002738 }
2739 }
2740
2741 return 0;
2742 }
2743
2744 CodePoint <<= 4;
2745 CodePoint += Value;
2746
2747 CurPtr += CharSize;
2748 }
2749
2750 if (Result) {
2751 Result->setFlag(Token::HasUCN);
2752 if (CurPtr - StartPtr == NumHexDigits + 2)
2753 StartPtr = CurPtr;
2754 else
2755 while (StartPtr != CurPtr)
2756 (void)getAndAdvanceChar(StartPtr, *Result);
2757 } else {
2758 StartPtr = CurPtr;
2759 }
2760
2761 // C99 6.4.3p2: A universal character name shall not specify a character whose
2762 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2763 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2764 // C++11 [lex.charset]p2: If the hexadecimal value for a
2765 // universal-character-name corresponds to a surrogate code point (in the
2766 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2767 // if the hexadecimal value for a universal-character-name outside the
2768 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2769 // string literal corresponds to a control character (in either of the
2770 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2771 // basic source character set, the program is ill-formed.
2772 if (CodePoint < 0xA0) {
2773 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2774 return CodePoint;
2775
2776 // We don't use isLexingRawMode() here because we need to warn about bad
2777 // UCNs even when skipping preprocessing tokens in a #if block.
2778 if (Result && PP) {
2779 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2780 Diag(BufferPtr, diag::err_ucn_control_character);
2781 else {
2782 char C = static_cast<char>(CodePoint);
2783 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2784 }
2785 }
2786
2787 return 0;
2788
2789 } else if ((!LangOpts.CPlusPlus || LangOpts.CPlusPlus11) &&
2790 (CodePoint >= 0xD800 && CodePoint <= 0xDFFF)) {
2791 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2792 // We don't use isLexingRawMode() here because we need to warn about bad
2793 // UCNs even when skipping preprocessing tokens in a #if block.
2794 if (Result && PP)
2795 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2796 return 0;
2797 }
2798
2799 return CodePoint;
2800}
2801
Jordan Rosefc120602013-01-24 20:50:50 +00002802static bool isUnicodeWhitespace(uint32_t C) {
2803 return (C == 0x0085 || C == 0x00A0 || C == 0x1680 ||
2804 C == 0x180E || (C >= 0x2000 && C <= 0x200A) ||
2805 C == 0x2028 || C == 0x2029 || C == 0x202F ||
2806 C == 0x205F || C == 0x3000);
2807}
2808
Jordan Rosec7629d92013-01-24 20:50:46 +00002809void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rosefc120602013-01-24 20:50:50 +00002810 if (isUnicodeWhitespace(C)) {
2811 if (!isLexingRawMode()) {
2812 CharSourceRange CharRange =
2813 CharSourceRange::getCharRange(getSourceLocation(),
2814 getSourceLocation(CurPtr));
2815 Diag(BufferPtr, diag::ext_unicode_whitespace)
2816 << CharRange;
2817 }
2818
2819 Result.setFlag(Token::LeadingSpace);
2820 if (SkipWhitespace(Result, CurPtr))
2821 return; // KeepWhitespaceMode
2822
2823 return LexTokenInternal(Result);
2824 }
2825
Jordan Rosec7629d92013-01-24 20:50:46 +00002826 if (isAllowedIDChar(C) && isAllowedInitiallyIDChar(C)) {
2827 MIOpt.ReadToken();
2828 return LexIdentifier(Result, CurPtr);
2829 }
2830
2831 if (!isASCII(*BufferPtr) && !isAllowedIDChar(C)) {
2832 // Non-ASCII characters tend to creep into source code unintentionally.
2833 // Instead of letting the parser complain about the unknown token,
2834 // just drop the character.
2835 // Note that we can /only/ do this when the non-ASCII character is actually
2836 // spelled as Unicode, not written as a UCN. The standard requires that
2837 // we not throw away any possible preprocessor tokens, but there's a
2838 // loophole in the mapping of Unicode characters to basic character set
2839 // characters that allows us to map these particular characters to, say,
2840 // whitespace.
2841 if (!isLexingRawMode()) {
2842 CharSourceRange CharRange =
2843 CharSourceRange::getCharRange(getSourceLocation(),
2844 getSourceLocation(CurPtr));
2845 Diag(BufferPtr, diag::err_non_ascii)
2846 << FixItHint::CreateRemoval(CharRange);
2847 }
2848
2849 BufferPtr = CurPtr;
2850 return LexTokenInternal(Result);
2851 }
2852
2853 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2854 // up by accident.
2855 MIOpt.ReadToken();
2856 FormTokenWithChars(Result, CurPtr, tok::unknown);
2857}
2858
Reid Spencer5f016e22007-07-11 17:01:13 +00002859
2860/// LexTokenInternal - This implements a simple C family lexer. It is an
2861/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattnerefb173d2009-07-07 05:05:42 +00002862/// has a null character at the end of the file. This returns a preprocessing
2863/// token, not a normal token, as such, it is an internal interface. It assumes
2864/// that the Flags of result have been cleared before calling this.
Chris Lattnerd2177732007-07-20 16:59:19 +00002865void Lexer::LexTokenInternal(Token &Result) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002866LexNextToken:
2867 // New token, can't need cleaning yet.
Chris Lattnerd2177732007-07-20 16:59:19 +00002868 Result.clearFlag(Token::NeedsCleaning);
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 Result.setIdentifierInfo(0);
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 // CurPtr - Cache BufferPtr in an automatic variable.
2872 const char *CurPtr = BufferPtr;
2873
2874 // Small amounts of horizontal whitespace is very common between tokens.
2875 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2876 ++CurPtr;
2877 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2878 ++CurPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Chris Lattnerd88dc482008-10-12 04:05:48 +00002880 // If we are keeping whitespace and other tokens, just return what we just
2881 // skipped. The next lexer invocation will return the token after the
2882 // whitespace.
2883 if (isKeepWhitespaceMode()) {
Chris Lattner9e6293d2008-10-12 04:51:35 +00002884 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002885 return;
2886 }
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 BufferPtr = CurPtr;
Chris Lattnerd2177732007-07-20 16:59:19 +00002889 Result.setFlag(Token::LeadingSpace);
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 }
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 // Read a character, advancing over it.
2895 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00002896 tok::TokenKind Kind;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Reid Spencer5f016e22007-07-11 17:01:13 +00002898 switch (Char) {
2899 case 0: // Null.
2900 // Found end of file?
2901 if (CurPtr-1 == BufferEnd) {
2902 // Read the PP instance variable into an automatic variable, because
2903 // LexEndOfFile will often delete 'this'.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002904 Preprocessor *PPCache = PP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2906 return; // Got a token to return.
Chris Lattner168ae2d2007-10-17 20:41:00 +00002907 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2908 return PPCache->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 }
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002911 // Check if we are performing code completion.
2912 if (isCodeCompletionPoint(CurPtr-1)) {
2913 // Return the code-completion token.
2914 Result.startToken();
2915 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2916 return;
2917 }
2918
Chris Lattner74d15df2008-11-22 02:02:22 +00002919 if (!isLexingRawMode())
2920 Diag(CurPtr-1, diag::null_in_file);
Chris Lattnerd2177732007-07-20 16:59:19 +00002921 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002922 if (SkipWhitespace(Result, CurPtr))
2923 return; // KeepWhitespaceMode
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002926
2927 case 26: // DOS & CP/M EOF: "^Z".
2928 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikie4e4d0842012-03-11 07:00:24 +00002929 if (LangOpts.MicrosoftExt) {
Chris Lattnera2bf1052009-12-17 05:29:40 +00002930 // Read the PP instance variable into an automatic variable, because
2931 // LexEndOfFile will often delete 'this'.
2932 Preprocessor *PPCache = PP;
2933 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2934 return; // Got a token to return.
2935 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2936 return PPCache->Lex(Result);
2937 }
2938 // If Microsoft extensions are disabled, this is just random garbage.
2939 Kind = tok::unknown;
2940 break;
2941
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 case '\n':
2943 case '\r':
2944 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne84021552011-02-28 02:37:51 +00002945 // we know we are done with the directive, so return an EOD token.
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 if (ParsingPreprocessorDirective) {
2947 // Done parsing the "line".
2948 ParsingPreprocessorDirective = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie1a835462012-06-15 00:47:13 +00002951 if (PP)
David Blaikie8c0b3782012-06-06 18:52:13 +00002952 SetCommentRetentionState(PP->getCommentRetentionState());
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 // Since we consumed a newline, we are back at the start of a line.
2955 IsAtStartOfLine = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002956
Peter Collingbourne84021552011-02-28 02:37:51 +00002957 Kind = tok::eod;
Reid Spencer5f016e22007-07-11 17:01:13 +00002958 break;
2959 }
2960 // The returned token is at the start of the line.
Chris Lattnerd2177732007-07-20 16:59:19 +00002961 Result.setFlag(Token::StartOfLine);
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 // No leading whitespace seen so far.
Chris Lattnerd2177732007-07-20 16:59:19 +00002963 Result.clearFlag(Token::LeadingSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Chris Lattnerd88dc482008-10-12 04:05:48 +00002965 if (SkipWhitespace(Result, CurPtr))
2966 return; // KeepWhitespaceMode
Reid Spencer5f016e22007-07-11 17:01:13 +00002967 goto LexNextToken; // GCC isn't tail call eliminating.
2968 case ' ':
2969 case '\t':
2970 case '\f':
2971 case '\v':
Chris Lattner8133cfc2007-07-22 06:29:05 +00002972 SkipHorizontalWhitespace:
Chris Lattnerd2177732007-07-20 16:59:19 +00002973 Result.setFlag(Token::LeadingSpace);
Chris Lattnerd88dc482008-10-12 04:05:48 +00002974 if (SkipWhitespace(Result, CurPtr))
2975 return; // KeepWhitespaceMode
Chris Lattner8133cfc2007-07-22 06:29:05 +00002976
2977 SkipIgnoredUnits:
2978 CurPtr = BufferPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Chris Lattner8133cfc2007-07-22 06:29:05 +00002980 // If the next token is obviously a // or /* */ comment, skip it efficiently
2981 // too (without going through the big switch stmt).
Chris Lattner8402c732009-01-16 22:39:25 +00002982 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weberbb236282012-11-11 07:02:14 +00002983 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2984 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner046c2272010-01-18 22:35:47 +00002985 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002986 goto SkipIgnoredUnits;
Chris Lattnerfa95a012008-10-12 03:22:02 +00002987 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner046c2272010-01-18 22:35:47 +00002988 if (SkipBlockComment(Result, CurPtr+2))
2989 return; // There is a token to return.
Chris Lattner8133cfc2007-07-22 06:29:05 +00002990 goto SkipIgnoredUnits;
2991 } else if (isHorizontalWhitespace(*CurPtr)) {
2992 goto SkipHorizontalWhitespace;
2993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002994 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattnera2bf1052009-12-17 05:29:40 +00002995
Chris Lattner3a570772008-01-03 17:58:54 +00002996 // C99 6.4.4.1: Integer Constants.
2997 // C99 6.4.4.2: Floating Constants.
2998 case '0': case '1': case '2': case '3': case '4':
2999 case '5': case '6': case '7': case '8': case '9':
3000 // Notify MIOpt that we read a non-whitespace/non-comment token.
3001 MIOpt.ReadToken();
3002 return LexNumericConstant(Result, CurPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Douglas Gregor5cee1192011-07-27 05:40:30 +00003004 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
3005 // Notify MIOpt that we read a non-whitespace/non-comment token.
3006 MIOpt.ReadToken();
3007
Richard Smith80ad52f2013-01-02 11:42:31 +00003008 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00003009 Char = getCharAndSize(CurPtr, SizeTmp);
3010
3011 // UTF-16 string literal
3012 if (Char == '"')
3013 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3014 tok::utf16_string_literal);
3015
3016 // UTF-16 character constant
3017 if (Char == '\'')
3018 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3019 tok::utf16_char_constant);
3020
Craig Topper2fa4e862011-08-11 04:06:15 +00003021 // UTF-16 raw string literal
3022 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3023 return LexRawStringLiteral(Result,
3024 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3025 SizeTmp2, Result),
3026 tok::utf16_string_literal);
3027
3028 if (Char == '8') {
3029 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3030
3031 // UTF-8 string literal
3032 if (Char2 == '"')
3033 return LexStringLiteral(Result,
3034 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3035 SizeTmp2, Result),
3036 tok::utf8_string_literal);
3037
3038 if (Char2 == 'R') {
3039 unsigned SizeTmp3;
3040 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3041 // UTF-8 raw string literal
3042 if (Char3 == '"') {
3043 return LexRawStringLiteral(Result,
3044 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3045 SizeTmp2, Result),
3046 SizeTmp3, Result),
3047 tok::utf8_string_literal);
3048 }
3049 }
3050 }
Douglas Gregor5cee1192011-07-27 05:40:30 +00003051 }
3052
3053 // treat u like the start of an identifier.
3054 return LexIdentifier(Result, CurPtr);
3055
3056 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
3057 // Notify MIOpt that we read a non-whitespace/non-comment token.
3058 MIOpt.ReadToken();
3059
Richard Smith80ad52f2013-01-02 11:42:31 +00003060 if (LangOpts.CPlusPlus11) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00003061 Char = getCharAndSize(CurPtr, SizeTmp);
3062
3063 // UTF-32 string literal
3064 if (Char == '"')
3065 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3066 tok::utf32_string_literal);
3067
3068 // UTF-32 character constant
3069 if (Char == '\'')
3070 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3071 tok::utf32_char_constant);
Craig Topper2fa4e862011-08-11 04:06:15 +00003072
3073 // UTF-32 raw string literal
3074 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3075 return LexRawStringLiteral(Result,
3076 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3077 SizeTmp2, Result),
3078 tok::utf32_string_literal);
Douglas Gregor5cee1192011-07-27 05:40:30 +00003079 }
3080
3081 // treat U like the start of an identifier.
3082 return LexIdentifier(Result, CurPtr);
3083
Craig Topper2fa4e862011-08-11 04:06:15 +00003084 case 'R': // Identifier or C++0x raw string literal
3085 // Notify MIOpt that we read a non-whitespace/non-comment token.
3086 MIOpt.ReadToken();
3087
Richard Smith80ad52f2013-01-02 11:42:31 +00003088 if (LangOpts.CPlusPlus11) {
Craig Topper2fa4e862011-08-11 04:06:15 +00003089 Char = getCharAndSize(CurPtr, SizeTmp);
3090
3091 if (Char == '"')
3092 return LexRawStringLiteral(Result,
3093 ConsumeChar(CurPtr, SizeTmp, Result),
3094 tok::string_literal);
3095 }
3096
3097 // treat R like the start of an identifier.
3098 return LexIdentifier(Result, CurPtr);
3099
Chris Lattner3a570772008-01-03 17:58:54 +00003100 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 // Notify MIOpt that we read a non-whitespace/non-comment token.
3102 MIOpt.ReadToken();
3103 Char = getCharAndSize(CurPtr, SizeTmp);
3104
3105 // Wide string literal.
3106 if (Char == '"')
3107 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003108 tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003109
Craig Topper2fa4e862011-08-11 04:06:15 +00003110 // Wide raw string literal.
Richard Smith80ad52f2013-01-02 11:42:31 +00003111 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper2fa4e862011-08-11 04:06:15 +00003112 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3113 return LexRawStringLiteral(Result,
3114 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3115 SizeTmp2, Result),
3116 tok::wide_string_literal);
3117
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 // Wide character constant.
3119 if (Char == '\'')
Douglas Gregor5cee1192011-07-27 05:40:30 +00003120 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3121 tok::wide_char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00003122 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Reid Spencer5f016e22007-07-11 17:01:13 +00003124 // C99 6.4.2: Identifiers.
3125 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3126 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper2fa4e862011-08-11 04:06:15 +00003127 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00003128 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3129 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3130 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregor5cee1192011-07-27 05:40:30 +00003131 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Reid Spencer5f016e22007-07-11 17:01:13 +00003132 case 'v': case 'w': case 'x': case 'y': case 'z':
3133 case '_':
3134 // Notify MIOpt that we read a non-whitespace/non-comment token.
3135 MIOpt.ReadToken();
3136 return LexIdentifier(Result, CurPtr);
Chris Lattner3a570772008-01-03 17:58:54 +00003137
3138 case '$': // $ in identifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00003139 if (LangOpts.DollarIdents) {
Chris Lattner74d15df2008-11-22 02:02:22 +00003140 if (!isLexingRawMode())
3141 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner3a570772008-01-03 17:58:54 +00003142 // Notify MIOpt that we read a non-whitespace/non-comment token.
3143 MIOpt.ReadToken();
3144 return LexIdentifier(Result, CurPtr);
3145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Chris Lattner9e6293d2008-10-12 04:51:35 +00003147 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003148 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 // C99 6.4.4: Character Constants.
3151 case '\'':
3152 // Notify MIOpt that we read a non-whitespace/non-comment token.
3153 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003154 return LexCharConstant(Result, CurPtr, tok::char_constant);
Reid Spencer5f016e22007-07-11 17:01:13 +00003155
3156 // C99 6.4.5: String Literals.
3157 case '"':
3158 // Notify MIOpt that we read a non-whitespace/non-comment token.
3159 MIOpt.ReadToken();
Douglas Gregor5cee1192011-07-27 05:40:30 +00003160 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003161
3162 // C99 6.4.6: Punctuators.
3163 case '?':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003164 Kind = tok::question;
Reid Spencer5f016e22007-07-11 17:01:13 +00003165 break;
3166 case '[':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003167 Kind = tok::l_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003168 break;
3169 case ']':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003170 Kind = tok::r_square;
Reid Spencer5f016e22007-07-11 17:01:13 +00003171 break;
3172 case '(':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003173 Kind = tok::l_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003174 break;
3175 case ')':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003176 Kind = tok::r_paren;
Reid Spencer5f016e22007-07-11 17:01:13 +00003177 break;
3178 case '{':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003179 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003180 break;
3181 case '}':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003182 Kind = tok::r_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003183 break;
3184 case '.':
3185 Char = getCharAndSize(CurPtr, SizeTmp);
3186 if (Char >= '0' && Char <= '9') {
3187 // Notify MIOpt that we read a non-whitespace/non-comment token.
3188 MIOpt.ReadToken();
3189
3190 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikie4e4d0842012-03-11 07:00:24 +00003191 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003192 Kind = tok::periodstar;
Reid Spencer5f016e22007-07-11 17:01:13 +00003193 CurPtr += SizeTmp;
3194 } else if (Char == '.' &&
3195 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003196 Kind = tok::ellipsis;
Reid Spencer5f016e22007-07-11 17:01:13 +00003197 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3198 SizeTmp2, Result);
3199 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003200 Kind = tok::period;
Reid Spencer5f016e22007-07-11 17:01:13 +00003201 }
3202 break;
3203 case '&':
3204 Char = getCharAndSize(CurPtr, SizeTmp);
3205 if (Char == '&') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003206 Kind = tok::ampamp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003207 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3208 } else if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003209 Kind = tok::ampequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3211 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003212 Kind = tok::amp;
Reid Spencer5f016e22007-07-11 17:01:13 +00003213 }
3214 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003215 case '*':
Reid Spencer5f016e22007-07-11 17:01:13 +00003216 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003217 Kind = tok::starequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3219 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003220 Kind = tok::star;
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 }
3222 break;
3223 case '+':
3224 Char = getCharAndSize(CurPtr, SizeTmp);
3225 if (Char == '+') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003226 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003227 Kind = tok::plusplus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003229 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003230 Kind = tok::plusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003231 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003232 Kind = tok::plus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003233 }
3234 break;
3235 case '-':
3236 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003237 if (Char == '-') { // --
Reid Spencer5f016e22007-07-11 17:01:13 +00003238 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003239 Kind = tok::minusminus;
David Blaikie4e4d0842012-03-11 07:00:24 +00003240 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattner9e6293d2008-10-12 04:51:35 +00003241 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Reid Spencer5f016e22007-07-11 17:01:13 +00003242 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3243 SizeTmp2, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003244 Kind = tok::arrowstar;
3245 } else if (Char == '>') { // ->
Reid Spencer5f016e22007-07-11 17:01:13 +00003246 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003247 Kind = tok::arrow;
3248 } else if (Char == '=') { // -=
Reid Spencer5f016e22007-07-11 17:01:13 +00003249 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003250 Kind = tok::minusequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003252 Kind = tok::minus;
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 }
3254 break;
3255 case '~':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003256 Kind = tok::tilde;
Reid Spencer5f016e22007-07-11 17:01:13 +00003257 break;
3258 case '!':
3259 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003260 Kind = tok::exclaimequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003261 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3262 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003263 Kind = tok::exclaim;
Reid Spencer5f016e22007-07-11 17:01:13 +00003264 }
3265 break;
3266 case '/':
3267 // 6.4.9: Comments
3268 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weberbb236282012-11-11 07:02:14 +00003269 if (Char == '/') { // Line comment.
3270 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner8402c732009-01-16 22:39:25 +00003271 // want to lex this as a comment. There is one problem with this though,
3272 // that in one particular corner case, this can change the behavior of the
3273 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weberbb236282012-11-11 07:02:14 +00003274 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner8402c732009-01-16 22:39:25 +00003275 // "foo". Check to see if the character after the second slash is a '*'.
3276 // If so, we will lex that as a "/" instead of the start of a comment.
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003277 // However, we never do this in -traditional-cpp mode.
Nico Weberbb236282012-11-11 07:02:14 +00003278 if ((LangOpts.LineComment ||
Daniel Dunbar2ed42282011-03-18 21:23:38 +00003279 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
David Blaikie4e4d0842012-03-11 07:00:24 +00003280 !LangOpts.TraditionalCPP) {
Nico Weberbb236282012-11-11 07:02:14 +00003281 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003282 return; // There is a token to return.
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Chris Lattner8402c732009-01-16 22:39:25 +00003284 // It is common for the tokens immediately after a // comment to be
3285 // whitespace (indentation for the next line). Instead of going through
3286 // the big switch, handle it efficiently now.
3287 goto SkipIgnoredUnits;
3288 }
3289 }
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Chris Lattner8402c732009-01-16 22:39:25 +00003291 if (Char == '*') { // /**/ comment.
Reid Spencer5f016e22007-07-11 17:01:13 +00003292 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner046c2272010-01-18 22:35:47 +00003293 return; // There is a token to return.
Chris Lattner2d381892008-10-12 04:15:42 +00003294 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner8402c732009-01-16 22:39:25 +00003295 }
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Chris Lattner8402c732009-01-16 22:39:25 +00003297 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003299 Kind = tok::slashequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003300 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003301 Kind = tok::slash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003302 }
3303 break;
3304 case '%':
3305 Char = getCharAndSize(CurPtr, SizeTmp);
3306 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003307 Kind = tok::percentequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003308 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003309 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003310 Kind = tok::r_brace; // '%>' -> '}'
Reid Spencer5f016e22007-07-11 17:01:13 +00003311 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003312 } else if (LangOpts.Digraphs && Char == ':') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003313 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3314 Char = getCharAndSize(CurPtr, SizeTmp);
3315 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003316 Kind = tok::hashhash; // '%:%:' -> '##'
Reid Spencer5f016e22007-07-11 17:01:13 +00003317 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3318 SizeTmp2, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003319 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Reid Spencer5f016e22007-07-11 17:01:13 +00003320 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner74d15df2008-11-22 02:02:22 +00003321 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003322 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003323 Kind = tok::hashat;
Chris Lattnere91e9322009-03-18 20:58:27 +00003324 } else { // '%:' -> '#'
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 // We parsed a # character. If this occurs at the start of the line,
3326 // it's actually the start of a preprocessing directive. Callback to
3327 // the preprocessor to handle it.
3328 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003329 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3330 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Chris Lattnere91e9322009-03-18 20:58:27 +00003332 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003333 }
3334 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003335 Kind = tok::percent;
Reid Spencer5f016e22007-07-11 17:01:13 +00003336 }
3337 break;
3338 case '<':
3339 Char = getCharAndSize(CurPtr, SizeTmp);
3340 if (ParsingFilename) {
Chris Lattner9cb51ce2009-04-17 23:56:52 +00003341 return LexAngledStringLiteral(Result, CurPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 } else if (Char == '<') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003343 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3344 if (After == '=') {
3345 Kind = tok::lesslessequal;
3346 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3347 SizeTmp2, Result);
3348 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3349 // If this is actually a '<<<<<<<' version control conflict marker,
3350 // recognize it as such and recover nicely.
3351 goto LexNextToken;
Richard Smithd5e1d602011-10-12 00:37:51 +00003352 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3353 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3354 // ignore it.
3355 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003356 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003357 Kind = tok::lesslessless;
3358 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3359 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003360 } else {
3361 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3362 Kind = tok::lessless;
3363 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003364 } else if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003365 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003366 Kind = tok::lessequal;
David Blaikie4e4d0842012-03-11 07:00:24 +00003367 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith80ad52f2013-01-02 11:42:31 +00003368 if (LangOpts.CPlusPlus11 &&
Richard Smith87a1e192011-04-14 18:36:27 +00003369 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3370 // C++0x [lex.pptoken]p3:
3371 // Otherwise, if the next three characters are <:: and the subsequent
3372 // character is neither : nor >, the < is treated as a preprocessor
3373 // token by itself and not as the first character of the alternative
3374 // token <:.
3375 unsigned SizeTmp3;
3376 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3377 if (After != ':' && After != '>') {
3378 Kind = tok::less;
Richard Smith661a9962011-10-15 01:18:56 +00003379 if (!isLexingRawMode())
3380 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smith87a1e192011-04-14 18:36:27 +00003381 break;
3382 }
3383 }
3384
Reid Spencer5f016e22007-07-11 17:01:13 +00003385 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003386 Kind = tok::l_square;
David Blaikie4e4d0842012-03-11 07:00:24 +00003387 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Reid Spencer5f016e22007-07-11 17:01:13 +00003388 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003389 Kind = tok::l_brace;
Reid Spencer5f016e22007-07-11 17:01:13 +00003390 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003391 Kind = tok::less;
Reid Spencer5f016e22007-07-11 17:01:13 +00003392 }
3393 break;
3394 case '>':
3395 Char = getCharAndSize(CurPtr, SizeTmp);
3396 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003397 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003398 Kind = tok::greaterequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003399 } else if (Char == '>') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003400 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3401 if (After == '=') {
3402 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3403 SizeTmp2, Result);
3404 Kind = tok::greatergreaterequal;
Richard Smithd5e1d602011-10-12 00:37:51 +00003405 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3406 // If this is actually a '>>>>' conflict marker, recognize it as such
3407 // and recover nicely.
3408 goto LexNextToken;
Chris Lattner34f349d2009-12-14 06:16:57 +00003409 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3410 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3411 goto LexNextToken;
David Blaikie4e4d0842012-03-11 07:00:24 +00003412 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbourne1b791d62011-02-09 21:08:21 +00003413 Kind = tok::greatergreatergreater;
3414 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3415 SizeTmp2, Result);
Chris Lattner34f349d2009-12-14 06:16:57 +00003416 } else {
3417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3418 Kind = tok::greatergreater;
3419 }
3420
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003422 Kind = tok::greater;
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 }
3424 break;
3425 case '^':
3426 Char = getCharAndSize(CurPtr, SizeTmp);
3427 if (Char == '=') {
Reid Spencer5f016e22007-07-11 17:01:13 +00003428 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner9e6293d2008-10-12 04:51:35 +00003429 Kind = tok::caretequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003431 Kind = tok::caret;
Reid Spencer5f016e22007-07-11 17:01:13 +00003432 }
3433 break;
3434 case '|':
3435 Char = getCharAndSize(CurPtr, SizeTmp);
3436 if (Char == '=') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003437 Kind = tok::pipeequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003438 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3439 } else if (Char == '|') {
Chris Lattner34f349d2009-12-14 06:16:57 +00003440 // If this is '|||||||' and we're in a conflict marker, ignore it.
3441 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3442 goto LexNextToken;
Chris Lattner9e6293d2008-10-12 04:51:35 +00003443 Kind = tok::pipepipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003444 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3445 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003446 Kind = tok::pipe;
Reid Spencer5f016e22007-07-11 17:01:13 +00003447 }
3448 break;
3449 case ':':
3450 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikie4e4d0842012-03-11 07:00:24 +00003451 if (LangOpts.Digraphs && Char == '>') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003452 Kind = tok::r_square; // ':>' -> ']'
Reid Spencer5f016e22007-07-11 17:01:13 +00003453 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003454 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003455 Kind = tok::coloncolon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003457 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003458 Kind = tok::colon;
Reid Spencer5f016e22007-07-11 17:01:13 +00003459 }
3460 break;
3461 case ';':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003462 Kind = tok::semi;
Reid Spencer5f016e22007-07-11 17:01:13 +00003463 break;
3464 case '=':
3465 Char = getCharAndSize(CurPtr, SizeTmp);
3466 if (Char == '=') {
Richard Smithd5e1d602011-10-12 00:37:51 +00003467 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner34f349d2009-12-14 06:16:57 +00003468 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3469 goto LexNextToken;
3470
Chris Lattner9e6293d2008-10-12 04:51:35 +00003471 Kind = tok::equalequal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003473 } else {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003474 Kind = tok::equal;
Reid Spencer5f016e22007-07-11 17:01:13 +00003475 }
3476 break;
3477 case ',':
Chris Lattner9e6293d2008-10-12 04:51:35 +00003478 Kind = tok::comma;
Reid Spencer5f016e22007-07-11 17:01:13 +00003479 break;
3480 case '#':
3481 Char = getCharAndSize(CurPtr, SizeTmp);
3482 if (Char == '#') {
Chris Lattner9e6293d2008-10-12 04:51:35 +00003483 Kind = tok::hashhash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikie4e4d0842012-03-11 07:00:24 +00003485 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattner9e6293d2008-10-12 04:51:35 +00003486 Kind = tok::hashat;
Chris Lattner74d15df2008-11-22 02:02:22 +00003487 if (!isLexingRawMode())
Ted Kremenek66d5ce12011-10-17 21:47:53 +00003488 Diag(BufferPtr, diag::ext_charize_microsoft);
Reid Spencer5f016e22007-07-11 17:01:13 +00003489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3490 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +00003491 // We parsed a # character. If this occurs at the start of the line,
3492 // it's actually the start of a preprocessing directive. Callback to
3493 // the preprocessor to handle it.
3494 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003495 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3496 goto HandleDirective;
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Chris Lattnere91e9322009-03-18 20:58:27 +00003498 Kind = tok::hash;
Reid Spencer5f016e22007-07-11 17:01:13 +00003499 }
3500 break;
3501
Chris Lattner3a570772008-01-03 17:58:54 +00003502 case '@':
3503 // Objective C support.
David Blaikie4e4d0842012-03-11 07:00:24 +00003504 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattner9e6293d2008-10-12 04:51:35 +00003505 Kind = tok::at;
Chris Lattner3a570772008-01-03 17:58:54 +00003506 else
Chris Lattner9e6293d2008-10-12 04:51:35 +00003507 Kind = tok::unknown;
Chris Lattner3a570772008-01-03 17:58:54 +00003508 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Jordan Rosec7629d92013-01-24 20:50:46 +00003510 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Reid Spencer5f016e22007-07-11 17:01:13 +00003511 case '\\':
Jordan Rosec7629d92013-01-24 20:50:46 +00003512 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3513 return LexUnicode(Result, CodePoint, CurPtr);
3514
Chris Lattner9e6293d2008-10-12 04:51:35 +00003515 Kind = tok::unknown;
Reid Spencer5f016e22007-07-11 17:01:13 +00003516 break;
Jordan Rosec7629d92013-01-24 20:50:46 +00003517
3518 default: {
3519 if (isASCII(Char)) {
3520 Kind = tok::unknown;
3521 break;
3522 }
3523
3524 UTF32 CodePoint;
3525
3526 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3527 // an escaped newline.
3528 --CurPtr;
3529 ConversionResult Status = convertUTF8Sequence((const UTF8 **)&CurPtr,
3530 (const UTF8 *)BufferEnd,
3531 &CodePoint,
3532 strictConversion);
3533 if (Status == conversionOK)
3534 return LexUnicode(Result, CodePoint, CurPtr);
3535
3536 // Non-ASCII characters tend to creep into source code unintentionally.
3537 // Instead of letting the parser complain about the unknown token,
3538 // just warn that we don't have valid UTF-8, then drop the character.
3539 if (!isLexingRawMode())
3540 Diag(CurPtr, diag::err_invalid_utf8);
3541
3542 BufferPtr = CurPtr+1;
3543 goto LexNextToken;
3544 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Reid Spencer5f016e22007-07-11 17:01:13 +00003547 // Notify MIOpt that we read a non-whitespace/non-comment token.
3548 MIOpt.ReadToken();
3549
3550 // Update the location of token as well as BufferPtr.
Chris Lattner9e6293d2008-10-12 04:51:35 +00003551 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis3185d4a2012-11-13 01:02:40 +00003552 return;
3553
3554HandleDirective:
3555 // We parsed a # character and it's the start of a preprocessing directive.
3556
3557 FormTokenWithChars(Result, CurPtr, tok::hash);
3558 PP->HandleDirective(Result);
3559
3560 // As an optimization, if the preprocessor didn't switch lexers, tail
3561 // recurse.
3562 if (PP->isCurrentLexer(this)) {
3563 // Start a new token. If this is a #include or something, the PP may
3564 // want us starting at the beginning of the line again. If so, set
3565 // the StartOfLine flag and clear LeadingSpace.
3566 if (IsAtStartOfLine) {
3567 Result.setFlag(Token::StartOfLine);
3568 Result.clearFlag(Token::LeadingSpace);
3569 IsAtStartOfLine = false;
3570 }
3571 goto LexNextToken; // GCC isn't tail call eliminating.
3572 }
3573 return PP->Lex(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003574}