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