xref: /aosp_15_r20/external/clang/lib/Lex/Lexer.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file implements the Lexer and Token interfaces.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "clang/Lex/Lexer.h"
15*67e74705SXin Li #include "UnicodeCharSets.h"
16*67e74705SXin Li #include "clang/Basic/CharInfo.h"
17*67e74705SXin Li #include "clang/Basic/SourceManager.h"
18*67e74705SXin Li #include "clang/Lex/CodeCompletionHandler.h"
19*67e74705SXin Li #include "clang/Lex/LexDiagnostic.h"
20*67e74705SXin Li #include "clang/Lex/LiteralSupport.h"
21*67e74705SXin Li #include "clang/Lex/Preprocessor.h"
22*67e74705SXin Li #include "llvm/ADT/STLExtras.h"
23*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
24*67e74705SXin Li #include "llvm/ADT/StringSwitch.h"
25*67e74705SXin Li #include "llvm/Support/Compiler.h"
26*67e74705SXin Li #include "llvm/Support/ConvertUTF.h"
27*67e74705SXin Li #include "llvm/Support/MemoryBuffer.h"
28*67e74705SXin Li #include <cstring>
29*67e74705SXin Li using namespace clang;
30*67e74705SXin Li 
31*67e74705SXin Li //===----------------------------------------------------------------------===//
32*67e74705SXin Li // Token Class Implementation
33*67e74705SXin Li //===----------------------------------------------------------------------===//
34*67e74705SXin Li 
35*67e74705SXin Li /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const36*67e74705SXin Li bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
37*67e74705SXin Li   if (IdentifierInfo *II = getIdentifierInfo())
38*67e74705SXin Li     return II->getObjCKeywordID() == objcKey;
39*67e74705SXin Li   return false;
40*67e74705SXin Li }
41*67e74705SXin Li 
42*67e74705SXin Li /// getObjCKeywordID - Return the ObjC keyword kind.
getObjCKeywordID() const43*67e74705SXin Li tok::ObjCKeywordKind Token::getObjCKeywordID() const {
44*67e74705SXin Li   IdentifierInfo *specId = getIdentifierInfo();
45*67e74705SXin Li   return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
46*67e74705SXin Li }
47*67e74705SXin Li 
48*67e74705SXin Li 
49*67e74705SXin Li //===----------------------------------------------------------------------===//
50*67e74705SXin Li // Lexer Class Implementation
51*67e74705SXin Li //===----------------------------------------------------------------------===//
52*67e74705SXin Li 
anchor()53*67e74705SXin Li void Lexer::anchor() { }
54*67e74705SXin Li 
InitLexer(const char * BufStart,const char * BufPtr,const char * BufEnd)55*67e74705SXin Li void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
56*67e74705SXin Li                       const char *BufEnd) {
57*67e74705SXin Li   BufferStart = BufStart;
58*67e74705SXin Li   BufferPtr = BufPtr;
59*67e74705SXin Li   BufferEnd = BufEnd;
60*67e74705SXin Li 
61*67e74705SXin Li   assert(BufEnd[0] == 0 &&
62*67e74705SXin Li          "We assume that the input buffer has a null character at the end"
63*67e74705SXin Li          " to simplify lexing!");
64*67e74705SXin Li 
65*67e74705SXin Li   // Check whether we have a BOM in the beginning of the buffer. If yes - act
66*67e74705SXin Li   // accordingly. Right now we support only UTF-8 with and without BOM, so, just
67*67e74705SXin Li   // skip the UTF-8 BOM if it's present.
68*67e74705SXin Li   if (BufferStart == BufferPtr) {
69*67e74705SXin Li     // Determine the size of the BOM.
70*67e74705SXin Li     StringRef Buf(BufferStart, BufferEnd - BufferStart);
71*67e74705SXin Li     size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
72*67e74705SXin Li       .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
73*67e74705SXin Li       .Default(0);
74*67e74705SXin Li 
75*67e74705SXin Li     // Skip the BOM.
76*67e74705SXin Li     BufferPtr += BOMLength;
77*67e74705SXin Li   }
78*67e74705SXin Li 
79*67e74705SXin Li   Is_PragmaLexer = false;
80*67e74705SXin Li   CurrentConflictMarkerState = CMK_None;
81*67e74705SXin Li 
82*67e74705SXin Li   // Start of the file is a start of line.
83*67e74705SXin Li   IsAtStartOfLine = true;
84*67e74705SXin Li   IsAtPhysicalStartOfLine = true;
85*67e74705SXin Li 
86*67e74705SXin Li   HasLeadingSpace = false;
87*67e74705SXin Li   HasLeadingEmptyMacro = false;
88*67e74705SXin Li 
89*67e74705SXin Li   // We are not after parsing a #.
90*67e74705SXin Li   ParsingPreprocessorDirective = false;
91*67e74705SXin Li 
92*67e74705SXin Li   // We are not after parsing #include.
93*67e74705SXin Li   ParsingFilename = false;
94*67e74705SXin Li 
95*67e74705SXin Li   // We are not in raw mode.  Raw mode disables diagnostics and interpretation
96*67e74705SXin Li   // of tokens (e.g. identifiers, thus disabling macro expansion).  It is used
97*67e74705SXin Li   // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
98*67e74705SXin Li   // or otherwise skipping over tokens.
99*67e74705SXin Li   LexingRawMode = false;
100*67e74705SXin Li 
101*67e74705SXin Li   // Default to not keeping comments.
102*67e74705SXin Li   ExtendedTokenMode = 0;
103*67e74705SXin Li }
104*67e74705SXin Li 
105*67e74705SXin Li /// Lexer constructor - Create a new lexer object for the specified buffer
106*67e74705SXin Li /// with the specified preprocessor managing the lexing process.  This lexer
107*67e74705SXin Li /// assumes that the associated file buffer and Preprocessor objects will
108*67e74705SXin Li /// outlive it, so it doesn't take ownership of either of them.
Lexer(FileID FID,const llvm::MemoryBuffer * InputFile,Preprocessor & PP)109*67e74705SXin Li Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
110*67e74705SXin Li   : PreprocessorLexer(&PP, FID),
111*67e74705SXin Li     FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
112*67e74705SXin Li     LangOpts(PP.getLangOpts()) {
113*67e74705SXin Li 
114*67e74705SXin Li   InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
115*67e74705SXin Li             InputFile->getBufferEnd());
116*67e74705SXin Li 
117*67e74705SXin Li   resetExtendedTokenMode();
118*67e74705SXin Li }
119*67e74705SXin Li 
resetExtendedTokenMode()120*67e74705SXin Li void Lexer::resetExtendedTokenMode() {
121*67e74705SXin Li   assert(PP && "Cannot reset token mode without a preprocessor");
122*67e74705SXin Li   if (LangOpts.TraditionalCPP)
123*67e74705SXin Li     SetKeepWhitespaceMode(true);
124*67e74705SXin Li   else
125*67e74705SXin Li     SetCommentRetentionState(PP->getCommentRetentionState());
126*67e74705SXin Li }
127*67e74705SXin Li 
128*67e74705SXin Li /// Lexer constructor - Create a new raw lexer object.  This object is only
129*67e74705SXin Li /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
130*67e74705SXin Li /// range will outlive it, so it doesn't take ownership of it.
Lexer(SourceLocation fileloc,const LangOptions & langOpts,const char * BufStart,const char * BufPtr,const char * BufEnd)131*67e74705SXin Li Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
132*67e74705SXin Li              const char *BufStart, const char *BufPtr, const char *BufEnd)
133*67e74705SXin Li   : FileLoc(fileloc), LangOpts(langOpts) {
134*67e74705SXin Li 
135*67e74705SXin Li   InitLexer(BufStart, BufPtr, BufEnd);
136*67e74705SXin Li 
137*67e74705SXin Li   // We *are* in raw mode.
138*67e74705SXin Li   LexingRawMode = true;
139*67e74705SXin Li }
140*67e74705SXin Li 
141*67e74705SXin Li /// Lexer constructor - Create a new raw lexer object.  This object is only
142*67e74705SXin Li /// suitable for calls to 'LexFromRawLexer'.  This lexer assumes that the text
143*67e74705SXin Li /// range will outlive it, so it doesn't take ownership of it.
Lexer(FileID FID,const llvm::MemoryBuffer * FromFile,const SourceManager & SM,const LangOptions & langOpts)144*67e74705SXin Li Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
145*67e74705SXin Li              const SourceManager &SM, const LangOptions &langOpts)
146*67e74705SXin Li     : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
147*67e74705SXin Li             FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
148*67e74705SXin Li 
149*67e74705SXin Li /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
150*67e74705SXin Li /// _Pragma expansion.  This has a variety of magic semantics that this method
151*67e74705SXin Li /// sets up.  It returns a new'd Lexer that must be delete'd when done.
152*67e74705SXin Li ///
153*67e74705SXin Li /// On entrance to this routine, TokStartLoc is a macro location which has a
154*67e74705SXin Li /// spelling loc that indicates the bytes to be lexed for the token and an
155*67e74705SXin Li /// expansion location that indicates where all lexed tokens should be
156*67e74705SXin Li /// "expanded from".
157*67e74705SXin Li ///
158*67e74705SXin Li /// TODO: It would really be nice to make _Pragma just be a wrapper around a
159*67e74705SXin Li /// normal lexer that remaps tokens as they fly by.  This would require making
160*67e74705SXin Li /// Preprocessor::Lex virtual.  Given that, we could just dump in a magic lexer
161*67e74705SXin Li /// interface that could handle this stuff.  This would pull GetMappedTokenLoc
162*67e74705SXin Li /// out of the critical path of the lexer!
163*67e74705SXin Li ///
Create_PragmaLexer(SourceLocation SpellingLoc,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd,unsigned TokLen,Preprocessor & PP)164*67e74705SXin Li Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
165*67e74705SXin Li                                  SourceLocation ExpansionLocStart,
166*67e74705SXin Li                                  SourceLocation ExpansionLocEnd,
167*67e74705SXin Li                                  unsigned TokLen, Preprocessor &PP) {
168*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
169*67e74705SXin Li 
170*67e74705SXin Li   // Create the lexer as if we were going to lex the file normally.
171*67e74705SXin Li   FileID SpellingFID = SM.getFileID(SpellingLoc);
172*67e74705SXin Li   const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
173*67e74705SXin Li   Lexer *L = new Lexer(SpellingFID, InputFile, PP);
174*67e74705SXin Li 
175*67e74705SXin Li   // Now that the lexer is created, change the start/end locations so that we
176*67e74705SXin Li   // just lex the subsection of the file that we want.  This is lexing from a
177*67e74705SXin Li   // scratch buffer.
178*67e74705SXin Li   const char *StrData = SM.getCharacterData(SpellingLoc);
179*67e74705SXin Li 
180*67e74705SXin Li   L->BufferPtr = StrData;
181*67e74705SXin Li   L->BufferEnd = StrData+TokLen;
182*67e74705SXin Li   assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
183*67e74705SXin Li 
184*67e74705SXin Li   // Set the SourceLocation with the remapping information.  This ensures that
185*67e74705SXin Li   // GetMappedTokenLoc will remap the tokens as they are lexed.
186*67e74705SXin Li   L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
187*67e74705SXin Li                                      ExpansionLocStart,
188*67e74705SXin Li                                      ExpansionLocEnd, TokLen);
189*67e74705SXin Li 
190*67e74705SXin Li   // Ensure that the lexer thinks it is inside a directive, so that end \n will
191*67e74705SXin Li   // return an EOD token.
192*67e74705SXin Li   L->ParsingPreprocessorDirective = true;
193*67e74705SXin Li 
194*67e74705SXin Li   // This lexer really is for _Pragma.
195*67e74705SXin Li   L->Is_PragmaLexer = true;
196*67e74705SXin Li   return L;
197*67e74705SXin Li }
198*67e74705SXin Li 
199*67e74705SXin Li 
200*67e74705SXin Li /// Stringify - Convert the specified string into a C string, with surrounding
201*67e74705SXin Li /// ""'s, and with escaped \ and " characters.
Stringify(StringRef Str,bool Charify)202*67e74705SXin Li std::string Lexer::Stringify(StringRef Str, bool Charify) {
203*67e74705SXin Li   std::string Result = Str;
204*67e74705SXin Li   char Quote = Charify ? '\'' : '"';
205*67e74705SXin Li   for (unsigned i = 0, e = Result.size(); i != e; ++i) {
206*67e74705SXin Li     if (Result[i] == '\\' || Result[i] == Quote) {
207*67e74705SXin Li       Result.insert(Result.begin()+i, '\\');
208*67e74705SXin Li       ++i; ++e;
209*67e74705SXin Li     }
210*67e74705SXin Li   }
211*67e74705SXin Li   return Result;
212*67e74705SXin Li }
213*67e74705SXin Li 
214*67e74705SXin Li /// Stringify - Convert the specified string into a C string by escaping '\'
215*67e74705SXin Li /// and " characters.  This does not add surrounding ""'s to the string.
Stringify(SmallVectorImpl<char> & Str)216*67e74705SXin Li void Lexer::Stringify(SmallVectorImpl<char> &Str) {
217*67e74705SXin Li   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
218*67e74705SXin Li     if (Str[i] == '\\' || Str[i] == '"') {
219*67e74705SXin Li       Str.insert(Str.begin()+i, '\\');
220*67e74705SXin Li       ++i; ++e;
221*67e74705SXin Li     }
222*67e74705SXin Li   }
223*67e74705SXin Li }
224*67e74705SXin Li 
225*67e74705SXin Li //===----------------------------------------------------------------------===//
226*67e74705SXin Li // Token Spelling
227*67e74705SXin Li //===----------------------------------------------------------------------===//
228*67e74705SXin Li 
229*67e74705SXin Li /// \brief Slow case of getSpelling. Extract the characters comprising the
230*67e74705SXin Li /// spelling of this token from the provided input buffer.
getSpellingSlow(const Token & Tok,const char * BufPtr,const LangOptions & LangOpts,char * Spelling)231*67e74705SXin Li static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
232*67e74705SXin Li                               const LangOptions &LangOpts, char *Spelling) {
233*67e74705SXin Li   assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
234*67e74705SXin Li 
235*67e74705SXin Li   size_t Length = 0;
236*67e74705SXin Li   const char *BufEnd = BufPtr + Tok.getLength();
237*67e74705SXin Li 
238*67e74705SXin Li   if (tok::isStringLiteral(Tok.getKind())) {
239*67e74705SXin Li     // Munch the encoding-prefix and opening double-quote.
240*67e74705SXin Li     while (BufPtr < BufEnd) {
241*67e74705SXin Li       unsigned Size;
242*67e74705SXin Li       Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
243*67e74705SXin Li       BufPtr += Size;
244*67e74705SXin Li 
245*67e74705SXin Li       if (Spelling[Length - 1] == '"')
246*67e74705SXin Li         break;
247*67e74705SXin Li     }
248*67e74705SXin Li 
249*67e74705SXin Li     // Raw string literals need special handling; trigraph expansion and line
250*67e74705SXin Li     // splicing do not occur within their d-char-sequence nor within their
251*67e74705SXin Li     // r-char-sequence.
252*67e74705SXin Li     if (Length >= 2 &&
253*67e74705SXin Li         Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
254*67e74705SXin Li       // Search backwards from the end of the token to find the matching closing
255*67e74705SXin Li       // quote.
256*67e74705SXin Li       const char *RawEnd = BufEnd;
257*67e74705SXin Li       do --RawEnd; while (*RawEnd != '"');
258*67e74705SXin Li       size_t RawLength = RawEnd - BufPtr + 1;
259*67e74705SXin Li 
260*67e74705SXin Li       // Everything between the quotes is included verbatim in the spelling.
261*67e74705SXin Li       memcpy(Spelling + Length, BufPtr, RawLength);
262*67e74705SXin Li       Length += RawLength;
263*67e74705SXin Li       BufPtr += RawLength;
264*67e74705SXin Li 
265*67e74705SXin Li       // The rest of the token is lexed normally.
266*67e74705SXin Li     }
267*67e74705SXin Li   }
268*67e74705SXin Li 
269*67e74705SXin Li   while (BufPtr < BufEnd) {
270*67e74705SXin Li     unsigned Size;
271*67e74705SXin Li     Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
272*67e74705SXin Li     BufPtr += Size;
273*67e74705SXin Li   }
274*67e74705SXin Li 
275*67e74705SXin Li   assert(Length < Tok.getLength() &&
276*67e74705SXin Li          "NeedsCleaning flag set on token that didn't need cleaning!");
277*67e74705SXin Li   return Length;
278*67e74705SXin Li }
279*67e74705SXin Li 
280*67e74705SXin Li /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
281*67e74705SXin Li /// token are the characters used to represent the token in the source file
282*67e74705SXin Li /// after trigraph expansion and escaped-newline folding.  In particular, this
283*67e74705SXin Li /// wants to get the true, uncanonicalized, spelling of things like digraphs
284*67e74705SXin Li /// UCNs, etc.
getSpelling(SourceLocation loc,SmallVectorImpl<char> & buffer,const SourceManager & SM,const LangOptions & options,bool * invalid)285*67e74705SXin Li StringRef Lexer::getSpelling(SourceLocation loc,
286*67e74705SXin Li                              SmallVectorImpl<char> &buffer,
287*67e74705SXin Li                              const SourceManager &SM,
288*67e74705SXin Li                              const LangOptions &options,
289*67e74705SXin Li                              bool *invalid) {
290*67e74705SXin Li   // Break down the source location.
291*67e74705SXin Li   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
292*67e74705SXin Li 
293*67e74705SXin Li   // Try to the load the file buffer.
294*67e74705SXin Li   bool invalidTemp = false;
295*67e74705SXin Li   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
296*67e74705SXin Li   if (invalidTemp) {
297*67e74705SXin Li     if (invalid) *invalid = true;
298*67e74705SXin Li     return StringRef();
299*67e74705SXin Li   }
300*67e74705SXin Li 
301*67e74705SXin Li   const char *tokenBegin = file.data() + locInfo.second;
302*67e74705SXin Li 
303*67e74705SXin Li   // Lex from the start of the given location.
304*67e74705SXin Li   Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
305*67e74705SXin Li               file.begin(), tokenBegin, file.end());
306*67e74705SXin Li   Token token;
307*67e74705SXin Li   lexer.LexFromRawLexer(token);
308*67e74705SXin Li 
309*67e74705SXin Li   unsigned length = token.getLength();
310*67e74705SXin Li 
311*67e74705SXin Li   // Common case:  no need for cleaning.
312*67e74705SXin Li   if (!token.needsCleaning())
313*67e74705SXin Li     return StringRef(tokenBegin, length);
314*67e74705SXin Li 
315*67e74705SXin Li   // Hard case, we need to relex the characters into the string.
316*67e74705SXin Li   buffer.resize(length);
317*67e74705SXin Li   buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
318*67e74705SXin Li   return StringRef(buffer.data(), buffer.size());
319*67e74705SXin Li }
320*67e74705SXin Li 
321*67e74705SXin Li /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
322*67e74705SXin Li /// token are the characters used to represent the token in the source file
323*67e74705SXin Li /// after trigraph expansion and escaped-newline folding.  In particular, this
324*67e74705SXin Li /// wants to get the true, uncanonicalized, spelling of things like digraphs
325*67e74705SXin Li /// UCNs, etc.
getSpelling(const Token & Tok,const SourceManager & SourceMgr,const LangOptions & LangOpts,bool * Invalid)326*67e74705SXin Li std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
327*67e74705SXin Li                                const LangOptions &LangOpts, bool *Invalid) {
328*67e74705SXin Li   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
329*67e74705SXin Li 
330*67e74705SXin Li   bool CharDataInvalid = false;
331*67e74705SXin Li   const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
332*67e74705SXin Li                                                     &CharDataInvalid);
333*67e74705SXin Li   if (Invalid)
334*67e74705SXin Li     *Invalid = CharDataInvalid;
335*67e74705SXin Li   if (CharDataInvalid)
336*67e74705SXin Li     return std::string();
337*67e74705SXin Li 
338*67e74705SXin Li   // If this token contains nothing interesting, return it directly.
339*67e74705SXin Li   if (!Tok.needsCleaning())
340*67e74705SXin Li     return std::string(TokStart, TokStart + Tok.getLength());
341*67e74705SXin Li 
342*67e74705SXin Li   std::string Result;
343*67e74705SXin Li   Result.resize(Tok.getLength());
344*67e74705SXin Li   Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
345*67e74705SXin Li   return Result;
346*67e74705SXin Li }
347*67e74705SXin Li 
348*67e74705SXin Li /// getSpelling - This method is used to get the spelling of a token into a
349*67e74705SXin Li /// preallocated buffer, instead of as an std::string.  The caller is required
350*67e74705SXin Li /// to allocate enough space for the token, which is guaranteed to be at least
351*67e74705SXin Li /// Tok.getLength() bytes long.  The actual length of the token is returned.
352*67e74705SXin Li ///
353*67e74705SXin Li /// Note that this method may do two possible things: it may either fill in
354*67e74705SXin Li /// the buffer specified with characters, or it may *change the input pointer*
355*67e74705SXin Li /// to point to a constant buffer with the data already in it (avoiding a
356*67e74705SXin Li /// copy).  The caller is not allowed to modify the returned buffer pointer
357*67e74705SXin Li /// if an internal buffer is returned.
getSpelling(const Token & Tok,const char * & Buffer,const SourceManager & SourceMgr,const LangOptions & LangOpts,bool * Invalid)358*67e74705SXin Li unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
359*67e74705SXin Li                             const SourceManager &SourceMgr,
360*67e74705SXin Li                             const LangOptions &LangOpts, bool *Invalid) {
361*67e74705SXin Li   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
362*67e74705SXin Li 
363*67e74705SXin Li   const char *TokStart = nullptr;
364*67e74705SXin Li   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
365*67e74705SXin Li   if (Tok.is(tok::raw_identifier))
366*67e74705SXin Li     TokStart = Tok.getRawIdentifier().data();
367*67e74705SXin Li   else if (!Tok.hasUCN()) {
368*67e74705SXin Li     if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
369*67e74705SXin Li       // Just return the string from the identifier table, which is very quick.
370*67e74705SXin Li       Buffer = II->getNameStart();
371*67e74705SXin Li       return II->getLength();
372*67e74705SXin Li     }
373*67e74705SXin Li   }
374*67e74705SXin Li 
375*67e74705SXin Li   // NOTE: this can be checked even after testing for an IdentifierInfo.
376*67e74705SXin Li   if (Tok.isLiteral())
377*67e74705SXin Li     TokStart = Tok.getLiteralData();
378*67e74705SXin Li 
379*67e74705SXin Li   if (!TokStart) {
380*67e74705SXin Li     // Compute the start of the token in the input lexer buffer.
381*67e74705SXin Li     bool CharDataInvalid = false;
382*67e74705SXin Li     TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
383*67e74705SXin Li     if (Invalid)
384*67e74705SXin Li       *Invalid = CharDataInvalid;
385*67e74705SXin Li     if (CharDataInvalid) {
386*67e74705SXin Li       Buffer = "";
387*67e74705SXin Li       return 0;
388*67e74705SXin Li     }
389*67e74705SXin Li   }
390*67e74705SXin Li 
391*67e74705SXin Li   // If this token contains nothing interesting, return it directly.
392*67e74705SXin Li   if (!Tok.needsCleaning()) {
393*67e74705SXin Li     Buffer = TokStart;
394*67e74705SXin Li     return Tok.getLength();
395*67e74705SXin Li   }
396*67e74705SXin Li 
397*67e74705SXin Li   // Otherwise, hard case, relex the characters into the string.
398*67e74705SXin Li   return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
399*67e74705SXin Li }
400*67e74705SXin Li 
401*67e74705SXin Li 
402*67e74705SXin Li /// MeasureTokenLength - Relex the token at the specified location and return
403*67e74705SXin Li /// its length in bytes in the input file.  If the token needs cleaning (e.g.
404*67e74705SXin Li /// includes a trigraph or an escaped newline) then this count includes bytes
405*67e74705SXin Li /// that are part of that.
MeasureTokenLength(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)406*67e74705SXin Li unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
407*67e74705SXin Li                                    const SourceManager &SM,
408*67e74705SXin Li                                    const LangOptions &LangOpts) {
409*67e74705SXin Li   Token TheTok;
410*67e74705SXin Li   if (getRawToken(Loc, TheTok, SM, LangOpts))
411*67e74705SXin Li     return 0;
412*67e74705SXin Li   return TheTok.getLength();
413*67e74705SXin Li }
414*67e74705SXin Li 
415*67e74705SXin Li /// \brief Relex the token at the specified location.
416*67e74705SXin Li /// \returns true if there was a failure, false on success.
getRawToken(SourceLocation Loc,Token & Result,const SourceManager & SM,const LangOptions & LangOpts,bool IgnoreWhiteSpace)417*67e74705SXin Li bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
418*67e74705SXin Li                         const SourceManager &SM,
419*67e74705SXin Li                         const LangOptions &LangOpts,
420*67e74705SXin Li                         bool IgnoreWhiteSpace) {
421*67e74705SXin Li   // TODO: this could be special cased for common tokens like identifiers, ')',
422*67e74705SXin Li   // etc to make this faster, if it mattered.  Just look at StrData[0] to handle
423*67e74705SXin Li   // all obviously single-char tokens.  This could use
424*67e74705SXin Li   // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
425*67e74705SXin Li   // something.
426*67e74705SXin Li 
427*67e74705SXin Li   // If this comes from a macro expansion, we really do want the macro name, not
428*67e74705SXin Li   // the token this macro expanded to.
429*67e74705SXin Li   Loc = SM.getExpansionLoc(Loc);
430*67e74705SXin Li   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
431*67e74705SXin Li   bool Invalid = false;
432*67e74705SXin Li   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
433*67e74705SXin Li   if (Invalid)
434*67e74705SXin Li     return true;
435*67e74705SXin Li 
436*67e74705SXin Li   const char *StrData = Buffer.data()+LocInfo.second;
437*67e74705SXin Li 
438*67e74705SXin Li   if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
439*67e74705SXin Li     return true;
440*67e74705SXin Li 
441*67e74705SXin Li   // Create a lexer starting at the beginning of this token.
442*67e74705SXin Li   Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
443*67e74705SXin Li                  Buffer.begin(), StrData, Buffer.end());
444*67e74705SXin Li   TheLexer.SetCommentRetentionState(true);
445*67e74705SXin Li   TheLexer.LexFromRawLexer(Result);
446*67e74705SXin Li   return false;
447*67e74705SXin Li }
448*67e74705SXin Li 
getBeginningOfFileToken(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)449*67e74705SXin Li static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
450*67e74705SXin Li                                               const SourceManager &SM,
451*67e74705SXin Li                                               const LangOptions &LangOpts) {
452*67e74705SXin Li   assert(Loc.isFileID());
453*67e74705SXin Li   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
454*67e74705SXin Li   if (LocInfo.first.isInvalid())
455*67e74705SXin Li     return Loc;
456*67e74705SXin Li 
457*67e74705SXin Li   bool Invalid = false;
458*67e74705SXin Li   StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
459*67e74705SXin Li   if (Invalid)
460*67e74705SXin Li     return Loc;
461*67e74705SXin Li 
462*67e74705SXin Li   // Back up from the current location until we hit the beginning of a line
463*67e74705SXin Li   // (or the buffer). We'll relex from that point.
464*67e74705SXin Li   const char *BufStart = Buffer.data();
465*67e74705SXin Li   if (LocInfo.second >= Buffer.size())
466*67e74705SXin Li     return Loc;
467*67e74705SXin Li 
468*67e74705SXin Li   const char *StrData = BufStart+LocInfo.second;
469*67e74705SXin Li   if (StrData[0] == '\n' || StrData[0] == '\r')
470*67e74705SXin Li     return Loc;
471*67e74705SXin Li 
472*67e74705SXin Li   const char *LexStart = StrData;
473*67e74705SXin Li   while (LexStart != BufStart) {
474*67e74705SXin Li     if (LexStart[0] == '\n' || LexStart[0] == '\r') {
475*67e74705SXin Li       ++LexStart;
476*67e74705SXin Li       break;
477*67e74705SXin Li     }
478*67e74705SXin Li 
479*67e74705SXin Li     --LexStart;
480*67e74705SXin Li   }
481*67e74705SXin Li 
482*67e74705SXin Li   // Create a lexer starting at the beginning of this token.
483*67e74705SXin Li   SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
484*67e74705SXin Li   Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
485*67e74705SXin Li   TheLexer.SetCommentRetentionState(true);
486*67e74705SXin Li 
487*67e74705SXin Li   // Lex tokens until we find the token that contains the source location.
488*67e74705SXin Li   Token TheTok;
489*67e74705SXin Li   do {
490*67e74705SXin Li     TheLexer.LexFromRawLexer(TheTok);
491*67e74705SXin Li 
492*67e74705SXin Li     if (TheLexer.getBufferLocation() > StrData) {
493*67e74705SXin Li       // Lexing this token has taken the lexer past the source location we're
494*67e74705SXin Li       // looking for. If the current token encompasses our source location,
495*67e74705SXin Li       // return the beginning of that token.
496*67e74705SXin Li       if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
497*67e74705SXin Li         return TheTok.getLocation();
498*67e74705SXin Li 
499*67e74705SXin Li       // We ended up skipping over the source location entirely, which means
500*67e74705SXin Li       // that it points into whitespace. We're done here.
501*67e74705SXin Li       break;
502*67e74705SXin Li     }
503*67e74705SXin Li   } while (TheTok.getKind() != tok::eof);
504*67e74705SXin Li 
505*67e74705SXin Li   // We've passed our source location; just return the original source location.
506*67e74705SXin Li   return Loc;
507*67e74705SXin Li }
508*67e74705SXin Li 
GetBeginningOfToken(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)509*67e74705SXin Li SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
510*67e74705SXin Li                                           const SourceManager &SM,
511*67e74705SXin Li                                           const LangOptions &LangOpts) {
512*67e74705SXin Li  if (Loc.isFileID())
513*67e74705SXin Li    return getBeginningOfFileToken(Loc, SM, LangOpts);
514*67e74705SXin Li 
515*67e74705SXin Li  if (!SM.isMacroArgExpansion(Loc))
516*67e74705SXin Li    return Loc;
517*67e74705SXin Li 
518*67e74705SXin Li  SourceLocation FileLoc = SM.getSpellingLoc(Loc);
519*67e74705SXin Li  SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
520*67e74705SXin Li  std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
521*67e74705SXin Li  std::pair<FileID, unsigned> BeginFileLocInfo
522*67e74705SXin Li    = SM.getDecomposedLoc(BeginFileLoc);
523*67e74705SXin Li  assert(FileLocInfo.first == BeginFileLocInfo.first &&
524*67e74705SXin Li         FileLocInfo.second >= BeginFileLocInfo.second);
525*67e74705SXin Li  return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
526*67e74705SXin Li }
527*67e74705SXin Li 
528*67e74705SXin Li namespace {
529*67e74705SXin Li   enum PreambleDirectiveKind {
530*67e74705SXin Li     PDK_Skipped,
531*67e74705SXin Li     PDK_StartIf,
532*67e74705SXin Li     PDK_EndIf,
533*67e74705SXin Li     PDK_Unknown
534*67e74705SXin Li   };
535*67e74705SXin Li }
536*67e74705SXin Li 
ComputePreamble(StringRef Buffer,const LangOptions & LangOpts,unsigned MaxLines)537*67e74705SXin Li std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
538*67e74705SXin Li                                                  const LangOptions &LangOpts,
539*67e74705SXin Li                                                  unsigned MaxLines) {
540*67e74705SXin Li   // Create a lexer starting at the beginning of the file. Note that we use a
541*67e74705SXin Li   // "fake" file source location at offset 1 so that the lexer will track our
542*67e74705SXin Li   // position within the file.
543*67e74705SXin Li   const unsigned StartOffset = 1;
544*67e74705SXin Li   SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
545*67e74705SXin Li   Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
546*67e74705SXin Li                  Buffer.end());
547*67e74705SXin Li   TheLexer.SetCommentRetentionState(true);
548*67e74705SXin Li 
549*67e74705SXin Li   // StartLoc will differ from FileLoc if there is a BOM that was skipped.
550*67e74705SXin Li   SourceLocation StartLoc = TheLexer.getSourceLocation();
551*67e74705SXin Li 
552*67e74705SXin Li   bool InPreprocessorDirective = false;
553*67e74705SXin Li   Token TheTok;
554*67e74705SXin Li   Token IfStartTok;
555*67e74705SXin Li   unsigned IfCount = 0;
556*67e74705SXin Li   SourceLocation ActiveCommentLoc;
557*67e74705SXin Li 
558*67e74705SXin Li   unsigned MaxLineOffset = 0;
559*67e74705SXin Li   if (MaxLines) {
560*67e74705SXin Li     const char *CurPtr = Buffer.begin();
561*67e74705SXin Li     unsigned CurLine = 0;
562*67e74705SXin Li     while (CurPtr != Buffer.end()) {
563*67e74705SXin Li       char ch = *CurPtr++;
564*67e74705SXin Li       if (ch == '\n') {
565*67e74705SXin Li         ++CurLine;
566*67e74705SXin Li         if (CurLine == MaxLines)
567*67e74705SXin Li           break;
568*67e74705SXin Li       }
569*67e74705SXin Li     }
570*67e74705SXin Li     if (CurPtr != Buffer.end())
571*67e74705SXin Li       MaxLineOffset = CurPtr - Buffer.begin();
572*67e74705SXin Li   }
573*67e74705SXin Li 
574*67e74705SXin Li   do {
575*67e74705SXin Li     TheLexer.LexFromRawLexer(TheTok);
576*67e74705SXin Li 
577*67e74705SXin Li     if (InPreprocessorDirective) {
578*67e74705SXin Li       // If we've hit the end of the file, we're done.
579*67e74705SXin Li       if (TheTok.getKind() == tok::eof) {
580*67e74705SXin Li         break;
581*67e74705SXin Li       }
582*67e74705SXin Li 
583*67e74705SXin Li       // If we haven't hit the end of the preprocessor directive, skip this
584*67e74705SXin Li       // token.
585*67e74705SXin Li       if (!TheTok.isAtStartOfLine())
586*67e74705SXin Li         continue;
587*67e74705SXin Li 
588*67e74705SXin Li       // We've passed the end of the preprocessor directive, and will look
589*67e74705SXin Li       // at this token again below.
590*67e74705SXin Li       InPreprocessorDirective = false;
591*67e74705SXin Li     }
592*67e74705SXin Li 
593*67e74705SXin Li     // Keep track of the # of lines in the preamble.
594*67e74705SXin Li     if (TheTok.isAtStartOfLine()) {
595*67e74705SXin Li       unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
596*67e74705SXin Li 
597*67e74705SXin Li       // If we were asked to limit the number of lines in the preamble,
598*67e74705SXin Li       // and we're about to exceed that limit, we're done.
599*67e74705SXin Li       if (MaxLineOffset && TokOffset >= MaxLineOffset)
600*67e74705SXin Li         break;
601*67e74705SXin Li     }
602*67e74705SXin Li 
603*67e74705SXin Li     // Comments are okay; skip over them.
604*67e74705SXin Li     if (TheTok.getKind() == tok::comment) {
605*67e74705SXin Li       if (ActiveCommentLoc.isInvalid())
606*67e74705SXin Li         ActiveCommentLoc = TheTok.getLocation();
607*67e74705SXin Li       continue;
608*67e74705SXin Li     }
609*67e74705SXin Li 
610*67e74705SXin Li     if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
611*67e74705SXin Li       // This is the start of a preprocessor directive.
612*67e74705SXin Li       Token HashTok = TheTok;
613*67e74705SXin Li       InPreprocessorDirective = true;
614*67e74705SXin Li       ActiveCommentLoc = SourceLocation();
615*67e74705SXin Li 
616*67e74705SXin Li       // Figure out which directive this is. Since we're lexing raw tokens,
617*67e74705SXin Li       // we don't have an identifier table available. Instead, just look at
618*67e74705SXin Li       // the raw identifier to recognize and categorize preprocessor directives.
619*67e74705SXin Li       TheLexer.LexFromRawLexer(TheTok);
620*67e74705SXin Li       if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
621*67e74705SXin Li         StringRef Keyword = TheTok.getRawIdentifier();
622*67e74705SXin Li         PreambleDirectiveKind PDK
623*67e74705SXin Li           = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
624*67e74705SXin Li               .Case("include", PDK_Skipped)
625*67e74705SXin Li               .Case("__include_macros", PDK_Skipped)
626*67e74705SXin Li               .Case("define", PDK_Skipped)
627*67e74705SXin Li               .Case("undef", PDK_Skipped)
628*67e74705SXin Li               .Case("line", PDK_Skipped)
629*67e74705SXin Li               .Case("error", PDK_Skipped)
630*67e74705SXin Li               .Case("pragma", PDK_Skipped)
631*67e74705SXin Li               .Case("import", PDK_Skipped)
632*67e74705SXin Li               .Case("include_next", PDK_Skipped)
633*67e74705SXin Li               .Case("warning", PDK_Skipped)
634*67e74705SXin Li               .Case("ident", PDK_Skipped)
635*67e74705SXin Li               .Case("sccs", PDK_Skipped)
636*67e74705SXin Li               .Case("assert", PDK_Skipped)
637*67e74705SXin Li               .Case("unassert", PDK_Skipped)
638*67e74705SXin Li               .Case("if", PDK_StartIf)
639*67e74705SXin Li               .Case("ifdef", PDK_StartIf)
640*67e74705SXin Li               .Case("ifndef", PDK_StartIf)
641*67e74705SXin Li               .Case("elif", PDK_Skipped)
642*67e74705SXin Li               .Case("else", PDK_Skipped)
643*67e74705SXin Li               .Case("endif", PDK_EndIf)
644*67e74705SXin Li               .Default(PDK_Unknown);
645*67e74705SXin Li 
646*67e74705SXin Li         switch (PDK) {
647*67e74705SXin Li         case PDK_Skipped:
648*67e74705SXin Li           continue;
649*67e74705SXin Li 
650*67e74705SXin Li         case PDK_StartIf:
651*67e74705SXin Li           if (IfCount == 0)
652*67e74705SXin Li             IfStartTok = HashTok;
653*67e74705SXin Li 
654*67e74705SXin Li           ++IfCount;
655*67e74705SXin Li           continue;
656*67e74705SXin Li 
657*67e74705SXin Li         case PDK_EndIf:
658*67e74705SXin Li           // Mismatched #endif. The preamble ends here.
659*67e74705SXin Li           if (IfCount == 0)
660*67e74705SXin Li             break;
661*67e74705SXin Li 
662*67e74705SXin Li           --IfCount;
663*67e74705SXin Li           continue;
664*67e74705SXin Li 
665*67e74705SXin Li         case PDK_Unknown:
666*67e74705SXin Li           // We don't know what this directive is; stop at the '#'.
667*67e74705SXin Li           break;
668*67e74705SXin Li         }
669*67e74705SXin Li       }
670*67e74705SXin Li 
671*67e74705SXin Li       // We only end up here if we didn't recognize the preprocessor
672*67e74705SXin Li       // directive or it was one that can't occur in the preamble at this
673*67e74705SXin Li       // point. Roll back the current token to the location of the '#'.
674*67e74705SXin Li       InPreprocessorDirective = false;
675*67e74705SXin Li       TheTok = HashTok;
676*67e74705SXin Li     }
677*67e74705SXin Li 
678*67e74705SXin Li     // We hit a token that we don't recognize as being in the
679*67e74705SXin Li     // "preprocessing only" part of the file, so we're no longer in
680*67e74705SXin Li     // the preamble.
681*67e74705SXin Li     break;
682*67e74705SXin Li   } while (true);
683*67e74705SXin Li 
684*67e74705SXin Li   SourceLocation End;
685*67e74705SXin Li   if (IfCount)
686*67e74705SXin Li     End = IfStartTok.getLocation();
687*67e74705SXin Li   else if (ActiveCommentLoc.isValid())
688*67e74705SXin Li     End = ActiveCommentLoc; // don't truncate a decl comment.
689*67e74705SXin Li   else
690*67e74705SXin Li     End = TheTok.getLocation();
691*67e74705SXin Li 
692*67e74705SXin Li   return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
693*67e74705SXin Li                         IfCount? IfStartTok.isAtStartOfLine()
694*67e74705SXin Li                                : TheTok.isAtStartOfLine());
695*67e74705SXin Li }
696*67e74705SXin Li 
697*67e74705SXin Li 
698*67e74705SXin Li /// AdvanceToTokenCharacter - Given a location that specifies the start of a
699*67e74705SXin Li /// token, return a new location that specifies a character within the token.
AdvanceToTokenCharacter(SourceLocation TokStart,unsigned CharNo,const SourceManager & SM,const LangOptions & LangOpts)700*67e74705SXin Li SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
701*67e74705SXin Li                                               unsigned CharNo,
702*67e74705SXin Li                                               const SourceManager &SM,
703*67e74705SXin Li                                               const LangOptions &LangOpts) {
704*67e74705SXin Li   // Figure out how many physical characters away the specified expansion
705*67e74705SXin Li   // character is.  This needs to take into consideration newlines and
706*67e74705SXin Li   // trigraphs.
707*67e74705SXin Li   bool Invalid = false;
708*67e74705SXin Li   const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
709*67e74705SXin Li 
710*67e74705SXin Li   // If they request the first char of the token, we're trivially done.
711*67e74705SXin Li   if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
712*67e74705SXin Li     return TokStart;
713*67e74705SXin Li 
714*67e74705SXin Li   unsigned PhysOffset = 0;
715*67e74705SXin Li 
716*67e74705SXin Li   // The usual case is that tokens don't contain anything interesting.  Skip
717*67e74705SXin Li   // over the uninteresting characters.  If a token only consists of simple
718*67e74705SXin Li   // chars, this method is extremely fast.
719*67e74705SXin Li   while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
720*67e74705SXin Li     if (CharNo == 0)
721*67e74705SXin Li       return TokStart.getLocWithOffset(PhysOffset);
722*67e74705SXin Li     ++TokPtr;
723*67e74705SXin Li     --CharNo;
724*67e74705SXin Li     ++PhysOffset;
725*67e74705SXin Li   }
726*67e74705SXin Li 
727*67e74705SXin Li   // If we have a character that may be a trigraph or escaped newline, use a
728*67e74705SXin Li   // lexer to parse it correctly.
729*67e74705SXin Li   for (; CharNo; --CharNo) {
730*67e74705SXin Li     unsigned Size;
731*67e74705SXin Li     Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
732*67e74705SXin Li     TokPtr += Size;
733*67e74705SXin Li     PhysOffset += Size;
734*67e74705SXin Li   }
735*67e74705SXin Li 
736*67e74705SXin Li   // Final detail: if we end up on an escaped newline, we want to return the
737*67e74705SXin Li   // location of the actual byte of the token.  For example foo\<newline>bar
738*67e74705SXin Li   // advanced by 3 should return the location of b, not of \\.  One compounding
739*67e74705SXin Li   // detail of this is that the escape may be made by a trigraph.
740*67e74705SXin Li   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
741*67e74705SXin Li     PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
742*67e74705SXin Li 
743*67e74705SXin Li   return TokStart.getLocWithOffset(PhysOffset);
744*67e74705SXin Li }
745*67e74705SXin Li 
746*67e74705SXin Li /// \brief Computes the source location just past the end of the
747*67e74705SXin Li /// token at this source location.
748*67e74705SXin Li ///
749*67e74705SXin Li /// This routine can be used to produce a source location that
750*67e74705SXin Li /// points just past the end of the token referenced by \p Loc, and
751*67e74705SXin Li /// is generally used when a diagnostic needs to point just after a
752*67e74705SXin Li /// token where it expected something different that it received. If
753*67e74705SXin Li /// the returned source location would not be meaningful (e.g., if
754*67e74705SXin Li /// it points into a macro), this routine returns an invalid
755*67e74705SXin Li /// source location.
756*67e74705SXin Li ///
757*67e74705SXin Li /// \param Offset an offset from the end of the token, where the source
758*67e74705SXin Li /// location should refer to. The default offset (0) produces a source
759*67e74705SXin Li /// location pointing just past the end of the token; an offset of 1 produces
760*67e74705SXin Li /// a source location pointing to the last character in the token, etc.
getLocForEndOfToken(SourceLocation Loc,unsigned Offset,const SourceManager & SM,const LangOptions & LangOpts)761*67e74705SXin Li SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
762*67e74705SXin Li                                           const SourceManager &SM,
763*67e74705SXin Li                                           const LangOptions &LangOpts) {
764*67e74705SXin Li   if (Loc.isInvalid())
765*67e74705SXin Li     return SourceLocation();
766*67e74705SXin Li 
767*67e74705SXin Li   if (Loc.isMacroID()) {
768*67e74705SXin Li     if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
769*67e74705SXin Li       return SourceLocation(); // Points inside the macro expansion.
770*67e74705SXin Li   }
771*67e74705SXin Li 
772*67e74705SXin Li   unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
773*67e74705SXin Li   if (Len > Offset)
774*67e74705SXin Li     Len = Len - Offset;
775*67e74705SXin Li   else
776*67e74705SXin Li     return Loc;
777*67e74705SXin Li 
778*67e74705SXin Li   return Loc.getLocWithOffset(Len);
779*67e74705SXin Li }
780*67e74705SXin Li 
781*67e74705SXin Li /// \brief Returns true if the given MacroID location points at the first
782*67e74705SXin Li /// token of the macro expansion.
isAtStartOfMacroExpansion(SourceLocation loc,const SourceManager & SM,const LangOptions & LangOpts,SourceLocation * MacroBegin)783*67e74705SXin Li bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
784*67e74705SXin Li                                       const SourceManager &SM,
785*67e74705SXin Li                                       const LangOptions &LangOpts,
786*67e74705SXin Li                                       SourceLocation *MacroBegin) {
787*67e74705SXin Li   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
788*67e74705SXin Li 
789*67e74705SXin Li   SourceLocation expansionLoc;
790*67e74705SXin Li   if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
791*67e74705SXin Li     return false;
792*67e74705SXin Li 
793*67e74705SXin Li   if (expansionLoc.isFileID()) {
794*67e74705SXin Li     // No other macro expansions, this is the first.
795*67e74705SXin Li     if (MacroBegin)
796*67e74705SXin Li       *MacroBegin = expansionLoc;
797*67e74705SXin Li     return true;
798*67e74705SXin Li   }
799*67e74705SXin Li 
800*67e74705SXin Li   return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
801*67e74705SXin Li }
802*67e74705SXin Li 
803*67e74705SXin Li /// \brief Returns true if the given MacroID location points at the last
804*67e74705SXin Li /// token of the macro expansion.
isAtEndOfMacroExpansion(SourceLocation loc,const SourceManager & SM,const LangOptions & LangOpts,SourceLocation * MacroEnd)805*67e74705SXin Li bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
806*67e74705SXin Li                                     const SourceManager &SM,
807*67e74705SXin Li                                     const LangOptions &LangOpts,
808*67e74705SXin Li                                     SourceLocation *MacroEnd) {
809*67e74705SXin Li   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
810*67e74705SXin Li 
811*67e74705SXin Li   SourceLocation spellLoc = SM.getSpellingLoc(loc);
812*67e74705SXin Li   unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
813*67e74705SXin Li   if (tokLen == 0)
814*67e74705SXin Li     return false;
815*67e74705SXin Li 
816*67e74705SXin Li   SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
817*67e74705SXin Li   SourceLocation expansionLoc;
818*67e74705SXin Li   if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
819*67e74705SXin Li     return false;
820*67e74705SXin Li 
821*67e74705SXin Li   if (expansionLoc.isFileID()) {
822*67e74705SXin Li     // No other macro expansions.
823*67e74705SXin Li     if (MacroEnd)
824*67e74705SXin Li       *MacroEnd = expansionLoc;
825*67e74705SXin Li     return true;
826*67e74705SXin Li   }
827*67e74705SXin Li 
828*67e74705SXin Li   return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
829*67e74705SXin Li }
830*67e74705SXin Li 
makeRangeFromFileLocs(CharSourceRange Range,const SourceManager & SM,const LangOptions & LangOpts)831*67e74705SXin Li static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
832*67e74705SXin Li                                              const SourceManager &SM,
833*67e74705SXin Li                                              const LangOptions &LangOpts) {
834*67e74705SXin Li   SourceLocation Begin = Range.getBegin();
835*67e74705SXin Li   SourceLocation End = Range.getEnd();
836*67e74705SXin Li   assert(Begin.isFileID() && End.isFileID());
837*67e74705SXin Li   if (Range.isTokenRange()) {
838*67e74705SXin Li     End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
839*67e74705SXin Li     if (End.isInvalid())
840*67e74705SXin Li       return CharSourceRange();
841*67e74705SXin Li   }
842*67e74705SXin Li 
843*67e74705SXin Li   // Break down the source locations.
844*67e74705SXin Li   FileID FID;
845*67e74705SXin Li   unsigned BeginOffs;
846*67e74705SXin Li   std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
847*67e74705SXin Li   if (FID.isInvalid())
848*67e74705SXin Li     return CharSourceRange();
849*67e74705SXin Li 
850*67e74705SXin Li   unsigned EndOffs;
851*67e74705SXin Li   if (!SM.isInFileID(End, FID, &EndOffs) ||
852*67e74705SXin Li       BeginOffs > EndOffs)
853*67e74705SXin Li     return CharSourceRange();
854*67e74705SXin Li 
855*67e74705SXin Li   return CharSourceRange::getCharRange(Begin, End);
856*67e74705SXin Li }
857*67e74705SXin Li 
makeFileCharRange(CharSourceRange Range,const SourceManager & SM,const LangOptions & LangOpts)858*67e74705SXin Li CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
859*67e74705SXin Li                                          const SourceManager &SM,
860*67e74705SXin Li                                          const LangOptions &LangOpts) {
861*67e74705SXin Li   SourceLocation Begin = Range.getBegin();
862*67e74705SXin Li   SourceLocation End = Range.getEnd();
863*67e74705SXin Li   if (Begin.isInvalid() || End.isInvalid())
864*67e74705SXin Li     return CharSourceRange();
865*67e74705SXin Li 
866*67e74705SXin Li   if (Begin.isFileID() && End.isFileID())
867*67e74705SXin Li     return makeRangeFromFileLocs(Range, SM, LangOpts);
868*67e74705SXin Li 
869*67e74705SXin Li   if (Begin.isMacroID() && End.isFileID()) {
870*67e74705SXin Li     if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
871*67e74705SXin Li       return CharSourceRange();
872*67e74705SXin Li     Range.setBegin(Begin);
873*67e74705SXin Li     return makeRangeFromFileLocs(Range, SM, LangOpts);
874*67e74705SXin Li   }
875*67e74705SXin Li 
876*67e74705SXin Li   if (Begin.isFileID() && End.isMacroID()) {
877*67e74705SXin Li     if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
878*67e74705SXin Li                                                           &End)) ||
879*67e74705SXin Li         (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
880*67e74705SXin Li                                                            &End)))
881*67e74705SXin Li       return CharSourceRange();
882*67e74705SXin Li     Range.setEnd(End);
883*67e74705SXin Li     return makeRangeFromFileLocs(Range, SM, LangOpts);
884*67e74705SXin Li   }
885*67e74705SXin Li 
886*67e74705SXin Li   assert(Begin.isMacroID() && End.isMacroID());
887*67e74705SXin Li   SourceLocation MacroBegin, MacroEnd;
888*67e74705SXin Li   if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
889*67e74705SXin Li       ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
890*67e74705SXin Li                                                         &MacroEnd)) ||
891*67e74705SXin Li        (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
892*67e74705SXin Li                                                          &MacroEnd)))) {
893*67e74705SXin Li     Range.setBegin(MacroBegin);
894*67e74705SXin Li     Range.setEnd(MacroEnd);
895*67e74705SXin Li     return makeRangeFromFileLocs(Range, SM, LangOpts);
896*67e74705SXin Li   }
897*67e74705SXin Li 
898*67e74705SXin Li   bool Invalid = false;
899*67e74705SXin Li   const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
900*67e74705SXin Li                                                         &Invalid);
901*67e74705SXin Li   if (Invalid)
902*67e74705SXin Li     return CharSourceRange();
903*67e74705SXin Li 
904*67e74705SXin Li   if (BeginEntry.getExpansion().isMacroArgExpansion()) {
905*67e74705SXin Li     const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
906*67e74705SXin Li                                                         &Invalid);
907*67e74705SXin Li     if (Invalid)
908*67e74705SXin Li       return CharSourceRange();
909*67e74705SXin Li 
910*67e74705SXin Li     if (EndEntry.getExpansion().isMacroArgExpansion() &&
911*67e74705SXin Li         BeginEntry.getExpansion().getExpansionLocStart() ==
912*67e74705SXin Li             EndEntry.getExpansion().getExpansionLocStart()) {
913*67e74705SXin Li       Range.setBegin(SM.getImmediateSpellingLoc(Begin));
914*67e74705SXin Li       Range.setEnd(SM.getImmediateSpellingLoc(End));
915*67e74705SXin Li       return makeFileCharRange(Range, SM, LangOpts);
916*67e74705SXin Li     }
917*67e74705SXin Li   }
918*67e74705SXin Li 
919*67e74705SXin Li   return CharSourceRange();
920*67e74705SXin Li }
921*67e74705SXin Li 
getSourceText(CharSourceRange Range,const SourceManager & SM,const LangOptions & LangOpts,bool * Invalid)922*67e74705SXin Li StringRef Lexer::getSourceText(CharSourceRange Range,
923*67e74705SXin Li                                const SourceManager &SM,
924*67e74705SXin Li                                const LangOptions &LangOpts,
925*67e74705SXin Li                                bool *Invalid) {
926*67e74705SXin Li   Range = makeFileCharRange(Range, SM, LangOpts);
927*67e74705SXin Li   if (Range.isInvalid()) {
928*67e74705SXin Li     if (Invalid) *Invalid = true;
929*67e74705SXin Li     return StringRef();
930*67e74705SXin Li   }
931*67e74705SXin Li 
932*67e74705SXin Li   // Break down the source location.
933*67e74705SXin Li   std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
934*67e74705SXin Li   if (beginInfo.first.isInvalid()) {
935*67e74705SXin Li     if (Invalid) *Invalid = true;
936*67e74705SXin Li     return StringRef();
937*67e74705SXin Li   }
938*67e74705SXin Li 
939*67e74705SXin Li   unsigned EndOffs;
940*67e74705SXin Li   if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
941*67e74705SXin Li       beginInfo.second > EndOffs) {
942*67e74705SXin Li     if (Invalid) *Invalid = true;
943*67e74705SXin Li     return StringRef();
944*67e74705SXin Li   }
945*67e74705SXin Li 
946*67e74705SXin Li   // Try to the load the file buffer.
947*67e74705SXin Li   bool invalidTemp = false;
948*67e74705SXin Li   StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
949*67e74705SXin Li   if (invalidTemp) {
950*67e74705SXin Li     if (Invalid) *Invalid = true;
951*67e74705SXin Li     return StringRef();
952*67e74705SXin Li   }
953*67e74705SXin Li 
954*67e74705SXin Li   if (Invalid) *Invalid = false;
955*67e74705SXin Li   return file.substr(beginInfo.second, EndOffs - beginInfo.second);
956*67e74705SXin Li }
957*67e74705SXin Li 
getImmediateMacroName(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)958*67e74705SXin Li StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
959*67e74705SXin Li                                        const SourceManager &SM,
960*67e74705SXin Li                                        const LangOptions &LangOpts) {
961*67e74705SXin Li   assert(Loc.isMacroID() && "Only reasonble to call this on macros");
962*67e74705SXin Li 
963*67e74705SXin Li   // Find the location of the immediate macro expansion.
964*67e74705SXin Li   while (1) {
965*67e74705SXin Li     FileID FID = SM.getFileID(Loc);
966*67e74705SXin Li     const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
967*67e74705SXin Li     const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
968*67e74705SXin Li     Loc = Expansion.getExpansionLocStart();
969*67e74705SXin Li     if (!Expansion.isMacroArgExpansion())
970*67e74705SXin Li       break;
971*67e74705SXin Li 
972*67e74705SXin Li     // For macro arguments we need to check that the argument did not come
973*67e74705SXin Li     // from an inner macro, e.g: "MAC1( MAC2(foo) )"
974*67e74705SXin Li 
975*67e74705SXin Li     // Loc points to the argument id of the macro definition, move to the
976*67e74705SXin Li     // macro expansion.
977*67e74705SXin Li     Loc = SM.getImmediateExpansionRange(Loc).first;
978*67e74705SXin Li     SourceLocation SpellLoc = Expansion.getSpellingLoc();
979*67e74705SXin Li     if (SpellLoc.isFileID())
980*67e74705SXin Li       break; // No inner macro.
981*67e74705SXin Li 
982*67e74705SXin Li     // If spelling location resides in the same FileID as macro expansion
983*67e74705SXin Li     // location, it means there is no inner macro.
984*67e74705SXin Li     FileID MacroFID = SM.getFileID(Loc);
985*67e74705SXin Li     if (SM.isInFileID(SpellLoc, MacroFID))
986*67e74705SXin Li       break;
987*67e74705SXin Li 
988*67e74705SXin Li     // Argument came from inner macro.
989*67e74705SXin Li     Loc = SpellLoc;
990*67e74705SXin Li   }
991*67e74705SXin Li 
992*67e74705SXin Li   // Find the spelling location of the start of the non-argument expansion
993*67e74705SXin Li   // range. This is where the macro name was spelled in order to begin
994*67e74705SXin Li   // expanding this macro.
995*67e74705SXin Li   Loc = SM.getSpellingLoc(Loc);
996*67e74705SXin Li 
997*67e74705SXin Li   // Dig out the buffer where the macro name was spelled and the extents of the
998*67e74705SXin Li   // name so that we can render it into the expansion note.
999*67e74705SXin Li   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1000*67e74705SXin Li   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1001*67e74705SXin Li   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1002*67e74705SXin Li   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1003*67e74705SXin Li }
1004*67e74705SXin Li 
getImmediateMacroNameForDiagnostics(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)1005*67e74705SXin Li StringRef Lexer::getImmediateMacroNameForDiagnostics(
1006*67e74705SXin Li     SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1007*67e74705SXin Li   assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1008*67e74705SXin Li   // Walk past macro argument expanions.
1009*67e74705SXin Li   while (SM.isMacroArgExpansion(Loc))
1010*67e74705SXin Li     Loc = SM.getImmediateExpansionRange(Loc).first;
1011*67e74705SXin Li 
1012*67e74705SXin Li   // If the macro's spelling has no FileID, then it's actually a token paste
1013*67e74705SXin Li   // or stringization (or similar) and not a macro at all.
1014*67e74705SXin Li   if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1015*67e74705SXin Li     return StringRef();
1016*67e74705SXin Li 
1017*67e74705SXin Li   // Find the spelling location of the start of the non-argument expansion
1018*67e74705SXin Li   // range. This is where the macro name was spelled in order to begin
1019*67e74705SXin Li   // expanding this macro.
1020*67e74705SXin Li   Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1021*67e74705SXin Li 
1022*67e74705SXin Li   // Dig out the buffer where the macro name was spelled and the extents of the
1023*67e74705SXin Li   // name so that we can render it into the expansion note.
1024*67e74705SXin Li   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1025*67e74705SXin Li   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1026*67e74705SXin Li   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1027*67e74705SXin Li   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1028*67e74705SXin Li }
1029*67e74705SXin Li 
isIdentifierBodyChar(char c,const LangOptions & LangOpts)1030*67e74705SXin Li bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1031*67e74705SXin Li   return isIdentifierBody(c, LangOpts.DollarIdents);
1032*67e74705SXin Li }
1033*67e74705SXin Li 
1034*67e74705SXin Li 
1035*67e74705SXin Li //===----------------------------------------------------------------------===//
1036*67e74705SXin Li // Diagnostics forwarding code.
1037*67e74705SXin Li //===----------------------------------------------------------------------===//
1038*67e74705SXin Li 
1039*67e74705SXin Li /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1040*67e74705SXin Li /// lexer buffer was all expanded at a single point, perform the mapping.
1041*67e74705SXin Li /// This is currently only used for _Pragma implementation, so it is the slow
1042*67e74705SXin Li /// path of the hot getSourceLocation method.  Do not allow it to be inlined.
1043*67e74705SXin Li static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1044*67e74705SXin Li     Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
GetMappedTokenLoc(Preprocessor & PP,SourceLocation FileLoc,unsigned CharNo,unsigned TokLen)1045*67e74705SXin Li static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1046*67e74705SXin Li                                         SourceLocation FileLoc,
1047*67e74705SXin Li                                         unsigned CharNo, unsigned TokLen) {
1048*67e74705SXin Li   assert(FileLoc.isMacroID() && "Must be a macro expansion");
1049*67e74705SXin Li 
1050*67e74705SXin Li   // Otherwise, we're lexing "mapped tokens".  This is used for things like
1051*67e74705SXin Li   // _Pragma handling.  Combine the expansion location of FileLoc with the
1052*67e74705SXin Li   // spelling location.
1053*67e74705SXin Li   SourceManager &SM = PP.getSourceManager();
1054*67e74705SXin Li 
1055*67e74705SXin Li   // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1056*67e74705SXin Li   // characters come from spelling(FileLoc)+Offset.
1057*67e74705SXin Li   SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1058*67e74705SXin Li   SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1059*67e74705SXin Li 
1060*67e74705SXin Li   // Figure out the expansion loc range, which is the range covered by the
1061*67e74705SXin Li   // original _Pragma(...) sequence.
1062*67e74705SXin Li   std::pair<SourceLocation,SourceLocation> II =
1063*67e74705SXin Li     SM.getImmediateExpansionRange(FileLoc);
1064*67e74705SXin Li 
1065*67e74705SXin Li   return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1066*67e74705SXin Li }
1067*67e74705SXin Li 
1068*67e74705SXin Li /// getSourceLocation - Return a source location identifier for the specified
1069*67e74705SXin Li /// offset in the current file.
getSourceLocation(const char * Loc,unsigned TokLen) const1070*67e74705SXin Li SourceLocation Lexer::getSourceLocation(const char *Loc,
1071*67e74705SXin Li                                         unsigned TokLen) const {
1072*67e74705SXin Li   assert(Loc >= BufferStart && Loc <= BufferEnd &&
1073*67e74705SXin Li          "Location out of range for this buffer!");
1074*67e74705SXin Li 
1075*67e74705SXin Li   // In the normal case, we're just lexing from a simple file buffer, return
1076*67e74705SXin Li   // the file id from FileLoc with the offset specified.
1077*67e74705SXin Li   unsigned CharNo = Loc-BufferStart;
1078*67e74705SXin Li   if (FileLoc.isFileID())
1079*67e74705SXin Li     return FileLoc.getLocWithOffset(CharNo);
1080*67e74705SXin Li 
1081*67e74705SXin Li   // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1082*67e74705SXin Li   // tokens are lexed from where the _Pragma was defined.
1083*67e74705SXin Li   assert(PP && "This doesn't work on raw lexers");
1084*67e74705SXin Li   return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1085*67e74705SXin Li }
1086*67e74705SXin Li 
1087*67e74705SXin Li /// Diag - Forwarding function for diagnostics.  This translate a source
1088*67e74705SXin Li /// position in the current buffer into a SourceLocation object for rendering.
Diag(const char * Loc,unsigned DiagID) const1089*67e74705SXin Li DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1090*67e74705SXin Li   return PP->Diag(getSourceLocation(Loc), DiagID);
1091*67e74705SXin Li }
1092*67e74705SXin Li 
1093*67e74705SXin Li //===----------------------------------------------------------------------===//
1094*67e74705SXin Li // Trigraph and Escaped Newline Handling Code.
1095*67e74705SXin Li //===----------------------------------------------------------------------===//
1096*67e74705SXin Li 
1097*67e74705SXin Li /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1098*67e74705SXin Li /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
GetTrigraphCharForLetter(char Letter)1099*67e74705SXin Li static char GetTrigraphCharForLetter(char Letter) {
1100*67e74705SXin Li   switch (Letter) {
1101*67e74705SXin Li   default:   return 0;
1102*67e74705SXin Li   case '=':  return '#';
1103*67e74705SXin Li   case ')':  return ']';
1104*67e74705SXin Li   case '(':  return '[';
1105*67e74705SXin Li   case '!':  return '|';
1106*67e74705SXin Li   case '\'': return '^';
1107*67e74705SXin Li   case '>':  return '}';
1108*67e74705SXin Li   case '/':  return '\\';
1109*67e74705SXin Li   case '<':  return '{';
1110*67e74705SXin Li   case '-':  return '~';
1111*67e74705SXin Li   }
1112*67e74705SXin Li }
1113*67e74705SXin Li 
1114*67e74705SXin Li /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1115*67e74705SXin Li /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
1116*67e74705SXin Li /// return the result character.  Finally, emit a warning about trigraph use
1117*67e74705SXin Li /// whether trigraphs are enabled or not.
DecodeTrigraphChar(const char * CP,Lexer * L)1118*67e74705SXin Li static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1119*67e74705SXin Li   char Res = GetTrigraphCharForLetter(*CP);
1120*67e74705SXin Li   if (!Res || !L) return Res;
1121*67e74705SXin Li 
1122*67e74705SXin Li   if (!L->getLangOpts().Trigraphs) {
1123*67e74705SXin Li     if (!L->isLexingRawMode())
1124*67e74705SXin Li       L->Diag(CP-2, diag::trigraph_ignored);
1125*67e74705SXin Li     return 0;
1126*67e74705SXin Li   }
1127*67e74705SXin Li 
1128*67e74705SXin Li   if (!L->isLexingRawMode())
1129*67e74705SXin Li     L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1130*67e74705SXin Li   return Res;
1131*67e74705SXin Li }
1132*67e74705SXin Li 
1133*67e74705SXin Li /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1134*67e74705SXin Li /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1135*67e74705SXin Li /// trigraph equivalent on entry to this function.
getEscapedNewLineSize(const char * Ptr)1136*67e74705SXin Li unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1137*67e74705SXin Li   unsigned Size = 0;
1138*67e74705SXin Li   while (isWhitespace(Ptr[Size])) {
1139*67e74705SXin Li     ++Size;
1140*67e74705SXin Li 
1141*67e74705SXin Li     if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1142*67e74705SXin Li       continue;
1143*67e74705SXin Li 
1144*67e74705SXin Li     // If this is a \r\n or \n\r, skip the other half.
1145*67e74705SXin Li     if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1146*67e74705SXin Li         Ptr[Size-1] != Ptr[Size])
1147*67e74705SXin Li       ++Size;
1148*67e74705SXin Li 
1149*67e74705SXin Li     return Size;
1150*67e74705SXin Li   }
1151*67e74705SXin Li 
1152*67e74705SXin Li   // Not an escaped newline, must be a \t or something else.
1153*67e74705SXin Li   return 0;
1154*67e74705SXin Li }
1155*67e74705SXin Li 
1156*67e74705SXin Li /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1157*67e74705SXin Li /// them), skip over them and return the first non-escaped-newline found,
1158*67e74705SXin Li /// otherwise return P.
SkipEscapedNewLines(const char * P)1159*67e74705SXin Li const char *Lexer::SkipEscapedNewLines(const char *P) {
1160*67e74705SXin Li   while (1) {
1161*67e74705SXin Li     const char *AfterEscape;
1162*67e74705SXin Li     if (*P == '\\') {
1163*67e74705SXin Li       AfterEscape = P+1;
1164*67e74705SXin Li     } else if (*P == '?') {
1165*67e74705SXin Li       // If not a trigraph for escape, bail out.
1166*67e74705SXin Li       if (P[1] != '?' || P[2] != '/')
1167*67e74705SXin Li         return P;
1168*67e74705SXin Li       AfterEscape = P+3;
1169*67e74705SXin Li     } else {
1170*67e74705SXin Li       return P;
1171*67e74705SXin Li     }
1172*67e74705SXin Li 
1173*67e74705SXin Li     unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1174*67e74705SXin Li     if (NewLineSize == 0) return P;
1175*67e74705SXin Li     P = AfterEscape+NewLineSize;
1176*67e74705SXin Li   }
1177*67e74705SXin Li }
1178*67e74705SXin Li 
1179*67e74705SXin Li /// \brief Checks that the given token is the first token that occurs after the
1180*67e74705SXin Li /// given location (this excludes comments and whitespace). Returns the location
1181*67e74705SXin Li /// immediately after the specified token. If the token is not found or the
1182*67e74705SXin Li /// location is inside a macro, the returned source location will be invalid.
findLocationAfterToken(SourceLocation Loc,tok::TokenKind TKind,const SourceManager & SM,const LangOptions & LangOpts,bool SkipTrailingWhitespaceAndNewLine)1183*67e74705SXin Li SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1184*67e74705SXin Li                                         tok::TokenKind TKind,
1185*67e74705SXin Li                                         const SourceManager &SM,
1186*67e74705SXin Li                                         const LangOptions &LangOpts,
1187*67e74705SXin Li                                         bool SkipTrailingWhitespaceAndNewLine) {
1188*67e74705SXin Li   if (Loc.isMacroID()) {
1189*67e74705SXin Li     if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1190*67e74705SXin Li       return SourceLocation();
1191*67e74705SXin Li   }
1192*67e74705SXin Li   Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1193*67e74705SXin Li 
1194*67e74705SXin Li   // Break down the source location.
1195*67e74705SXin Li   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1196*67e74705SXin Li 
1197*67e74705SXin Li   // Try to load the file buffer.
1198*67e74705SXin Li   bool InvalidTemp = false;
1199*67e74705SXin Li   StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1200*67e74705SXin Li   if (InvalidTemp)
1201*67e74705SXin Li     return SourceLocation();
1202*67e74705SXin Li 
1203*67e74705SXin Li   const char *TokenBegin = File.data() + LocInfo.second;
1204*67e74705SXin Li 
1205*67e74705SXin Li   // Lex from the start of the given location.
1206*67e74705SXin Li   Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1207*67e74705SXin Li                                       TokenBegin, File.end());
1208*67e74705SXin Li   // Find the token.
1209*67e74705SXin Li   Token Tok;
1210*67e74705SXin Li   lexer.LexFromRawLexer(Tok);
1211*67e74705SXin Li   if (Tok.isNot(TKind))
1212*67e74705SXin Li     return SourceLocation();
1213*67e74705SXin Li   SourceLocation TokenLoc = Tok.getLocation();
1214*67e74705SXin Li 
1215*67e74705SXin Li   // Calculate how much whitespace needs to be skipped if any.
1216*67e74705SXin Li   unsigned NumWhitespaceChars = 0;
1217*67e74705SXin Li   if (SkipTrailingWhitespaceAndNewLine) {
1218*67e74705SXin Li     const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1219*67e74705SXin Li                            Tok.getLength();
1220*67e74705SXin Li     unsigned char C = *TokenEnd;
1221*67e74705SXin Li     while (isHorizontalWhitespace(C)) {
1222*67e74705SXin Li       C = *(++TokenEnd);
1223*67e74705SXin Li       NumWhitespaceChars++;
1224*67e74705SXin Li     }
1225*67e74705SXin Li 
1226*67e74705SXin Li     // Skip \r, \n, \r\n, or \n\r
1227*67e74705SXin Li     if (C == '\n' || C == '\r') {
1228*67e74705SXin Li       char PrevC = C;
1229*67e74705SXin Li       C = *(++TokenEnd);
1230*67e74705SXin Li       NumWhitespaceChars++;
1231*67e74705SXin Li       if ((C == '\n' || C == '\r') && C != PrevC)
1232*67e74705SXin Li         NumWhitespaceChars++;
1233*67e74705SXin Li     }
1234*67e74705SXin Li   }
1235*67e74705SXin Li 
1236*67e74705SXin Li   return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1237*67e74705SXin Li }
1238*67e74705SXin Li 
1239*67e74705SXin Li /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1240*67e74705SXin Li /// get its size, and return it.  This is tricky in several cases:
1241*67e74705SXin Li ///   1. If currently at the start of a trigraph, we warn about the trigraph,
1242*67e74705SXin Li ///      then either return the trigraph (skipping 3 chars) or the '?',
1243*67e74705SXin Li ///      depending on whether trigraphs are enabled or not.
1244*67e74705SXin Li ///   2. If this is an escaped newline (potentially with whitespace between
1245*67e74705SXin Li ///      the backslash and newline), implicitly skip the newline and return
1246*67e74705SXin Li ///      the char after it.
1247*67e74705SXin Li ///
1248*67e74705SXin Li /// This handles the slow/uncommon case of the getCharAndSize method.  Here we
1249*67e74705SXin Li /// know that we can accumulate into Size, and that we have already incremented
1250*67e74705SXin Li /// Ptr by Size bytes.
1251*67e74705SXin Li ///
1252*67e74705SXin Li /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1253*67e74705SXin Li /// be updated to match.
1254*67e74705SXin Li ///
getCharAndSizeSlow(const char * Ptr,unsigned & Size,Token * Tok)1255*67e74705SXin Li char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1256*67e74705SXin Li                                Token *Tok) {
1257*67e74705SXin Li   // If we have a slash, look for an escaped newline.
1258*67e74705SXin Li   if (Ptr[0] == '\\') {
1259*67e74705SXin Li     ++Size;
1260*67e74705SXin Li     ++Ptr;
1261*67e74705SXin Li Slash:
1262*67e74705SXin Li     // Common case, backslash-char where the char is not whitespace.
1263*67e74705SXin Li     if (!isWhitespace(Ptr[0])) return '\\';
1264*67e74705SXin Li 
1265*67e74705SXin Li     // See if we have optional whitespace characters between the slash and
1266*67e74705SXin Li     // newline.
1267*67e74705SXin Li     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1268*67e74705SXin Li       // Remember that this token needs to be cleaned.
1269*67e74705SXin Li       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1270*67e74705SXin Li 
1271*67e74705SXin Li       // Warn if there was whitespace between the backslash and newline.
1272*67e74705SXin Li       if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1273*67e74705SXin Li         Diag(Ptr, diag::backslash_newline_space);
1274*67e74705SXin Li 
1275*67e74705SXin Li       // Found backslash<whitespace><newline>.  Parse the char after it.
1276*67e74705SXin Li       Size += EscapedNewLineSize;
1277*67e74705SXin Li       Ptr  += EscapedNewLineSize;
1278*67e74705SXin Li 
1279*67e74705SXin Li       // If the char that we finally got was a \n, then we must have had
1280*67e74705SXin Li       // something like \<newline><newline>.  We don't want to consume the
1281*67e74705SXin Li       // second newline.
1282*67e74705SXin Li       if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1283*67e74705SXin Li         return ' ';
1284*67e74705SXin Li 
1285*67e74705SXin Li       // Use slow version to accumulate a correct size field.
1286*67e74705SXin Li       return getCharAndSizeSlow(Ptr, Size, Tok);
1287*67e74705SXin Li     }
1288*67e74705SXin Li 
1289*67e74705SXin Li     // Otherwise, this is not an escaped newline, just return the slash.
1290*67e74705SXin Li     return '\\';
1291*67e74705SXin Li   }
1292*67e74705SXin Li 
1293*67e74705SXin Li   // If this is a trigraph, process it.
1294*67e74705SXin Li   if (Ptr[0] == '?' && Ptr[1] == '?') {
1295*67e74705SXin Li     // If this is actually a legal trigraph (not something like "??x"), emit
1296*67e74705SXin Li     // a trigraph warning.  If so, and if trigraphs are enabled, return it.
1297*67e74705SXin Li     if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1298*67e74705SXin Li       // Remember that this token needs to be cleaned.
1299*67e74705SXin Li       if (Tok) Tok->setFlag(Token::NeedsCleaning);
1300*67e74705SXin Li 
1301*67e74705SXin Li       Ptr += 3;
1302*67e74705SXin Li       Size += 3;
1303*67e74705SXin Li       if (C == '\\') goto Slash;
1304*67e74705SXin Li       return C;
1305*67e74705SXin Li     }
1306*67e74705SXin Li   }
1307*67e74705SXin Li 
1308*67e74705SXin Li   // If this is neither, return a single character.
1309*67e74705SXin Li   ++Size;
1310*67e74705SXin Li   return *Ptr;
1311*67e74705SXin Li }
1312*67e74705SXin Li 
1313*67e74705SXin Li 
1314*67e74705SXin Li /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1315*67e74705SXin Li /// getCharAndSizeNoWarn method.  Here we know that we can accumulate into Size,
1316*67e74705SXin Li /// and that we have already incremented Ptr by Size bytes.
1317*67e74705SXin Li ///
1318*67e74705SXin Li /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1319*67e74705SXin Li /// be updated to match.
getCharAndSizeSlowNoWarn(const char * Ptr,unsigned & Size,const LangOptions & LangOpts)1320*67e74705SXin Li char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1321*67e74705SXin Li                                      const LangOptions &LangOpts) {
1322*67e74705SXin Li   // If we have a slash, look for an escaped newline.
1323*67e74705SXin Li   if (Ptr[0] == '\\') {
1324*67e74705SXin Li     ++Size;
1325*67e74705SXin Li     ++Ptr;
1326*67e74705SXin Li Slash:
1327*67e74705SXin Li     // Common case, backslash-char where the char is not whitespace.
1328*67e74705SXin Li     if (!isWhitespace(Ptr[0])) return '\\';
1329*67e74705SXin Li 
1330*67e74705SXin Li     // See if we have optional whitespace characters followed by a newline.
1331*67e74705SXin Li     if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1332*67e74705SXin Li       // Found backslash<whitespace><newline>.  Parse the char after it.
1333*67e74705SXin Li       Size += EscapedNewLineSize;
1334*67e74705SXin Li       Ptr  += EscapedNewLineSize;
1335*67e74705SXin Li 
1336*67e74705SXin Li       // If the char that we finally got was a \n, then we must have had
1337*67e74705SXin Li       // something like \<newline><newline>.  We don't want to consume the
1338*67e74705SXin Li       // second newline.
1339*67e74705SXin Li       if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1340*67e74705SXin Li         return ' ';
1341*67e74705SXin Li 
1342*67e74705SXin Li       // Use slow version to accumulate a correct size field.
1343*67e74705SXin Li       return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1344*67e74705SXin Li     }
1345*67e74705SXin Li 
1346*67e74705SXin Li     // Otherwise, this is not an escaped newline, just return the slash.
1347*67e74705SXin Li     return '\\';
1348*67e74705SXin Li   }
1349*67e74705SXin Li 
1350*67e74705SXin Li   // If this is a trigraph, process it.
1351*67e74705SXin Li   if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1352*67e74705SXin Li     // If this is actually a legal trigraph (not something like "??x"), return
1353*67e74705SXin Li     // it.
1354*67e74705SXin Li     if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1355*67e74705SXin Li       Ptr += 3;
1356*67e74705SXin Li       Size += 3;
1357*67e74705SXin Li       if (C == '\\') goto Slash;
1358*67e74705SXin Li       return C;
1359*67e74705SXin Li     }
1360*67e74705SXin Li   }
1361*67e74705SXin Li 
1362*67e74705SXin Li   // If this is neither, return a single character.
1363*67e74705SXin Li   ++Size;
1364*67e74705SXin Li   return *Ptr;
1365*67e74705SXin Li }
1366*67e74705SXin Li 
1367*67e74705SXin Li //===----------------------------------------------------------------------===//
1368*67e74705SXin Li // Helper methods for lexing.
1369*67e74705SXin Li //===----------------------------------------------------------------------===//
1370*67e74705SXin Li 
1371*67e74705SXin Li /// \brief Routine that indiscriminately skips bytes in the source file.
SkipBytes(unsigned Bytes,bool StartOfLine)1372*67e74705SXin Li void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1373*67e74705SXin Li   BufferPtr += Bytes;
1374*67e74705SXin Li   if (BufferPtr > BufferEnd)
1375*67e74705SXin Li     BufferPtr = BufferEnd;
1376*67e74705SXin Li   // FIXME: What exactly does the StartOfLine bit mean?  There are two
1377*67e74705SXin Li   // possible meanings for the "start" of the line: the first token on the
1378*67e74705SXin Li   // unexpanded line, or the first token on the expanded line.
1379*67e74705SXin Li   IsAtStartOfLine = StartOfLine;
1380*67e74705SXin Li   IsAtPhysicalStartOfLine = StartOfLine;
1381*67e74705SXin Li }
1382*67e74705SXin Li 
isAllowedIDChar(uint32_t C,const LangOptions & LangOpts)1383*67e74705SXin Li static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1384*67e74705SXin Li   if (LangOpts.AsmPreprocessor) {
1385*67e74705SXin Li     return false;
1386*67e74705SXin Li   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1387*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1388*67e74705SXin Li         C11AllowedIDCharRanges);
1389*67e74705SXin Li     return C11AllowedIDChars.contains(C);
1390*67e74705SXin Li   } else if (LangOpts.CPlusPlus) {
1391*67e74705SXin Li     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1392*67e74705SXin Li         CXX03AllowedIDCharRanges);
1393*67e74705SXin Li     return CXX03AllowedIDChars.contains(C);
1394*67e74705SXin Li   } else {
1395*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1396*67e74705SXin Li         C99AllowedIDCharRanges);
1397*67e74705SXin Li     return C99AllowedIDChars.contains(C);
1398*67e74705SXin Li   }
1399*67e74705SXin Li }
1400*67e74705SXin Li 
isAllowedInitiallyIDChar(uint32_t C,const LangOptions & LangOpts)1401*67e74705SXin Li static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1402*67e74705SXin Li   assert(isAllowedIDChar(C, LangOpts));
1403*67e74705SXin Li   if (LangOpts.AsmPreprocessor) {
1404*67e74705SXin Li     return false;
1405*67e74705SXin Li   } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1406*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1407*67e74705SXin Li         C11DisallowedInitialIDCharRanges);
1408*67e74705SXin Li     return !C11DisallowedInitialIDChars.contains(C);
1409*67e74705SXin Li   } else if (LangOpts.CPlusPlus) {
1410*67e74705SXin Li     return true;
1411*67e74705SXin Li   } else {
1412*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1413*67e74705SXin Li         C99DisallowedInitialIDCharRanges);
1414*67e74705SXin Li     return !C99DisallowedInitialIDChars.contains(C);
1415*67e74705SXin Li   }
1416*67e74705SXin Li }
1417*67e74705SXin Li 
makeCharRange(Lexer & L,const char * Begin,const char * End)1418*67e74705SXin Li static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1419*67e74705SXin Li                                             const char *End) {
1420*67e74705SXin Li   return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1421*67e74705SXin Li                                        L.getSourceLocation(End));
1422*67e74705SXin Li }
1423*67e74705SXin Li 
maybeDiagnoseIDCharCompat(DiagnosticsEngine & Diags,uint32_t C,CharSourceRange Range,bool IsFirst)1424*67e74705SXin Li static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1425*67e74705SXin Li                                       CharSourceRange Range, bool IsFirst) {
1426*67e74705SXin Li   // Check C99 compatibility.
1427*67e74705SXin Li   if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1428*67e74705SXin Li     enum {
1429*67e74705SXin Li       CannotAppearInIdentifier = 0,
1430*67e74705SXin Li       CannotStartIdentifier
1431*67e74705SXin Li     };
1432*67e74705SXin Li 
1433*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1434*67e74705SXin Li         C99AllowedIDCharRanges);
1435*67e74705SXin Li     static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1436*67e74705SXin Li         C99DisallowedInitialIDCharRanges);
1437*67e74705SXin Li     if (!C99AllowedIDChars.contains(C)) {
1438*67e74705SXin Li       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1439*67e74705SXin Li         << Range
1440*67e74705SXin Li         << CannotAppearInIdentifier;
1441*67e74705SXin Li     } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1442*67e74705SXin Li       Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1443*67e74705SXin Li         << Range
1444*67e74705SXin Li         << CannotStartIdentifier;
1445*67e74705SXin Li     }
1446*67e74705SXin Li   }
1447*67e74705SXin Li 
1448*67e74705SXin Li   // Check C++98 compatibility.
1449*67e74705SXin Li   if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1450*67e74705SXin Li     static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1451*67e74705SXin Li         CXX03AllowedIDCharRanges);
1452*67e74705SXin Li     if (!CXX03AllowedIDChars.contains(C)) {
1453*67e74705SXin Li       Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1454*67e74705SXin Li         << Range;
1455*67e74705SXin Li     }
1456*67e74705SXin Li   }
1457*67e74705SXin Li }
1458*67e74705SXin Li 
tryConsumeIdentifierUCN(const char * & CurPtr,unsigned Size,Token & Result)1459*67e74705SXin Li bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1460*67e74705SXin Li                                     Token &Result) {
1461*67e74705SXin Li   const char *UCNPtr = CurPtr + Size;
1462*67e74705SXin Li   uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1463*67e74705SXin Li   if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1464*67e74705SXin Li     return false;
1465*67e74705SXin Li 
1466*67e74705SXin Li   if (!isLexingRawMode())
1467*67e74705SXin Li     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1468*67e74705SXin Li                               makeCharRange(*this, CurPtr, UCNPtr),
1469*67e74705SXin Li                               /*IsFirst=*/false);
1470*67e74705SXin Li 
1471*67e74705SXin Li   Result.setFlag(Token::HasUCN);
1472*67e74705SXin Li   if ((UCNPtr - CurPtr ==  6 && CurPtr[1] == 'u') ||
1473*67e74705SXin Li       (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1474*67e74705SXin Li     CurPtr = UCNPtr;
1475*67e74705SXin Li   else
1476*67e74705SXin Li     while (CurPtr != UCNPtr)
1477*67e74705SXin Li       (void)getAndAdvanceChar(CurPtr, Result);
1478*67e74705SXin Li   return true;
1479*67e74705SXin Li }
1480*67e74705SXin Li 
tryConsumeIdentifierUTF8Char(const char * & CurPtr)1481*67e74705SXin Li bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1482*67e74705SXin Li   const char *UnicodePtr = CurPtr;
1483*67e74705SXin Li   UTF32 CodePoint;
1484*67e74705SXin Li   ConversionResult Result =
1485*67e74705SXin Li       llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1486*67e74705SXin Li                                 (const UTF8 *)BufferEnd,
1487*67e74705SXin Li                                 &CodePoint,
1488*67e74705SXin Li                                 strictConversion);
1489*67e74705SXin Li   if (Result != conversionOK ||
1490*67e74705SXin Li       !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1491*67e74705SXin Li     return false;
1492*67e74705SXin Li 
1493*67e74705SXin Li   if (!isLexingRawMode())
1494*67e74705SXin Li     maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495*67e74705SXin Li                               makeCharRange(*this, CurPtr, UnicodePtr),
1496*67e74705SXin Li                               /*IsFirst=*/false);
1497*67e74705SXin Li 
1498*67e74705SXin Li   CurPtr = UnicodePtr;
1499*67e74705SXin Li   return true;
1500*67e74705SXin Li }
1501*67e74705SXin Li 
LexIdentifier(Token & Result,const char * CurPtr)1502*67e74705SXin Li bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1503*67e74705SXin Li   // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1504*67e74705SXin Li   unsigned Size;
1505*67e74705SXin Li   unsigned char C = *CurPtr++;
1506*67e74705SXin Li   while (isIdentifierBody(C))
1507*67e74705SXin Li     C = *CurPtr++;
1508*67e74705SXin Li 
1509*67e74705SXin Li   --CurPtr;   // Back up over the skipped character.
1510*67e74705SXin Li 
1511*67e74705SXin Li   // Fast path, no $,\,? in identifier found.  '\' might be an escaped newline
1512*67e74705SXin Li   // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1513*67e74705SXin Li   //
1514*67e74705SXin Li   // TODO: Could merge these checks into an InfoTable flag to make the
1515*67e74705SXin Li   // comparison cheaper
1516*67e74705SXin Li   if (isASCII(C) && C != '\\' && C != '?' &&
1517*67e74705SXin Li       (C != '$' || !LangOpts.DollarIdents)) {
1518*67e74705SXin Li FinishIdentifier:
1519*67e74705SXin Li     const char *IdStart = BufferPtr;
1520*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1521*67e74705SXin Li     Result.setRawIdentifierData(IdStart);
1522*67e74705SXin Li 
1523*67e74705SXin Li     // If we are in raw mode, return this identifier raw.  There is no need to
1524*67e74705SXin Li     // look up identifier information or attempt to macro expand it.
1525*67e74705SXin Li     if (LexingRawMode)
1526*67e74705SXin Li       return true;
1527*67e74705SXin Li 
1528*67e74705SXin Li     // Fill in Result.IdentifierInfo and update the token kind,
1529*67e74705SXin Li     // looking up the identifier in the identifier table.
1530*67e74705SXin Li     IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1531*67e74705SXin Li 
1532*67e74705SXin Li     // Finally, now that we know we have an identifier, pass this off to the
1533*67e74705SXin Li     // preprocessor, which may macro expand it or something.
1534*67e74705SXin Li     if (II->isHandleIdentifierCase())
1535*67e74705SXin Li       return PP->HandleIdentifier(Result);
1536*67e74705SXin Li 
1537*67e74705SXin Li     return true;
1538*67e74705SXin Li   }
1539*67e74705SXin Li 
1540*67e74705SXin Li   // Otherwise, $,\,? in identifier found.  Enter slower path.
1541*67e74705SXin Li 
1542*67e74705SXin Li   C = getCharAndSize(CurPtr, Size);
1543*67e74705SXin Li   while (1) {
1544*67e74705SXin Li     if (C == '$') {
1545*67e74705SXin Li       // If we hit a $ and they are not supported in identifiers, we are done.
1546*67e74705SXin Li       if (!LangOpts.DollarIdents) goto FinishIdentifier;
1547*67e74705SXin Li 
1548*67e74705SXin Li       // Otherwise, emit a diagnostic and continue.
1549*67e74705SXin Li       if (!isLexingRawMode())
1550*67e74705SXin Li         Diag(CurPtr, diag::ext_dollar_in_identifier);
1551*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, Size, Result);
1552*67e74705SXin Li       C = getCharAndSize(CurPtr, Size);
1553*67e74705SXin Li       continue;
1554*67e74705SXin Li 
1555*67e74705SXin Li     } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1556*67e74705SXin Li       C = getCharAndSize(CurPtr, Size);
1557*67e74705SXin Li       continue;
1558*67e74705SXin Li     } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1559*67e74705SXin Li       C = getCharAndSize(CurPtr, Size);
1560*67e74705SXin Li       continue;
1561*67e74705SXin Li     } else if (!isIdentifierBody(C)) {
1562*67e74705SXin Li       goto FinishIdentifier;
1563*67e74705SXin Li     }
1564*67e74705SXin Li 
1565*67e74705SXin Li     // Otherwise, this character is good, consume it.
1566*67e74705SXin Li     CurPtr = ConsumeChar(CurPtr, Size, Result);
1567*67e74705SXin Li 
1568*67e74705SXin Li     C = getCharAndSize(CurPtr, Size);
1569*67e74705SXin Li     while (isIdentifierBody(C)) {
1570*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, Size, Result);
1571*67e74705SXin Li       C = getCharAndSize(CurPtr, Size);
1572*67e74705SXin Li     }
1573*67e74705SXin Li   }
1574*67e74705SXin Li }
1575*67e74705SXin Li 
1576*67e74705SXin Li /// isHexaLiteral - Return true if Start points to a hex constant.
1577*67e74705SXin Li /// in microsoft mode (where this is supposed to be several different tokens).
isHexaLiteral(const char * Start,const LangOptions & LangOpts)1578*67e74705SXin Li bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1579*67e74705SXin Li   unsigned Size;
1580*67e74705SXin Li   char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1581*67e74705SXin Li   if (C1 != '0')
1582*67e74705SXin Li     return false;
1583*67e74705SXin Li   char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1584*67e74705SXin Li   return (C2 == 'x' || C2 == 'X');
1585*67e74705SXin Li }
1586*67e74705SXin Li 
1587*67e74705SXin Li /// LexNumericConstant - Lex the remainder of a integer or floating point
1588*67e74705SXin Li /// constant. From[-1] is the first character lexed.  Return the end of the
1589*67e74705SXin Li /// constant.
LexNumericConstant(Token & Result,const char * CurPtr)1590*67e74705SXin Li bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1591*67e74705SXin Li   unsigned Size;
1592*67e74705SXin Li   char C = getCharAndSize(CurPtr, Size);
1593*67e74705SXin Li   char PrevCh = 0;
1594*67e74705SXin Li   while (isPreprocessingNumberBody(C)) {
1595*67e74705SXin Li     CurPtr = ConsumeChar(CurPtr, Size, Result);
1596*67e74705SXin Li     PrevCh = C;
1597*67e74705SXin Li     C = getCharAndSize(CurPtr, Size);
1598*67e74705SXin Li   }
1599*67e74705SXin Li 
1600*67e74705SXin Li   // If we fell out, check for a sign, due to 1e+12.  If we have one, continue.
1601*67e74705SXin Li   if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1602*67e74705SXin Li     // If we are in Microsoft mode, don't continue if the constant is hex.
1603*67e74705SXin Li     // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1604*67e74705SXin Li     if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1605*67e74705SXin Li       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1606*67e74705SXin Li   }
1607*67e74705SXin Li 
1608*67e74705SXin Li   // If we have a hex FP constant, continue.
1609*67e74705SXin Li   if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1610*67e74705SXin Li     // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1611*67e74705SXin Li     // not-quite-conforming extension. Only do so if this looks like it's
1612*67e74705SXin Li     // actually meant to be a hexfloat, and not if it has a ud-suffix.
1613*67e74705SXin Li     bool IsHexFloat = true;
1614*67e74705SXin Li     if (!LangOpts.C99) {
1615*67e74705SXin Li       if (!isHexaLiteral(BufferPtr, LangOpts))
1616*67e74705SXin Li         IsHexFloat = false;
1617*67e74705SXin Li       else if (!getLangOpts().CPlusPlus1z &&
1618*67e74705SXin Li                std::find(BufferPtr, CurPtr, '_') != CurPtr)
1619*67e74705SXin Li         IsHexFloat = false;
1620*67e74705SXin Li     }
1621*67e74705SXin Li     if (IsHexFloat)
1622*67e74705SXin Li       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1623*67e74705SXin Li   }
1624*67e74705SXin Li 
1625*67e74705SXin Li   // If we have a digit separator, continue.
1626*67e74705SXin Li   if (C == '\'' && getLangOpts().CPlusPlus14) {
1627*67e74705SXin Li     unsigned NextSize;
1628*67e74705SXin Li     char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1629*67e74705SXin Li     if (isIdentifierBody(Next)) {
1630*67e74705SXin Li       if (!isLexingRawMode())
1631*67e74705SXin Li         Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1632*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, Size, Result);
1633*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1634*67e74705SXin Li       return LexNumericConstant(Result, CurPtr);
1635*67e74705SXin Li     }
1636*67e74705SXin Li   }
1637*67e74705SXin Li 
1638*67e74705SXin Li   // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1639*67e74705SXin Li   if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1640*67e74705SXin Li     return LexNumericConstant(Result, CurPtr);
1641*67e74705SXin Li   if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1642*67e74705SXin Li     return LexNumericConstant(Result, CurPtr);
1643*67e74705SXin Li 
1644*67e74705SXin Li   // Update the location of token as well as BufferPtr.
1645*67e74705SXin Li   const char *TokStart = BufferPtr;
1646*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1647*67e74705SXin Li   Result.setLiteralData(TokStart);
1648*67e74705SXin Li   return true;
1649*67e74705SXin Li }
1650*67e74705SXin Li 
1651*67e74705SXin Li /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1652*67e74705SXin Li /// in C++11, or warn on a ud-suffix in C++98.
LexUDSuffix(Token & Result,const char * CurPtr,bool IsStringLiteral)1653*67e74705SXin Li const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1654*67e74705SXin Li                                bool IsStringLiteral) {
1655*67e74705SXin Li   assert(getLangOpts().CPlusPlus);
1656*67e74705SXin Li 
1657*67e74705SXin Li   // Maximally munch an identifier.
1658*67e74705SXin Li   unsigned Size;
1659*67e74705SXin Li   char C = getCharAndSize(CurPtr, Size);
1660*67e74705SXin Li   bool Consumed = false;
1661*67e74705SXin Li 
1662*67e74705SXin Li   if (!isIdentifierHead(C)) {
1663*67e74705SXin Li     if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1664*67e74705SXin Li       Consumed = true;
1665*67e74705SXin Li     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1666*67e74705SXin Li       Consumed = true;
1667*67e74705SXin Li     else
1668*67e74705SXin Li       return CurPtr;
1669*67e74705SXin Li   }
1670*67e74705SXin Li 
1671*67e74705SXin Li   if (!getLangOpts().CPlusPlus11) {
1672*67e74705SXin Li     if (!isLexingRawMode())
1673*67e74705SXin Li       Diag(CurPtr,
1674*67e74705SXin Li            C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1675*67e74705SXin Li                     : diag::warn_cxx11_compat_reserved_user_defined_literal)
1676*67e74705SXin Li         << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1677*67e74705SXin Li     return CurPtr;
1678*67e74705SXin Li   }
1679*67e74705SXin Li 
1680*67e74705SXin Li   // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1681*67e74705SXin Li   // that does not start with an underscore is ill-formed. As a conforming
1682*67e74705SXin Li   // extension, we treat all such suffixes as if they had whitespace before
1683*67e74705SXin Li   // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1684*67e74705SXin Li   // likely to be a ud-suffix than a macro, however, and accept that.
1685*67e74705SXin Li   if (!Consumed) {
1686*67e74705SXin Li     bool IsUDSuffix = false;
1687*67e74705SXin Li     if (C == '_')
1688*67e74705SXin Li       IsUDSuffix = true;
1689*67e74705SXin Li     else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1690*67e74705SXin Li       // In C++1y, we need to look ahead a few characters to see if this is a
1691*67e74705SXin Li       // valid suffix for a string literal or a numeric literal (this could be
1692*67e74705SXin Li       // the 'operator""if' defining a numeric literal operator).
1693*67e74705SXin Li       const unsigned MaxStandardSuffixLength = 3;
1694*67e74705SXin Li       char Buffer[MaxStandardSuffixLength] = { C };
1695*67e74705SXin Li       unsigned Consumed = Size;
1696*67e74705SXin Li       unsigned Chars = 1;
1697*67e74705SXin Li       while (true) {
1698*67e74705SXin Li         unsigned NextSize;
1699*67e74705SXin Li         char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1700*67e74705SXin Li                                          getLangOpts());
1701*67e74705SXin Li         if (!isIdentifierBody(Next)) {
1702*67e74705SXin Li           // End of suffix. Check whether this is on the whitelist.
1703*67e74705SXin Li           IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1704*67e74705SXin Li                        NumericLiteralParser::isValidUDSuffix(
1705*67e74705SXin Li                            getLangOpts(), StringRef(Buffer, Chars));
1706*67e74705SXin Li           break;
1707*67e74705SXin Li         }
1708*67e74705SXin Li 
1709*67e74705SXin Li         if (Chars == MaxStandardSuffixLength)
1710*67e74705SXin Li           // Too long: can't be a standard suffix.
1711*67e74705SXin Li           break;
1712*67e74705SXin Li 
1713*67e74705SXin Li         Buffer[Chars++] = Next;
1714*67e74705SXin Li         Consumed += NextSize;
1715*67e74705SXin Li       }
1716*67e74705SXin Li     }
1717*67e74705SXin Li 
1718*67e74705SXin Li     if (!IsUDSuffix) {
1719*67e74705SXin Li       if (!isLexingRawMode())
1720*67e74705SXin Li         Diag(CurPtr, getLangOpts().MSVCCompat
1721*67e74705SXin Li                          ? diag::ext_ms_reserved_user_defined_literal
1722*67e74705SXin Li                          : diag::ext_reserved_user_defined_literal)
1723*67e74705SXin Li           << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1724*67e74705SXin Li       return CurPtr;
1725*67e74705SXin Li     }
1726*67e74705SXin Li 
1727*67e74705SXin Li     CurPtr = ConsumeChar(CurPtr, Size, Result);
1728*67e74705SXin Li   }
1729*67e74705SXin Li 
1730*67e74705SXin Li   Result.setFlag(Token::HasUDSuffix);
1731*67e74705SXin Li   while (true) {
1732*67e74705SXin Li     C = getCharAndSize(CurPtr, Size);
1733*67e74705SXin Li     if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1734*67e74705SXin Li     else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1735*67e74705SXin Li     else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1736*67e74705SXin Li     else break;
1737*67e74705SXin Li   }
1738*67e74705SXin Li 
1739*67e74705SXin Li   return CurPtr;
1740*67e74705SXin Li }
1741*67e74705SXin Li 
1742*67e74705SXin Li /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1743*67e74705SXin Li /// either " or L" or u8" or u" or U".
LexStringLiteral(Token & Result,const char * CurPtr,tok::TokenKind Kind)1744*67e74705SXin Li bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1745*67e74705SXin Li                              tok::TokenKind Kind) {
1746*67e74705SXin Li   // Does this string contain the \0 character?
1747*67e74705SXin Li   const char *NulCharacter = nullptr;
1748*67e74705SXin Li 
1749*67e74705SXin Li   if (!isLexingRawMode() &&
1750*67e74705SXin Li       (Kind == tok::utf8_string_literal ||
1751*67e74705SXin Li        Kind == tok::utf16_string_literal ||
1752*67e74705SXin Li        Kind == tok::utf32_string_literal))
1753*67e74705SXin Li     Diag(BufferPtr, getLangOpts().CPlusPlus
1754*67e74705SXin Li            ? diag::warn_cxx98_compat_unicode_literal
1755*67e74705SXin Li            : diag::warn_c99_compat_unicode_literal);
1756*67e74705SXin Li 
1757*67e74705SXin Li   char C = getAndAdvanceChar(CurPtr, Result);
1758*67e74705SXin Li   while (C != '"') {
1759*67e74705SXin Li     // Skip escaped characters.  Escaped newlines will already be processed by
1760*67e74705SXin Li     // getAndAdvanceChar.
1761*67e74705SXin Li     if (C == '\\')
1762*67e74705SXin Li       C = getAndAdvanceChar(CurPtr, Result);
1763*67e74705SXin Li 
1764*67e74705SXin Li     if (C == '\n' || C == '\r' ||             // Newline.
1765*67e74705SXin Li         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
1766*67e74705SXin Li       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1767*67e74705SXin Li         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1768*67e74705SXin Li       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1769*67e74705SXin Li       return true;
1770*67e74705SXin Li     }
1771*67e74705SXin Li 
1772*67e74705SXin Li     if (C == 0) {
1773*67e74705SXin Li       if (isCodeCompletionPoint(CurPtr-1)) {
1774*67e74705SXin Li         PP->CodeCompleteNaturalLanguage();
1775*67e74705SXin Li         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1776*67e74705SXin Li         cutOffLexing();
1777*67e74705SXin Li         return true;
1778*67e74705SXin Li       }
1779*67e74705SXin Li 
1780*67e74705SXin Li       NulCharacter = CurPtr-1;
1781*67e74705SXin Li     }
1782*67e74705SXin Li     C = getAndAdvanceChar(CurPtr, Result);
1783*67e74705SXin Li   }
1784*67e74705SXin Li 
1785*67e74705SXin Li   // If we are in C++11, lex the optional ud-suffix.
1786*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1787*67e74705SXin Li     CurPtr = LexUDSuffix(Result, CurPtr, true);
1788*67e74705SXin Li 
1789*67e74705SXin Li   // If a nul character existed in the string, warn about it.
1790*67e74705SXin Li   if (NulCharacter && !isLexingRawMode())
1791*67e74705SXin Li     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1792*67e74705SXin Li 
1793*67e74705SXin Li   // Update the location of the token as well as the BufferPtr instance var.
1794*67e74705SXin Li   const char *TokStart = BufferPtr;
1795*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, Kind);
1796*67e74705SXin Li   Result.setLiteralData(TokStart);
1797*67e74705SXin Li   return true;
1798*67e74705SXin Li }
1799*67e74705SXin Li 
1800*67e74705SXin Li /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1801*67e74705SXin Li /// having lexed R", LR", u8R", uR", or UR".
LexRawStringLiteral(Token & Result,const char * CurPtr,tok::TokenKind Kind)1802*67e74705SXin Li bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1803*67e74705SXin Li                                 tok::TokenKind Kind) {
1804*67e74705SXin Li   // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1805*67e74705SXin Li   //  Between the initial and final double quote characters of the raw string,
1806*67e74705SXin Li   //  any transformations performed in phases 1 and 2 (trigraphs,
1807*67e74705SXin Li   //  universal-character-names, and line splicing) are reverted.
1808*67e74705SXin Li 
1809*67e74705SXin Li   if (!isLexingRawMode())
1810*67e74705SXin Li     Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1811*67e74705SXin Li 
1812*67e74705SXin Li   unsigned PrefixLen = 0;
1813*67e74705SXin Li 
1814*67e74705SXin Li   while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1815*67e74705SXin Li     ++PrefixLen;
1816*67e74705SXin Li 
1817*67e74705SXin Li   // If the last character was not a '(', then we didn't lex a valid delimiter.
1818*67e74705SXin Li   if (CurPtr[PrefixLen] != '(') {
1819*67e74705SXin Li     if (!isLexingRawMode()) {
1820*67e74705SXin Li       const char *PrefixEnd = &CurPtr[PrefixLen];
1821*67e74705SXin Li       if (PrefixLen == 16) {
1822*67e74705SXin Li         Diag(PrefixEnd, diag::err_raw_delim_too_long);
1823*67e74705SXin Li       } else {
1824*67e74705SXin Li         Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1825*67e74705SXin Li           << StringRef(PrefixEnd, 1);
1826*67e74705SXin Li       }
1827*67e74705SXin Li     }
1828*67e74705SXin Li 
1829*67e74705SXin Li     // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1830*67e74705SXin Li     // it's possible the '"' was intended to be part of the raw string, but
1831*67e74705SXin Li     // there's not much we can do about that.
1832*67e74705SXin Li     while (1) {
1833*67e74705SXin Li       char C = *CurPtr++;
1834*67e74705SXin Li 
1835*67e74705SXin Li       if (C == '"')
1836*67e74705SXin Li         break;
1837*67e74705SXin Li       if (C == 0 && CurPtr-1 == BufferEnd) {
1838*67e74705SXin Li         --CurPtr;
1839*67e74705SXin Li         break;
1840*67e74705SXin Li       }
1841*67e74705SXin Li     }
1842*67e74705SXin Li 
1843*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::unknown);
1844*67e74705SXin Li     return true;
1845*67e74705SXin Li   }
1846*67e74705SXin Li 
1847*67e74705SXin Li   // Save prefix and move CurPtr past it
1848*67e74705SXin Li   const char *Prefix = CurPtr;
1849*67e74705SXin Li   CurPtr += PrefixLen + 1; // skip over prefix and '('
1850*67e74705SXin Li 
1851*67e74705SXin Li   while (1) {
1852*67e74705SXin Li     char C = *CurPtr++;
1853*67e74705SXin Li 
1854*67e74705SXin Li     if (C == ')') {
1855*67e74705SXin Li       // Check for prefix match and closing quote.
1856*67e74705SXin Li       if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1857*67e74705SXin Li         CurPtr += PrefixLen + 1; // skip over prefix and '"'
1858*67e74705SXin Li         break;
1859*67e74705SXin Li       }
1860*67e74705SXin Li     } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1861*67e74705SXin Li       if (!isLexingRawMode())
1862*67e74705SXin Li         Diag(BufferPtr, diag::err_unterminated_raw_string)
1863*67e74705SXin Li           << StringRef(Prefix, PrefixLen);
1864*67e74705SXin Li       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1865*67e74705SXin Li       return true;
1866*67e74705SXin Li     }
1867*67e74705SXin Li   }
1868*67e74705SXin Li 
1869*67e74705SXin Li   // If we are in C++11, lex the optional ud-suffix.
1870*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1871*67e74705SXin Li     CurPtr = LexUDSuffix(Result, CurPtr, true);
1872*67e74705SXin Li 
1873*67e74705SXin Li   // Update the location of token as well as BufferPtr.
1874*67e74705SXin Li   const char *TokStart = BufferPtr;
1875*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, Kind);
1876*67e74705SXin Li   Result.setLiteralData(TokStart);
1877*67e74705SXin Li   return true;
1878*67e74705SXin Li }
1879*67e74705SXin Li 
1880*67e74705SXin Li /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1881*67e74705SXin Li /// after having lexed the '<' character.  This is used for #include filenames.
LexAngledStringLiteral(Token & Result,const char * CurPtr)1882*67e74705SXin Li bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1883*67e74705SXin Li   // Does this string contain the \0 character?
1884*67e74705SXin Li   const char *NulCharacter = nullptr;
1885*67e74705SXin Li   const char *AfterLessPos = CurPtr;
1886*67e74705SXin Li   char C = getAndAdvanceChar(CurPtr, Result);
1887*67e74705SXin Li   while (C != '>') {
1888*67e74705SXin Li     // Skip escaped characters.
1889*67e74705SXin Li     if (C == '\\' && CurPtr < BufferEnd) {
1890*67e74705SXin Li       // Skip the escaped character.
1891*67e74705SXin Li       getAndAdvanceChar(CurPtr, Result);
1892*67e74705SXin Li     } else if (C == '\n' || C == '\r' ||             // Newline.
1893*67e74705SXin Li                (C == 0 && (CurPtr-1 == BufferEnd ||  // End of file.
1894*67e74705SXin Li                            isCodeCompletionPoint(CurPtr-1)))) {
1895*67e74705SXin Li       // If the filename is unterminated, then it must just be a lone <
1896*67e74705SXin Li       // character.  Return this as such.
1897*67e74705SXin Li       FormTokenWithChars(Result, AfterLessPos, tok::less);
1898*67e74705SXin Li       return true;
1899*67e74705SXin Li     } else if (C == 0) {
1900*67e74705SXin Li       NulCharacter = CurPtr-1;
1901*67e74705SXin Li     }
1902*67e74705SXin Li     C = getAndAdvanceChar(CurPtr, Result);
1903*67e74705SXin Li   }
1904*67e74705SXin Li 
1905*67e74705SXin Li   // If a nul character existed in the string, warn about it.
1906*67e74705SXin Li   if (NulCharacter && !isLexingRawMode())
1907*67e74705SXin Li     Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1908*67e74705SXin Li 
1909*67e74705SXin Li   // Update the location of token as well as BufferPtr.
1910*67e74705SXin Li   const char *TokStart = BufferPtr;
1911*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1912*67e74705SXin Li   Result.setLiteralData(TokStart);
1913*67e74705SXin Li   return true;
1914*67e74705SXin Li }
1915*67e74705SXin Li 
1916*67e74705SXin Li 
1917*67e74705SXin Li /// LexCharConstant - Lex the remainder of a character constant, after having
1918*67e74705SXin Li /// lexed either ' or L' or u8' or u' or U'.
LexCharConstant(Token & Result,const char * CurPtr,tok::TokenKind Kind)1919*67e74705SXin Li bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1920*67e74705SXin Li                             tok::TokenKind Kind) {
1921*67e74705SXin Li   // Does this character contain the \0 character?
1922*67e74705SXin Li   const char *NulCharacter = nullptr;
1923*67e74705SXin Li 
1924*67e74705SXin Li   if (!isLexingRawMode()) {
1925*67e74705SXin Li     if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1926*67e74705SXin Li       Diag(BufferPtr, getLangOpts().CPlusPlus
1927*67e74705SXin Li                           ? diag::warn_cxx98_compat_unicode_literal
1928*67e74705SXin Li                           : diag::warn_c99_compat_unicode_literal);
1929*67e74705SXin Li     else if (Kind == tok::utf8_char_constant)
1930*67e74705SXin Li       Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1931*67e74705SXin Li   }
1932*67e74705SXin Li 
1933*67e74705SXin Li   char C = getAndAdvanceChar(CurPtr, Result);
1934*67e74705SXin Li   if (C == '\'') {
1935*67e74705SXin Li     if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1936*67e74705SXin Li       Diag(BufferPtr, diag::ext_empty_character);
1937*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::unknown);
1938*67e74705SXin Li     return true;
1939*67e74705SXin Li   }
1940*67e74705SXin Li 
1941*67e74705SXin Li   while (C != '\'') {
1942*67e74705SXin Li     // Skip escaped characters.
1943*67e74705SXin Li     if (C == '\\')
1944*67e74705SXin Li       C = getAndAdvanceChar(CurPtr, Result);
1945*67e74705SXin Li 
1946*67e74705SXin Li     if (C == '\n' || C == '\r' ||             // Newline.
1947*67e74705SXin Li         (C == 0 && CurPtr-1 == BufferEnd)) {  // End of file.
1948*67e74705SXin Li       if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1949*67e74705SXin Li         Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1950*67e74705SXin Li       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1951*67e74705SXin Li       return true;
1952*67e74705SXin Li     }
1953*67e74705SXin Li 
1954*67e74705SXin Li     if (C == 0) {
1955*67e74705SXin Li       if (isCodeCompletionPoint(CurPtr-1)) {
1956*67e74705SXin Li         PP->CodeCompleteNaturalLanguage();
1957*67e74705SXin Li         FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1958*67e74705SXin Li         cutOffLexing();
1959*67e74705SXin Li         return true;
1960*67e74705SXin Li       }
1961*67e74705SXin Li 
1962*67e74705SXin Li       NulCharacter = CurPtr-1;
1963*67e74705SXin Li     }
1964*67e74705SXin Li     C = getAndAdvanceChar(CurPtr, Result);
1965*67e74705SXin Li   }
1966*67e74705SXin Li 
1967*67e74705SXin Li   // If we are in C++11, lex the optional ud-suffix.
1968*67e74705SXin Li   if (getLangOpts().CPlusPlus)
1969*67e74705SXin Li     CurPtr = LexUDSuffix(Result, CurPtr, false);
1970*67e74705SXin Li 
1971*67e74705SXin Li   // If a nul character existed in the character, warn about it.
1972*67e74705SXin Li   if (NulCharacter && !isLexingRawMode())
1973*67e74705SXin Li     Diag(NulCharacter, diag::null_in_char_or_string) << 0;
1974*67e74705SXin Li 
1975*67e74705SXin Li   // Update the location of token as well as BufferPtr.
1976*67e74705SXin Li   const char *TokStart = BufferPtr;
1977*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, Kind);
1978*67e74705SXin Li   Result.setLiteralData(TokStart);
1979*67e74705SXin Li   return true;
1980*67e74705SXin Li }
1981*67e74705SXin Li 
1982*67e74705SXin Li /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1983*67e74705SXin Li /// Update BufferPtr to point to the next non-whitespace character and return.
1984*67e74705SXin Li ///
1985*67e74705SXin Li /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1986*67e74705SXin Li ///
SkipWhitespace(Token & Result,const char * CurPtr,bool & TokAtPhysicalStartOfLine)1987*67e74705SXin Li bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1988*67e74705SXin Li                            bool &TokAtPhysicalStartOfLine) {
1989*67e74705SXin Li   // Whitespace - Skip it, then return the token after the whitespace.
1990*67e74705SXin Li   bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1991*67e74705SXin Li 
1992*67e74705SXin Li   unsigned char Char = *CurPtr;
1993*67e74705SXin Li 
1994*67e74705SXin Li   // Skip consecutive spaces efficiently.
1995*67e74705SXin Li   while (1) {
1996*67e74705SXin Li     // Skip horizontal whitespace very aggressively.
1997*67e74705SXin Li     while (isHorizontalWhitespace(Char))
1998*67e74705SXin Li       Char = *++CurPtr;
1999*67e74705SXin Li 
2000*67e74705SXin Li     // Otherwise if we have something other than whitespace, we're done.
2001*67e74705SXin Li     if (!isVerticalWhitespace(Char))
2002*67e74705SXin Li       break;
2003*67e74705SXin Li 
2004*67e74705SXin Li     if (ParsingPreprocessorDirective) {
2005*67e74705SXin Li       // End of preprocessor directive line, let LexTokenInternal handle this.
2006*67e74705SXin Li       BufferPtr = CurPtr;
2007*67e74705SXin Li       return false;
2008*67e74705SXin Li     }
2009*67e74705SXin Li 
2010*67e74705SXin Li     // OK, but handle newline.
2011*67e74705SXin Li     SawNewline = true;
2012*67e74705SXin Li     Char = *++CurPtr;
2013*67e74705SXin Li   }
2014*67e74705SXin Li 
2015*67e74705SXin Li   // If the client wants us to return whitespace, return it now.
2016*67e74705SXin Li   if (isKeepWhitespaceMode()) {
2017*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::unknown);
2018*67e74705SXin Li     if (SawNewline) {
2019*67e74705SXin Li       IsAtStartOfLine = true;
2020*67e74705SXin Li       IsAtPhysicalStartOfLine = true;
2021*67e74705SXin Li     }
2022*67e74705SXin Li     // FIXME: The next token will not have LeadingSpace set.
2023*67e74705SXin Li     return true;
2024*67e74705SXin Li   }
2025*67e74705SXin Li 
2026*67e74705SXin Li   // If this isn't immediately after a newline, there is leading space.
2027*67e74705SXin Li   char PrevChar = CurPtr[-1];
2028*67e74705SXin Li   bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2029*67e74705SXin Li 
2030*67e74705SXin Li   Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2031*67e74705SXin Li   if (SawNewline) {
2032*67e74705SXin Li     Result.setFlag(Token::StartOfLine);
2033*67e74705SXin Li     TokAtPhysicalStartOfLine = true;
2034*67e74705SXin Li   }
2035*67e74705SXin Li 
2036*67e74705SXin Li   BufferPtr = CurPtr;
2037*67e74705SXin Li   return false;
2038*67e74705SXin Li }
2039*67e74705SXin Li 
2040*67e74705SXin Li /// We have just read the // characters from input.  Skip until we find the
2041*67e74705SXin Li /// newline character thats terminate the comment.  Then update BufferPtr and
2042*67e74705SXin Li /// return.
2043*67e74705SXin Li ///
2044*67e74705SXin Li /// If we're in KeepCommentMode or any CommentHandler has inserted
2045*67e74705SXin Li /// some tokens, this will store the first token and return true.
SkipLineComment(Token & Result,const char * CurPtr,bool & TokAtPhysicalStartOfLine)2046*67e74705SXin Li bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2047*67e74705SXin Li                             bool &TokAtPhysicalStartOfLine) {
2048*67e74705SXin Li   // If Line comments aren't explicitly enabled for this language, emit an
2049*67e74705SXin Li   // extension warning.
2050*67e74705SXin Li   if (!LangOpts.LineComment && !isLexingRawMode()) {
2051*67e74705SXin Li     Diag(BufferPtr, diag::ext_line_comment);
2052*67e74705SXin Li 
2053*67e74705SXin Li     // Mark them enabled so we only emit one warning for this translation
2054*67e74705SXin Li     // unit.
2055*67e74705SXin Li     LangOpts.LineComment = true;
2056*67e74705SXin Li   }
2057*67e74705SXin Li 
2058*67e74705SXin Li   // Scan over the body of the comment.  The common case, when scanning, is that
2059*67e74705SXin Li   // the comment contains normal ascii characters with nothing interesting in
2060*67e74705SXin Li   // them.  As such, optimize for this case with the inner loop.
2061*67e74705SXin Li   char C;
2062*67e74705SXin Li   do {
2063*67e74705SXin Li     C = *CurPtr;
2064*67e74705SXin Li     // Skip over characters in the fast loop.
2065*67e74705SXin Li     while (C != 0 &&                // Potentially EOF.
2066*67e74705SXin Li            C != '\n' && C != '\r')  // Newline or DOS-style newline.
2067*67e74705SXin Li       C = *++CurPtr;
2068*67e74705SXin Li 
2069*67e74705SXin Li     const char *NextLine = CurPtr;
2070*67e74705SXin Li     if (C != 0) {
2071*67e74705SXin Li       // We found a newline, see if it's escaped.
2072*67e74705SXin Li       const char *EscapePtr = CurPtr-1;
2073*67e74705SXin Li       bool HasSpace = false;
2074*67e74705SXin Li       while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2075*67e74705SXin Li         --EscapePtr;
2076*67e74705SXin Li         HasSpace = true;
2077*67e74705SXin Li       }
2078*67e74705SXin Li 
2079*67e74705SXin Li       if (*EscapePtr == '\\') // Escaped newline.
2080*67e74705SXin Li         CurPtr = EscapePtr;
2081*67e74705SXin Li       else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2082*67e74705SXin Li                EscapePtr[-2] == '?') // Trigraph-escaped newline.
2083*67e74705SXin Li         CurPtr = EscapePtr-2;
2084*67e74705SXin Li       else
2085*67e74705SXin Li         break; // This is a newline, we're done.
2086*67e74705SXin Li 
2087*67e74705SXin Li       // If there was space between the backslash and newline, warn about it.
2088*67e74705SXin Li       if (HasSpace && !isLexingRawMode())
2089*67e74705SXin Li         Diag(EscapePtr, diag::backslash_newline_space);
2090*67e74705SXin Li     }
2091*67e74705SXin Li 
2092*67e74705SXin Li     // Otherwise, this is a hard case.  Fall back on getAndAdvanceChar to
2093*67e74705SXin Li     // properly decode the character.  Read it in raw mode to avoid emitting
2094*67e74705SXin Li     // diagnostics about things like trigraphs.  If we see an escaped newline,
2095*67e74705SXin Li     // we'll handle it below.
2096*67e74705SXin Li     const char *OldPtr = CurPtr;
2097*67e74705SXin Li     bool OldRawMode = isLexingRawMode();
2098*67e74705SXin Li     LexingRawMode = true;
2099*67e74705SXin Li     C = getAndAdvanceChar(CurPtr, Result);
2100*67e74705SXin Li     LexingRawMode = OldRawMode;
2101*67e74705SXin Li 
2102*67e74705SXin Li     // If we only read only one character, then no special handling is needed.
2103*67e74705SXin Li     // We're done and can skip forward to the newline.
2104*67e74705SXin Li     if (C != 0 && CurPtr == OldPtr+1) {
2105*67e74705SXin Li       CurPtr = NextLine;
2106*67e74705SXin Li       break;
2107*67e74705SXin Li     }
2108*67e74705SXin Li 
2109*67e74705SXin Li     // If we read multiple characters, and one of those characters was a \r or
2110*67e74705SXin Li     // \n, then we had an escaped newline within the comment.  Emit diagnostic
2111*67e74705SXin Li     // unless the next line is also a // comment.
2112*67e74705SXin Li     if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2113*67e74705SXin Li       for (; OldPtr != CurPtr; ++OldPtr)
2114*67e74705SXin Li         if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2115*67e74705SXin Li           // Okay, we found a // comment that ends in a newline, if the next
2116*67e74705SXin Li           // line is also a // comment, but has spaces, don't emit a diagnostic.
2117*67e74705SXin Li           if (isWhitespace(C)) {
2118*67e74705SXin Li             const char *ForwardPtr = CurPtr;
2119*67e74705SXin Li             while (isWhitespace(*ForwardPtr))  // Skip whitespace.
2120*67e74705SXin Li               ++ForwardPtr;
2121*67e74705SXin Li             if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2122*67e74705SXin Li               break;
2123*67e74705SXin Li           }
2124*67e74705SXin Li 
2125*67e74705SXin Li           if (!isLexingRawMode())
2126*67e74705SXin Li             Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2127*67e74705SXin Li           break;
2128*67e74705SXin Li         }
2129*67e74705SXin Li     }
2130*67e74705SXin Li 
2131*67e74705SXin Li     if (CurPtr == BufferEnd+1) {
2132*67e74705SXin Li       --CurPtr;
2133*67e74705SXin Li       break;
2134*67e74705SXin Li     }
2135*67e74705SXin Li 
2136*67e74705SXin Li     if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2137*67e74705SXin Li       PP->CodeCompleteNaturalLanguage();
2138*67e74705SXin Li       cutOffLexing();
2139*67e74705SXin Li       return false;
2140*67e74705SXin Li     }
2141*67e74705SXin Li 
2142*67e74705SXin Li   } while (C != '\n' && C != '\r');
2143*67e74705SXin Li 
2144*67e74705SXin Li   // Found but did not consume the newline.  Notify comment handlers about the
2145*67e74705SXin Li   // comment unless we're in a #if 0 block.
2146*67e74705SXin Li   if (PP && !isLexingRawMode() &&
2147*67e74705SXin Li       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2148*67e74705SXin Li                                             getSourceLocation(CurPtr)))) {
2149*67e74705SXin Li     BufferPtr = CurPtr;
2150*67e74705SXin Li     return true; // A token has to be returned.
2151*67e74705SXin Li   }
2152*67e74705SXin Li 
2153*67e74705SXin Li   // If we are returning comments as tokens, return this comment as a token.
2154*67e74705SXin Li   if (inKeepCommentMode())
2155*67e74705SXin Li     return SaveLineComment(Result, CurPtr);
2156*67e74705SXin Li 
2157*67e74705SXin Li   // If we are inside a preprocessor directive and we see the end of line,
2158*67e74705SXin Li   // return immediately, so that the lexer can return this as an EOD token.
2159*67e74705SXin Li   if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2160*67e74705SXin Li     BufferPtr = CurPtr;
2161*67e74705SXin Li     return false;
2162*67e74705SXin Li   }
2163*67e74705SXin Li 
2164*67e74705SXin Li   // Otherwise, eat the \n character.  We don't care if this is a \n\r or
2165*67e74705SXin Li   // \r\n sequence.  This is an efficiency hack (because we know the \n can't
2166*67e74705SXin Li   // contribute to another token), it isn't needed for correctness.  Note that
2167*67e74705SXin Li   // this is ok even in KeepWhitespaceMode, because we would have returned the
2168*67e74705SXin Li   /// comment above in that mode.
2169*67e74705SXin Li   ++CurPtr;
2170*67e74705SXin Li 
2171*67e74705SXin Li   // The next returned token is at the start of the line.
2172*67e74705SXin Li   Result.setFlag(Token::StartOfLine);
2173*67e74705SXin Li   TokAtPhysicalStartOfLine = true;
2174*67e74705SXin Li   // No leading whitespace seen so far.
2175*67e74705SXin Li   Result.clearFlag(Token::LeadingSpace);
2176*67e74705SXin Li   BufferPtr = CurPtr;
2177*67e74705SXin Li   return false;
2178*67e74705SXin Li }
2179*67e74705SXin Li 
2180*67e74705SXin Li /// If in save-comment mode, package up this Line comment in an appropriate
2181*67e74705SXin Li /// way and return it.
SaveLineComment(Token & Result,const char * CurPtr)2182*67e74705SXin Li bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2183*67e74705SXin Li   // If we're not in a preprocessor directive, just return the // comment
2184*67e74705SXin Li   // directly.
2185*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, tok::comment);
2186*67e74705SXin Li 
2187*67e74705SXin Li   if (!ParsingPreprocessorDirective || LexingRawMode)
2188*67e74705SXin Li     return true;
2189*67e74705SXin Li 
2190*67e74705SXin Li   // If this Line-style comment is in a macro definition, transmogrify it into
2191*67e74705SXin Li   // a C-style block comment.
2192*67e74705SXin Li   bool Invalid = false;
2193*67e74705SXin Li   std::string Spelling = PP->getSpelling(Result, &Invalid);
2194*67e74705SXin Li   if (Invalid)
2195*67e74705SXin Li     return true;
2196*67e74705SXin Li 
2197*67e74705SXin Li   assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2198*67e74705SXin Li   Spelling[1] = '*';   // Change prefix to "/*".
2199*67e74705SXin Li   Spelling += "*/";    // add suffix.
2200*67e74705SXin Li 
2201*67e74705SXin Li   Result.setKind(tok::comment);
2202*67e74705SXin Li   PP->CreateString(Spelling, Result,
2203*67e74705SXin Li                    Result.getLocation(), Result.getLocation());
2204*67e74705SXin Li   return true;
2205*67e74705SXin Li }
2206*67e74705SXin Li 
2207*67e74705SXin Li /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2208*67e74705SXin Li /// character (either \\n or \\r) is part of an escaped newline sequence.  Issue
2209*67e74705SXin Li /// a diagnostic if so.  We know that the newline is inside of a block comment.
isEndOfBlockCommentWithEscapedNewLine(const char * CurPtr,Lexer * L)2210*67e74705SXin Li static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2211*67e74705SXin Li                                                   Lexer *L) {
2212*67e74705SXin Li   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2213*67e74705SXin Li 
2214*67e74705SXin Li   // Back up off the newline.
2215*67e74705SXin Li   --CurPtr;
2216*67e74705SXin Li 
2217*67e74705SXin Li   // If this is a two-character newline sequence, skip the other character.
2218*67e74705SXin Li   if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2219*67e74705SXin Li     // \n\n or \r\r -> not escaped newline.
2220*67e74705SXin Li     if (CurPtr[0] == CurPtr[1])
2221*67e74705SXin Li       return false;
2222*67e74705SXin Li     // \n\r or \r\n -> skip the newline.
2223*67e74705SXin Li     --CurPtr;
2224*67e74705SXin Li   }
2225*67e74705SXin Li 
2226*67e74705SXin Li   // If we have horizontal whitespace, skip over it.  We allow whitespace
2227*67e74705SXin Li   // between the slash and newline.
2228*67e74705SXin Li   bool HasSpace = false;
2229*67e74705SXin Li   while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2230*67e74705SXin Li     --CurPtr;
2231*67e74705SXin Li     HasSpace = true;
2232*67e74705SXin Li   }
2233*67e74705SXin Li 
2234*67e74705SXin Li   // If we have a slash, we know this is an escaped newline.
2235*67e74705SXin Li   if (*CurPtr == '\\') {
2236*67e74705SXin Li     if (CurPtr[-1] != '*') return false;
2237*67e74705SXin Li   } else {
2238*67e74705SXin Li     // It isn't a slash, is it the ?? / trigraph?
2239*67e74705SXin Li     if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2240*67e74705SXin Li         CurPtr[-3] != '*')
2241*67e74705SXin Li       return false;
2242*67e74705SXin Li 
2243*67e74705SXin Li     // This is the trigraph ending the comment.  Emit a stern warning!
2244*67e74705SXin Li     CurPtr -= 2;
2245*67e74705SXin Li 
2246*67e74705SXin Li     // If no trigraphs are enabled, warn that we ignored this trigraph and
2247*67e74705SXin Li     // ignore this * character.
2248*67e74705SXin Li     if (!L->getLangOpts().Trigraphs) {
2249*67e74705SXin Li       if (!L->isLexingRawMode())
2250*67e74705SXin Li         L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2251*67e74705SXin Li       return false;
2252*67e74705SXin Li     }
2253*67e74705SXin Li     if (!L->isLexingRawMode())
2254*67e74705SXin Li       L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2255*67e74705SXin Li   }
2256*67e74705SXin Li 
2257*67e74705SXin Li   // Warn about having an escaped newline between the */ characters.
2258*67e74705SXin Li   if (!L->isLexingRawMode())
2259*67e74705SXin Li     L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2260*67e74705SXin Li 
2261*67e74705SXin Li   // If there was space between the backslash and newline, warn about it.
2262*67e74705SXin Li   if (HasSpace && !L->isLexingRawMode())
2263*67e74705SXin Li     L->Diag(CurPtr, diag::backslash_newline_space);
2264*67e74705SXin Li 
2265*67e74705SXin Li   return true;
2266*67e74705SXin Li }
2267*67e74705SXin Li 
2268*67e74705SXin Li #ifdef __SSE2__
2269*67e74705SXin Li #include <emmintrin.h>
2270*67e74705SXin Li #elif __ALTIVEC__
2271*67e74705SXin Li #include <altivec.h>
2272*67e74705SXin Li #undef bool
2273*67e74705SXin Li #endif
2274*67e74705SXin Li 
2275*67e74705SXin Li /// We have just read from input the / and * characters that started a comment.
2276*67e74705SXin Li /// Read until we find the * and / characters that terminate the comment.
2277*67e74705SXin Li /// Note that we don't bother decoding trigraphs or escaped newlines in block
2278*67e74705SXin Li /// comments, because they cannot cause the comment to end.  The only thing
2279*67e74705SXin Li /// that can happen is the comment could end with an escaped newline between
2280*67e74705SXin Li /// the terminating * and /.
2281*67e74705SXin Li ///
2282*67e74705SXin Li /// If we're in KeepCommentMode or any CommentHandler has inserted
2283*67e74705SXin Li /// some tokens, this will store the first token and return true.
SkipBlockComment(Token & Result,const char * CurPtr,bool & TokAtPhysicalStartOfLine)2284*67e74705SXin Li bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2285*67e74705SXin Li                              bool &TokAtPhysicalStartOfLine) {
2286*67e74705SXin Li   // Scan one character past where we should, looking for a '/' character.  Once
2287*67e74705SXin Li   // we find it, check to see if it was preceded by a *.  This common
2288*67e74705SXin Li   // optimization helps people who like to put a lot of * characters in their
2289*67e74705SXin Li   // comments.
2290*67e74705SXin Li 
2291*67e74705SXin Li   // The first character we get with newlines and trigraphs skipped to handle
2292*67e74705SXin Li   // the degenerate /*/ case below correctly if the * has an escaped newline
2293*67e74705SXin Li   // after it.
2294*67e74705SXin Li   unsigned CharSize;
2295*67e74705SXin Li   unsigned char C = getCharAndSize(CurPtr, CharSize);
2296*67e74705SXin Li   CurPtr += CharSize;
2297*67e74705SXin Li   if (C == 0 && CurPtr == BufferEnd+1) {
2298*67e74705SXin Li     if (!isLexingRawMode())
2299*67e74705SXin Li       Diag(BufferPtr, diag::err_unterminated_block_comment);
2300*67e74705SXin Li     --CurPtr;
2301*67e74705SXin Li 
2302*67e74705SXin Li     // KeepWhitespaceMode should return this broken comment as a token.  Since
2303*67e74705SXin Li     // it isn't a well formed comment, just return it as an 'unknown' token.
2304*67e74705SXin Li     if (isKeepWhitespaceMode()) {
2305*67e74705SXin Li       FormTokenWithChars(Result, CurPtr, tok::unknown);
2306*67e74705SXin Li       return true;
2307*67e74705SXin Li     }
2308*67e74705SXin Li 
2309*67e74705SXin Li     BufferPtr = CurPtr;
2310*67e74705SXin Li     return false;
2311*67e74705SXin Li   }
2312*67e74705SXin Li 
2313*67e74705SXin Li   // Check to see if the first character after the '/*' is another /.  If so,
2314*67e74705SXin Li   // then this slash does not end the block comment, it is part of it.
2315*67e74705SXin Li   if (C == '/')
2316*67e74705SXin Li     C = *CurPtr++;
2317*67e74705SXin Li 
2318*67e74705SXin Li   while (1) {
2319*67e74705SXin Li     // Skip over all non-interesting characters until we find end of buffer or a
2320*67e74705SXin Li     // (probably ending) '/' character.
2321*67e74705SXin Li     if (CurPtr + 24 < BufferEnd &&
2322*67e74705SXin Li         // If there is a code-completion point avoid the fast scan because it
2323*67e74705SXin Li         // doesn't check for '\0'.
2324*67e74705SXin Li         !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2325*67e74705SXin Li       // While not aligned to a 16-byte boundary.
2326*67e74705SXin Li       while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2327*67e74705SXin Li         C = *CurPtr++;
2328*67e74705SXin Li 
2329*67e74705SXin Li       if (C == '/') goto FoundSlash;
2330*67e74705SXin Li 
2331*67e74705SXin Li #ifdef __SSE2__
2332*67e74705SXin Li       __m128i Slashes = _mm_set1_epi8('/');
2333*67e74705SXin Li       while (CurPtr+16 <= BufferEnd) {
2334*67e74705SXin Li         int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2335*67e74705SXin Li                                     Slashes));
2336*67e74705SXin Li         if (cmp != 0) {
2337*67e74705SXin Li           // Adjust the pointer to point directly after the first slash. It's
2338*67e74705SXin Li           // not necessary to set C here, it will be overwritten at the end of
2339*67e74705SXin Li           // the outer loop.
2340*67e74705SXin Li           CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2341*67e74705SXin Li           goto FoundSlash;
2342*67e74705SXin Li         }
2343*67e74705SXin Li         CurPtr += 16;
2344*67e74705SXin Li       }
2345*67e74705SXin Li #elif __ALTIVEC__
2346*67e74705SXin Li       __vector unsigned char Slashes = {
2347*67e74705SXin Li         '/', '/', '/', '/',  '/', '/', '/', '/',
2348*67e74705SXin Li         '/', '/', '/', '/',  '/', '/', '/', '/'
2349*67e74705SXin Li       };
2350*67e74705SXin Li       while (CurPtr+16 <= BufferEnd &&
2351*67e74705SXin Li              !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2352*67e74705SXin Li         CurPtr += 16;
2353*67e74705SXin Li #else
2354*67e74705SXin Li       // Scan for '/' quickly.  Many block comments are very large.
2355*67e74705SXin Li       while (CurPtr[0] != '/' &&
2356*67e74705SXin Li              CurPtr[1] != '/' &&
2357*67e74705SXin Li              CurPtr[2] != '/' &&
2358*67e74705SXin Li              CurPtr[3] != '/' &&
2359*67e74705SXin Li              CurPtr+4 < BufferEnd) {
2360*67e74705SXin Li         CurPtr += 4;
2361*67e74705SXin Li       }
2362*67e74705SXin Li #endif
2363*67e74705SXin Li 
2364*67e74705SXin Li       // It has to be one of the bytes scanned, increment to it and read one.
2365*67e74705SXin Li       C = *CurPtr++;
2366*67e74705SXin Li     }
2367*67e74705SXin Li 
2368*67e74705SXin Li     // Loop to scan the remainder.
2369*67e74705SXin Li     while (C != '/' && C != '\0')
2370*67e74705SXin Li       C = *CurPtr++;
2371*67e74705SXin Li 
2372*67e74705SXin Li     if (C == '/') {
2373*67e74705SXin Li   FoundSlash:
2374*67e74705SXin Li       if (CurPtr[-2] == '*')  // We found the final */.  We're done!
2375*67e74705SXin Li         break;
2376*67e74705SXin Li 
2377*67e74705SXin Li       if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2378*67e74705SXin Li         if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2379*67e74705SXin Li           // We found the final */, though it had an escaped newline between the
2380*67e74705SXin Li           // * and /.  We're done!
2381*67e74705SXin Li           break;
2382*67e74705SXin Li         }
2383*67e74705SXin Li       }
2384*67e74705SXin Li       if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2385*67e74705SXin Li         // If this is a /* inside of the comment, emit a warning.  Don't do this
2386*67e74705SXin Li         // if this is a /*/, which will end the comment.  This misses cases with
2387*67e74705SXin Li         // embedded escaped newlines, but oh well.
2388*67e74705SXin Li         if (!isLexingRawMode())
2389*67e74705SXin Li           Diag(CurPtr-1, diag::warn_nested_block_comment);
2390*67e74705SXin Li       }
2391*67e74705SXin Li     } else if (C == 0 && CurPtr == BufferEnd+1) {
2392*67e74705SXin Li       if (!isLexingRawMode())
2393*67e74705SXin Li         Diag(BufferPtr, diag::err_unterminated_block_comment);
2394*67e74705SXin Li       // Note: the user probably forgot a */.  We could continue immediately
2395*67e74705SXin Li       // after the /*, but this would involve lexing a lot of what really is the
2396*67e74705SXin Li       // comment, which surely would confuse the parser.
2397*67e74705SXin Li       --CurPtr;
2398*67e74705SXin Li 
2399*67e74705SXin Li       // KeepWhitespaceMode should return this broken comment as a token.  Since
2400*67e74705SXin Li       // it isn't a well formed comment, just return it as an 'unknown' token.
2401*67e74705SXin Li       if (isKeepWhitespaceMode()) {
2402*67e74705SXin Li         FormTokenWithChars(Result, CurPtr, tok::unknown);
2403*67e74705SXin Li         return true;
2404*67e74705SXin Li       }
2405*67e74705SXin Li 
2406*67e74705SXin Li       BufferPtr = CurPtr;
2407*67e74705SXin Li       return false;
2408*67e74705SXin Li     } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2409*67e74705SXin Li       PP->CodeCompleteNaturalLanguage();
2410*67e74705SXin Li       cutOffLexing();
2411*67e74705SXin Li       return false;
2412*67e74705SXin Li     }
2413*67e74705SXin Li 
2414*67e74705SXin Li     C = *CurPtr++;
2415*67e74705SXin Li   }
2416*67e74705SXin Li 
2417*67e74705SXin Li   // Notify comment handlers about the comment unless we're in a #if 0 block.
2418*67e74705SXin Li   if (PP && !isLexingRawMode() &&
2419*67e74705SXin Li       PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2420*67e74705SXin Li                                             getSourceLocation(CurPtr)))) {
2421*67e74705SXin Li     BufferPtr = CurPtr;
2422*67e74705SXin Li     return true; // A token has to be returned.
2423*67e74705SXin Li   }
2424*67e74705SXin Li 
2425*67e74705SXin Li   // If we are returning comments as tokens, return this comment as a token.
2426*67e74705SXin Li   if (inKeepCommentMode()) {
2427*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::comment);
2428*67e74705SXin Li     return true;
2429*67e74705SXin Li   }
2430*67e74705SXin Li 
2431*67e74705SXin Li   // It is common for the tokens immediately after a /**/ comment to be
2432*67e74705SXin Li   // whitespace.  Instead of going through the big switch, handle it
2433*67e74705SXin Li   // efficiently now.  This is safe even in KeepWhitespaceMode because we would
2434*67e74705SXin Li   // have already returned above with the comment as a token.
2435*67e74705SXin Li   if (isHorizontalWhitespace(*CurPtr)) {
2436*67e74705SXin Li     SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2437*67e74705SXin Li     return false;
2438*67e74705SXin Li   }
2439*67e74705SXin Li 
2440*67e74705SXin Li   // Otherwise, just return so that the next character will be lexed as a token.
2441*67e74705SXin Li   BufferPtr = CurPtr;
2442*67e74705SXin Li   Result.setFlag(Token::LeadingSpace);
2443*67e74705SXin Li   return false;
2444*67e74705SXin Li }
2445*67e74705SXin Li 
2446*67e74705SXin Li //===----------------------------------------------------------------------===//
2447*67e74705SXin Li // Primary Lexing Entry Points
2448*67e74705SXin Li //===----------------------------------------------------------------------===//
2449*67e74705SXin Li 
2450*67e74705SXin Li /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2451*67e74705SXin Li /// uninterpreted string.  This switches the lexer out of directive mode.
ReadToEndOfLine(SmallVectorImpl<char> * Result)2452*67e74705SXin Li void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2453*67e74705SXin Li   assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2454*67e74705SXin Li          "Must be in a preprocessing directive!");
2455*67e74705SXin Li   Token Tmp;
2456*67e74705SXin Li 
2457*67e74705SXin Li   // CurPtr - Cache BufferPtr in an automatic variable.
2458*67e74705SXin Li   const char *CurPtr = BufferPtr;
2459*67e74705SXin Li   while (1) {
2460*67e74705SXin Li     char Char = getAndAdvanceChar(CurPtr, Tmp);
2461*67e74705SXin Li     switch (Char) {
2462*67e74705SXin Li     default:
2463*67e74705SXin Li       if (Result)
2464*67e74705SXin Li         Result->push_back(Char);
2465*67e74705SXin Li       break;
2466*67e74705SXin Li     case 0:  // Null.
2467*67e74705SXin Li       // Found end of file?
2468*67e74705SXin Li       if (CurPtr-1 != BufferEnd) {
2469*67e74705SXin Li         if (isCodeCompletionPoint(CurPtr-1)) {
2470*67e74705SXin Li           PP->CodeCompleteNaturalLanguage();
2471*67e74705SXin Li           cutOffLexing();
2472*67e74705SXin Li           return;
2473*67e74705SXin Li         }
2474*67e74705SXin Li 
2475*67e74705SXin Li         // Nope, normal character, continue.
2476*67e74705SXin Li         if (Result)
2477*67e74705SXin Li           Result->push_back(Char);
2478*67e74705SXin Li         break;
2479*67e74705SXin Li       }
2480*67e74705SXin Li       // FALL THROUGH.
2481*67e74705SXin Li     case '\r':
2482*67e74705SXin Li     case '\n':
2483*67e74705SXin Li       // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2484*67e74705SXin Li       assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2485*67e74705SXin Li       BufferPtr = CurPtr-1;
2486*67e74705SXin Li 
2487*67e74705SXin Li       // Next, lex the character, which should handle the EOD transition.
2488*67e74705SXin Li       Lex(Tmp);
2489*67e74705SXin Li       if (Tmp.is(tok::code_completion)) {
2490*67e74705SXin Li         if (PP)
2491*67e74705SXin Li           PP->CodeCompleteNaturalLanguage();
2492*67e74705SXin Li         Lex(Tmp);
2493*67e74705SXin Li       }
2494*67e74705SXin Li       assert(Tmp.is(tok::eod) && "Unexpected token!");
2495*67e74705SXin Li 
2496*67e74705SXin Li       // Finally, we're done;
2497*67e74705SXin Li       return;
2498*67e74705SXin Li     }
2499*67e74705SXin Li   }
2500*67e74705SXin Li }
2501*67e74705SXin Li 
2502*67e74705SXin Li /// LexEndOfFile - CurPtr points to the end of this file.  Handle this
2503*67e74705SXin Li /// condition, reporting diagnostics and handling other edge cases as required.
2504*67e74705SXin Li /// This returns true if Result contains a token, false if PP.Lex should be
2505*67e74705SXin Li /// called again.
LexEndOfFile(Token & Result,const char * CurPtr)2506*67e74705SXin Li bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2507*67e74705SXin Li   // If we hit the end of the file while parsing a preprocessor directive,
2508*67e74705SXin Li   // end the preprocessor directive first.  The next token returned will
2509*67e74705SXin Li   // then be the end of file.
2510*67e74705SXin Li   if (ParsingPreprocessorDirective) {
2511*67e74705SXin Li     // Done parsing the "line".
2512*67e74705SXin Li     ParsingPreprocessorDirective = false;
2513*67e74705SXin Li     // Update the location of token as well as BufferPtr.
2514*67e74705SXin Li     FormTokenWithChars(Result, CurPtr, tok::eod);
2515*67e74705SXin Li 
2516*67e74705SXin Li     // Restore comment saving mode, in case it was disabled for directive.
2517*67e74705SXin Li     if (PP)
2518*67e74705SXin Li       resetExtendedTokenMode();
2519*67e74705SXin Li     return true;  // Have a token.
2520*67e74705SXin Li   }
2521*67e74705SXin Li 
2522*67e74705SXin Li   // If we are in raw mode, return this event as an EOF token.  Let the caller
2523*67e74705SXin Li   // that put us in raw mode handle the event.
2524*67e74705SXin Li   if (isLexingRawMode()) {
2525*67e74705SXin Li     Result.startToken();
2526*67e74705SXin Li     BufferPtr = BufferEnd;
2527*67e74705SXin Li     FormTokenWithChars(Result, BufferEnd, tok::eof);
2528*67e74705SXin Li     return true;
2529*67e74705SXin Li   }
2530*67e74705SXin Li 
2531*67e74705SXin Li   // Issue diagnostics for unterminated #if and missing newline.
2532*67e74705SXin Li 
2533*67e74705SXin Li   // If we are in a #if directive, emit an error.
2534*67e74705SXin Li   while (!ConditionalStack.empty()) {
2535*67e74705SXin Li     if (PP->getCodeCompletionFileLoc() != FileLoc)
2536*67e74705SXin Li       PP->Diag(ConditionalStack.back().IfLoc,
2537*67e74705SXin Li                diag::err_pp_unterminated_conditional);
2538*67e74705SXin Li     ConditionalStack.pop_back();
2539*67e74705SXin Li   }
2540*67e74705SXin Li 
2541*67e74705SXin Li   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2542*67e74705SXin Li   // a pedwarn.
2543*67e74705SXin Li   if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2544*67e74705SXin Li     DiagnosticsEngine &Diags = PP->getDiagnostics();
2545*67e74705SXin Li     SourceLocation EndLoc = getSourceLocation(BufferEnd);
2546*67e74705SXin Li     unsigned DiagID;
2547*67e74705SXin Li 
2548*67e74705SXin Li     if (LangOpts.CPlusPlus11) {
2549*67e74705SXin Li       // C++11 [lex.phases] 2.2 p2
2550*67e74705SXin Li       // Prefer the C++98 pedantic compatibility warning over the generic,
2551*67e74705SXin Li       // non-extension, user-requested "missing newline at EOF" warning.
2552*67e74705SXin Li       if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2553*67e74705SXin Li         DiagID = diag::warn_cxx98_compat_no_newline_eof;
2554*67e74705SXin Li       } else {
2555*67e74705SXin Li         DiagID = diag::warn_no_newline_eof;
2556*67e74705SXin Li       }
2557*67e74705SXin Li     } else {
2558*67e74705SXin Li       DiagID = diag::ext_no_newline_eof;
2559*67e74705SXin Li     }
2560*67e74705SXin Li 
2561*67e74705SXin Li     Diag(BufferEnd, DiagID)
2562*67e74705SXin Li       << FixItHint::CreateInsertion(EndLoc, "\n");
2563*67e74705SXin Li   }
2564*67e74705SXin Li 
2565*67e74705SXin Li   BufferPtr = CurPtr;
2566*67e74705SXin Li 
2567*67e74705SXin Li   // Finally, let the preprocessor handle this.
2568*67e74705SXin Li   return PP->HandleEndOfFile(Result, isPragmaLexer());
2569*67e74705SXin Li }
2570*67e74705SXin Li 
2571*67e74705SXin Li /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2572*67e74705SXin Li /// the specified lexer will return a tok::l_paren token, 0 if it is something
2573*67e74705SXin Li /// else and 2 if there are no more tokens in the buffer controlled by the
2574*67e74705SXin Li /// lexer.
isNextPPTokenLParen()2575*67e74705SXin Li unsigned Lexer::isNextPPTokenLParen() {
2576*67e74705SXin Li   assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2577*67e74705SXin Li 
2578*67e74705SXin Li   // Switch to 'skipping' mode.  This will ensure that we can lex a token
2579*67e74705SXin Li   // without emitting diagnostics, disables macro expansion, and will cause EOF
2580*67e74705SXin Li   // to return an EOF token instead of popping the include stack.
2581*67e74705SXin Li   LexingRawMode = true;
2582*67e74705SXin Li 
2583*67e74705SXin Li   // Save state that can be changed while lexing so that we can restore it.
2584*67e74705SXin Li   const char *TmpBufferPtr = BufferPtr;
2585*67e74705SXin Li   bool inPPDirectiveMode = ParsingPreprocessorDirective;
2586*67e74705SXin Li   bool atStartOfLine = IsAtStartOfLine;
2587*67e74705SXin Li   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2588*67e74705SXin Li   bool leadingSpace = HasLeadingSpace;
2589*67e74705SXin Li 
2590*67e74705SXin Li   Token Tok;
2591*67e74705SXin Li   Lex(Tok);
2592*67e74705SXin Li 
2593*67e74705SXin Li   // Restore state that may have changed.
2594*67e74705SXin Li   BufferPtr = TmpBufferPtr;
2595*67e74705SXin Li   ParsingPreprocessorDirective = inPPDirectiveMode;
2596*67e74705SXin Li   HasLeadingSpace = leadingSpace;
2597*67e74705SXin Li   IsAtStartOfLine = atStartOfLine;
2598*67e74705SXin Li   IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2599*67e74705SXin Li 
2600*67e74705SXin Li   // Restore the lexer back to non-skipping mode.
2601*67e74705SXin Li   LexingRawMode = false;
2602*67e74705SXin Li 
2603*67e74705SXin Li   if (Tok.is(tok::eof))
2604*67e74705SXin Li     return 2;
2605*67e74705SXin Li   return Tok.is(tok::l_paren);
2606*67e74705SXin Li }
2607*67e74705SXin Li 
2608*67e74705SXin Li /// \brief Find the end of a version control conflict marker.
FindConflictEnd(const char * CurPtr,const char * BufferEnd,ConflictMarkerKind CMK)2609*67e74705SXin Li static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2610*67e74705SXin Li                                    ConflictMarkerKind CMK) {
2611*67e74705SXin Li   const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2612*67e74705SXin Li   size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2613*67e74705SXin Li   auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2614*67e74705SXin Li   size_t Pos = RestOfBuffer.find(Terminator);
2615*67e74705SXin Li   while (Pos != StringRef::npos) {
2616*67e74705SXin Li     // Must occur at start of line.
2617*67e74705SXin Li     if (Pos == 0 ||
2618*67e74705SXin Li         (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2619*67e74705SXin Li       RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2620*67e74705SXin Li       Pos = RestOfBuffer.find(Terminator);
2621*67e74705SXin Li       continue;
2622*67e74705SXin Li     }
2623*67e74705SXin Li     return RestOfBuffer.data()+Pos;
2624*67e74705SXin Li   }
2625*67e74705SXin Li   return nullptr;
2626*67e74705SXin Li }
2627*67e74705SXin Li 
2628*67e74705SXin Li /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2629*67e74705SXin Li /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2630*67e74705SXin Li /// and recover nicely.  This returns true if it is a conflict marker and false
2631*67e74705SXin Li /// if not.
IsStartOfConflictMarker(const char * CurPtr)2632*67e74705SXin Li bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2633*67e74705SXin Li   // Only a conflict marker if it starts at the beginning of a line.
2634*67e74705SXin Li   if (CurPtr != BufferStart &&
2635*67e74705SXin Li       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2636*67e74705SXin Li     return false;
2637*67e74705SXin Li 
2638*67e74705SXin Li   // Check to see if we have <<<<<<< or >>>>.
2639*67e74705SXin Li   if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2640*67e74705SXin Li       !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2641*67e74705SXin Li     return false;
2642*67e74705SXin Li 
2643*67e74705SXin Li   // If we have a situation where we don't care about conflict markers, ignore
2644*67e74705SXin Li   // it.
2645*67e74705SXin Li   if (CurrentConflictMarkerState || isLexingRawMode())
2646*67e74705SXin Li     return false;
2647*67e74705SXin Li 
2648*67e74705SXin Li   ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2649*67e74705SXin Li 
2650*67e74705SXin Li   // Check to see if there is an ending marker somewhere in the buffer at the
2651*67e74705SXin Li   // start of a line to terminate this conflict marker.
2652*67e74705SXin Li   if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2653*67e74705SXin Li     // We found a match.  We are really in a conflict marker.
2654*67e74705SXin Li     // Diagnose this, and ignore to the end of line.
2655*67e74705SXin Li     Diag(CurPtr, diag::err_conflict_marker);
2656*67e74705SXin Li     CurrentConflictMarkerState = Kind;
2657*67e74705SXin Li 
2658*67e74705SXin Li     // Skip ahead to the end of line.  We know this exists because the
2659*67e74705SXin Li     // end-of-conflict marker starts with \r or \n.
2660*67e74705SXin Li     while (*CurPtr != '\r' && *CurPtr != '\n') {
2661*67e74705SXin Li       assert(CurPtr != BufferEnd && "Didn't find end of line");
2662*67e74705SXin Li       ++CurPtr;
2663*67e74705SXin Li     }
2664*67e74705SXin Li     BufferPtr = CurPtr;
2665*67e74705SXin Li     return true;
2666*67e74705SXin Li   }
2667*67e74705SXin Li 
2668*67e74705SXin Li   // No end of conflict marker found.
2669*67e74705SXin Li   return false;
2670*67e74705SXin Li }
2671*67e74705SXin Li 
2672*67e74705SXin Li 
2673*67e74705SXin Li /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2674*67e74705SXin Li /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2675*67e74705SXin Li /// is the end of a conflict marker.  Handle it by ignoring up until the end of
2676*67e74705SXin Li /// the line.  This returns true if it is a conflict marker and false if not.
HandleEndOfConflictMarker(const char * CurPtr)2677*67e74705SXin Li bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2678*67e74705SXin Li   // Only a conflict marker if it starts at the beginning of a line.
2679*67e74705SXin Li   if (CurPtr != BufferStart &&
2680*67e74705SXin Li       CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2681*67e74705SXin Li     return false;
2682*67e74705SXin Li 
2683*67e74705SXin Li   // If we have a situation where we don't care about conflict markers, ignore
2684*67e74705SXin Li   // it.
2685*67e74705SXin Li   if (!CurrentConflictMarkerState || isLexingRawMode())
2686*67e74705SXin Li     return false;
2687*67e74705SXin Li 
2688*67e74705SXin Li   // Check to see if we have the marker (4 characters in a row).
2689*67e74705SXin Li   for (unsigned i = 1; i != 4; ++i)
2690*67e74705SXin Li     if (CurPtr[i] != CurPtr[0])
2691*67e74705SXin Li       return false;
2692*67e74705SXin Li 
2693*67e74705SXin Li   // If we do have it, search for the end of the conflict marker.  This could
2694*67e74705SXin Li   // fail if it got skipped with a '#if 0' or something.  Note that CurPtr might
2695*67e74705SXin Li   // be the end of conflict marker.
2696*67e74705SXin Li   if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2697*67e74705SXin Li                                         CurrentConflictMarkerState)) {
2698*67e74705SXin Li     CurPtr = End;
2699*67e74705SXin Li 
2700*67e74705SXin Li     // Skip ahead to the end of line.
2701*67e74705SXin Li     while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2702*67e74705SXin Li       ++CurPtr;
2703*67e74705SXin Li 
2704*67e74705SXin Li     BufferPtr = CurPtr;
2705*67e74705SXin Li 
2706*67e74705SXin Li     // No longer in the conflict marker.
2707*67e74705SXin Li     CurrentConflictMarkerState = CMK_None;
2708*67e74705SXin Li     return true;
2709*67e74705SXin Li   }
2710*67e74705SXin Li 
2711*67e74705SXin Li   return false;
2712*67e74705SXin Li }
2713*67e74705SXin Li 
isCodeCompletionPoint(const char * CurPtr) const2714*67e74705SXin Li bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2715*67e74705SXin Li   if (PP && PP->isCodeCompletionEnabled()) {
2716*67e74705SXin Li     SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2717*67e74705SXin Li     return Loc == PP->getCodeCompletionLoc();
2718*67e74705SXin Li   }
2719*67e74705SXin Li 
2720*67e74705SXin Li   return false;
2721*67e74705SXin Li }
2722*67e74705SXin Li 
tryReadUCN(const char * & StartPtr,const char * SlashLoc,Token * Result)2723*67e74705SXin Li uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2724*67e74705SXin Li                            Token *Result) {
2725*67e74705SXin Li   unsigned CharSize;
2726*67e74705SXin Li   char Kind = getCharAndSize(StartPtr, CharSize);
2727*67e74705SXin Li 
2728*67e74705SXin Li   unsigned NumHexDigits;
2729*67e74705SXin Li   if (Kind == 'u')
2730*67e74705SXin Li     NumHexDigits = 4;
2731*67e74705SXin Li   else if (Kind == 'U')
2732*67e74705SXin Li     NumHexDigits = 8;
2733*67e74705SXin Li   else
2734*67e74705SXin Li     return 0;
2735*67e74705SXin Li 
2736*67e74705SXin Li   if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2737*67e74705SXin Li     if (Result && !isLexingRawMode())
2738*67e74705SXin Li       Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2739*67e74705SXin Li     return 0;
2740*67e74705SXin Li   }
2741*67e74705SXin Li 
2742*67e74705SXin Li   const char *CurPtr = StartPtr + CharSize;
2743*67e74705SXin Li   const char *KindLoc = &CurPtr[-1];
2744*67e74705SXin Li 
2745*67e74705SXin Li   uint32_t CodePoint = 0;
2746*67e74705SXin Li   for (unsigned i = 0; i < NumHexDigits; ++i) {
2747*67e74705SXin Li     char C = getCharAndSize(CurPtr, CharSize);
2748*67e74705SXin Li 
2749*67e74705SXin Li     unsigned Value = llvm::hexDigitValue(C);
2750*67e74705SXin Li     if (Value == -1U) {
2751*67e74705SXin Li       if (Result && !isLexingRawMode()) {
2752*67e74705SXin Li         if (i == 0) {
2753*67e74705SXin Li           Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2754*67e74705SXin Li             << StringRef(KindLoc, 1);
2755*67e74705SXin Li         } else {
2756*67e74705SXin Li           Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2757*67e74705SXin Li 
2758*67e74705SXin Li           // If the user wrote \U1234, suggest a fixit to \u.
2759*67e74705SXin Li           if (i == 4 && NumHexDigits == 8) {
2760*67e74705SXin Li             CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2761*67e74705SXin Li             Diag(KindLoc, diag::note_ucn_four_not_eight)
2762*67e74705SXin Li               << FixItHint::CreateReplacement(URange, "u");
2763*67e74705SXin Li           }
2764*67e74705SXin Li         }
2765*67e74705SXin Li       }
2766*67e74705SXin Li 
2767*67e74705SXin Li       return 0;
2768*67e74705SXin Li     }
2769*67e74705SXin Li 
2770*67e74705SXin Li     CodePoint <<= 4;
2771*67e74705SXin Li     CodePoint += Value;
2772*67e74705SXin Li 
2773*67e74705SXin Li     CurPtr += CharSize;
2774*67e74705SXin Li   }
2775*67e74705SXin Li 
2776*67e74705SXin Li   if (Result) {
2777*67e74705SXin Li     Result->setFlag(Token::HasUCN);
2778*67e74705SXin Li     if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2779*67e74705SXin Li       StartPtr = CurPtr;
2780*67e74705SXin Li     else
2781*67e74705SXin Li       while (StartPtr != CurPtr)
2782*67e74705SXin Li         (void)getAndAdvanceChar(StartPtr, *Result);
2783*67e74705SXin Li   } else {
2784*67e74705SXin Li     StartPtr = CurPtr;
2785*67e74705SXin Li   }
2786*67e74705SXin Li 
2787*67e74705SXin Li   // Don't apply C family restrictions to UCNs in assembly mode
2788*67e74705SXin Li   if (LangOpts.AsmPreprocessor)
2789*67e74705SXin Li     return CodePoint;
2790*67e74705SXin Li 
2791*67e74705SXin Li   // C99 6.4.3p2: A universal character name shall not specify a character whose
2792*67e74705SXin Li   //   short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2793*67e74705SXin Li   //   0060 (`), nor one in the range D800 through DFFF inclusive.)
2794*67e74705SXin Li   // C++11 [lex.charset]p2: If the hexadecimal value for a
2795*67e74705SXin Li   //   universal-character-name corresponds to a surrogate code point (in the
2796*67e74705SXin Li   //   range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2797*67e74705SXin Li   //   if the hexadecimal value for a universal-character-name outside the
2798*67e74705SXin Li   //   c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2799*67e74705SXin Li   //   string literal corresponds to a control character (in either of the
2800*67e74705SXin Li   //   ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2801*67e74705SXin Li   //   basic source character set, the program is ill-formed.
2802*67e74705SXin Li   if (CodePoint < 0xA0) {
2803*67e74705SXin Li     if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2804*67e74705SXin Li       return CodePoint;
2805*67e74705SXin Li 
2806*67e74705SXin Li     // We don't use isLexingRawMode() here because we need to warn about bad
2807*67e74705SXin Li     // UCNs even when skipping preprocessing tokens in a #if block.
2808*67e74705SXin Li     if (Result && PP) {
2809*67e74705SXin Li       if (CodePoint < 0x20 || CodePoint >= 0x7F)
2810*67e74705SXin Li         Diag(BufferPtr, diag::err_ucn_control_character);
2811*67e74705SXin Li       else {
2812*67e74705SXin Li         char C = static_cast<char>(CodePoint);
2813*67e74705SXin Li         Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2814*67e74705SXin Li       }
2815*67e74705SXin Li     }
2816*67e74705SXin Li 
2817*67e74705SXin Li     return 0;
2818*67e74705SXin Li 
2819*67e74705SXin Li   } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2820*67e74705SXin Li     // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2821*67e74705SXin Li     // We don't use isLexingRawMode() here because we need to diagnose bad
2822*67e74705SXin Li     // UCNs even when skipping preprocessing tokens in a #if block.
2823*67e74705SXin Li     if (Result && PP) {
2824*67e74705SXin Li       if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2825*67e74705SXin Li         Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2826*67e74705SXin Li       else
2827*67e74705SXin Li         Diag(BufferPtr, diag::err_ucn_escape_invalid);
2828*67e74705SXin Li     }
2829*67e74705SXin Li     return 0;
2830*67e74705SXin Li   }
2831*67e74705SXin Li 
2832*67e74705SXin Li   return CodePoint;
2833*67e74705SXin Li }
2834*67e74705SXin Li 
CheckUnicodeWhitespace(Token & Result,uint32_t C,const char * CurPtr)2835*67e74705SXin Li bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2836*67e74705SXin Li                                    const char *CurPtr) {
2837*67e74705SXin Li   static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2838*67e74705SXin Li       UnicodeWhitespaceCharRanges);
2839*67e74705SXin Li   if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2840*67e74705SXin Li       UnicodeWhitespaceChars.contains(C)) {
2841*67e74705SXin Li     Diag(BufferPtr, diag::ext_unicode_whitespace)
2842*67e74705SXin Li       << makeCharRange(*this, BufferPtr, CurPtr);
2843*67e74705SXin Li 
2844*67e74705SXin Li     Result.setFlag(Token::LeadingSpace);
2845*67e74705SXin Li     return true;
2846*67e74705SXin Li   }
2847*67e74705SXin Li   return false;
2848*67e74705SXin Li }
2849*67e74705SXin Li 
LexUnicode(Token & Result,uint32_t C,const char * CurPtr)2850*67e74705SXin Li bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2851*67e74705SXin Li   if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2852*67e74705SXin Li     if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2853*67e74705SXin Li         !PP->isPreprocessedOutput()) {
2854*67e74705SXin Li       maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2855*67e74705SXin Li                                 makeCharRange(*this, BufferPtr, CurPtr),
2856*67e74705SXin Li                                 /*IsFirst=*/true);
2857*67e74705SXin Li     }
2858*67e74705SXin Li 
2859*67e74705SXin Li     MIOpt.ReadToken();
2860*67e74705SXin Li     return LexIdentifier(Result, CurPtr);
2861*67e74705SXin Li   }
2862*67e74705SXin Li 
2863*67e74705SXin Li   if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2864*67e74705SXin Li       !PP->isPreprocessedOutput() &&
2865*67e74705SXin Li       !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2866*67e74705SXin Li     // Non-ASCII characters tend to creep into source code unintentionally.
2867*67e74705SXin Li     // Instead of letting the parser complain about the unknown token,
2868*67e74705SXin Li     // just drop the character.
2869*67e74705SXin Li     // Note that we can /only/ do this when the non-ASCII character is actually
2870*67e74705SXin Li     // spelled as Unicode, not written as a UCN. The standard requires that
2871*67e74705SXin Li     // we not throw away any possible preprocessor tokens, but there's a
2872*67e74705SXin Li     // loophole in the mapping of Unicode characters to basic character set
2873*67e74705SXin Li     // characters that allows us to map these particular characters to, say,
2874*67e74705SXin Li     // whitespace.
2875*67e74705SXin Li     Diag(BufferPtr, diag::err_non_ascii)
2876*67e74705SXin Li       << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2877*67e74705SXin Li 
2878*67e74705SXin Li     BufferPtr = CurPtr;
2879*67e74705SXin Li     return false;
2880*67e74705SXin Li   }
2881*67e74705SXin Li 
2882*67e74705SXin Li   // Otherwise, we have an explicit UCN or a character that's unlikely to show
2883*67e74705SXin Li   // up by accident.
2884*67e74705SXin Li   MIOpt.ReadToken();
2885*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, tok::unknown);
2886*67e74705SXin Li   return true;
2887*67e74705SXin Li }
2888*67e74705SXin Li 
PropagateLineStartLeadingSpaceInfo(Token & Result)2889*67e74705SXin Li void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2890*67e74705SXin Li   IsAtStartOfLine = Result.isAtStartOfLine();
2891*67e74705SXin Li   HasLeadingSpace = Result.hasLeadingSpace();
2892*67e74705SXin Li   HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2893*67e74705SXin Li   // Note that this doesn't affect IsAtPhysicalStartOfLine.
2894*67e74705SXin Li }
2895*67e74705SXin Li 
Lex(Token & Result)2896*67e74705SXin Li bool Lexer::Lex(Token &Result) {
2897*67e74705SXin Li   // Start a new token.
2898*67e74705SXin Li   Result.startToken();
2899*67e74705SXin Li 
2900*67e74705SXin Li   // Set up misc whitespace flags for LexTokenInternal.
2901*67e74705SXin Li   if (IsAtStartOfLine) {
2902*67e74705SXin Li     Result.setFlag(Token::StartOfLine);
2903*67e74705SXin Li     IsAtStartOfLine = false;
2904*67e74705SXin Li   }
2905*67e74705SXin Li 
2906*67e74705SXin Li   if (HasLeadingSpace) {
2907*67e74705SXin Li     Result.setFlag(Token::LeadingSpace);
2908*67e74705SXin Li     HasLeadingSpace = false;
2909*67e74705SXin Li   }
2910*67e74705SXin Li 
2911*67e74705SXin Li   if (HasLeadingEmptyMacro) {
2912*67e74705SXin Li     Result.setFlag(Token::LeadingEmptyMacro);
2913*67e74705SXin Li     HasLeadingEmptyMacro = false;
2914*67e74705SXin Li   }
2915*67e74705SXin Li 
2916*67e74705SXin Li   bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2917*67e74705SXin Li   IsAtPhysicalStartOfLine = false;
2918*67e74705SXin Li   bool isRawLex = isLexingRawMode();
2919*67e74705SXin Li   (void) isRawLex;
2920*67e74705SXin Li   bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2921*67e74705SXin Li   // (After the LexTokenInternal call, the lexer might be destroyed.)
2922*67e74705SXin Li   assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2923*67e74705SXin Li   return returnedToken;
2924*67e74705SXin Li }
2925*67e74705SXin Li 
2926*67e74705SXin Li /// LexTokenInternal - This implements a simple C family lexer.  It is an
2927*67e74705SXin Li /// extremely performance critical piece of code.  This assumes that the buffer
2928*67e74705SXin Li /// has a null character at the end of the file.  This returns a preprocessing
2929*67e74705SXin Li /// token, not a normal token, as such, it is an internal interface.  It assumes
2930*67e74705SXin Li /// that the Flags of result have been cleared before calling this.
LexTokenInternal(Token & Result,bool TokAtPhysicalStartOfLine)2931*67e74705SXin Li bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
2932*67e74705SXin Li LexNextToken:
2933*67e74705SXin Li   // New token, can't need cleaning yet.
2934*67e74705SXin Li   Result.clearFlag(Token::NeedsCleaning);
2935*67e74705SXin Li   Result.setIdentifierInfo(nullptr);
2936*67e74705SXin Li 
2937*67e74705SXin Li   // CurPtr - Cache BufferPtr in an automatic variable.
2938*67e74705SXin Li   const char *CurPtr = BufferPtr;
2939*67e74705SXin Li 
2940*67e74705SXin Li   // Small amounts of horizontal whitespace is very common between tokens.
2941*67e74705SXin Li   if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2942*67e74705SXin Li     ++CurPtr;
2943*67e74705SXin Li     while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2944*67e74705SXin Li       ++CurPtr;
2945*67e74705SXin Li 
2946*67e74705SXin Li     // If we are keeping whitespace and other tokens, just return what we just
2947*67e74705SXin Li     // skipped.  The next lexer invocation will return the token after the
2948*67e74705SXin Li     // whitespace.
2949*67e74705SXin Li     if (isKeepWhitespaceMode()) {
2950*67e74705SXin Li       FormTokenWithChars(Result, CurPtr, tok::unknown);
2951*67e74705SXin Li       // FIXME: The next token will not have LeadingSpace set.
2952*67e74705SXin Li       return true;
2953*67e74705SXin Li     }
2954*67e74705SXin Li 
2955*67e74705SXin Li     BufferPtr = CurPtr;
2956*67e74705SXin Li     Result.setFlag(Token::LeadingSpace);
2957*67e74705SXin Li   }
2958*67e74705SXin Li 
2959*67e74705SXin Li   unsigned SizeTmp, SizeTmp2;   // Temporaries for use in cases below.
2960*67e74705SXin Li 
2961*67e74705SXin Li   // Read a character, advancing over it.
2962*67e74705SXin Li   char Char = getAndAdvanceChar(CurPtr, Result);
2963*67e74705SXin Li   tok::TokenKind Kind;
2964*67e74705SXin Li 
2965*67e74705SXin Li   switch (Char) {
2966*67e74705SXin Li   case 0:  // Null.
2967*67e74705SXin Li     // Found end of file?
2968*67e74705SXin Li     if (CurPtr-1 == BufferEnd)
2969*67e74705SXin Li       return LexEndOfFile(Result, CurPtr-1);
2970*67e74705SXin Li 
2971*67e74705SXin Li     // Check if we are performing code completion.
2972*67e74705SXin Li     if (isCodeCompletionPoint(CurPtr-1)) {
2973*67e74705SXin Li       // Return the code-completion token.
2974*67e74705SXin Li       Result.startToken();
2975*67e74705SXin Li       FormTokenWithChars(Result, CurPtr, tok::code_completion);
2976*67e74705SXin Li       return true;
2977*67e74705SXin Li     }
2978*67e74705SXin Li 
2979*67e74705SXin Li     if (!isLexingRawMode())
2980*67e74705SXin Li       Diag(CurPtr-1, diag::null_in_file);
2981*67e74705SXin Li     Result.setFlag(Token::LeadingSpace);
2982*67e74705SXin Li     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2983*67e74705SXin Li       return true; // KeepWhitespaceMode
2984*67e74705SXin Li 
2985*67e74705SXin Li     // We know the lexer hasn't changed, so just try again with this lexer.
2986*67e74705SXin Li     // (We manually eliminate the tail call to avoid recursion.)
2987*67e74705SXin Li     goto LexNextToken;
2988*67e74705SXin Li 
2989*67e74705SXin Li   case 26:  // DOS & CP/M EOF: "^Z".
2990*67e74705SXin Li     // If we're in Microsoft extensions mode, treat this as end of file.
2991*67e74705SXin Li     if (LangOpts.MicrosoftExt) {
2992*67e74705SXin Li       if (!isLexingRawMode())
2993*67e74705SXin Li         Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
2994*67e74705SXin Li       return LexEndOfFile(Result, CurPtr-1);
2995*67e74705SXin Li     }
2996*67e74705SXin Li 
2997*67e74705SXin Li     // If Microsoft extensions are disabled, this is just random garbage.
2998*67e74705SXin Li     Kind = tok::unknown;
2999*67e74705SXin Li     break;
3000*67e74705SXin Li 
3001*67e74705SXin Li   case '\n':
3002*67e74705SXin Li   case '\r':
3003*67e74705SXin Li     // If we are inside a preprocessor directive and we see the end of line,
3004*67e74705SXin Li     // we know we are done with the directive, so return an EOD token.
3005*67e74705SXin Li     if (ParsingPreprocessorDirective) {
3006*67e74705SXin Li       // Done parsing the "line".
3007*67e74705SXin Li       ParsingPreprocessorDirective = false;
3008*67e74705SXin Li 
3009*67e74705SXin Li       // Restore comment saving mode, in case it was disabled for directive.
3010*67e74705SXin Li       if (PP)
3011*67e74705SXin Li         resetExtendedTokenMode();
3012*67e74705SXin Li 
3013*67e74705SXin Li       // Since we consumed a newline, we are back at the start of a line.
3014*67e74705SXin Li       IsAtStartOfLine = true;
3015*67e74705SXin Li       IsAtPhysicalStartOfLine = true;
3016*67e74705SXin Li 
3017*67e74705SXin Li       Kind = tok::eod;
3018*67e74705SXin Li       break;
3019*67e74705SXin Li     }
3020*67e74705SXin Li 
3021*67e74705SXin Li     // No leading whitespace seen so far.
3022*67e74705SXin Li     Result.clearFlag(Token::LeadingSpace);
3023*67e74705SXin Li 
3024*67e74705SXin Li     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3025*67e74705SXin Li       return true; // KeepWhitespaceMode
3026*67e74705SXin Li 
3027*67e74705SXin Li     // We only saw whitespace, so just try again with this lexer.
3028*67e74705SXin Li     // (We manually eliminate the tail call to avoid recursion.)
3029*67e74705SXin Li     goto LexNextToken;
3030*67e74705SXin Li   case ' ':
3031*67e74705SXin Li   case '\t':
3032*67e74705SXin Li   case '\f':
3033*67e74705SXin Li   case '\v':
3034*67e74705SXin Li   SkipHorizontalWhitespace:
3035*67e74705SXin Li     Result.setFlag(Token::LeadingSpace);
3036*67e74705SXin Li     if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3037*67e74705SXin Li       return true; // KeepWhitespaceMode
3038*67e74705SXin Li 
3039*67e74705SXin Li   SkipIgnoredUnits:
3040*67e74705SXin Li     CurPtr = BufferPtr;
3041*67e74705SXin Li 
3042*67e74705SXin Li     // If the next token is obviously a // or /* */ comment, skip it efficiently
3043*67e74705SXin Li     // too (without going through the big switch stmt).
3044*67e74705SXin Li     if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3045*67e74705SXin Li         LangOpts.LineComment &&
3046*67e74705SXin Li         (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3047*67e74705SXin Li       if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3048*67e74705SXin Li         return true; // There is a token to return.
3049*67e74705SXin Li       goto SkipIgnoredUnits;
3050*67e74705SXin Li     } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3051*67e74705SXin Li       if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3052*67e74705SXin Li         return true; // There is a token to return.
3053*67e74705SXin Li       goto SkipIgnoredUnits;
3054*67e74705SXin Li     } else if (isHorizontalWhitespace(*CurPtr)) {
3055*67e74705SXin Li       goto SkipHorizontalWhitespace;
3056*67e74705SXin Li     }
3057*67e74705SXin Li     // We only saw whitespace, so just try again with this lexer.
3058*67e74705SXin Li     // (We manually eliminate the tail call to avoid recursion.)
3059*67e74705SXin Li     goto LexNextToken;
3060*67e74705SXin Li 
3061*67e74705SXin Li   // C99 6.4.4.1: Integer Constants.
3062*67e74705SXin Li   // C99 6.4.4.2: Floating Constants.
3063*67e74705SXin Li   case '0': case '1': case '2': case '3': case '4':
3064*67e74705SXin Li   case '5': case '6': case '7': case '8': case '9':
3065*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3066*67e74705SXin Li     MIOpt.ReadToken();
3067*67e74705SXin Li     return LexNumericConstant(Result, CurPtr);
3068*67e74705SXin Li 
3069*67e74705SXin Li   case 'u':   // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3070*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3071*67e74705SXin Li     MIOpt.ReadToken();
3072*67e74705SXin Li 
3073*67e74705SXin Li     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3074*67e74705SXin Li       Char = getCharAndSize(CurPtr, SizeTmp);
3075*67e74705SXin Li 
3076*67e74705SXin Li       // UTF-16 string literal
3077*67e74705SXin Li       if (Char == '"')
3078*67e74705SXin Li         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3079*67e74705SXin Li                                 tok::utf16_string_literal);
3080*67e74705SXin Li 
3081*67e74705SXin Li       // UTF-16 character constant
3082*67e74705SXin Li       if (Char == '\'')
3083*67e74705SXin Li         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3084*67e74705SXin Li                                tok::utf16_char_constant);
3085*67e74705SXin Li 
3086*67e74705SXin Li       // UTF-16 raw string literal
3087*67e74705SXin Li       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3088*67e74705SXin Li           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3089*67e74705SXin Li         return LexRawStringLiteral(Result,
3090*67e74705SXin Li                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3091*67e74705SXin Li                                            SizeTmp2, Result),
3092*67e74705SXin Li                                tok::utf16_string_literal);
3093*67e74705SXin Li 
3094*67e74705SXin Li       if (Char == '8') {
3095*67e74705SXin Li         char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3096*67e74705SXin Li 
3097*67e74705SXin Li         // UTF-8 string literal
3098*67e74705SXin Li         if (Char2 == '"')
3099*67e74705SXin Li           return LexStringLiteral(Result,
3100*67e74705SXin Li                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3101*67e74705SXin Li                                            SizeTmp2, Result),
3102*67e74705SXin Li                                tok::utf8_string_literal);
3103*67e74705SXin Li         if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3104*67e74705SXin Li           return LexCharConstant(
3105*67e74705SXin Li               Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3106*67e74705SXin Li                                   SizeTmp2, Result),
3107*67e74705SXin Li               tok::utf8_char_constant);
3108*67e74705SXin Li 
3109*67e74705SXin Li         if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3110*67e74705SXin Li           unsigned SizeTmp3;
3111*67e74705SXin Li           char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3112*67e74705SXin Li           // UTF-8 raw string literal
3113*67e74705SXin Li           if (Char3 == '"') {
3114*67e74705SXin Li             return LexRawStringLiteral(Result,
3115*67e74705SXin Li                    ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3116*67e74705SXin Li                                            SizeTmp2, Result),
3117*67e74705SXin Li                                SizeTmp3, Result),
3118*67e74705SXin Li                    tok::utf8_string_literal);
3119*67e74705SXin Li           }
3120*67e74705SXin Li         }
3121*67e74705SXin Li       }
3122*67e74705SXin Li     }
3123*67e74705SXin Li 
3124*67e74705SXin Li     // treat u like the start of an identifier.
3125*67e74705SXin Li     return LexIdentifier(Result, CurPtr);
3126*67e74705SXin Li 
3127*67e74705SXin Li   case 'U':   // Identifier (Uber) or C11/C++11 UTF-32 string literal
3128*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3129*67e74705SXin Li     MIOpt.ReadToken();
3130*67e74705SXin Li 
3131*67e74705SXin Li     if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3132*67e74705SXin Li       Char = getCharAndSize(CurPtr, SizeTmp);
3133*67e74705SXin Li 
3134*67e74705SXin Li       // UTF-32 string literal
3135*67e74705SXin Li       if (Char == '"')
3136*67e74705SXin Li         return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3137*67e74705SXin Li                                 tok::utf32_string_literal);
3138*67e74705SXin Li 
3139*67e74705SXin Li       // UTF-32 character constant
3140*67e74705SXin Li       if (Char == '\'')
3141*67e74705SXin Li         return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3142*67e74705SXin Li                                tok::utf32_char_constant);
3143*67e74705SXin Li 
3144*67e74705SXin Li       // UTF-32 raw string literal
3145*67e74705SXin Li       if (Char == 'R' && LangOpts.CPlusPlus11 &&
3146*67e74705SXin Li           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3147*67e74705SXin Li         return LexRawStringLiteral(Result,
3148*67e74705SXin Li                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3149*67e74705SXin Li                                            SizeTmp2, Result),
3150*67e74705SXin Li                                tok::utf32_string_literal);
3151*67e74705SXin Li     }
3152*67e74705SXin Li 
3153*67e74705SXin Li     // treat U like the start of an identifier.
3154*67e74705SXin Li     return LexIdentifier(Result, CurPtr);
3155*67e74705SXin Li 
3156*67e74705SXin Li   case 'R': // Identifier or C++0x raw string literal
3157*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3158*67e74705SXin Li     MIOpt.ReadToken();
3159*67e74705SXin Li 
3160*67e74705SXin Li     if (LangOpts.CPlusPlus11) {
3161*67e74705SXin Li       Char = getCharAndSize(CurPtr, SizeTmp);
3162*67e74705SXin Li 
3163*67e74705SXin Li       if (Char == '"')
3164*67e74705SXin Li         return LexRawStringLiteral(Result,
3165*67e74705SXin Li                                    ConsumeChar(CurPtr, SizeTmp, Result),
3166*67e74705SXin Li                                    tok::string_literal);
3167*67e74705SXin Li     }
3168*67e74705SXin Li 
3169*67e74705SXin Li     // treat R like the start of an identifier.
3170*67e74705SXin Li     return LexIdentifier(Result, CurPtr);
3171*67e74705SXin Li 
3172*67e74705SXin Li   case 'L':   // Identifier (Loony) or wide literal (L'x' or L"xyz").
3173*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3174*67e74705SXin Li     MIOpt.ReadToken();
3175*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3176*67e74705SXin Li 
3177*67e74705SXin Li     // Wide string literal.
3178*67e74705SXin Li     if (Char == '"')
3179*67e74705SXin Li       return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3180*67e74705SXin Li                               tok::wide_string_literal);
3181*67e74705SXin Li 
3182*67e74705SXin Li     // Wide raw string literal.
3183*67e74705SXin Li     if (LangOpts.CPlusPlus11 && Char == 'R' &&
3184*67e74705SXin Li         getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3185*67e74705SXin Li       return LexRawStringLiteral(Result,
3186*67e74705SXin Li                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3187*67e74705SXin Li                                            SizeTmp2, Result),
3188*67e74705SXin Li                                tok::wide_string_literal);
3189*67e74705SXin Li 
3190*67e74705SXin Li     // Wide character constant.
3191*67e74705SXin Li     if (Char == '\'')
3192*67e74705SXin Li       return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3193*67e74705SXin Li                              tok::wide_char_constant);
3194*67e74705SXin Li     // FALL THROUGH, treating L like the start of an identifier.
3195*67e74705SXin Li 
3196*67e74705SXin Li   // C99 6.4.2: Identifiers.
3197*67e74705SXin Li   case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3198*67e74705SXin Li   case 'H': case 'I': case 'J': case 'K':    /*'L'*/case 'M': case 'N':
3199*67e74705SXin Li   case 'O': case 'P': case 'Q':    /*'R'*/case 'S': case 'T':    /*'U'*/
3200*67e74705SXin Li   case 'V': case 'W': case 'X': case 'Y': case 'Z':
3201*67e74705SXin Li   case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3202*67e74705SXin Li   case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3203*67e74705SXin Li   case 'o': case 'p': case 'q': case 'r': case 's': case 't':    /*'u'*/
3204*67e74705SXin Li   case 'v': case 'w': case 'x': case 'y': case 'z':
3205*67e74705SXin Li   case '_':
3206*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3207*67e74705SXin Li     MIOpt.ReadToken();
3208*67e74705SXin Li     return LexIdentifier(Result, CurPtr);
3209*67e74705SXin Li 
3210*67e74705SXin Li   case '$':   // $ in identifiers.
3211*67e74705SXin Li     if (LangOpts.DollarIdents) {
3212*67e74705SXin Li       if (!isLexingRawMode())
3213*67e74705SXin Li         Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3214*67e74705SXin Li       // Notify MIOpt that we read a non-whitespace/non-comment token.
3215*67e74705SXin Li       MIOpt.ReadToken();
3216*67e74705SXin Li       return LexIdentifier(Result, CurPtr);
3217*67e74705SXin Li     }
3218*67e74705SXin Li 
3219*67e74705SXin Li     Kind = tok::unknown;
3220*67e74705SXin Li     break;
3221*67e74705SXin Li 
3222*67e74705SXin Li   // C99 6.4.4: Character Constants.
3223*67e74705SXin Li   case '\'':
3224*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3225*67e74705SXin Li     MIOpt.ReadToken();
3226*67e74705SXin Li     return LexCharConstant(Result, CurPtr, tok::char_constant);
3227*67e74705SXin Li 
3228*67e74705SXin Li   // C99 6.4.5: String Literals.
3229*67e74705SXin Li   case '"':
3230*67e74705SXin Li     // Notify MIOpt that we read a non-whitespace/non-comment token.
3231*67e74705SXin Li     MIOpt.ReadToken();
3232*67e74705SXin Li     return LexStringLiteral(Result, CurPtr, tok::string_literal);
3233*67e74705SXin Li 
3234*67e74705SXin Li   // C99 6.4.6: Punctuators.
3235*67e74705SXin Li   case '?':
3236*67e74705SXin Li     Kind = tok::question;
3237*67e74705SXin Li     break;
3238*67e74705SXin Li   case '[':
3239*67e74705SXin Li     Kind = tok::l_square;
3240*67e74705SXin Li     break;
3241*67e74705SXin Li   case ']':
3242*67e74705SXin Li     Kind = tok::r_square;
3243*67e74705SXin Li     break;
3244*67e74705SXin Li   case '(':
3245*67e74705SXin Li     Kind = tok::l_paren;
3246*67e74705SXin Li     break;
3247*67e74705SXin Li   case ')':
3248*67e74705SXin Li     Kind = tok::r_paren;
3249*67e74705SXin Li     break;
3250*67e74705SXin Li   case '{':
3251*67e74705SXin Li     Kind = tok::l_brace;
3252*67e74705SXin Li     break;
3253*67e74705SXin Li   case '}':
3254*67e74705SXin Li     Kind = tok::r_brace;
3255*67e74705SXin Li     break;
3256*67e74705SXin Li   case '.':
3257*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3258*67e74705SXin Li     if (Char >= '0' && Char <= '9') {
3259*67e74705SXin Li       // Notify MIOpt that we read a non-whitespace/non-comment token.
3260*67e74705SXin Li       MIOpt.ReadToken();
3261*67e74705SXin Li 
3262*67e74705SXin Li       return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3263*67e74705SXin Li     } else if (LangOpts.CPlusPlus && Char == '*') {
3264*67e74705SXin Li       Kind = tok::periodstar;
3265*67e74705SXin Li       CurPtr += SizeTmp;
3266*67e74705SXin Li     } else if (Char == '.' &&
3267*67e74705SXin Li                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3268*67e74705SXin Li       Kind = tok::ellipsis;
3269*67e74705SXin Li       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3270*67e74705SXin Li                            SizeTmp2, Result);
3271*67e74705SXin Li     } else {
3272*67e74705SXin Li       Kind = tok::period;
3273*67e74705SXin Li     }
3274*67e74705SXin Li     break;
3275*67e74705SXin Li   case '&':
3276*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3277*67e74705SXin Li     if (Char == '&') {
3278*67e74705SXin Li       Kind = tok::ampamp;
3279*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3280*67e74705SXin Li     } else if (Char == '=') {
3281*67e74705SXin Li       Kind = tok::ampequal;
3282*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3283*67e74705SXin Li     } else {
3284*67e74705SXin Li       Kind = tok::amp;
3285*67e74705SXin Li     }
3286*67e74705SXin Li     break;
3287*67e74705SXin Li   case '*':
3288*67e74705SXin Li     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3289*67e74705SXin Li       Kind = tok::starequal;
3290*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3291*67e74705SXin Li     } else {
3292*67e74705SXin Li       Kind = tok::star;
3293*67e74705SXin Li     }
3294*67e74705SXin Li     break;
3295*67e74705SXin Li   case '+':
3296*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3297*67e74705SXin Li     if (Char == '+') {
3298*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3299*67e74705SXin Li       Kind = tok::plusplus;
3300*67e74705SXin Li     } else if (Char == '=') {
3301*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3302*67e74705SXin Li       Kind = tok::plusequal;
3303*67e74705SXin Li     } else {
3304*67e74705SXin Li       Kind = tok::plus;
3305*67e74705SXin Li     }
3306*67e74705SXin Li     break;
3307*67e74705SXin Li   case '-':
3308*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3309*67e74705SXin Li     if (Char == '-') {      // --
3310*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3311*67e74705SXin Li       Kind = tok::minusminus;
3312*67e74705SXin Li     } else if (Char == '>' && LangOpts.CPlusPlus &&
3313*67e74705SXin Li                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') {  // C++ ->*
3314*67e74705SXin Li       CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3315*67e74705SXin Li                            SizeTmp2, Result);
3316*67e74705SXin Li       Kind = tok::arrowstar;
3317*67e74705SXin Li     } else if (Char == '>') {   // ->
3318*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3319*67e74705SXin Li       Kind = tok::arrow;
3320*67e74705SXin Li     } else if (Char == '=') {   // -=
3321*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3322*67e74705SXin Li       Kind = tok::minusequal;
3323*67e74705SXin Li     } else {
3324*67e74705SXin Li       Kind = tok::minus;
3325*67e74705SXin Li     }
3326*67e74705SXin Li     break;
3327*67e74705SXin Li   case '~':
3328*67e74705SXin Li     Kind = tok::tilde;
3329*67e74705SXin Li     break;
3330*67e74705SXin Li   case '!':
3331*67e74705SXin Li     if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3332*67e74705SXin Li       Kind = tok::exclaimequal;
3333*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3334*67e74705SXin Li     } else {
3335*67e74705SXin Li       Kind = tok::exclaim;
3336*67e74705SXin Li     }
3337*67e74705SXin Li     break;
3338*67e74705SXin Li   case '/':
3339*67e74705SXin Li     // 6.4.9: Comments
3340*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3341*67e74705SXin Li     if (Char == '/') {         // Line comment.
3342*67e74705SXin Li       // Even if Line comments are disabled (e.g. in C89 mode), we generally
3343*67e74705SXin Li       // want to lex this as a comment.  There is one problem with this though,
3344*67e74705SXin Li       // that in one particular corner case, this can change the behavior of the
3345*67e74705SXin Li       // resultant program.  For example, In  "foo //**/ bar", C89 would lex
3346*67e74705SXin Li       // this as "foo / bar" and langauges with Line comments would lex it as
3347*67e74705SXin Li       // "foo".  Check to see if the character after the second slash is a '*'.
3348*67e74705SXin Li       // If so, we will lex that as a "/" instead of the start of a comment.
3349*67e74705SXin Li       // However, we never do this if we are just preprocessing.
3350*67e74705SXin Li       bool TreatAsComment = LangOpts.LineComment &&
3351*67e74705SXin Li                             (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3352*67e74705SXin Li       if (!TreatAsComment)
3353*67e74705SXin Li         if (!(PP && PP->isPreprocessedOutput()))
3354*67e74705SXin Li           TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3355*67e74705SXin Li 
3356*67e74705SXin Li       if (TreatAsComment) {
3357*67e74705SXin Li         if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3358*67e74705SXin Li                             TokAtPhysicalStartOfLine))
3359*67e74705SXin Li           return true; // There is a token to return.
3360*67e74705SXin Li 
3361*67e74705SXin Li         // It is common for the tokens immediately after a // comment to be
3362*67e74705SXin Li         // whitespace (indentation for the next line).  Instead of going through
3363*67e74705SXin Li         // the big switch, handle it efficiently now.
3364*67e74705SXin Li         goto SkipIgnoredUnits;
3365*67e74705SXin Li       }
3366*67e74705SXin Li     }
3367*67e74705SXin Li 
3368*67e74705SXin Li     if (Char == '*') {  // /**/ comment.
3369*67e74705SXin Li       if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3370*67e74705SXin Li                            TokAtPhysicalStartOfLine))
3371*67e74705SXin Li         return true; // There is a token to return.
3372*67e74705SXin Li 
3373*67e74705SXin Li       // We only saw whitespace, so just try again with this lexer.
3374*67e74705SXin Li       // (We manually eliminate the tail call to avoid recursion.)
3375*67e74705SXin Li       goto LexNextToken;
3376*67e74705SXin Li     }
3377*67e74705SXin Li 
3378*67e74705SXin Li     if (Char == '=') {
3379*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3380*67e74705SXin Li       Kind = tok::slashequal;
3381*67e74705SXin Li     } else {
3382*67e74705SXin Li       Kind = tok::slash;
3383*67e74705SXin Li     }
3384*67e74705SXin Li     break;
3385*67e74705SXin Li   case '%':
3386*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3387*67e74705SXin Li     if (Char == '=') {
3388*67e74705SXin Li       Kind = tok::percentequal;
3389*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3390*67e74705SXin Li     } else if (LangOpts.Digraphs && Char == '>') {
3391*67e74705SXin Li       Kind = tok::r_brace;                             // '%>' -> '}'
3392*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3393*67e74705SXin Li     } else if (LangOpts.Digraphs && Char == ':') {
3394*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3395*67e74705SXin Li       Char = getCharAndSize(CurPtr, SizeTmp);
3396*67e74705SXin Li       if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3397*67e74705SXin Li         Kind = tok::hashhash;                          // '%:%:' -> '##'
3398*67e74705SXin Li         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3399*67e74705SXin Li                              SizeTmp2, Result);
3400*67e74705SXin Li       } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3401*67e74705SXin Li         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3402*67e74705SXin Li         if (!isLexingRawMode())
3403*67e74705SXin Li           Diag(BufferPtr, diag::ext_charize_microsoft);
3404*67e74705SXin Li         Kind = tok::hashat;
3405*67e74705SXin Li       } else {                                         // '%:' -> '#'
3406*67e74705SXin Li         // We parsed a # character.  If this occurs at the start of the line,
3407*67e74705SXin Li         // it's actually the start of a preprocessing directive.  Callback to
3408*67e74705SXin Li         // the preprocessor to handle it.
3409*67e74705SXin Li         // TODO: -fpreprocessed mode??
3410*67e74705SXin Li         if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3411*67e74705SXin Li           goto HandleDirective;
3412*67e74705SXin Li 
3413*67e74705SXin Li         Kind = tok::hash;
3414*67e74705SXin Li       }
3415*67e74705SXin Li     } else {
3416*67e74705SXin Li       Kind = tok::percent;
3417*67e74705SXin Li     }
3418*67e74705SXin Li     break;
3419*67e74705SXin Li   case '<':
3420*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3421*67e74705SXin Li     if (ParsingFilename) {
3422*67e74705SXin Li       return LexAngledStringLiteral(Result, CurPtr);
3423*67e74705SXin Li     } else if (Char == '<') {
3424*67e74705SXin Li       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3425*67e74705SXin Li       if (After == '=') {
3426*67e74705SXin Li         Kind = tok::lesslessequal;
3427*67e74705SXin Li         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3428*67e74705SXin Li                              SizeTmp2, Result);
3429*67e74705SXin Li       } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3430*67e74705SXin Li         // If this is actually a '<<<<<<<' version control conflict marker,
3431*67e74705SXin Li         // recognize it as such and recover nicely.
3432*67e74705SXin Li         goto LexNextToken;
3433*67e74705SXin Li       } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3434*67e74705SXin Li         // If this is '<<<<' and we're in a Perforce-style conflict marker,
3435*67e74705SXin Li         // ignore it.
3436*67e74705SXin Li         goto LexNextToken;
3437*67e74705SXin Li       } else if (LangOpts.CUDA && After == '<') {
3438*67e74705SXin Li         Kind = tok::lesslessless;
3439*67e74705SXin Li         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3440*67e74705SXin Li                              SizeTmp2, Result);
3441*67e74705SXin Li       } else {
3442*67e74705SXin Li         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3443*67e74705SXin Li         Kind = tok::lessless;
3444*67e74705SXin Li       }
3445*67e74705SXin Li     } else if (Char == '=') {
3446*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3447*67e74705SXin Li       Kind = tok::lessequal;
3448*67e74705SXin Li     } else if (LangOpts.Digraphs && Char == ':') {     // '<:' -> '['
3449*67e74705SXin Li       if (LangOpts.CPlusPlus11 &&
3450*67e74705SXin Li           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3451*67e74705SXin Li         // C++0x [lex.pptoken]p3:
3452*67e74705SXin Li         //  Otherwise, if the next three characters are <:: and the subsequent
3453*67e74705SXin Li         //  character is neither : nor >, the < is treated as a preprocessor
3454*67e74705SXin Li         //  token by itself and not as the first character of the alternative
3455*67e74705SXin Li         //  token <:.
3456*67e74705SXin Li         unsigned SizeTmp3;
3457*67e74705SXin Li         char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3458*67e74705SXin Li         if (After != ':' && After != '>') {
3459*67e74705SXin Li           Kind = tok::less;
3460*67e74705SXin Li           if (!isLexingRawMode())
3461*67e74705SXin Li             Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3462*67e74705SXin Li           break;
3463*67e74705SXin Li         }
3464*67e74705SXin Li       }
3465*67e74705SXin Li 
3466*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3467*67e74705SXin Li       Kind = tok::l_square;
3468*67e74705SXin Li     } else if (LangOpts.Digraphs && Char == '%') {     // '<%' -> '{'
3469*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3470*67e74705SXin Li       Kind = tok::l_brace;
3471*67e74705SXin Li     } else {
3472*67e74705SXin Li       Kind = tok::less;
3473*67e74705SXin Li     }
3474*67e74705SXin Li     break;
3475*67e74705SXin Li   case '>':
3476*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3477*67e74705SXin Li     if (Char == '=') {
3478*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3479*67e74705SXin Li       Kind = tok::greaterequal;
3480*67e74705SXin Li     } else if (Char == '>') {
3481*67e74705SXin Li       char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3482*67e74705SXin Li       if (After == '=') {
3483*67e74705SXin Li         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3484*67e74705SXin Li                              SizeTmp2, Result);
3485*67e74705SXin Li         Kind = tok::greatergreaterequal;
3486*67e74705SXin Li       } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3487*67e74705SXin Li         // If this is actually a '>>>>' conflict marker, recognize it as such
3488*67e74705SXin Li         // and recover nicely.
3489*67e74705SXin Li         goto LexNextToken;
3490*67e74705SXin Li       } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3491*67e74705SXin Li         // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3492*67e74705SXin Li         goto LexNextToken;
3493*67e74705SXin Li       } else if (LangOpts.CUDA && After == '>') {
3494*67e74705SXin Li         Kind = tok::greatergreatergreater;
3495*67e74705SXin Li         CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3496*67e74705SXin Li                              SizeTmp2, Result);
3497*67e74705SXin Li       } else {
3498*67e74705SXin Li         CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3499*67e74705SXin Li         Kind = tok::greatergreater;
3500*67e74705SXin Li       }
3501*67e74705SXin Li 
3502*67e74705SXin Li     } else {
3503*67e74705SXin Li       Kind = tok::greater;
3504*67e74705SXin Li     }
3505*67e74705SXin Li     break;
3506*67e74705SXin Li   case '^':
3507*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3508*67e74705SXin Li     if (Char == '=') {
3509*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3510*67e74705SXin Li       Kind = tok::caretequal;
3511*67e74705SXin Li     } else if (LangOpts.OpenCL && Char == '^') {
3512*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3513*67e74705SXin Li       Kind = tok::caretcaret;
3514*67e74705SXin Li     } else {
3515*67e74705SXin Li       Kind = tok::caret;
3516*67e74705SXin Li     }
3517*67e74705SXin Li     break;
3518*67e74705SXin Li   case '|':
3519*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3520*67e74705SXin Li     if (Char == '=') {
3521*67e74705SXin Li       Kind = tok::pipeequal;
3522*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3523*67e74705SXin Li     } else if (Char == '|') {
3524*67e74705SXin Li       // If this is '|||||||' and we're in a conflict marker, ignore it.
3525*67e74705SXin Li       if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3526*67e74705SXin Li         goto LexNextToken;
3527*67e74705SXin Li       Kind = tok::pipepipe;
3528*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3529*67e74705SXin Li     } else {
3530*67e74705SXin Li       Kind = tok::pipe;
3531*67e74705SXin Li     }
3532*67e74705SXin Li     break;
3533*67e74705SXin Li   case ':':
3534*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3535*67e74705SXin Li     if (LangOpts.Digraphs && Char == '>') {
3536*67e74705SXin Li       Kind = tok::r_square; // ':>' -> ']'
3537*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3538*67e74705SXin Li     } else if (LangOpts.CPlusPlus && Char == ':') {
3539*67e74705SXin Li       Kind = tok::coloncolon;
3540*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3541*67e74705SXin Li     } else {
3542*67e74705SXin Li       Kind = tok::colon;
3543*67e74705SXin Li     }
3544*67e74705SXin Li     break;
3545*67e74705SXin Li   case ';':
3546*67e74705SXin Li     Kind = tok::semi;
3547*67e74705SXin Li     break;
3548*67e74705SXin Li   case '=':
3549*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3550*67e74705SXin Li     if (Char == '=') {
3551*67e74705SXin Li       // If this is '====' and we're in a conflict marker, ignore it.
3552*67e74705SXin Li       if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3553*67e74705SXin Li         goto LexNextToken;
3554*67e74705SXin Li 
3555*67e74705SXin Li       Kind = tok::equalequal;
3556*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3557*67e74705SXin Li     } else {
3558*67e74705SXin Li       Kind = tok::equal;
3559*67e74705SXin Li     }
3560*67e74705SXin Li     break;
3561*67e74705SXin Li   case ',':
3562*67e74705SXin Li     Kind = tok::comma;
3563*67e74705SXin Li     break;
3564*67e74705SXin Li   case '#':
3565*67e74705SXin Li     Char = getCharAndSize(CurPtr, SizeTmp);
3566*67e74705SXin Li     if (Char == '#') {
3567*67e74705SXin Li       Kind = tok::hashhash;
3568*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569*67e74705SXin Li     } else if (Char == '@' && LangOpts.MicrosoftExt) {  // #@ -> Charize
3570*67e74705SXin Li       Kind = tok::hashat;
3571*67e74705SXin Li       if (!isLexingRawMode())
3572*67e74705SXin Li         Diag(BufferPtr, diag::ext_charize_microsoft);
3573*67e74705SXin Li       CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3574*67e74705SXin Li     } else {
3575*67e74705SXin Li       // We parsed a # character.  If this occurs at the start of the line,
3576*67e74705SXin Li       // it's actually the start of a preprocessing directive.  Callback to
3577*67e74705SXin Li       // the preprocessor to handle it.
3578*67e74705SXin Li       // TODO: -fpreprocessed mode??
3579*67e74705SXin Li       if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3580*67e74705SXin Li         goto HandleDirective;
3581*67e74705SXin Li 
3582*67e74705SXin Li       Kind = tok::hash;
3583*67e74705SXin Li     }
3584*67e74705SXin Li     break;
3585*67e74705SXin Li 
3586*67e74705SXin Li   case '@':
3587*67e74705SXin Li     // Objective C support.
3588*67e74705SXin Li     if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3589*67e74705SXin Li       Kind = tok::at;
3590*67e74705SXin Li     else
3591*67e74705SXin Li       Kind = tok::unknown;
3592*67e74705SXin Li     break;
3593*67e74705SXin Li 
3594*67e74705SXin Li   // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3595*67e74705SXin Li   case '\\':
3596*67e74705SXin Li     if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3597*67e74705SXin Li       if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3598*67e74705SXin Li         if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3599*67e74705SXin Li           return true; // KeepWhitespaceMode
3600*67e74705SXin Li 
3601*67e74705SXin Li         // We only saw whitespace, so just try again with this lexer.
3602*67e74705SXin Li         // (We manually eliminate the tail call to avoid recursion.)
3603*67e74705SXin Li         goto LexNextToken;
3604*67e74705SXin Li       }
3605*67e74705SXin Li 
3606*67e74705SXin Li       return LexUnicode(Result, CodePoint, CurPtr);
3607*67e74705SXin Li     }
3608*67e74705SXin Li 
3609*67e74705SXin Li     Kind = tok::unknown;
3610*67e74705SXin Li     break;
3611*67e74705SXin Li 
3612*67e74705SXin Li   default: {
3613*67e74705SXin Li     if (isASCII(Char)) {
3614*67e74705SXin Li       Kind = tok::unknown;
3615*67e74705SXin Li       break;
3616*67e74705SXin Li     }
3617*67e74705SXin Li 
3618*67e74705SXin Li     UTF32 CodePoint;
3619*67e74705SXin Li 
3620*67e74705SXin Li     // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3621*67e74705SXin Li     // an escaped newline.
3622*67e74705SXin Li     --CurPtr;
3623*67e74705SXin Li     ConversionResult Status =
3624*67e74705SXin Li         llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3625*67e74705SXin Li                                   (const UTF8 *)BufferEnd,
3626*67e74705SXin Li                                   &CodePoint,
3627*67e74705SXin Li                                   strictConversion);
3628*67e74705SXin Li     if (Status == conversionOK) {
3629*67e74705SXin Li       if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3630*67e74705SXin Li         if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3631*67e74705SXin Li           return true; // KeepWhitespaceMode
3632*67e74705SXin Li 
3633*67e74705SXin Li         // We only saw whitespace, so just try again with this lexer.
3634*67e74705SXin Li         // (We manually eliminate the tail call to avoid recursion.)
3635*67e74705SXin Li         goto LexNextToken;
3636*67e74705SXin Li       }
3637*67e74705SXin Li       return LexUnicode(Result, CodePoint, CurPtr);
3638*67e74705SXin Li     }
3639*67e74705SXin Li 
3640*67e74705SXin Li     if (isLexingRawMode() || ParsingPreprocessorDirective ||
3641*67e74705SXin Li         PP->isPreprocessedOutput()) {
3642*67e74705SXin Li       ++CurPtr;
3643*67e74705SXin Li       Kind = tok::unknown;
3644*67e74705SXin Li       break;
3645*67e74705SXin Li     }
3646*67e74705SXin Li 
3647*67e74705SXin Li     // Non-ASCII characters tend to creep into source code unintentionally.
3648*67e74705SXin Li     // Instead of letting the parser complain about the unknown token,
3649*67e74705SXin Li     // just diagnose the invalid UTF-8, then drop the character.
3650*67e74705SXin Li     Diag(CurPtr, diag::err_invalid_utf8);
3651*67e74705SXin Li 
3652*67e74705SXin Li     BufferPtr = CurPtr+1;
3653*67e74705SXin Li     // We're pretending the character didn't exist, so just try again with
3654*67e74705SXin Li     // this lexer.
3655*67e74705SXin Li     // (We manually eliminate the tail call to avoid recursion.)
3656*67e74705SXin Li     goto LexNextToken;
3657*67e74705SXin Li   }
3658*67e74705SXin Li   }
3659*67e74705SXin Li 
3660*67e74705SXin Li   // Notify MIOpt that we read a non-whitespace/non-comment token.
3661*67e74705SXin Li   MIOpt.ReadToken();
3662*67e74705SXin Li 
3663*67e74705SXin Li   // Update the location of token as well as BufferPtr.
3664*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, Kind);
3665*67e74705SXin Li   return true;
3666*67e74705SXin Li 
3667*67e74705SXin Li HandleDirective:
3668*67e74705SXin Li   // We parsed a # character and it's the start of a preprocessing directive.
3669*67e74705SXin Li 
3670*67e74705SXin Li   FormTokenWithChars(Result, CurPtr, tok::hash);
3671*67e74705SXin Li   PP->HandleDirective(Result);
3672*67e74705SXin Li 
3673*67e74705SXin Li   if (PP->hadModuleLoaderFatalFailure()) {
3674*67e74705SXin Li     // With a fatal failure in the module loader, we abort parsing.
3675*67e74705SXin Li     assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3676*67e74705SXin Li     return true;
3677*67e74705SXin Li   }
3678*67e74705SXin Li 
3679*67e74705SXin Li   // We parsed the directive; lex a token with the new state.
3680*67e74705SXin Li   return false;
3681*67e74705SXin Li }
3682