blob: dc911ef91b6caeb731cad8ddeb1f2a5ae9b27f15 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000013
14#include "clang/Lex/Lexer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "UnicodeCharSets.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000016#include "clang/Basic/CharInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000018#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/LexDiagnostic.h"
Richard Smith2a988622013-09-24 04:06:10 +000020#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000022#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000024#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000025#include "llvm/Support/ConvertUTF.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000027#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000028#include "llvm/Support/UnicodeCharRanges.h"
29#include <algorithm>
30#include <cassert>
31#include <cstddef>
32#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000033#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include <string>
35#include <tuple>
36#include <utility>
37
Chris Lattner22eb9722006-06-18 05:43:12 +000038using namespace clang;
39
Chris Lattner4894f482007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump11289f42009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000046 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
48 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000049}
50
51/// getObjCKeywordID - Return the ObjC keyword kind.
52tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
55}
56
57//===----------------------------------------------------------------------===//
58// Lexer Class Implementation
59//===----------------------------------------------------------------------===//
60
David Blaikie68e081d2011-12-20 02:48:34 +000061void Lexer::anchor() { }
62
Mike Stump11289f42009-09-09 15:08:12 +000063void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000064 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000065 BufferStart = BufStart;
66 BufferPtr = BufPtr;
67 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000068
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 assert(BufEnd[0] == 0 &&
70 "We assume that the input buffer has a null character at the end"
71 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000072
Eric Christopher7f36a792011-04-09 00:01:04 +000073 // Check whether we have a BOM in the beginning of the buffer. If yes - act
74 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
75 // skip the UTF-8 BOM if it's present.
76 if (BufferStart == BufferPtr) {
77 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000078 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000079 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000080 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
81 .Default(0);
82
83 // Skip the BOM.
84 BufferPtr += BOMLength;
85 }
86
Chris Lattnerf76b9202009-01-17 06:55:17 +000087 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000088 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000089
Chris Lattnerf76b9202009-01-17 06:55:17 +000090 // Start of the file is a start of line.
91 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000092 IsAtPhysicalStartOfLine = true;
93
94 HasLeadingSpace = false;
95 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +000096
Chris Lattnerf76b9202009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000099
Chris Lattnerf76b9202009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattnerf76b9202009-01-17 06:55:17 +0000103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerf76b9202009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner5965a282009-01-17 07:56:59 +0000113/// Lexer constructor - Create a new lexer object for the specified buffer
114/// with the specified preprocessor managing the lexing process. This lexer
115/// assumes that the associated file buffer and Preprocessor objects will
116/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000121
Chris Lattner5965a282009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000124
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000125 resetExtendedTokenMode();
126}
127
128void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
132 else
133 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000134}
Chris Lattner4894f482007-10-07 08:47:24 +0000135
Chris Lattner02b436a2007-10-17 20:41:00 +0000136/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000137/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000138/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000139Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000140 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000141 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000142
Chris Lattnerf76b9202009-01-17 06:55:17 +0000143 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattner02b436a2007-10-17 20:41:00 +0000145 // We *are* in raw mode.
146 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000147}
148
Chris Lattner08354fe2009-01-17 07:35:14 +0000149/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000150/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000151/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000152Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000153 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000154 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
155 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000156
Chris Lattner757169b2009-01-17 08:27:52 +0000157/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
158/// _Pragma expansion. This has a variety of magic semantics that this method
159/// sets up. It returns a new'd Lexer that must be delete'd when done.
160///
161/// On entrance to this routine, TokStartLoc is a macro location which has a
162/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000163/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000164/// "expanded from".
165///
Alp Toker7755aff2014-05-18 18:37:59 +0000166/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000167/// normal lexer that remaps tokens as they fly by. This would require making
168/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
169/// interface that could handle this stuff. This would pull GetMappedTokenLoc
170/// out of the critical path of the lexer!
171///
Mike Stump11289f42009-09-09 15:08:12 +0000172Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000173 SourceLocation ExpansionLocStart,
174 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000175 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000176 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000177
178 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000179 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000180 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
181 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner757169b2009-01-17 08:27:52 +0000183 // Now that the lexer is created, change the start/end locations so that we
184 // just lex the subsection of the file that we want. This is lexing from a
185 // scratch buffer.
186 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner757169b2009-01-17 08:27:52 +0000188 L->BufferPtr = StrData;
189 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000190 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000191
192 // Set the SourceLocation with the remapping information. This ensures that
193 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000194 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
195 ExpansionLocStart,
196 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner757169b2009-01-17 08:27:52 +0000198 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000199 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000200 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattner757169b2009-01-17 08:27:52 +0000202 // This lexer really is for _Pragma.
203 L->Is_PragmaLexer = true;
204 return L;
205}
206
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000207/// Stringify - Convert the specified string into a C string, with surrounding
208/// ""'s, and with escaped \ and " characters.
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000209std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000210 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000211 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000213 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000214 Result.insert(Result.begin()+i, '\\');
215 ++i; ++e;
216 }
217 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000218 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000219}
220
Chris Lattner4c4a2452007-07-24 06:57:14 +0000221/// Stringify - Convert the specified string into a C string by escaping '\'
222/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000223void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
230}
231
Chris Lattner39720112010-11-17 07:26:20 +0000232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
Richard Smith9a67f472012-11-28 07:29:00 +0000236/// \brief Slow case of getSpelling. Extract the characters comprising the
237/// spelling of this token from the provided input buffer.
238static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
241
242 size_t Length = 0;
243 const char *BufEnd = BufPtr + Tok.getLength();
244
Craig Toppera6324c92015-10-22 15:35:21 +0000245 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
248 unsigned Size;
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
250 BufPtr += Size;
251
252 if (Spelling[Length - 1] == '"')
253 break;
254 }
255
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
258 // r-char-sequence.
259 if (Length >= 2 &&
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
262 // quote.
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
266
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
269 Length += RawLength;
270 BufPtr += RawLength;
271
272 // The rest of the token is lexed normally.
273 }
274 }
275
276 while (BufPtr < BufEnd) {
277 unsigned Size;
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
279 BufPtr += Size;
280 }
281
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
284 return Length;
285}
286
Chris Lattner39720112010-11-17 07:26:20 +0000287/// getSpelling() - Return the 'spelling' of this token. The spelling of a
288/// token are the characters used to represent the token in the source file
289/// after trigraph expansion and escaped-newline folding. In particular, this
290/// wants to get the true, uncanonicalized, spelling of things like digraphs
291/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000292StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
296 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000303 if (invalidTemp) {
304 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000306 }
307
308 const char *tokenBegin = file.data() + locInfo.second;
309
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
313 Token token;
314 lexer.LexFromRawLexer(token);
315
316 unsigned length = token.getLength();
317
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000320 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000321
Richard Smith9a67f472012-11-28 07:29:00 +0000322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000326}
327
328/// getSpelling() - Return the 'spelling' of this token. The spelling of a
329/// token are the characters used to represent the token in the source file
330/// after trigraph expansion and escaped-newline folding. In particular, this
331/// wants to get the true, uncanonicalized, spelling of things like digraphs
332/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000333std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000334 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000336
Chris Lattner39720112010-11-17 07:26:20 +0000337 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000339 &CharDataInvalid);
340 if (Invalid)
341 *Invalid = CharDataInvalid;
342 if (CharDataInvalid)
343 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000344
345 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000346 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000347 return std::string(TokStart, TokStart + Tok.getLength());
348
Chris Lattner39720112010-11-17 07:26:20 +0000349 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000352 return Result;
353}
354
355/// getSpelling - This method is used to get the spelling of a token into a
356/// preallocated buffer, instead of as an std::string. The caller is required
357/// to allocate enough space for the token, which is guaranteed to be at least
358/// Tok.getLength() bytes long. The actual length of the token is returned.
359///
360/// Note that this method may do two possible things: it may either fill in
361/// the buffer specified with characters, or it may *change the input pointer*
362/// to point to a constant buffer with the data already in it (avoiding a
363/// copy). The caller is not allowed to modify the returned buffer pointer
364/// if an internal buffer is returned.
365unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000367 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000369
Craig Topperd2d442c2014-05-17 23:10:59 +0000370 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000373 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000374 else if (!Tok.hasUCN()) {
375 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
376 // Just return the string from the identifier table, which is very quick.
377 Buffer = II->getNameStart();
378 return II->getLength();
379 }
Chris Lattner39720112010-11-17 07:26:20 +0000380 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000381
382 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000383 if (Tok.isLiteral())
384 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000385
Craig Topperd2d442c2014-05-17 23:10:59 +0000386 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000387 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000388 bool CharDataInvalid = false;
389 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
390 if (Invalid)
391 *Invalid = CharDataInvalid;
392 if (CharDataInvalid) {
393 Buffer = "";
394 return 0;
395 }
396 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000397
Chris Lattner39720112010-11-17 07:26:20 +0000398 // If this token contains nothing interesting, return it directly.
399 if (!Tok.needsCleaning()) {
400 Buffer = TokStart;
401 return Tok.getLength();
402 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000403
Chris Lattner39720112010-11-17 07:26:20 +0000404 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000405 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000406}
407
Chris Lattner8e129c22007-10-17 21:18:47 +0000408/// MeasureTokenLength - Relex the token at the specified location and return
409/// its length in bytes in the input file. If the token needs cleaning (e.g.
410/// includes a trigraph or an escaped newline) then this count includes bytes
411/// that are part of that.
412unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000413 const SourceManager &SM,
414 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000415 Token TheTok;
416 if (getRawToken(Loc, TheTok, SM, LangOpts))
417 return 0;
418 return TheTok.getLength();
419}
420
421/// \brief Relex the token at the specified location.
422/// \returns true if there was a failure, false on success.
423bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000425 const LangOptions &LangOpts,
426 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000429 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
431 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000432
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000435 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000437 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000439 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000440 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000441
442 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000443
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000445 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000446
Chris Lattner8e129c22007-10-17 21:18:47 +0000447 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000450 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000451 TheLexer.LexFromRawLexer(Result);
452 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000453}
454
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000455static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
456 const SourceManager &SM,
457 const LangOptions &LangOpts) {
458 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000460 if (LocInfo.first.isInvalid())
461 return Loc;
462
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000463 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000465 if (Invalid)
466 return Loc;
467
468 // Back up from the current location until we hit the beginning of a line
469 // (or the buffer). We'll relex from that point.
470 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000471 if (LocInfo.second >= Buffer.size())
472 return Loc;
473
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000474 const char *StrData = BufStart+LocInfo.second;
475 if (StrData[0] == '\n' || StrData[0] == '\r')
476 return Loc;
477
478 const char *LexStart = StrData;
479 while (LexStart != BufStart) {
480 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
481 ++LexStart;
482 break;
483 }
484
485 --LexStart;
486 }
487
488 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000489 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000490 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
491 TheLexer.SetCommentRetentionState(true);
492
493 // Lex tokens until we find the token that contains the source location.
494 Token TheTok;
495 do {
496 TheLexer.LexFromRawLexer(TheTok);
497
498 if (TheLexer.getBufferLocation() > StrData) {
499 // Lexing this token has taken the lexer past the source location we're
500 // looking for. If the current token encompasses our source location,
501 // return the beginning of that token.
502 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
503 return TheTok.getLocation();
504
505 // We ended up skipping over the source location entirely, which means
506 // that it points into whitespace. We're done here.
507 break;
508 }
509 } while (TheTok.getKind() != tok::eof);
510
511 // We've passed our source location; just return the original source location.
512 return Loc;
513}
514
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000515SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
516 const SourceManager &SM,
517 const LangOptions &LangOpts) {
518 if (Loc.isFileID())
519 return getBeginningOfFileToken(Loc, SM, LangOpts);
520
521 if (!SM.isMacroArgExpansion(Loc))
522 return Loc;
523
524 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
525 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
526 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000527 std::pair<FileID, unsigned> BeginFileLocInfo
528 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000529 assert(FileLocInfo.first == BeginFileLocInfo.first &&
530 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000531 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000532}
533
Douglas Gregoraf82e352010-07-20 20:18:03 +0000534namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000535
Douglas Gregoraf82e352010-07-20 20:18:03 +0000536 enum PreambleDirectiveKind {
537 PDK_Skipped,
538 PDK_StartIf,
539 PDK_EndIf,
540 PDK_Unknown
541 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000542
543} // end anonymous namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000544
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000545std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000546 const LangOptions &LangOpts,
547 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000548 // Create a lexer starting at the beginning of the file. Note that we use a
549 // "fake" file source location at offset 1 so that the lexer will track our
550 // position within the file.
551 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000552 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000553 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
554 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000555 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000556
557 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
558 SourceLocation StartLoc = TheLexer.getSourceLocation();
559
Douglas Gregoraf82e352010-07-20 20:18:03 +0000560 bool InPreprocessorDirective = false;
561 Token TheTok;
562 Token IfStartTok;
563 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000564 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000565
566 unsigned MaxLineOffset = 0;
567 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000568 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000569 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000570 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000571 char ch = *CurPtr++;
572 if (ch == '\n') {
573 ++CurLine;
574 if (CurLine == MaxLines)
575 break;
576 }
577 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000578 if (CurPtr != Buffer.end())
579 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000580 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000581
Douglas Gregoraf82e352010-07-20 20:18:03 +0000582 do {
583 TheLexer.LexFromRawLexer(TheTok);
584
585 if (InPreprocessorDirective) {
586 // If we've hit the end of the file, we're done.
587 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000588 break;
589 }
590
591 // If we haven't hit the end of the preprocessor directive, skip this
592 // token.
593 if (!TheTok.isAtStartOfLine())
594 continue;
595
596 // We've passed the end of the preprocessor directive, and will look
597 // at this token again below.
598 InPreprocessorDirective = false;
599 }
600
Douglas Gregor028d3e42010-08-09 20:45:32 +0000601 // Keep track of the # of lines in the preamble.
602 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000603 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000604
605 // If we were asked to limit the number of lines in the preamble,
606 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000607 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000608 break;
609 }
610
Douglas Gregoraf82e352010-07-20 20:18:03 +0000611 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000612 if (TheTok.getKind() == tok::comment) {
613 if (ActiveCommentLoc.isInvalid())
614 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000616 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000617
618 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
619 // This is the start of a preprocessor directive.
620 Token HashTok = TheTok;
621 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000622 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000623
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000624 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000625 // we don't have an identifier table available. Instead, just look at
626 // the raw identifier to recognize and categorize preprocessor directives.
627 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000628 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000629 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000630 PreambleDirectiveKind PDK
631 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
632 .Case("include", PDK_Skipped)
633 .Case("__include_macros", PDK_Skipped)
634 .Case("define", PDK_Skipped)
635 .Case("undef", PDK_Skipped)
636 .Case("line", PDK_Skipped)
637 .Case("error", PDK_Skipped)
638 .Case("pragma", PDK_Skipped)
639 .Case("import", PDK_Skipped)
640 .Case("include_next", PDK_Skipped)
641 .Case("warning", PDK_Skipped)
642 .Case("ident", PDK_Skipped)
643 .Case("sccs", PDK_Skipped)
644 .Case("assert", PDK_Skipped)
645 .Case("unassert", PDK_Skipped)
646 .Case("if", PDK_StartIf)
647 .Case("ifdef", PDK_StartIf)
648 .Case("ifndef", PDK_StartIf)
649 .Case("elif", PDK_Skipped)
650 .Case("else", PDK_Skipped)
651 .Case("endif", PDK_EndIf)
652 .Default(PDK_Unknown);
653
654 switch (PDK) {
655 case PDK_Skipped:
656 continue;
657
658 case PDK_StartIf:
659 if (IfCount == 0)
660 IfStartTok = HashTok;
661
662 ++IfCount;
663 continue;
664
665 case PDK_EndIf:
666 // Mismatched #endif. The preamble ends here.
667 if (IfCount == 0)
668 break;
669
670 --IfCount;
671 continue;
672
673 case PDK_Unknown:
674 // We don't know what this directive is; stop at the '#'.
675 break;
676 }
677 }
678
679 // We only end up here if we didn't recognize the preprocessor
680 // directive or it was one that can't occur in the preamble at this
681 // point. Roll back the current token to the location of the '#'.
682 InPreprocessorDirective = false;
683 TheTok = HashTok;
684 }
685
Douglas Gregor028d3e42010-08-09 20:45:32 +0000686 // We hit a token that we don't recognize as being in the
687 // "preprocessing only" part of the file, so we're no longer in
688 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000689 break;
690 } while (true);
691
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000692 SourceLocation End;
693 if (IfCount)
694 End = IfStartTok.getLocation();
695 else if (ActiveCommentLoc.isValid())
696 End = ActiveCommentLoc; // don't truncate a decl comment.
697 else
698 End = TheTok.getLocation();
699
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000700 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
701 IfCount? IfStartTok.isAtStartOfLine()
702 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000703}
704
Chris Lattner2a6ee912010-11-17 07:05:50 +0000705/// AdvanceToTokenCharacter - Given a location that specifies the start of a
706/// token, return a new location that specifies a character within the token.
707SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
708 unsigned CharNo,
709 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000710 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000711 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000712 // character is. This needs to take into consideration newlines and
713 // trigraphs.
714 bool Invalid = false;
715 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
716
717 // If they request the first char of the token, we're trivially done.
718 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
719 return TokStart;
720
721 unsigned PhysOffset = 0;
722
723 // The usual case is that tokens don't contain anything interesting. Skip
724 // over the uninteresting characters. If a token only consists of simple
725 // chars, this method is extremely fast.
726 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
727 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000728 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000729 ++TokPtr;
730 --CharNo;
731 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000732 }
733
734 // If we have a character that may be a trigraph or escaped newline, use a
735 // lexer to parse it correctly.
736 for (; CharNo; --CharNo) {
737 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000738 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000739 TokPtr += Size;
740 PhysOffset += Size;
741 }
742
743 // Final detail: if we end up on an escaped newline, we want to return the
744 // location of the actual byte of the token. For example foo\<newline>bar
745 // advanced by 3 should return the location of b, not of \\. One compounding
746 // detail of this is that the escape may be made by a trigraph.
747 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
748 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
749
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000750 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000751}
752
753/// \brief Computes the source location just past the end of the
754/// token at this source location.
755///
756/// This routine can be used to produce a source location that
757/// points just past the end of the token referenced by \p Loc, and
758/// is generally used when a diagnostic needs to point just after a
759/// token where it expected something different that it received. If
760/// the returned source location would not be meaningful (e.g., if
761/// it points into a macro), this routine returns an invalid
762/// source location.
763///
764/// \param Offset an offset from the end of the token, where the source
765/// location should refer to. The default offset (0) produces a source
766/// location pointing just past the end of the token; an offset of 1 produces
767/// a source location pointing to the last character in the token, etc.
768SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
769 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000770 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000771 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000772 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000773
774 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000775 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000776 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000777 }
778
David Blaikiebbafb8a2012-03-11 07:00:24 +0000779 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000780 if (Len > Offset)
781 Len = Len - Offset;
782 else
783 return Loc;
784
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000785 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000786}
787
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000788/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000789/// token of the macro expansion.
790bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000791 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000792 const LangOptions &LangOpts,
793 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000794 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
795
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000796 SourceLocation expansionLoc;
797 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
798 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000800 if (expansionLoc.isFileID()) {
801 // No other macro expansions, this is the first.
802 if (MacroBegin)
803 *MacroBegin = expansionLoc;
804 return true;
805 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000806
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000807 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000808}
809
810/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000811/// token of the macro expansion.
812bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000813 const SourceManager &SM,
814 const LangOptions &LangOpts,
815 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000816 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
817
818 SourceLocation spellLoc = SM.getSpellingLoc(loc);
819 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
820 if (tokLen == 0)
821 return false;
822
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000823 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
824 SourceLocation expansionLoc;
825 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
826 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000828 if (expansionLoc.isFileID()) {
829 // No other macro expansions.
830 if (MacroEnd)
831 *MacroEnd = expansionLoc;
832 return true;
833 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000834
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000835 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000836}
837
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000838static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000839 const SourceManager &SM,
840 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000841 SourceLocation Begin = Range.getBegin();
842 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000843 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000844 if (Range.isTokenRange()) {
845 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
846 if (End.isInvalid())
847 return CharSourceRange();
848 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000849
850 // Break down the source locations.
851 FileID FID;
852 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000853 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000854 if (FID.isInvalid())
855 return CharSourceRange();
856
857 unsigned EndOffs;
858 if (!SM.isInFileID(End, FID, &EndOffs) ||
859 BeginOffs > EndOffs)
860 return CharSourceRange();
861
862 return CharSourceRange::getCharRange(Begin, End);
863}
864
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000865CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000866 const SourceManager &SM,
867 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000868 SourceLocation Begin = Range.getBegin();
869 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000870 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000871 return CharSourceRange();
872
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000873 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000874 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000875
876 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000877 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
878 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000879 Range.setBegin(Begin);
880 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000882
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000883 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000884 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
885 &End)) ||
886 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
887 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000888 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 Range.setEnd(End);
890 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000891 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000892
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000893 assert(Begin.isMacroID() && End.isMacroID());
894 SourceLocation MacroBegin, MacroEnd;
895 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000896 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
897 &MacroEnd)) ||
898 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
899 &MacroEnd)))) {
900 Range.setBegin(MacroBegin);
901 Range.setEnd(MacroEnd);
902 return makeRangeFromFileLocs(Range, SM, LangOpts);
903 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000904
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000905 bool Invalid = false;
906 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
907 &Invalid);
908 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000909 return CharSourceRange();
910
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000911 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
912 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
913 &Invalid);
914 if (Invalid)
915 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000916
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000917 if (EndEntry.getExpansion().isMacroArgExpansion() &&
918 BeginEntry.getExpansion().getExpansionLocStart() ==
919 EndEntry.getExpansion().getExpansionLocStart()) {
920 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
921 Range.setEnd(SM.getImmediateSpellingLoc(End));
922 return makeFileCharRange(Range, SM, LangOpts);
923 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000924 }
925
926 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000927}
928
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000929StringRef Lexer::getSourceText(CharSourceRange Range,
930 const SourceManager &SM,
931 const LangOptions &LangOpts,
932 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000933 Range = makeFileCharRange(Range, SM, LangOpts);
934 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000935 if (Invalid) *Invalid = true;
936 return StringRef();
937 }
938
939 // Break down the source location.
940 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
941 if (beginInfo.first.isInvalid()) {
942 if (Invalid) *Invalid = true;
943 return StringRef();
944 }
945
946 unsigned EndOffs;
947 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
948 beginInfo.second > EndOffs) {
949 if (Invalid) *Invalid = true;
950 return StringRef();
951 }
952
953 // Try to the load the file buffer.
954 bool invalidTemp = false;
955 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
956 if (invalidTemp) {
957 if (Invalid) *Invalid = true;
958 return StringRef();
959 }
960
961 if (Invalid) *Invalid = false;
962 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
963}
964
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000965StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
966 const SourceManager &SM,
967 const LangOptions &LangOpts) {
968 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000969
970 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000971 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000972 FileID FID = SM.getFileID(Loc);
973 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
974 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
975 Loc = Expansion.getExpansionLocStart();
976 if (!Expansion.isMacroArgExpansion())
977 break;
978
979 // For macro arguments we need to check that the argument did not come
980 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
981
982 // Loc points to the argument id of the macro definition, move to the
983 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000984 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000985 SourceLocation SpellLoc = Expansion.getSpellingLoc();
986 if (SpellLoc.isFileID())
987 break; // No inner macro.
988
989 // If spelling location resides in the same FileID as macro expansion
990 // location, it means there is no inner macro.
991 FileID MacroFID = SM.getFileID(Loc);
992 if (SM.isInFileID(SpellLoc, MacroFID))
993 break;
994
995 // Argument came from inner macro.
996 Loc = SpellLoc;
997 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000998
999 // Find the spelling location of the start of the non-argument expansion
1000 // range. This is where the macro name was spelled in order to begin
1001 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001002 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001003
1004 // Dig out the buffer where the macro name was spelled and the extents of the
1005 // name so that we can render it into the expansion note.
1006 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1007 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1008 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1009 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1010}
1011
Richard Trieu3a5c9582016-01-26 02:51:55 +00001012StringRef Lexer::getImmediateMacroNameForDiagnostics(
1013 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1014 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1015 // Walk past macro argument expanions.
1016 while (SM.isMacroArgExpansion(Loc))
1017 Loc = SM.getImmediateExpansionRange(Loc).first;
1018
1019 // If the macro's spelling has no FileID, then it's actually a token paste
1020 // or stringization (or similar) and not a macro at all.
1021 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1022 return StringRef();
1023
1024 // Find the spelling location of the start of the non-argument expansion
1025 // range. This is where the macro name was spelled in order to begin
1026 // expanding this macro.
1027 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1028
1029 // Dig out the buffer where the macro name was spelled and the extents of the
1030 // name so that we can render it into the expansion note.
1031 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1032 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1033 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1034 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1035}
1036
Jordan Rose288c4212012-06-07 01:10:31 +00001037bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001038 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001039}
1040
Chris Lattner22eb9722006-06-18 05:43:12 +00001041//===----------------------------------------------------------------------===//
1042// Diagnostics forwarding code.
1043//===----------------------------------------------------------------------===//
1044
Chris Lattner619c1742007-07-22 18:38:25 +00001045/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001046/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001047/// This is currently only used for _Pragma implementation, so it is the slow
1048/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001049static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1050 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001051static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1052 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001053 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001054 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001055
Chris Lattner619c1742007-07-22 18:38:25 +00001056 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001057 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001058 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001059 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001061 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001062 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001063 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001064 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Chris Lattner9dc9c202009-02-15 20:52:18 +00001066 // Figure out the expansion loc range, which is the range covered by the
1067 // original _Pragma(...) sequence.
1068 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001069 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chandler Carruth115b0772011-07-26 03:03:05 +00001071 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001072}
1073
Chris Lattner22eb9722006-06-18 05:43:12 +00001074/// getSourceLocation - Return a source location identifier for the specified
1075/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001076SourceLocation Lexer::getSourceLocation(const char *Loc,
1077 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001078 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001079 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001080
1081 // In the normal case, we're just lexing from a simple file buffer, return
1082 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001083 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001084 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001085 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattnerd32480d2009-01-17 06:22:33 +00001087 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1088 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001089 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001090 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001091}
1092
Chris Lattner22eb9722006-06-18 05:43:12 +00001093/// Diag - Forwarding function for diagnostics. This translate a source
1094/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001095DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001096 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001097}
1098
1099//===----------------------------------------------------------------------===//
1100// Trigraph and Escaped Newline Handling Code.
1101//===----------------------------------------------------------------------===//
1102
1103/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1104/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1105static char GetTrigraphCharForLetter(char Letter) {
1106 switch (Letter) {
1107 default: return 0;
1108 case '=': return '#';
1109 case ')': return ']';
1110 case '(': return '[';
1111 case '!': return '|';
1112 case '\'': return '^';
1113 case '>': return '}';
1114 case '/': return '\\';
1115 case '<': return '{';
1116 case '-': return '~';
1117 }
1118}
1119
1120/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1121/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1122/// return the result character. Finally, emit a warning about trigraph use
1123/// whether trigraphs are enabled or not.
1124static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1125 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001126 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001127
David Blaikiebbafb8a2012-03-11 07:00:24 +00001128 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001129 if (!L->isLexingRawMode())
1130 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001131 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattner6d27a162008-11-22 02:02:22 +00001134 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001135 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001136 return Res;
1137}
1138
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001139/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1140/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump11289f42009-09-09 15:08:12 +00001141/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001142unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1143 unsigned Size = 0;
1144 while (isWhitespace(Ptr[Size])) {
1145 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001147 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1148 continue;
1149
1150 // If this is a \r\n or \n\r, skip the other half.
1151 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1152 Ptr[Size-1] != Ptr[Size])
1153 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001154
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001155 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001156 }
1157
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001158 // Not an escaped newline, must be a \t or something else.
1159 return 0;
1160}
1161
Chris Lattner38b2cde2009-04-18 22:27:02 +00001162/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1163/// them), skip over them and return the first non-escaped-newline found,
1164/// otherwise return P.
1165const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001166 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001167 const char *AfterEscape;
1168 if (*P == '\\') {
1169 AfterEscape = P+1;
1170 } else if (*P == '?') {
1171 // If not a trigraph for escape, bail out.
1172 if (P[1] != '?' || P[2] != '/')
1173 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001174 // FIXME: Take LangOpts into account; the language might not
1175 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001176 AfterEscape = P+3;
1177 } else {
1178 return P;
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattner38b2cde2009-04-18 22:27:02 +00001181 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1182 if (NewLineSize == 0) return P;
1183 P = AfterEscape+NewLineSize;
1184 }
1185}
1186
Anna Zaks59a3c802011-07-27 21:43:43 +00001187/// \brief Checks that the given token is the first token that occurs after the
1188/// given location (this excludes comments and whitespace). Returns the location
1189/// immediately after the specified token. If the token is not found or the
1190/// location is inside a macro, the returned source location will be invalid.
1191SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1192 tok::TokenKind TKind,
1193 const SourceManager &SM,
1194 const LangOptions &LangOpts,
1195 bool SkipTrailingWhitespaceAndNewLine) {
1196 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001197 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001198 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001199 }
1200 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1201
1202 // Break down the source location.
1203 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1204
1205 // Try to load the file buffer.
1206 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001207 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001208 if (InvalidTemp)
1209 return SourceLocation();
1210
1211 const char *TokenBegin = File.data() + LocInfo.second;
1212
1213 // Lex from the start of the given location.
1214 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1215 TokenBegin, File.end());
1216 // Find the token.
1217 Token Tok;
1218 lexer.LexFromRawLexer(Tok);
1219 if (Tok.isNot(TKind))
1220 return SourceLocation();
1221 SourceLocation TokenLoc = Tok.getLocation();
1222
1223 // Calculate how much whitespace needs to be skipped if any.
1224 unsigned NumWhitespaceChars = 0;
1225 if (SkipTrailingWhitespaceAndNewLine) {
1226 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1227 Tok.getLength();
1228 unsigned char C = *TokenEnd;
1229 while (isHorizontalWhitespace(C)) {
1230 C = *(++TokenEnd);
1231 NumWhitespaceChars++;
1232 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001233
1234 // Skip \r, \n, \r\n, or \n\r
1235 if (C == '\n' || C == '\r') {
1236 char PrevC = C;
1237 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001238 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001239 if ((C == '\n' || C == '\r') && C != PrevC)
1240 NumWhitespaceChars++;
1241 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001242 }
1243
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001244 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001245}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001246
Chris Lattner22eb9722006-06-18 05:43:12 +00001247/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1248/// get its size, and return it. This is tricky in several cases:
1249/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1250/// then either return the trigraph (skipping 3 chars) or the '?',
1251/// depending on whether trigraphs are enabled or not.
1252/// 2. If this is an escaped newline (potentially with whitespace between
1253/// the backslash and newline), implicitly skip the newline and return
1254/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001255///
1256/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1257/// know that we can accumulate into Size, and that we have already incremented
1258/// Ptr by Size bytes.
1259///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001260/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1261/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001262///
1263char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001264 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001265 // If we have a slash, look for an escaped newline.
1266 if (Ptr[0] == '\\') {
1267 ++Size;
1268 ++Ptr;
1269Slash:
1270 // Common case, backslash-char where the char is not whitespace.
1271 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerc1835952009-06-23 05:15:06 +00001273 // See if we have optional whitespace characters between the slash and
1274 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001275 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1276 // Remember that this token needs to be cleaned.
1277 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001278
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001279 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001280 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001281 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001282
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001283 // Found backslash<whitespace><newline>. Parse the char after it.
1284 Size += EscapedNewLineSize;
1285 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001286
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001287 // Use slow version to accumulate a correct size field.
1288 return getCharAndSizeSlow(Ptr, Size, Tok);
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Chris Lattner22eb9722006-06-18 05:43:12 +00001291 // Otherwise, this is not an escaped newline, just return the slash.
1292 return '\\';
1293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 // If this is a trigraph, process it.
1296 if (Ptr[0] == '?' && Ptr[1] == '?') {
1297 // If this is actually a legal trigraph (not something like "??x"), emit
1298 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001299 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001301 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001302
1303 Ptr += 3;
1304 Size += 3;
1305 if (C == '\\') goto Slash;
1306 return C;
1307 }
1308 }
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // If this is neither, return a single character.
1311 ++Size;
1312 return *Ptr;
1313}
1314
1315/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1316/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1317/// and that we have already incremented Ptr by Size bytes.
1318///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001319/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1320/// be updated to match.
1321char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001322 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 // If we have a slash, look for an escaped newline.
1324 if (Ptr[0] == '\\') {
1325 ++Size;
1326 ++Ptr;
1327Slash:
1328 // Common case, backslash-char where the char is not whitespace.
1329 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001332 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1333 // Found backslash<whitespace><newline>. Parse the char after it.
1334 Size += EscapedNewLineSize;
1335 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001337 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001338 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // Otherwise, this is not an escaped newline, just return the slash.
1342 return '\\';
1343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001346 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001347 // If this is actually a legal trigraph (not something like "??x"), return
1348 // it.
1349 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1350 Ptr += 3;
1351 Size += 3;
1352 if (C == '\\') goto Slash;
1353 return C;
1354 }
1355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattner22eb9722006-06-18 05:43:12 +00001357 // If this is neither, return a single character.
1358 ++Size;
1359 return *Ptr;
1360}
1361
Chris Lattner22eb9722006-06-18 05:43:12 +00001362//===----------------------------------------------------------------------===//
1363// Helper methods for lexing.
1364//===----------------------------------------------------------------------===//
1365
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001366/// \brief Routine that indiscriminately skips bytes in the source file.
1367void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1368 BufferPtr += Bytes;
1369 if (BufferPtr > BufferEnd)
1370 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001371 // FIXME: What exactly does the StartOfLine bit mean? There are two
1372 // possible meanings for the "start" of the line: the first token on the
1373 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001374 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001375 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001376}
1377
Jordan Rose58c61e02013-02-09 01:10:25 +00001378static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001379 if (LangOpts.AsmPreprocessor) {
1380 return false;
1381 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001382 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1383 C11AllowedIDCharRanges);
1384 return C11AllowedIDChars.contains(C);
1385 } else if (LangOpts.CPlusPlus) {
1386 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1387 CXX03AllowedIDCharRanges);
1388 return CXX03AllowedIDChars.contains(C);
1389 } else {
1390 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1391 C99AllowedIDCharRanges);
1392 return C99AllowedIDChars.contains(C);
1393 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001394}
1395
Jordan Rose58c61e02013-02-09 01:10:25 +00001396static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1397 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001398 if (LangOpts.AsmPreprocessor) {
1399 return false;
1400 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001401 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1402 C11DisallowedInitialIDCharRanges);
1403 return !C11DisallowedInitialIDChars.contains(C);
1404 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001405 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001406 } else {
1407 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1408 C99DisallowedInitialIDCharRanges);
1409 return !C99DisallowedInitialIDChars.contains(C);
1410 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001411}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001412
Jordan Rose58c61e02013-02-09 01:10:25 +00001413static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1414 const char *End) {
1415 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1416 L.getSourceLocation(End));
1417}
1418
1419static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1420 CharSourceRange Range, bool IsFirst) {
1421 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001422 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001423 enum {
1424 CannotAppearInIdentifier = 0,
1425 CannotStartIdentifier
1426 };
1427
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001428 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1429 C99AllowedIDCharRanges);
1430 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1431 C99DisallowedInitialIDCharRanges);
1432 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001433 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1434 << Range
1435 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001436 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001437 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1438 << Range
1439 << CannotStartIdentifier;
1440 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001441 }
1442
Jordan Rose58c61e02013-02-09 01:10:25 +00001443 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001444 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001445 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1446 CXX03AllowedIDCharRanges);
1447 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001448 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1449 << Range;
1450 }
1451 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001452}
1453
1454bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1455 Token &Result) {
1456 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001457 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001458 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1459 return false;
1460
1461 if (!isLexingRawMode())
1462 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1463 makeCharRange(*this, CurPtr, UCNPtr),
1464 /*IsFirst=*/false);
1465
1466 Result.setFlag(Token::HasUCN);
1467 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1468 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1469 CurPtr = UCNPtr;
1470 else
1471 while (CurPtr != UCNPtr)
1472 (void)getAndAdvanceChar(CurPtr, Result);
1473 return true;
1474}
1475
1476bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1477 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001478 llvm::UTF32 CodePoint;
1479 llvm::ConversionResult Result =
1480 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1481 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001482 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001483 llvm::strictConversion);
1484 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001485 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1486 return false;
1487
1488 if (!isLexingRawMode())
1489 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1490 makeCharRange(*this, CurPtr, UnicodePtr),
1491 /*IsFirst=*/false);
1492
1493 CurPtr = UnicodePtr;
1494 return true;
1495}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001496
Eli Friedman0834a4b2013-09-19 00:41:32 +00001497bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001498 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1499 unsigned Size;
1500 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001501 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001502 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001503
Chris Lattner22eb9722006-06-18 05:43:12 +00001504 --CurPtr; // Back up over the skipped character.
1505
1506 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1507 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001508 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001509 // TODO: Could merge these checks into an InfoTable flag to make the
1510 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001511 if (isASCII(C) && C != '\\' && C != '?' &&
1512 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001513FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001514 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001515 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1516 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001517
Chris Lattner0f1f5052006-07-20 04:16:23 +00001518 // If we are in raw mode, return this identifier raw. There is no need to
1519 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001520 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001521 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001523 // Fill in Result.IdentifierInfo and update the token kind,
1524 // looking up the identifier in the identifier table.
1525 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerc5a00062006-06-18 16:41:01 +00001527 // Finally, now that we know we have an identifier, pass this off to the
1528 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001529 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001530 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001531
1532 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1533 && II->getPPKeywordID() == tok::pp_not_keyword
1534 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1535 // Return the code-completion token.
1536 Result.setKind(tok::code_completion);
1537 cutOffLexing();
1538 return true;
1539 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001540 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Chris Lattner22eb9722006-06-18 05:43:12 +00001543 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattner22eb9722006-06-18 05:43:12 +00001545 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001546 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001547 if (C == '$') {
1548 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001549 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001550
Chris Lattner22eb9722006-06-18 05:43:12 +00001551 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001552 if (!isLexingRawMode())
1553 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001554 CurPtr = ConsumeChar(CurPtr, Size, Result);
1555 C = getCharAndSize(CurPtr, Size);
1556 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001557
Richard Smith8b7258b2014-02-17 21:52:30 +00001558 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001559 C = getCharAndSize(CurPtr, Size);
1560 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001561 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001562 C = getCharAndSize(CurPtr, Size);
1563 continue;
1564 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001565 goto FinishIdentifier;
1566 }
1567
1568 // Otherwise, this character is good, consume it.
1569 CurPtr = ConsumeChar(CurPtr, Size, Result);
1570
1571 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001572 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001573 CurPtr = ConsumeChar(CurPtr, Size, Result);
1574 C = getCharAndSize(CurPtr, Size);
1575 }
1576 }
1577}
1578
Douglas Gregor759ef232010-08-30 14:50:47 +00001579/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001580/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001581bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001582 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001583 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001584 if (C1 != '0')
1585 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001586 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001587 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001588}
Chris Lattner22eb9722006-06-18 05:43:12 +00001589
Nate Begeman5eee9332008-04-14 02:26:39 +00001590/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001591/// constant. From[-1] is the first character lexed. Return the end of the
1592/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001593bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001594 unsigned Size;
1595 char C = getCharAndSize(CurPtr, Size);
1596 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001597 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001598 CurPtr = ConsumeChar(CurPtr, Size, Result);
1599 PrevCh = C;
1600 C = getCharAndSize(CurPtr, Size);
1601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
Chris Lattner22eb9722006-06-18 05:43:12 +00001603 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001604 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1605 // If we are in Microsoft mode, don't continue if the constant is hex.
1606 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001607 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001608 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1609 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001610
1611 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001612 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001613 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001614 // not-quite-conforming extension. Only do so if this looks like it's
1615 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1616 bool IsHexFloat = true;
1617 if (!LangOpts.C99) {
1618 if (!isHexaLiteral(BufferPtr, LangOpts))
1619 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001620 else if (!getLangOpts().CPlusPlus1z &&
1621 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001622 IsHexFloat = false;
1623 }
1624 if (IsHexFloat)
1625 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
Richard Smithfde94852013-09-26 03:33:06 +00001628 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001629 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001630 unsigned NextSize;
1631 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001632 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001633 if (!isLexingRawMode())
1634 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1635 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001636 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001637 return LexNumericConstant(Result, CurPtr);
1638 }
1639 }
1640
Richard Smith8b7258b2014-02-17 21:52:30 +00001641 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1642 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1643 return LexNumericConstant(Result, CurPtr);
1644 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1645 return LexNumericConstant(Result, CurPtr);
1646
Chris Lattnerd01e2912006-06-18 16:22:51 +00001647 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001648 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001649 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001650 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001651 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001652}
1653
Richard Smithe18f0fa2012-03-05 04:02:15 +00001654/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001655/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001656const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1657 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001659
Richard Smith8b7258b2014-02-17 21:52:30 +00001660 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001661 unsigned Size;
1662 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001663 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001664
Richard Smith8b7258b2014-02-17 21:52:30 +00001665 if (!isIdentifierHead(C)) {
1666 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1667 Consumed = true;
1668 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1669 Consumed = true;
1670 else
1671 return CurPtr;
1672 }
1673
1674 if (!getLangOpts().CPlusPlus11) {
1675 if (!isLexingRawMode())
1676 Diag(CurPtr,
1677 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1678 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1679 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1680 return CurPtr;
1681 }
1682
1683 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1684 // that does not start with an underscore is ill-formed. As a conforming
1685 // extension, we treat all such suffixes as if they had whitespace before
1686 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1687 // likely to be a ud-suffix than a macro, however, and accept that.
1688 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001689 bool IsUDSuffix = false;
1690 if (C == '_')
1691 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001692 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001693 // In C++1y, we need to look ahead a few characters to see if this is a
1694 // valid suffix for a string literal or a numeric literal (this could be
1695 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001696 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001697 char Buffer[MaxStandardSuffixLength] = { C };
1698 unsigned Consumed = Size;
1699 unsigned Chars = 1;
1700 while (true) {
1701 unsigned NextSize;
1702 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1703 getLangOpts());
1704 if (!isIdentifierBody(Next)) {
1705 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001706 const StringRef CompleteSuffix(Buffer, Chars);
1707 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1708 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001709 break;
1710 }
1711
1712 if (Chars == MaxStandardSuffixLength)
1713 // Too long: can't be a standard suffix.
1714 break;
1715
1716 Buffer[Chars++] = Next;
1717 Consumed += NextSize;
1718 }
Richard Smithf4198b72013-07-23 08:14:48 +00001719 }
1720
1721 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001722 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001723 Diag(CurPtr, getLangOpts().MSVCCompat
1724 ? diag::ext_ms_reserved_user_defined_literal
1725 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001726 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001727 return CurPtr;
1728 }
1729
Richard Smith8b7258b2014-02-17 21:52:30 +00001730 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001731 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001732
1733 Result.setFlag(Token::HasUDSuffix);
1734 while (true) {
1735 C = getCharAndSize(CurPtr, Size);
1736 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1737 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1738 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1739 else break;
1740 }
1741
Richard Smithe18f0fa2012-03-05 04:02:15 +00001742 return CurPtr;
1743}
1744
Chris Lattner22eb9722006-06-18 05:43:12 +00001745/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001746/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001747bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001748 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001749 // Does this string contain the \0 character?
1750 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001751
Richard Smithacd4d3d2011-10-15 01:18:56 +00001752 if (!isLexingRawMode() &&
1753 (Kind == tok::utf8_string_literal ||
1754 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001755 Kind == tok::utf32_string_literal))
1756 Diag(BufferPtr, getLangOpts().CPlusPlus
1757 ? diag::warn_cxx98_compat_unicode_literal
1758 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001759
Chris Lattner22eb9722006-06-18 05:43:12 +00001760 char C = getAndAdvanceChar(CurPtr, Result);
1761 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001762 // Skip escaped characters. Escaped newlines will already be processed by
1763 // getAndAdvanceChar.
1764 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001765 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001766
Chris Lattner52d96ac2010-05-30 23:27:38 +00001767 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001768 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001769 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001770 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001771 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001772 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001773 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001774
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001775 if (C == 0) {
1776 if (isCodeCompletionPoint(CurPtr-1)) {
1777 PP->CodeCompleteNaturalLanguage();
1778 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001779 cutOffLexing();
1780 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001781 }
1782
Chris Lattner52d96ac2010-05-30 23:27:38 +00001783 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001784 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001785 C = getAndAdvanceChar(CurPtr, Result);
1786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787
Richard Smithe18f0fa2012-03-05 04:02:15 +00001788 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001789 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001790 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001791
Chris Lattner5a78a022006-07-20 06:02:19 +00001792 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001793 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001794 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001795
Chris Lattnerd01e2912006-06-18 16:22:51 +00001796 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001797 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001798 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001799 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001800 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001801}
1802
Craig Topper54edcca2011-08-11 04:06:15 +00001803/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1804/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001805bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001806 tok::TokenKind Kind) {
1807 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1808 // Between the initial and final double quote characters of the raw string,
1809 // any transformations performed in phases 1 and 2 (trigraphs,
1810 // universal-character-names, and line splicing) are reverted.
1811
Richard Smithacd4d3d2011-10-15 01:18:56 +00001812 if (!isLexingRawMode())
1813 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1814
Craig Topper54edcca2011-08-11 04:06:15 +00001815 unsigned PrefixLen = 0;
1816
1817 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1818 ++PrefixLen;
1819
1820 // If the last character was not a '(', then we didn't lex a valid delimiter.
1821 if (CurPtr[PrefixLen] != '(') {
1822 if (!isLexingRawMode()) {
1823 const char *PrefixEnd = &CurPtr[PrefixLen];
1824 if (PrefixLen == 16) {
1825 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1826 } else {
1827 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1828 << StringRef(PrefixEnd, 1);
1829 }
1830 }
1831
1832 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1833 // it's possible the '"' was intended to be part of the raw string, but
1834 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001835 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001836 char C = *CurPtr++;
1837
1838 if (C == '"')
1839 break;
1840 if (C == 0 && CurPtr-1 == BufferEnd) {
1841 --CurPtr;
1842 break;
1843 }
1844 }
1845
1846 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001847 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001848 }
1849
1850 // Save prefix and move CurPtr past it
1851 const char *Prefix = CurPtr;
1852 CurPtr += PrefixLen + 1; // skip over prefix and '('
1853
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001854 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001855 char C = *CurPtr++;
1856
1857 if (C == ')') {
1858 // Check for prefix match and closing quote.
1859 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1860 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1861 break;
1862 }
1863 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1864 if (!isLexingRawMode())
1865 Diag(BufferPtr, diag::err_unterminated_raw_string)
1866 << StringRef(Prefix, PrefixLen);
1867 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001868 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001869 }
1870 }
1871
Richard Smithe18f0fa2012-03-05 04:02:15 +00001872 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001873 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001874 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001875
Craig Topper54edcca2011-08-11 04:06:15 +00001876 // Update the location of token as well as BufferPtr.
1877 const char *TokStart = BufferPtr;
1878 FormTokenWithChars(Result, CurPtr, Kind);
1879 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001880 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001881}
1882
Chris Lattner22eb9722006-06-18 05:43:12 +00001883/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1884/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001885bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001886 // Does this string contain the \0 character?
1887 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001888 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 char C = getAndAdvanceChar(CurPtr, Result);
1890 while (C != '>') {
1891 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001892 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001894 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001895 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001896 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1897 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001898 // If the filename is unterminated, then it must just be a lone <
1899 // character. Return this as such.
1900 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001901 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001902 } else if (C == 0) {
1903 NulCharacter = CurPtr-1;
1904 }
1905 C = getAndAdvanceChar(CurPtr, Result);
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Chris Lattner5a78a022006-07-20 06:02:19 +00001908 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001909 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001910 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattnerd01e2912006-06-18 16:22:51 +00001912 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001913 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001914 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001915 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001916 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001917}
1918
Chris Lattner22eb9722006-06-18 05:43:12 +00001919/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001920/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001921bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001922 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001923 // Does this character contain the \0 character?
1924 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001925
Richard Smith3e3a7052014-11-08 06:08:42 +00001926 if (!isLexingRawMode()) {
1927 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1928 Diag(BufferPtr, getLangOpts().CPlusPlus
1929 ? diag::warn_cxx98_compat_unicode_literal
1930 : diag::warn_c99_compat_unicode_literal);
1931 else if (Kind == tok::utf8_char_constant)
1932 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1933 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001934
Chris Lattner22eb9722006-06-18 05:43:12 +00001935 char C = getAndAdvanceChar(CurPtr, Result);
1936 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001937 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001938 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001939 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001940 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001941 }
1942
1943 while (C != '\'') {
1944 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001945 if (C == '\\')
1946 C = getAndAdvanceChar(CurPtr, Result);
1947
1948 if (C == '\n' || C == '\r' || // Newline.
1949 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001951 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001952 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001953 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001954 }
1955
1956 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001957 if (isCodeCompletionPoint(CurPtr-1)) {
1958 PP->CodeCompleteNaturalLanguage();
1959 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001960 cutOffLexing();
1961 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001962 }
1963
Chris Lattner86851b82010-07-07 23:24:27 +00001964 NulCharacter = CurPtr-1;
1965 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001966 C = getAndAdvanceChar(CurPtr, Result);
1967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
Richard Smithe18f0fa2012-03-05 04:02:15 +00001969 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001970 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001971 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001972
Chris Lattner86851b82010-07-07 23:24:27 +00001973 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001974 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001975 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001976
Chris Lattnerd01e2912006-06-18 16:22:51 +00001977 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001978 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001979 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001980 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001981 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001982}
1983
1984/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1985/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001986///
1987/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1988///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001989bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1990 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001991 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001992 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1993
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001994 unsigned char Char = *CurPtr;
1995
1996 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001997 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001998 // Skip horizontal whitespace very aggressively.
1999 while (isHorizontalWhitespace(Char))
2000 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002001
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002002 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002003 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 break;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 if (ParsingPreprocessorDirective) {
2007 // End of preprocessor directive line, let LexTokenInternal handle this.
2008 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002009 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002010 }
Mike Stump11289f42009-09-09 15:08:12 +00002011
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002012 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002013 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 Char = *++CurPtr;
2015 }
2016
Chris Lattner4d963442008-10-12 04:05:48 +00002017 // If the client wants us to return whitespace, return it now.
2018 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002019 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002020 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002021 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002022 IsAtPhysicalStartOfLine = true;
2023 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002024 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002025 return true;
2026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002028 // If this isn't immediately after a newline, there is leading space.
2029 char PrevChar = CurPtr[-1];
2030 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2031
2032 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002033 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002034 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002035 TokAtPhysicalStartOfLine = true;
2036 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002037
Chris Lattner22eb9722006-06-18 05:43:12 +00002038 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002039 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002040}
2041
Nico Weber158a31a2012-11-11 07:02:14 +00002042/// We have just read the // characters from input. Skip until we find the
2043/// newline character thats terminate the comment. Then update BufferPtr and
2044/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002045///
2046/// If we're in KeepCommentMode or any CommentHandler has inserted
2047/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002048bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2049 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002050 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002051 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002052 if (!LangOpts.LineComment && !isLexingRawMode()) {
2053 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Chris Lattner22eb9722006-06-18 05:43:12 +00002055 // Mark them enabled so we only emit one warning for this translation
2056 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002057 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 // Scan over the body of the comment. The common case, when scanning, is that
2061 // the comment contains normal ascii characters with nothing interesting in
2062 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002063 //
2064 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2065 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002067 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002068 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002069 // Skip over characters in the fast loop.
2070 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002071 C != '\n' && C != '\r') // Newline or DOS-style newline.
2072 C = *++CurPtr;
2073
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002074 const char *NextLine = CurPtr;
2075 if (C != 0) {
2076 // We found a newline, see if it's escaped.
2077 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002078 bool HasSpace = false;
2079 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002080 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002081 HasSpace = true;
2082 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002083
Richard Smith4c132e52017-04-18 21:45:04 +00002084 if (*EscapePtr == '\\')
2085 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002086 CurPtr = EscapePtr;
2087 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002088 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2089 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002090 CurPtr = EscapePtr-2;
2091 else
2092 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002093
2094 // If there was space between the backslash and newline, warn about it.
2095 if (HasSpace && !isLexingRawMode())
2096 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
Chris Lattner22eb9722006-06-18 05:43:12 +00002099 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002100 // properly decode the character. Read it in raw mode to avoid emitting
2101 // diagnostics about things like trigraphs. If we see an escaped newline,
2102 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002103 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002104 bool OldRawMode = isLexingRawMode();
2105 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002106 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002107 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002108
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002109 // If we only read only one character, then no special handling is needed.
2110 // We're done and can skip forward to the newline.
2111 if (C != 0 && CurPtr == OldPtr+1) {
2112 CurPtr = NextLine;
2113 break;
2114 }
2115
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002117 // \n, then we had an escaped newline within the comment. Emit diagnostic
2118 // unless the next line is also a // comment.
2119 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002120 for (; OldPtr != CurPtr; ++OldPtr)
2121 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002122 // Okay, we found a // comment that ends in a newline, if the next
2123 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002124 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002125 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002126 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002127 ++ForwardPtr;
2128 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2129 break;
2130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattner6d27a162008-11-22 02:02:22 +00002132 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002133 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002134 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 }
2136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Richard Smith1d2ae942017-04-17 23:44:51 +00002138 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2139 --CurPtr;
2140 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002141 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002142
2143 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2144 PP->CodeCompleteNaturalLanguage();
2145 cutOffLexing();
2146 return false;
2147 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002148 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002149
Chris Lattner93ddf802010-02-03 21:06:21 +00002150 // Found but did not consume the newline. Notify comment handlers about the
2151 // comment unless we're in a #if 0 block.
2152 if (PP && !isLexingRawMode() &&
2153 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2154 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002155 BufferPtr = CurPtr;
2156 return true; // A token has to be returned.
2157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Chris Lattner457fc152006-07-29 06:30:25 +00002159 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002160 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002161 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002162
2163 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002164 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002165 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002166 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002167 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 }
Mike Stump11289f42009-09-09 15:08:12 +00002169
Chris Lattner22eb9722006-06-18 05:43:12 +00002170 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002171 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002172 // contribute to another token), it isn't needed for correctness. Note that
2173 // this is ok even in KeepWhitespaceMode, because we would have returned the
2174 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002175 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002176
Chris Lattner22eb9722006-06-18 05:43:12 +00002177 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002178 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002179 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002181 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002183 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002184}
Chris Lattner22eb9722006-06-18 05:43:12 +00002185
Nico Weber158a31a2012-11-11 07:02:14 +00002186/// If in save-comment mode, package up this Line comment in an appropriate
2187/// way and return it.
2188bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002189 // If we're not in a preprocessor directive, just return the // comment
2190 // directly.
2191 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002192
David Blaikied5321242012-06-06 18:52:13 +00002193 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002194 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002195
Nico Weber158a31a2012-11-11 07:02:14 +00002196 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002197 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002198 bool Invalid = false;
2199 std::string Spelling = PP->getSpelling(Result, &Invalid);
2200 if (Invalid)
2201 return true;
2202
Nico Weber158a31a2012-11-11 07:02:14 +00002203 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002204 Spelling[1] = '*'; // Change prefix to "/*".
2205 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattnerb11c3232008-10-12 04:51:35 +00002207 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002208 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002209 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002210 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002211}
2212
Chris Lattnercb283342006-06-18 06:48:37 +00002213/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002214/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2215/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002216static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002217 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002218 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002219
Chris Lattner22eb9722006-06-18 05:43:12 +00002220 // Back up off the newline.
2221 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 // If this is a two-character newline sequence, skip the other character.
2224 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2225 // \n\n or \r\r -> not escaped newline.
2226 if (CurPtr[0] == CurPtr[1])
2227 return false;
2228 // \n\r or \r\n -> skip the newline.
2229 --CurPtr;
2230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattner22eb9722006-06-18 05:43:12 +00002232 // If we have horizontal whitespace, skip over it. We allow whitespace
2233 // between the slash and newline.
2234 bool HasSpace = false;
2235 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2236 --CurPtr;
2237 HasSpace = true;
2238 }
Mike Stump11289f42009-09-09 15:08:12 +00002239
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 // If we have a slash, we know this is an escaped newline.
2241 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002242 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002243 } else {
2244 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002245 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2246 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002247 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002248
Chris Lattnercb283342006-06-18 06:48:37 +00002249 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002250 CurPtr -= 2;
2251
2252 // If no trigraphs are enabled, warn that we ignored this trigraph and
2253 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002254 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002255 if (!L->isLexingRawMode())
2256 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002257 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002258 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002259 if (!L->isLexingRawMode())
2260 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 }
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002264 if (!L->isLexingRawMode())
2265 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002266
Chris Lattner22eb9722006-06-18 05:43:12 +00002267 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002268 if (HasSpace && !L->isLexingRawMode())
2269 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chris Lattnercb283342006-06-18 06:48:37 +00002271 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002272}
2273
Chris Lattneraded4a92006-10-27 04:42:31 +00002274#ifdef __SSE2__
2275#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002276#elif __ALTIVEC__
2277#include <altivec.h>
2278#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002279#endif
2280
James Dennettf442d242012-06-17 03:40:43 +00002281/// We have just read from input the / and * characters that started a comment.
2282/// Read until we find the * and / characters that terminate the comment.
2283/// Note that we don't bother decoding trigraphs or escaped newlines in block
2284/// comments, because they cannot cause the comment to end. The only thing
2285/// that can happen is the comment could end with an escaped newline between
2286/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002287///
Chris Lattner87d02082010-01-18 22:35:47 +00002288/// If we're in KeepCommentMode or any CommentHandler has inserted
2289/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002290bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2291 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002292 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002293 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 // optimization helps people who like to put a lot of * characters in their
2295 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002296
2297 // The first character we get with newlines and trigraphs skipped to handle
2298 // the degenerate /*/ case below correctly if the * has an escaped newline
2299 // after it.
2300 unsigned CharSize;
2301 unsigned char C = getCharAndSize(CurPtr, CharSize);
2302 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002303 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002304 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002305 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002306 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002307
Chris Lattner99e7d232008-10-12 04:19:49 +00002308 // KeepWhitespaceMode should return this broken comment as a token. Since
2309 // it isn't a well formed comment, just return it as an 'unknown' token.
2310 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002311 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002312 return true;
2313 }
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattner99e7d232008-10-12 04:19:49 +00002315 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002316 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002317 }
Mike Stump11289f42009-09-09 15:08:12 +00002318
Chris Lattnerc850ad62007-07-21 23:43:37 +00002319 // Check to see if the first character after the '/*' is another /. If so,
2320 // then this slash does not end the block comment, it is part of it.
2321 if (C == '/')
2322 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002323
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002324 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002325 // Skip over all non-interesting characters until we find end of buffer or a
2326 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002327 if (CurPtr + 24 < BufferEnd &&
2328 // If there is a code-completion point avoid the fast scan because it
2329 // doesn't check for '\0'.
2330 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002331 // While not aligned to a 16-byte boundary.
2332 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2333 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002334
Chris Lattner6cc3e362006-10-27 04:12:35 +00002335 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002336
2337#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002338 __m128i Slashes = _mm_set1_epi8('/');
2339 while (CurPtr+16 <= BufferEnd) {
2340 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2341 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002342 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002343 // Adjust the pointer to point directly after the first slash. It's
2344 // not necessary to set C here, it will be overwritten at the end of
2345 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002346 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002347 goto FoundSlash;
2348 }
Roman Divacky61509902014-04-03 18:04:52 +00002349 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002350 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002351#elif __ALTIVEC__
2352 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002353 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002354 '/', '/', '/', '/', '/', '/', '/', '/'
2355 };
2356 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002357 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002358 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002359#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002360 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002361 while (CurPtr[0] != '/' &&
2362 CurPtr[1] != '/' &&
2363 CurPtr[2] != '/' &&
2364 CurPtr[3] != '/' &&
2365 CurPtr+4 < BufferEnd) {
2366 CurPtr += 4;
2367 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002368#endif
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattneraded4a92006-10-27 04:42:31 +00002370 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002371 C = *CurPtr++;
2372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattneraded4a92006-10-27 04:42:31 +00002374 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002375 while (C != '/' && C != '\0')
2376 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002379 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002380 if (CurPtr[-2] == '*') // We found the final */. We're done!
2381 break;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Chris Lattner22eb9722006-06-18 05:43:12 +00002383 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002384 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002385 // We found the final */, though it had an escaped newline between the
2386 // * and /. We're done!
2387 break;
2388 }
2389 }
2390 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2391 // If this is a /* inside of the comment, emit a warning. Don't do this
2392 // if this is a /*/, which will end the comment. This misses cases with
2393 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002394 if (!isLexingRawMode())
2395 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002396 }
2397 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002398 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002399 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002400 // Note: the user probably forgot a */. We could continue immediately
2401 // after the /*, but this would involve lexing a lot of what really is the
2402 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002403 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002404
Chris Lattner99e7d232008-10-12 04:19:49 +00002405 // KeepWhitespaceMode should return this broken comment as a token. Since
2406 // it isn't a well formed comment, just return it as an 'unknown' token.
2407 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002408 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002409 return true;
2410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chris Lattner99e7d232008-10-12 04:19:49 +00002412 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002413 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002414 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2415 PP->CodeCompleteNaturalLanguage();
2416 cutOffLexing();
2417 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002418 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002419
Chris Lattner22eb9722006-06-18 05:43:12 +00002420 C = *CurPtr++;
2421 }
Mike Stump11289f42009-09-09 15:08:12 +00002422
Chris Lattner93ddf802010-02-03 21:06:21 +00002423 // Notify comment handlers about the comment unless we're in a #if 0 block.
2424 if (PP && !isLexingRawMode() &&
2425 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2426 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002427 BufferPtr = CurPtr;
2428 return true; // A token has to be returned.
2429 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002430
Chris Lattner457fc152006-07-29 06:30:25 +00002431 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002432 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002433 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002434 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002435 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002436
2437 // It is common for the tokens immediately after a /**/ comment to be
2438 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002439 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2440 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002441 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002442 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002443 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002444 }
2445
2446 // Otherwise, just return so that the next character will be lexed as a token.
2447 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002448 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002449 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002450}
2451
2452//===----------------------------------------------------------------------===//
2453// Primary Lexing Entry Points
2454//===----------------------------------------------------------------------===//
2455
Chris Lattner22eb9722006-06-18 05:43:12 +00002456/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2457/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002458void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002459 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2460 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002461 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002462
2463 // CurPtr - Cache BufferPtr in an automatic variable.
2464 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002465 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002466 char Char = getAndAdvanceChar(CurPtr, Tmp);
2467 switch (Char) {
2468 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002469 if (Result)
2470 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002471 break;
2472 case 0: // Null.
2473 // Found end of file?
2474 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002475 if (isCodeCompletionPoint(CurPtr-1)) {
2476 PP->CodeCompleteNaturalLanguage();
2477 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002478 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002479 }
2480
Chris Lattner22eb9722006-06-18 05:43:12 +00002481 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002482 if (Result)
2483 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002484 break;
2485 }
2486 // FALL THROUGH.
2487 case '\r':
2488 case '\n':
2489 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2490 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2491 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002492
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002493 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002494 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002495 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002496 if (PP)
2497 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002498 Lex(Tmp);
2499 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002500 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002501
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002502 // Finally, we're done;
2503 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002504 }
2505 }
2506}
2507
2508/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2509/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002510/// This returns true if Result contains a token, false if PP.Lex should be
2511/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002512bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002513 // If we hit the end of the file while parsing a preprocessor directive,
2514 // end the preprocessor directive first. The next token returned will
2515 // then be the end of file.
2516 if (ParsingPreprocessorDirective) {
2517 // Done parsing the "line".
2518 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002519 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002520 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattner457fc152006-07-29 06:30:25 +00002522 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002523 if (PP)
2524 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002525 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002526 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002527
Chris Lattner30a2fa12006-07-19 06:31:49 +00002528 // If we are in raw mode, return this event as an EOF token. Let the caller
2529 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002530 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002531 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002532 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002533 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002534 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002535 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002536
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002537 // Issue diagnostics for unterminated #if and missing newline.
2538
Chris Lattner30a2fa12006-07-19 06:31:49 +00002539 // If we are in a #if directive, emit an error.
2540 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002541 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002542 PP->Diag(ConditionalStack.back().IfLoc,
2543 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002544 ConditionalStack.pop_back();
2545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Chris Lattner8f96d042008-04-12 05:54:25 +00002547 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2548 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002549 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2550 DiagnosticsEngine &Diags = PP->getDiagnostics();
2551 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2552 unsigned DiagID;
2553
2554 if (LangOpts.CPlusPlus11) {
2555 // C++11 [lex.phases] 2.2 p2
2556 // Prefer the C++98 pedantic compatibility warning over the generic,
2557 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002558 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002559 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2560 } else {
2561 DiagID = diag::warn_no_newline_eof;
2562 }
2563 } else {
2564 DiagID = diag::ext_no_newline_eof;
2565 }
2566
2567 Diag(BufferEnd, DiagID)
2568 << FixItHint::CreateInsertion(EndLoc, "\n");
2569 }
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner22eb9722006-06-18 05:43:12 +00002571 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002572
2573 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002574 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002575}
2576
Chris Lattner678c8802006-07-11 05:46:12 +00002577/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2578/// the specified lexer will return a tok::l_paren token, 0 if it is something
2579/// else and 2 if there are no more tokens in the buffer controlled by the
2580/// lexer.
2581unsigned Lexer::isNextPPTokenLParen() {
2582 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002583
Chris Lattner678c8802006-07-11 05:46:12 +00002584 // Switch to 'skipping' mode. This will ensure that we can lex a token
2585 // without emitting diagnostics, disables macro expansion, and will cause EOF
2586 // to return an EOF token instead of popping the include stack.
2587 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002588
Chris Lattner678c8802006-07-11 05:46:12 +00002589 // Save state that can be changed while lexing so that we can restore it.
2590 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002591 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002592 bool atStartOfLine = IsAtStartOfLine;
2593 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2594 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002595
Chris Lattner146762e2007-07-20 16:59:19 +00002596 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002597 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002598
Chris Lattner678c8802006-07-11 05:46:12 +00002599 // Restore state that may have changed.
2600 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002601 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002602 HasLeadingSpace = leadingSpace;
2603 IsAtStartOfLine = atStartOfLine;
2604 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002605
Chris Lattner678c8802006-07-11 05:46:12 +00002606 // Restore the lexer back to non-skipping mode.
2607 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002608
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002609 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002610 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002611 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002612}
2613
James Dennettf442d242012-06-17 03:40:43 +00002614/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002615static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2616 ConflictMarkerKind CMK) {
2617 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2618 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002619 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002620 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002621 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002622 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002623 if (Pos == 0 ||
2624 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002625 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2626 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002627 continue;
2628 }
2629 return RestOfBuffer.data()+Pos;
2630 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002631 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002632}
2633
2634/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2635/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2636/// and recover nicely. This returns true if it is a conflict marker and false
2637/// if not.
2638bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2639 // Only a conflict marker if it starts at the beginning of a line.
2640 if (CurPtr != BufferStart &&
2641 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2642 return false;
2643
Richard Smitha9e33d42011-10-12 00:37:51 +00002644 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002645 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2646 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002647 return false;
2648
2649 // If we have a situation where we don't care about conflict markers, ignore
2650 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002651 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002652 return false;
2653
Richard Smitha9e33d42011-10-12 00:37:51 +00002654 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2655
2656 // Check to see if there is an ending marker somewhere in the buffer at the
2657 // start of a line to terminate this conflict marker.
2658 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002659 // We found a match. We are really in a conflict marker.
2660 // Diagnose this, and ignore to the end of line.
2661 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002662 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002663
2664 // Skip ahead to the end of line. We know this exists because the
2665 // end-of-conflict marker starts with \r or \n.
2666 while (*CurPtr != '\r' && *CurPtr != '\n') {
2667 assert(CurPtr != BufferEnd && "Didn't find end of line");
2668 ++CurPtr;
2669 }
2670 BufferPtr = CurPtr;
2671 return true;
2672 }
2673
2674 // No end of conflict marker found.
2675 return false;
2676}
2677
Richard Smitha9e33d42011-10-12 00:37:51 +00002678/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2679/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2680/// is the end of a conflict marker. Handle it by ignoring up until the end of
2681/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002682bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2683 // Only a conflict marker if it starts at the beginning of a line.
2684 if (CurPtr != BufferStart &&
2685 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2686 return false;
2687
2688 // If we have a situation where we don't care about conflict markers, ignore
2689 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002690 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002691 return false;
2692
Richard Smitha9e33d42011-10-12 00:37:51 +00002693 // Check to see if we have the marker (4 characters in a row).
2694 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002695 if (CurPtr[i] != CurPtr[0])
2696 return false;
2697
2698 // If we do have it, search for the end of the conflict marker. This could
2699 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2700 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002701 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2702 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002703 CurPtr = End;
2704
2705 // Skip ahead to the end of line.
2706 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2707 ++CurPtr;
2708
2709 BufferPtr = CurPtr;
2710
2711 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002712 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002713 return true;
2714 }
2715
2716 return false;
2717}
2718
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002719bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2720 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002721 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002722 return Loc == PP->getCodeCompletionLoc();
2723 }
2724
2725 return false;
2726}
2727
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002728uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2729 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002730 unsigned CharSize;
2731 char Kind = getCharAndSize(StartPtr, CharSize);
2732
2733 unsigned NumHexDigits;
2734 if (Kind == 'u')
2735 NumHexDigits = 4;
2736 else if (Kind == 'U')
2737 NumHexDigits = 8;
2738 else
2739 return 0;
2740
Jordan Rosec0cba272013-01-27 20:12:04 +00002741 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002742 if (Result && !isLexingRawMode())
2743 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002744 return 0;
2745 }
2746
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002747 const char *CurPtr = StartPtr + CharSize;
2748 const char *KindLoc = &CurPtr[-1];
2749
2750 uint32_t CodePoint = 0;
2751 for (unsigned i = 0; i < NumHexDigits; ++i) {
2752 char C = getCharAndSize(CurPtr, CharSize);
2753
2754 unsigned Value = llvm::hexDigitValue(C);
2755 if (Value == -1U) {
2756 if (Result && !isLexingRawMode()) {
2757 if (i == 0) {
2758 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2759 << StringRef(KindLoc, 1);
2760 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002761 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002762
2763 // If the user wrote \U1234, suggest a fixit to \u.
2764 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002765 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002766 Diag(KindLoc, diag::note_ucn_four_not_eight)
2767 << FixItHint::CreateReplacement(URange, "u");
2768 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002769 }
2770 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002771
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002772 return 0;
2773 }
2774
2775 CodePoint <<= 4;
2776 CodePoint += Value;
2777
2778 CurPtr += CharSize;
2779 }
2780
2781 if (Result) {
2782 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002783 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002784 StartPtr = CurPtr;
2785 else
2786 while (StartPtr != CurPtr)
2787 (void)getAndAdvanceChar(StartPtr, *Result);
2788 } else {
2789 StartPtr = CurPtr;
2790 }
2791
Justin Bogner53535132013-10-21 05:02:28 +00002792 // Don't apply C family restrictions to UCNs in assembly mode
2793 if (LangOpts.AsmPreprocessor)
2794 return CodePoint;
2795
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002796 // C99 6.4.3p2: A universal character name shall not specify a character whose
2797 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2798 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2799 // C++11 [lex.charset]p2: If the hexadecimal value for a
2800 // universal-character-name corresponds to a surrogate code point (in the
2801 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2802 // if the hexadecimal value for a universal-character-name outside the
2803 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2804 // string literal corresponds to a control character (in either of the
2805 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2806 // basic source character set, the program is ill-formed.
2807 if (CodePoint < 0xA0) {
2808 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2809 return CodePoint;
2810
2811 // We don't use isLexingRawMode() here because we need to warn about bad
2812 // UCNs even when skipping preprocessing tokens in a #if block.
2813 if (Result && PP) {
2814 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2815 Diag(BufferPtr, diag::err_ucn_control_character);
2816 else {
2817 char C = static_cast<char>(CodePoint);
2818 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2819 }
2820 }
2821
2822 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002823
2824 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002825 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002826 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002827 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002828 if (Result && PP) {
2829 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2830 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2831 else
2832 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2833 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002834 return 0;
2835 }
2836
2837 return CodePoint;
2838}
2839
Eli Friedman0834a4b2013-09-19 00:41:32 +00002840bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2841 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002842 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2843 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002844 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002845 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002846 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002847 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002848
2849 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002850 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002851 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002852 return false;
2853}
Jordan Rose4246ae02013-01-24 20:50:50 +00002854
Eli Friedman0834a4b2013-09-19 00:41:32 +00002855bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002856 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2857 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2858 !PP->isPreprocessedOutput()) {
2859 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2860 makeCharRange(*this, BufferPtr, CurPtr),
2861 /*IsFirst=*/true);
2862 }
2863
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002864 MIOpt.ReadToken();
2865 return LexIdentifier(Result, CurPtr);
2866 }
2867
Jordan Rosecc538342013-01-31 19:48:48 +00002868 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2869 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002870 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002871 // Non-ASCII characters tend to creep into source code unintentionally.
2872 // Instead of letting the parser complain about the unknown token,
2873 // just drop the character.
2874 // Note that we can /only/ do this when the non-ASCII character is actually
2875 // spelled as Unicode, not written as a UCN. The standard requires that
2876 // we not throw away any possible preprocessor tokens, but there's a
2877 // loophole in the mapping of Unicode characters to basic character set
2878 // characters that allows us to map these particular characters to, say,
2879 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002880 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002881 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002882
2883 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002884 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002885 }
2886
2887 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2888 // up by accident.
2889 MIOpt.ReadToken();
2890 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002891 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002892}
2893
Eli Friedman0834a4b2013-09-19 00:41:32 +00002894void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2895 IsAtStartOfLine = Result.isAtStartOfLine();
2896 HasLeadingSpace = Result.hasLeadingSpace();
2897 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2898 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2899}
2900
2901bool Lexer::Lex(Token &Result) {
2902 // Start a new token.
2903 Result.startToken();
2904
2905 // Set up misc whitespace flags for LexTokenInternal.
2906 if (IsAtStartOfLine) {
2907 Result.setFlag(Token::StartOfLine);
2908 IsAtStartOfLine = false;
2909 }
2910
2911 if (HasLeadingSpace) {
2912 Result.setFlag(Token::LeadingSpace);
2913 HasLeadingSpace = false;
2914 }
2915
2916 if (HasLeadingEmptyMacro) {
2917 Result.setFlag(Token::LeadingEmptyMacro);
2918 HasLeadingEmptyMacro = false;
2919 }
2920
2921 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2922 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002923 bool isRawLex = isLexingRawMode();
2924 (void) isRawLex;
2925 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2926 // (After the LexTokenInternal call, the lexer might be destroyed.)
2927 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2928 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002929}
Chris Lattner22eb9722006-06-18 05:43:12 +00002930
2931/// LexTokenInternal - This implements a simple C family lexer. It is an
2932/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002933/// has a null character at the end of the file. This returns a preprocessing
2934/// token, not a normal token, as such, it is an internal interface. It assumes
2935/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002936bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002937LexNextToken:
2938 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002939 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002940 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Chris Lattner22eb9722006-06-18 05:43:12 +00002942 // CurPtr - Cache BufferPtr in an automatic variable.
2943 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002944
Chris Lattnereb54b592006-07-10 06:34:27 +00002945 // Small amounts of horizontal whitespace is very common between tokens.
2946 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2947 ++CurPtr;
2948 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2949 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002950
Chris Lattner4d963442008-10-12 04:05:48 +00002951 // If we are keeping whitespace and other tokens, just return what we just
2952 // skipped. The next lexer invocation will return the token after the
2953 // whitespace.
2954 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002955 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002956 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002957 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002958 }
Mike Stump11289f42009-09-09 15:08:12 +00002959
Chris Lattnereb54b592006-07-10 06:34:27 +00002960 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002961 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Chris Lattner22eb9722006-06-18 05:43:12 +00002964 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002965
Chris Lattner22eb9722006-06-18 05:43:12 +00002966 // Read a character, advancing over it.
2967 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002968 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002969
Chris Lattner22eb9722006-06-18 05:43:12 +00002970 switch (Char) {
2971 case 0: // Null.
2972 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002973 if (CurPtr-1 == BufferEnd)
2974 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002975
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002976 // Check if we are performing code completion.
2977 if (isCodeCompletionPoint(CurPtr-1)) {
2978 // Return the code-completion token.
2979 Result.startToken();
2980 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002981 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002982 }
2983
Chris Lattner6d27a162008-11-22 02:02:22 +00002984 if (!isLexingRawMode())
2985 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002986 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002987 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2988 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002989
Eli Friedman0834a4b2013-09-19 00:41:32 +00002990 // We know the lexer hasn't changed, so just try again with this lexer.
2991 // (We manually eliminate the tail call to avoid recursion.)
2992 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002993
2994 case 26: // DOS & CP/M EOF: "^Z".
2995 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00002996 if (LangOpts.MicrosoftExt) {
2997 if (!isLexingRawMode())
2998 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002999 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003000 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003001
Chris Lattner3dfff972009-12-17 05:29:40 +00003002 // If Microsoft extensions are disabled, this is just random garbage.
3003 Kind = tok::unknown;
3004 break;
3005
Chris Lattner22eb9722006-06-18 05:43:12 +00003006 case '\n':
3007 case '\r':
3008 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003009 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003010 if (ParsingPreprocessorDirective) {
3011 // Done parsing the "line".
3012 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattner457fc152006-07-29 06:30:25 +00003014 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003015 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003016 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattner22eb9722006-06-18 05:43:12 +00003018 // Since we consumed a newline, we are back at the start of a line.
3019 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003020 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003022 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003023 break;
3024 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003025
Chris Lattner22eb9722006-06-18 05:43:12 +00003026 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003027 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003028
Eli Friedman0834a4b2013-09-19 00:41:32 +00003029 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3030 return true; // KeepWhitespaceMode
3031
3032 // We only saw whitespace, so just try again with this lexer.
3033 // (We manually eliminate the tail call to avoid recursion.)
3034 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003035 case ' ':
3036 case '\t':
3037 case '\f':
3038 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003039 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003040 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003041 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3042 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003043
3044 SkipIgnoredUnits:
3045 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003046
Chris Lattnerb9b85972007-07-22 06:29:05 +00003047 // If the next token is obviously a // or /* */ comment, skip it efficiently
3048 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003049 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003050 LangOpts.LineComment &&
3051 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003052 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3053 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003054 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003055 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003056 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3057 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003058 goto SkipIgnoredUnits;
3059 } else if (isHorizontalWhitespace(*CurPtr)) {
3060 goto SkipHorizontalWhitespace;
3061 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003062 // We only saw whitespace, so just try again with this lexer.
3063 // (We manually eliminate the tail call to avoid recursion.)
3064 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003065
Chris Lattner2b15cf72008-01-03 17:58:54 +00003066 // C99 6.4.4.1: Integer Constants.
3067 // C99 6.4.4.2: Floating Constants.
3068 case '0': case '1': case '2': case '3': case '4':
3069 case '5': case '6': case '7': case '8': case '9':
3070 // Notify MIOpt that we read a non-whitespace/non-comment token.
3071 MIOpt.ReadToken();
3072 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003073
Richard Smith9b362092013-03-09 23:56:02 +00003074 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003075 // Notify MIOpt that we read a non-whitespace/non-comment token.
3076 MIOpt.ReadToken();
3077
Richard Smith9b362092013-03-09 23:56:02 +00003078 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003079 Char = getCharAndSize(CurPtr, SizeTmp);
3080
3081 // UTF-16 string literal
3082 if (Char == '"')
3083 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3084 tok::utf16_string_literal);
3085
3086 // UTF-16 character constant
3087 if (Char == '\'')
3088 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3089 tok::utf16_char_constant);
3090
Craig Topper54edcca2011-08-11 04:06:15 +00003091 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003092 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3093 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003094 return LexRawStringLiteral(Result,
3095 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3096 SizeTmp2, Result),
3097 tok::utf16_string_literal);
3098
3099 if (Char == '8') {
3100 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3101
3102 // UTF-8 string literal
3103 if (Char2 == '"')
3104 return LexStringLiteral(Result,
3105 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3106 SizeTmp2, Result),
3107 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003108 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3109 return LexCharConstant(
3110 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3111 SizeTmp2, Result),
3112 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003113
Richard Smith9b362092013-03-09 23:56:02 +00003114 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003115 unsigned SizeTmp3;
3116 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3117 // UTF-8 raw string literal
3118 if (Char3 == '"') {
3119 return LexRawStringLiteral(Result,
3120 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3121 SizeTmp2, Result),
3122 SizeTmp3, Result),
3123 tok::utf8_string_literal);
3124 }
3125 }
3126 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003127 }
3128
3129 // treat u like the start of an identifier.
3130 return LexIdentifier(Result, CurPtr);
3131
Richard Smith9b362092013-03-09 23:56:02 +00003132 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003133 // Notify MIOpt that we read a non-whitespace/non-comment token.
3134 MIOpt.ReadToken();
3135
Richard Smith9b362092013-03-09 23:56:02 +00003136 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003137 Char = getCharAndSize(CurPtr, SizeTmp);
3138
3139 // UTF-32 string literal
3140 if (Char == '"')
3141 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3142 tok::utf32_string_literal);
3143
3144 // UTF-32 character constant
3145 if (Char == '\'')
3146 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3147 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003148
3149 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003150 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3151 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003152 return LexRawStringLiteral(Result,
3153 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3154 SizeTmp2, Result),
3155 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003156 }
3157
3158 // treat U like the start of an identifier.
3159 return LexIdentifier(Result, CurPtr);
3160
Craig Topper54edcca2011-08-11 04:06:15 +00003161 case 'R': // Identifier or C++0x raw string literal
3162 // Notify MIOpt that we read a non-whitespace/non-comment token.
3163 MIOpt.ReadToken();
3164
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003165 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003166 Char = getCharAndSize(CurPtr, SizeTmp);
3167
3168 if (Char == '"')
3169 return LexRawStringLiteral(Result,
3170 ConsumeChar(CurPtr, SizeTmp, Result),
3171 tok::string_literal);
3172 }
3173
3174 // treat R like the start of an identifier.
3175 return LexIdentifier(Result, CurPtr);
3176
Chris Lattner2b15cf72008-01-03 17:58:54 +00003177 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003178 // Notify MIOpt that we read a non-whitespace/non-comment token.
3179 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003180 Char = getCharAndSize(CurPtr, SizeTmp);
3181
3182 // Wide string literal.
3183 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003184 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003185 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003186
Craig Topper54edcca2011-08-11 04:06:15 +00003187 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003188 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003189 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3190 return LexRawStringLiteral(Result,
3191 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3192 SizeTmp2, Result),
3193 tok::wide_string_literal);
3194
Chris Lattner22eb9722006-06-18 05:43:12 +00003195 // Wide character constant.
3196 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003197 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3198 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003199 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003200
Chris Lattner22eb9722006-06-18 05:43:12 +00003201 // C99 6.4.2: Identifiers.
3202 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3203 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003204 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003205 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3206 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3207 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003208 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003209 case 'v': case 'w': case 'x': case 'y': case 'z':
3210 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003211 // Notify MIOpt that we read a non-whitespace/non-comment token.
3212 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003213 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003214
3215 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003216 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003217 if (!isLexingRawMode())
3218 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003219 // Notify MIOpt that we read a non-whitespace/non-comment token.
3220 MIOpt.ReadToken();
3221 return LexIdentifier(Result, CurPtr);
3222 }
Mike Stump11289f42009-09-09 15:08:12 +00003223
Chris Lattnerb11c3232008-10-12 04:51:35 +00003224 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003225 break;
Mike Stump11289f42009-09-09 15:08:12 +00003226
Chris Lattner22eb9722006-06-18 05:43:12 +00003227 // C99 6.4.4: Character Constants.
3228 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003229 // Notify MIOpt that we read a non-whitespace/non-comment token.
3230 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003231 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003232
3233 // C99 6.4.5: String Literals.
3234 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003235 // Notify MIOpt that we read a non-whitespace/non-comment token.
3236 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003237 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003238
3239 // C99 6.4.6: Punctuators.
3240 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003241 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003242 break;
3243 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003244 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003245 break;
3246 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003247 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003248 break;
3249 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003250 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 break;
3252 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003253 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003254 break;
3255 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003256 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003257 break;
3258 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003259 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003260 break;
3261 case '.':
3262 Char = getCharAndSize(CurPtr, SizeTmp);
3263 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003264 // Notify MIOpt that we read a non-whitespace/non-comment token.
3265 MIOpt.ReadToken();
3266
Chris Lattner22eb9722006-06-18 05:43:12 +00003267 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003268 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003269 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003270 CurPtr += SizeTmp;
3271 } else if (Char == '.' &&
3272 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003273 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003274 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3275 SizeTmp2, Result);
3276 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003277 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003278 }
3279 break;
3280 case '&':
3281 Char = getCharAndSize(CurPtr, SizeTmp);
3282 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003283 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003284 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3285 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003286 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003287 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3288 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003289 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003290 }
3291 break;
Mike Stump11289f42009-09-09 15:08:12 +00003292 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003293 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003294 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3296 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003297 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 }
3299 break;
3300 case '+':
3301 Char = getCharAndSize(CurPtr, SizeTmp);
3302 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003304 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003305 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003306 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003307 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003308 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003309 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003310 }
3311 break;
3312 case '-':
3313 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003314 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003315 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003316 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003317 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003318 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003319 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3320 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003321 Kind = tok::arrowstar;
3322 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003323 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003324 Kind = tok::arrow;
3325 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003326 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003327 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003328 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 }
3331 break;
3332 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003333 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003334 break;
3335 case '!':
3336 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003337 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003338 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3339 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003340 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003341 }
3342 break;
3343 case '/':
3344 // 6.4.9: Comments
3345 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003346 if (Char == '/') { // Line comment.
3347 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003348 // want to lex this as a comment. There is one problem with this though,
3349 // that in one particular corner case, this can change the behavior of the
3350 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003351 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003352 // "foo". Check to see if the character after the second slash is a '*'.
3353 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003354 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003355 bool TreatAsComment = LangOpts.LineComment &&
3356 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003357 if (!TreatAsComment)
3358 if (!(PP && PP->isPreprocessedOutput()))
3359 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3360
3361 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003362 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3363 TokAtPhysicalStartOfLine))
3364 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattner58827712009-01-16 22:39:25 +00003366 // It is common for the tokens immediately after a // comment to be
3367 // whitespace (indentation for the next line). Instead of going through
3368 // the big switch, handle it efficiently now.
3369 goto SkipIgnoredUnits;
3370 }
3371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
Chris Lattner58827712009-01-16 22:39:25 +00003373 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003374 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3375 TokAtPhysicalStartOfLine))
3376 return true; // There is a token to return.
3377
3378 // We only saw whitespace, so just try again with this lexer.
3379 // (We manually eliminate the tail call to avoid recursion.)
3380 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003381 }
Mike Stump11289f42009-09-09 15:08:12 +00003382
Chris Lattner58827712009-01-16 22:39:25 +00003383 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003384 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003385 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003387 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003388 }
3389 break;
3390 case '%':
3391 Char = getCharAndSize(CurPtr, SizeTmp);
3392 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003393 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003395 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003396 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003397 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003398 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003399 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003400 Char = getCharAndSize(CurPtr, SizeTmp);
3401 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003402 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003403 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3404 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003405 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003406 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003407 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003408 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003409 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003410 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 // We parsed a # character. If this occurs at the start of the line,
3412 // it's actually the start of a preprocessing directive. Callback to
3413 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003414 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003415 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003416 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003417
Chris Lattner2534324a2009-03-18 20:58:27 +00003418 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003419 }
3420 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003421 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003422 }
3423 break;
3424 case '<':
3425 Char = getCharAndSize(CurPtr, SizeTmp);
3426 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003427 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003428 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003429 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3430 if (After == '=') {
3431 Kind = tok::lesslessequal;
3432 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3433 SizeTmp2, Result);
3434 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3435 // If this is actually a '<<<<<<<' version control conflict marker,
3436 // recognize it as such and recover nicely.
3437 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003438 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3439 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3440 // ignore it.
3441 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003442 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003443 Kind = tok::lesslessless;
3444 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3445 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003446 } else {
3447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3448 Kind = tok::lessless;
3449 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003450 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003451 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003452 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003453 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003454 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003455 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3456 // C++0x [lex.pptoken]p3:
3457 // Otherwise, if the next three characters are <:: and the subsequent
3458 // character is neither : nor >, the < is treated as a preprocessor
3459 // token by itself and not as the first character of the alternative
3460 // token <:.
3461 unsigned SizeTmp3;
3462 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3463 if (After != ':' && After != '>') {
3464 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003465 if (!isLexingRawMode())
3466 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003467 break;
3468 }
3469 }
3470
Chris Lattner22eb9722006-06-18 05:43:12 +00003471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003472 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003473 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003477 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 }
3479 break;
3480 case '>':
3481 Char = getCharAndSize(CurPtr, SizeTmp);
3482 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003483 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003484 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003485 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003486 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3487 if (After == '=') {
3488 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3489 SizeTmp2, Result);
3490 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003491 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3492 // If this is actually a '>>>>' conflict marker, recognize it as such
3493 // and recover nicely.
3494 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003495 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3496 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3497 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003498 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003499 Kind = tok::greatergreatergreater;
3500 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3501 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003502 } else {
3503 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3504 Kind = tok::greatergreater;
3505 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003506 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003507 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003508 }
3509 break;
3510 case '^':
3511 Char = getCharAndSize(CurPtr, SizeTmp);
3512 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003513 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003514 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003515 } else if (LangOpts.OpenCL && Char == '^') {
3516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3517 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003518 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003519 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003520 }
3521 break;
3522 case '|':
3523 Char = getCharAndSize(CurPtr, SizeTmp);
3524 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003525 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003526 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3527 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003528 // If this is '|||||||' and we're in a conflict marker, ignore it.
3529 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3530 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003531 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003532 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3533 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003534 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003535 }
3536 break;
3537 case ':':
3538 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003539 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003540 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003541 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003542 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003543 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003544 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003545 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003546 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003547 }
3548 break;
3549 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003550 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003551 break;
3552 case '=':
3553 Char = getCharAndSize(CurPtr, SizeTmp);
3554 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003555 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003556 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3557 goto LexNextToken;
3558
Chris Lattnerb11c3232008-10-12 04:51:35 +00003559 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003560 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003561 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003562 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003563 }
3564 break;
3565 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003566 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003567 break;
3568 case '#':
3569 Char = getCharAndSize(CurPtr, SizeTmp);
3570 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003571 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003574 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003575 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003576 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003577 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003578 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003579 // We parsed a # character. If this occurs at the start of the line,
3580 // it's actually the start of a preprocessing directive. Callback to
3581 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003582 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003583 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003584 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattner2534324a2009-03-18 20:58:27 +00003586 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 }
3588 break;
3589
Chris Lattner2b15cf72008-01-03 17:58:54 +00003590 case '@':
3591 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003592 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003593 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003594 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003595 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003596 break;
Mike Stump11289f42009-09-09 15:08:12 +00003597
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003598 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003599 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003600 if (!LangOpts.AsmPreprocessor) {
3601 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3602 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3603 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3604 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003605
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003606 // We only saw whitespace, so just try again with this lexer.
3607 // (We manually eliminate the tail call to avoid recursion.)
3608 goto LexNextToken;
3609 }
3610
3611 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003612 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003613 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003614
Chris Lattnerb11c3232008-10-12 04:51:35 +00003615 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003616 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003617
3618 default: {
3619 if (isASCII(Char)) {
3620 Kind = tok::unknown;
3621 break;
3622 }
3623
Justin Lebar90910552016-09-30 00:38:45 +00003624 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003625
3626 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3627 // an escaped newline.
3628 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003629 llvm::ConversionResult Status =
3630 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3631 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003632 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003633 llvm::strictConversion);
3634 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003635 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3636 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3637 return true; // KeepWhitespaceMode
3638
3639 // We only saw whitespace, so just try again with this lexer.
3640 // (We manually eliminate the tail call to avoid recursion.)
3641 goto LexNextToken;
3642 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003643 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003644 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003645
Jordan Rosecc538342013-01-31 19:48:48 +00003646 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3647 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003648 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003649 Kind = tok::unknown;
3650 break;
3651 }
3652
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003653 // Non-ASCII characters tend to creep into source code unintentionally.
3654 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003655 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003656 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003657
3658 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003659 // We're pretending the character didn't exist, so just try again with
3660 // this lexer.
3661 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003662 goto LexNextToken;
3663 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003664 }
Mike Stump11289f42009-09-09 15:08:12 +00003665
Chris Lattner371ac8a2006-07-04 07:11:10 +00003666 // Notify MIOpt that we read a non-whitespace/non-comment token.
3667 MIOpt.ReadToken();
3668
Chris Lattnerd01e2912006-06-18 16:22:51 +00003669 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003670 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003671 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003672
3673HandleDirective:
3674 // We parsed a # character and it's the start of a preprocessing directive.
3675
3676 FormTokenWithChars(Result, CurPtr, tok::hash);
3677 PP->HandleDirective(Result);
3678
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003679 if (PP->hadModuleLoaderFatalFailure()) {
3680 // With a fatal failure in the module loader, we abort parsing.
3681 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003682 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003683 }
3684
Eli Friedman0834a4b2013-09-19 00:41:32 +00003685 // We parsed the directive; lex a token with the new state.
3686 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003687}