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