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