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