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