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