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