1 //===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
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 #include "SourceCode.h"
9 
10 #include "Context.h"
11 #include "FuzzyMatch.h"
12 #include "Logger.h"
13 #include "Protocol.h"
14 #include "refactor/Tweak.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/TokenKinds.h"
20 #include "clang/Driver/Types.h"
21 #include "clang/Format/Format.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Lex/Token.h"
25 #include "clang/Tooling/Core/Replacement.h"
26 #include "clang/Tooling/Syntax/Tokens.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/None.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Errc.h"
35 #include "llvm/Support/Error.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/LineIterator.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/SHA1.h"
41 #include "llvm/Support/VirtualFileSystem.h"
42 #include "llvm/Support/xxhash.h"
43 #include <algorithm>
44 #include <cstddef>
45 #include <string>
46 #include <vector>
47 
48 namespace clang {
49 namespace clangd {
50 
51 // Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
52 // Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
53 
54 // Iterates over unicode codepoints in the (UTF-8) string. For each,
55 // invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
56 // Returns true if CB returned true, false if we hit the end of string.
57 template <typename Callback>
58 static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
59   // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
60   // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
61   for (size_t I = 0; I < U8.size();) {
62     unsigned char C = static_cast<unsigned char>(U8[I]);
63     if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
64       if (CB(1, 1))
65         return true;
66       ++I;
67       continue;
68     }
69     // This convenient property of UTF-8 holds for all non-ASCII characters.
70     size_t UTF8Length = llvm::countLeadingOnes(C);
71     // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
72     // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
73     assert((UTF8Length >= 2 && UTF8Length <= 4) &&
74            "Invalid UTF-8, or transcoding bug?");
75     I += UTF8Length; // Skip over all trailing bytes.
76     // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
77     // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
78     if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
79       return true;
80   }
81   return false;
82 }
83 
84 // Returns the byte offset into the string that is an offset of \p Units in
85 // the specified encoding.
86 // Conceptually, this converts to the encoding, truncates to CodeUnits,
87 // converts back to UTF-8, and returns the length in bytes.
88 static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
89                            bool &Valid) {
90   Valid = Units >= 0;
91   if (Units <= 0)
92     return 0;
93   size_t Result = 0;
94   switch (Enc) {
95   case OffsetEncoding::UTF8:
96     Result = Units;
97     break;
98   case OffsetEncoding::UTF16:
99     Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
100       Result += U8Len;
101       Units -= U16Len;
102       return Units <= 0;
103     });
104     if (Units < 0) // Offset in the middle of a surrogate pair.
105       Valid = false;
106     break;
107   case OffsetEncoding::UTF32:
108     Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
109       Result += U8Len;
110       Units--;
111       return Units <= 0;
112     });
113     break;
114   case OffsetEncoding::UnsupportedEncoding:
115     llvm_unreachable("unsupported encoding");
116   }
117   // Don't return an out-of-range index if we overran.
118   if (Result > U8.size()) {
119     Valid = false;
120     return U8.size();
121   }
122   return Result;
123 }
124 
125 Key<OffsetEncoding> kCurrentOffsetEncoding;
126 static OffsetEncoding lspEncoding() {
127   auto *Enc = Context::current().get(kCurrentOffsetEncoding);
128   return Enc ? *Enc : OffsetEncoding::UTF16;
129 }
130 
131 // Like most strings in clangd, the input is UTF-8 encoded.
132 size_t lspLength(llvm::StringRef Code) {
133   size_t Count = 0;
134   switch (lspEncoding()) {
135   case OffsetEncoding::UTF8:
136     Count = Code.size();
137     break;
138   case OffsetEncoding::UTF16:
139     iterateCodepoints(Code, [&](int U8Len, int U16Len) {
140       Count += U16Len;
141       return false;
142     });
143     break;
144   case OffsetEncoding::UTF32:
145     iterateCodepoints(Code, [&](int U8Len, int U16Len) {
146       ++Count;
147       return false;
148     });
149     break;
150   case OffsetEncoding::UnsupportedEncoding:
151     llvm_unreachable("unsupported encoding");
152   }
153   return Count;
154 }
155 
156 llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
157                                         bool AllowColumnsBeyondLineLength) {
158   if (P.line < 0)
159     return llvm::make_error<llvm::StringError>(
160         llvm::formatv("Line value can't be negative ({0})", P.line),
161         llvm::errc::invalid_argument);
162   if (P.character < 0)
163     return llvm::make_error<llvm::StringError>(
164         llvm::formatv("Character value can't be negative ({0})", P.character),
165         llvm::errc::invalid_argument);
166   size_t StartOfLine = 0;
167   for (int I = 0; I != P.line; ++I) {
168     size_t NextNL = Code.find('\n', StartOfLine);
169     if (NextNL == llvm::StringRef::npos)
170       return llvm::make_error<llvm::StringError>(
171           llvm::formatv("Line value is out of range ({0})", P.line),
172           llvm::errc::invalid_argument);
173     StartOfLine = NextNL + 1;
174   }
175   StringRef Line =
176       Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
177 
178   // P.character may be in UTF-16, transcode if necessary.
179   bool Valid;
180   size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
181   if (!Valid && !AllowColumnsBeyondLineLength)
182     return llvm::make_error<llvm::StringError>(
183         llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
184                       P.character, P.line),
185         llvm::errc::invalid_argument);
186   return StartOfLine + ByteInLine;
187 }
188 
189 Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
190   Offset = std::min(Code.size(), Offset);
191   llvm::StringRef Before = Code.substr(0, Offset);
192   int Lines = Before.count('\n');
193   size_t PrevNL = Before.rfind('\n');
194   size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
195   Position Pos;
196   Pos.line = Lines;
197   Pos.character = lspLength(Before.substr(StartOfLine));
198   return Pos;
199 }
200 
201 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
202   // We use the SourceManager's line tables, but its column number is in bytes.
203   FileID FID;
204   unsigned Offset;
205   std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
206   Position P;
207   P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
208   bool Invalid = false;
209   llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
210   if (!Invalid) {
211     auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
212     auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
213     P.character = lspLength(LineSoFar);
214   }
215   return P;
216 }
217 
218 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
219   if (Loc.isMacroID()) {
220     std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
221     if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
222         llvm::StringRef(PrintLoc).startswith("<command line>"))
223       return false;
224   }
225   return true;
226 }
227 
228 bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
229   if (!R.getBegin().isValid() || !R.getEnd().isValid())
230     return false;
231 
232   FileID BeginFID;
233   size_t BeginOffset = 0;
234   std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
235 
236   FileID EndFID;
237   size_t EndOffset = 0;
238   std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
239 
240   return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
241 }
242 
243 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
244                            SourceLocation L) {
245   assert(isValidFileRange(Mgr, R));
246 
247   FileID BeginFID;
248   size_t BeginOffset = 0;
249   std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
250   size_t EndOffset = Mgr.getFileOffset(R.getEnd());
251 
252   FileID LFid;
253   size_t LOffset;
254   std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
255   return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
256 }
257 
258 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
259                           SourceLocation L) {
260   return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
261 }
262 
263 SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) {
264   assert(SM.getLocForEndOfFile(IncludedFile).isFileID());
265   FileID IncludingFile;
266   unsigned Offset;
267   std::tie(IncludingFile, Offset) =
268       SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile));
269   bool Invalid = false;
270   llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid);
271   if (Invalid)
272     return SourceLocation();
273   // Now buf is "...\n#include <foo>\n..."
274   // and Offset points here:   ^
275   // Rewind to the preceding # on the line.
276   assert(Offset < Buf.size());
277   for (;; --Offset) {
278     if (Buf[Offset] == '#')
279       return SM.getComposedLoc(IncludingFile, Offset);
280     if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on?
281       return SourceLocation();
282   }
283 }
284 
285 static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
286                                     const LangOptions &LangOpts) {
287   Token TheTok;
288   if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
289     return 0;
290   // FIXME: Here we check whether the token at the location is a greatergreater
291   // (>>) token and consider it as a single greater (>). This is to get it
292   // working for templates but it isn't correct for the right shift operator. We
293   // can avoid this by using half open char ranges in getFileRange() but getting
294   // token ending is not well supported in macroIDs.
295   if (TheTok.is(tok::greatergreater))
296     return 1;
297   return TheTok.getLength();
298 }
299 
300 // Returns location of the last character of the token at a given loc
301 static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
302                                         const SourceManager &SM,
303                                         const LangOptions &LangOpts) {
304   unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
305   return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
306 }
307 
308 // Returns location of the starting of the token at a given EndLoc
309 static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
310                                           const SourceManager &SM,
311                                           const LangOptions &LangOpts) {
312   return EndLoc.getLocWithOffset(
313       -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
314 }
315 
316 // Converts a char source range to a token range.
317 static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
318                                 const LangOptions &LangOpts) {
319   if (!Range.isTokenRange())
320     Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
321   return Range.getAsRange();
322 }
323 // Returns the union of two token ranges.
324 // To find the maximum of the Ends of the ranges, we compare the location of the
325 // last character of the token.
326 static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
327                                    const SourceManager &SM,
328                                    const LangOptions &LangOpts) {
329   SourceLocation Begin =
330       SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin())
331           ? R1.getBegin()
332           : R2.getBegin();
333   SourceLocation End =
334       SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts),
335                                    getLocForTokenEnd(R2.getEnd(), SM, LangOpts))
336           ? R2.getEnd()
337           : R1.getEnd();
338   return SourceRange(Begin, End);
339 }
340 
341 // Given a range whose endpoints may be in different expansions or files,
342 // tries to find a range within a common file by following up the expansion and
343 // include location in each.
344 static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM,
345                                      const LangOptions &LangOpts) {
346   // Fast path for most common cases.
347   if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
348     return R;
349   // Record the stack of expansion locations for the beginning, keyed by FileID.
350   llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
351   for (SourceLocation Begin = R.getBegin(); Begin.isValid();
352        Begin = Begin.isFileID()
353                    ? includeHashLoc(SM.getFileID(Begin), SM)
354                    : SM.getImmediateExpansionRange(Begin).getBegin()) {
355     BeginExpansions[SM.getFileID(Begin)] = Begin;
356   }
357   // Move up the stack of expansion locations for the end until we find the
358   // location in BeginExpansions with that has the same file id.
359   for (SourceLocation End = R.getEnd(); End.isValid();
360        End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM)
361                             : toTokenRange(SM.getImmediateExpansionRange(End),
362                                            SM, LangOpts)
363                                   .getEnd()) {
364     auto It = BeginExpansions.find(SM.getFileID(End));
365     if (It != BeginExpansions.end()) {
366       if (SM.getFileOffset(It->second) > SM.getFileOffset(End))
367         return SourceLocation();
368       return {It->second, End};
369     }
370   }
371   return SourceRange();
372 }
373 
374 // Find an expansion range (not necessarily immediate) the ends of which are in
375 // the same file id.
376 static SourceRange
377 getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
378                                  const LangOptions &LangOpts) {
379   return rangeInCommonFile(
380       toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
381       LangOpts);
382 }
383 
384 // Returns the file range for a given Location as a Token Range
385 // This is quite similar to getFileLoc in SourceManager as both use
386 // getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
387 // However:
388 // - We want to maintain the full range information as we move from one file to
389 //   the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
390 // - We want to split '>>' tokens as the lexer parses the '>>' in nested
391 //   template instantiations as a '>>' instead of two '>'s.
392 // There is also getExpansionRange but it simply calls
393 // getImmediateExpansionRange on the begin and ends separately which is wrong.
394 static SourceRange getTokenFileRange(SourceLocation Loc,
395                                      const SourceManager &SM,
396                                      const LangOptions &LangOpts) {
397   SourceRange FileRange = Loc;
398   while (!FileRange.getBegin().isFileID()) {
399     if (SM.isMacroArgExpansion(FileRange.getBegin())) {
400       FileRange = unionTokenRange(
401           SM.getImmediateSpellingLoc(FileRange.getBegin()),
402           SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
403       assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
404     } else {
405       SourceRange ExpansionRangeForBegin =
406           getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
407       SourceRange ExpansionRangeForEnd =
408           getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
409       if (ExpansionRangeForBegin.isInvalid() ||
410           ExpansionRangeForEnd.isInvalid())
411         return SourceRange();
412       assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
413                                     ExpansionRangeForEnd.getBegin()) &&
414              "Both Expansion ranges should be in same file.");
415       FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
416                                   SM, LangOpts);
417     }
418   }
419   return FileRange;
420 }
421 
422 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
423   if (!Loc.isValid())
424     return false;
425   FileID FID = SM.getFileID(SM.getExpansionLoc(Loc));
426   return FID == SM.getMainFileID() || FID == SM.getPreambleFileID();
427 }
428 
429 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
430                                                 const LangOptions &LangOpts,
431                                                 SourceRange R) {
432   SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
433   if (!isValidFileRange(SM, R1))
434     return llvm::None;
435 
436   SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
437   if (!isValidFileRange(SM, R2))
438     return llvm::None;
439 
440   SourceRange Result =
441       rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
442   unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
443   // Convert from closed token range to half-open (char) range
444   Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
445   if (!isValidFileRange(SM, Result))
446     return llvm::None;
447 
448   return Result;
449 }
450 
451 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
452   assert(isValidFileRange(SM, R));
453   bool Invalid = false;
454   auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
455   assert(!Invalid);
456 
457   size_t BeginOffset = SM.getFileOffset(R.getBegin());
458   size_t EndOffset = SM.getFileOffset(R.getEnd());
459   return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
460 }
461 
462 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
463                                                         Position P) {
464   llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
465   auto Offset =
466       positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
467   if (!Offset)
468     return Offset.takeError();
469   return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
470 }
471 
472 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
473   // Clang is 1-based, LSP uses 0-based indexes.
474   Position Begin = sourceLocToPosition(SM, R.getBegin());
475   Position End = sourceLocToPosition(SM, R.getEnd());
476 
477   return {Begin, End};
478 }
479 
480 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
481                                                   size_t Offset) {
482   Offset = std::min(Code.size(), Offset);
483   llvm::StringRef Before = Code.substr(0, Offset);
484   int Lines = Before.count('\n');
485   size_t PrevNL = Before.rfind('\n');
486   size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
487   return {Lines + 1, Offset - StartOfLine + 1};
488 }
489 
490 std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
491   size_t Pos = QName.rfind("::");
492   if (Pos == llvm::StringRef::npos)
493     return {llvm::StringRef(), QName};
494   return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
495 }
496 
497 TextEdit replacementToEdit(llvm::StringRef Code,
498                            const tooling::Replacement &R) {
499   Range ReplacementRange = {
500       offsetToPosition(Code, R.getOffset()),
501       offsetToPosition(Code, R.getOffset() + R.getLength())};
502   return {ReplacementRange, std::string(R.getReplacementText())};
503 }
504 
505 std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
506                                           const tooling::Replacements &Repls) {
507   std::vector<TextEdit> Edits;
508   for (const auto &R : Repls)
509     Edits.push_back(replacementToEdit(Code, R));
510   return Edits;
511 }
512 
513 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
514                                              const SourceManager &SourceMgr) {
515   if (!F)
516     return None;
517 
518   llvm::SmallString<128> FilePath = F->getName();
519   if (!llvm::sys::path::is_absolute(FilePath)) {
520     if (auto EC =
521             SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
522                 FilePath)) {
523       elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
524            EC.message());
525       return None;
526     }
527   }
528 
529   // Handle the symbolic link path case where the current working directory
530   // (getCurrentWorkingDirectory) is a symlink. We always want to the real
531   // file path (instead of the symlink path) for the  C++ symbols.
532   //
533   // Consider the following example:
534   //
535   //   src dir: /project/src/foo.h
536   //   current working directory (symlink): /tmp/build -> /project/src/
537   //
538   //  The file path of Symbol is "/project/src/foo.h" instead of
539   //  "/tmp/build/foo.h"
540   if (auto Dir = SourceMgr.getFileManager().getDirectory(
541           llvm::sys::path::parent_path(FilePath))) {
542     llvm::SmallString<128> RealPath;
543     llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
544     llvm::sys::path::append(RealPath, DirName,
545                             llvm::sys::path::filename(FilePath));
546     return RealPath.str().str();
547   }
548 
549   return FilePath.str().str();
550 }
551 
552 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
553                     const LangOptions &L) {
554   TextEdit Result;
555   Result.range =
556       halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
557   Result.newText = FixIt.CodeToInsert;
558   return Result;
559 }
560 
561 bool isRangeConsecutive(const Range &Left, const Range &Right) {
562   return Left.end.line == Right.start.line &&
563          Left.end.character == Right.start.character;
564 }
565 
566 FileDigest digest(llvm::StringRef Content) {
567   uint64_t Hash{llvm::xxHash64(Content)};
568   FileDigest Result;
569   for (unsigned I = 0; I < Result.size(); ++I) {
570     Result[I] = uint8_t(Hash);
571     Hash >>= 8;
572   }
573   return Result;
574 }
575 
576 llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
577   bool Invalid = false;
578   llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
579   if (Invalid)
580     return None;
581   return digest(Content);
582 }
583 
584 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
585                                           llvm::StringRef Content,
586                                           llvm::vfs::FileSystem *FS) {
587   auto Style = format::getStyle(format::DefaultFormatStyle, File,
588                                 format::DefaultFallbackStyle, Content, FS);
589   if (!Style) {
590     log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
591         Style.takeError());
592     Style = format::getLLVMStyle();
593   }
594   return *Style;
595 }
596 
597 llvm::Expected<tooling::Replacements>
598 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
599                  const format::FormatStyle &Style) {
600   auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
601   if (!CleanReplaces)
602     return CleanReplaces;
603   return formatReplacements(Code, std::move(*CleanReplaces), Style);
604 }
605 
606 static void
607 lex(llvm::StringRef Code, const LangOptions &LangOpts,
608     llvm::function_ref<void(const syntax::Token &, const SourceManager &SM)>
609         Action) {
610   // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
611   std::string NullTerminatedCode = Code.str();
612   SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
613   auto &SM = FileSM.get();
614   for (const auto &Tok : syntax::tokenize(SM.getMainFileID(), SM, LangOpts))
615     Action(Tok, SM);
616 }
617 
618 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
619                                              const format::FormatStyle &Style) {
620   llvm::StringMap<unsigned> Identifiers;
621   auto LangOpt = format::getFormattingLangOpts(Style);
622   lex(Content, LangOpt, [&](const syntax::Token &Tok, const SourceManager &SM) {
623     if (Tok.kind() == tok::identifier)
624       ++Identifiers[Tok.text(SM)];
625     // FIXME: Should this function really return keywords too ?
626     else if (const auto *Keyword = tok::getKeywordSpelling(Tok.kind()))
627       ++Identifiers[Keyword];
628   });
629   return Identifiers;
630 }
631 
632 std::vector<Range> collectIdentifierRanges(llvm::StringRef Identifier,
633                                            llvm::StringRef Content,
634                                            const LangOptions &LangOpts) {
635   std::vector<Range> Ranges;
636   lex(Content, LangOpts,
637       [&](const syntax::Token &Tok, const SourceManager &SM) {
638         if (Tok.kind() != tok::identifier || Tok.text(SM) != Identifier)
639           return;
640         Ranges.push_back(halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
641       });
642   return Ranges;
643 }
644 
645 namespace {
646 struct NamespaceEvent {
647   enum {
648     BeginNamespace, // namespace <ns> {.     Payload is resolved <ns>.
649     EndNamespace,   // } // namespace <ns>.  Payload is resolved *outer*
650                     // namespace.
651     UsingDirective  // using namespace <ns>. Payload is unresolved <ns>.
652   } Trigger;
653   std::string Payload;
654   Position Pos;
655 };
656 // Scans C++ source code for constructs that change the visible namespaces.
657 void parseNamespaceEvents(llvm::StringRef Code,
658                           const format::FormatStyle &Style,
659                           llvm::function_ref<void(NamespaceEvent)> Callback) {
660 
661   // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
662   std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
663   // Stack counts open braces. true if the brace opened a namespace.
664   std::vector<bool> BraceStack;
665 
666   enum {
667     Default,
668     Namespace,          // just saw 'namespace'
669     NamespaceName,      // just saw 'namespace' NSName
670     Using,              // just saw 'using'
671     UsingNamespace,     // just saw 'using namespace'
672     UsingNamespaceName, // just saw 'using namespace' NSName
673   } State = Default;
674   std::string NSName;
675 
676   NamespaceEvent Event;
677   lex(Code, format::getFormattingLangOpts(Style),
678       [&](const syntax::Token &Tok, const SourceManager &SM) {
679         Event.Pos = sourceLocToPosition(SM, Tok.location());
680         switch (Tok.kind()) {
681         case tok::kw_using:
682           State = State == Default ? Using : Default;
683           break;
684         case tok::kw_namespace:
685           switch (State) {
686           case Using:
687             State = UsingNamespace;
688             break;
689           case Default:
690             State = Namespace;
691             break;
692           default:
693             State = Default;
694             break;
695           }
696           break;
697         case tok::identifier:
698           switch (State) {
699           case UsingNamespace:
700             NSName.clear();
701             LLVM_FALLTHROUGH;
702           case UsingNamespaceName:
703             NSName.append(Tok.text(SM).str());
704             State = UsingNamespaceName;
705             break;
706           case Namespace:
707             NSName.clear();
708             LLVM_FALLTHROUGH;
709           case NamespaceName:
710             NSName.append(Tok.text(SM).str());
711             State = NamespaceName;
712             break;
713           case Using:
714           case Default:
715             State = Default;
716             break;
717           }
718           break;
719         case tok::coloncolon:
720           // This can come at the beginning or in the middle of a namespace
721           // name.
722           switch (State) {
723           case UsingNamespace:
724             NSName.clear();
725             LLVM_FALLTHROUGH;
726           case UsingNamespaceName:
727             NSName.append("::");
728             State = UsingNamespaceName;
729             break;
730           case NamespaceName:
731             NSName.append("::");
732             State = NamespaceName;
733             break;
734           case Namespace: // Not legal here.
735           case Using:
736           case Default:
737             State = Default;
738             break;
739           }
740           break;
741         case tok::l_brace:
742           // Record which { started a namespace, so we know when } ends one.
743           if (State == NamespaceName) {
744             // Parsed: namespace <name> {
745             BraceStack.push_back(true);
746             Enclosing.push_back(NSName);
747             Event.Trigger = NamespaceEvent::BeginNamespace;
748             Event.Payload = llvm::join(Enclosing, "::");
749             Callback(Event);
750           } else {
751             // This case includes anonymous namespaces (State = Namespace).
752             // For our purposes, they're not namespaces and we ignore them.
753             BraceStack.push_back(false);
754           }
755           State = Default;
756           break;
757         case tok::r_brace:
758           // If braces are unmatched, we're going to be confused, but don't
759           // crash.
760           if (!BraceStack.empty()) {
761             if (BraceStack.back()) {
762               // Parsed: } // namespace
763               Enclosing.pop_back();
764               Event.Trigger = NamespaceEvent::EndNamespace;
765               Event.Payload = llvm::join(Enclosing, "::");
766               Callback(Event);
767             }
768             BraceStack.pop_back();
769           }
770           break;
771         case tok::semi:
772           if (State == UsingNamespaceName) {
773             // Parsed: using namespace <name> ;
774             Event.Trigger = NamespaceEvent::UsingDirective;
775             Event.Payload = std::move(NSName);
776             Callback(Event);
777           }
778           State = Default;
779           break;
780         default:
781           State = Default;
782           break;
783         }
784       });
785 }
786 
787 // Returns the prefix namespaces of NS: {"" ... NS}.
788 llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
789   llvm::SmallVector<llvm::StringRef, 8> Results;
790   Results.push_back(NS.take_front(0));
791   NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
792   for (llvm::StringRef &R : Results)
793     R = NS.take_front(R.end() - NS.begin());
794   return Results;
795 }
796 
797 } // namespace
798 
799 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
800                                            const format::FormatStyle &Style) {
801   std::string Current;
802   // Map from namespace to (resolved) namespaces introduced via using directive.
803   llvm::StringMap<llvm::StringSet<>> UsingDirectives;
804 
805   parseNamespaceEvents(Code, Style, [&](NamespaceEvent Event) {
806     llvm::StringRef NS = Event.Payload;
807     switch (Event.Trigger) {
808     case NamespaceEvent::BeginNamespace:
809     case NamespaceEvent::EndNamespace:
810       Current = std::move(Event.Payload);
811       break;
812     case NamespaceEvent::UsingDirective:
813       if (NS.consume_front("::"))
814         UsingDirectives[Current].insert(NS);
815       else {
816         for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
817           if (Enclosing.empty())
818             UsingDirectives[Current].insert(NS);
819           else
820             UsingDirectives[Current].insert((Enclosing + "::" + NS).str());
821         }
822       }
823       break;
824     }
825   });
826 
827   std::vector<std::string> Found;
828   for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
829     Found.push_back(std::string(Enclosing));
830     auto It = UsingDirectives.find(Enclosing);
831     if (It != UsingDirectives.end())
832       for (const auto &Used : It->second)
833         Found.push_back(std::string(Used.getKey()));
834   }
835 
836   llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
837     if (Current == RHS)
838       return false;
839     if (Current == LHS)
840       return true;
841     return LHS < RHS;
842   });
843   Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
844   return Found;
845 }
846 
847 llvm::StringSet<> collectWords(llvm::StringRef Content) {
848   // We assume short words are not significant.
849   // We may want to consider other stopwords, e.g. language keywords.
850   // (A very naive implementation showed no benefit, but lexing might do better)
851   static constexpr int MinWordLength = 4;
852 
853   std::vector<CharRole> Roles(Content.size());
854   calculateRoles(Content, Roles);
855 
856   llvm::StringSet<> Result;
857   llvm::SmallString<256> Word;
858   auto Flush = [&] {
859     if (Word.size() >= MinWordLength) {
860       for (char &C : Word)
861         C = llvm::toLower(C);
862       Result.insert(Word);
863     }
864     Word.clear();
865   };
866   for (unsigned I = 0; I < Content.size(); ++I) {
867     switch (Roles[I]) {
868     case Head:
869       Flush();
870       LLVM_FALLTHROUGH;
871     case Tail:
872       Word.push_back(Content[I]);
873       break;
874     case Unknown:
875     case Separator:
876       Flush();
877       break;
878     }
879   }
880   Flush();
881 
882   return Result;
883 }
884 
885 llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
886                                            Preprocessor &PP) {
887   SourceLocation Loc = SpelledTok.location();
888   assert(Loc.isFileID());
889   const auto &SM = PP.getSourceManager();
890   IdentifierInfo *IdentifierInfo = PP.getIdentifierInfo(SpelledTok.text(SM));
891   if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
892     return None;
893 
894   // Get the definition just before the searched location so that a macro
895   // referenced in a '#undef MACRO' can still be found. Note that we only do
896   // that if Loc is not pointing at start of file.
897   if (SM.getLocForStartOfFile(SM.getFileID(Loc)) != Loc)
898     Loc = Loc.getLocWithOffset(-1);
899   MacroDefinition MacroDef = PP.getMacroDefinitionAtLoc(IdentifierInfo, Loc);
900   if (auto *MI = MacroDef.getMacroInfo())
901     return DefinedMacro{IdentifierInfo->getName(), MI};
902   return None;
903 }
904 
905 llvm::Expected<std::string> Edit::apply() const {
906   return tooling::applyAllReplacements(InitialCode, Replacements);
907 }
908 
909 std::vector<TextEdit> Edit::asTextEdits() const {
910   return replacementsToEdits(InitialCode, Replacements);
911 }
912 
913 bool Edit::canApplyTo(llvm::StringRef Code) const {
914   // Create line iterators, since line numbers are important while applying our
915   // edit we cannot skip blank lines.
916   auto LHS = llvm::MemoryBuffer::getMemBuffer(Code);
917   llvm::line_iterator LHSIt(*LHS, /*SkipBlanks=*/false);
918 
919   auto RHS = llvm::MemoryBuffer::getMemBuffer(InitialCode);
920   llvm::line_iterator RHSIt(*RHS, /*SkipBlanks=*/false);
921 
922   // Compare the InitialCode we prepared the edit for with the Code we received
923   // line by line to make sure there are no differences.
924   // FIXME: This check is too conservative now, it should be enough to only
925   // check lines around the replacements contained inside the Edit.
926   while (!LHSIt.is_at_eof() && !RHSIt.is_at_eof()) {
927     if (*LHSIt != *RHSIt)
928       return false;
929     ++LHSIt;
930     ++RHSIt;
931   }
932 
933   // After we reach EOF for any of the files we make sure the other one doesn't
934   // contain any additional content except empty lines, they should not
935   // interfere with the edit we produced.
936   while (!LHSIt.is_at_eof()) {
937     if (!LHSIt->empty())
938       return false;
939     ++LHSIt;
940   }
941   while (!RHSIt.is_at_eof()) {
942     if (!RHSIt->empty())
943       return false;
944     ++RHSIt;
945   }
946   return true;
947 }
948 
949 llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style) {
950   if (auto NewEdits = cleanupAndFormat(E.InitialCode, E.Replacements, Style))
951     E.Replacements = std::move(*NewEdits);
952   else
953     return NewEdits.takeError();
954   return llvm::Error::success();
955 }
956 
957 EligibleRegion getEligiblePoints(llvm::StringRef Code,
958                                  llvm::StringRef FullyQualifiedName,
959                                  const format::FormatStyle &Style) {
960   EligibleRegion ER;
961   // Start with global namespace.
962   std::vector<std::string> Enclosing = {""};
963   // FIXME: In addition to namespaces try to generate events for function
964   // definitions as well. One might use a closing parantheses(")" followed by an
965   // opening brace "{" to trigger the start.
966   parseNamespaceEvents(Code, Style, [&](NamespaceEvent Event) {
967     // Using Directives only introduces declarations to current scope, they do
968     // not change the current namespace, so skip them.
969     if (Event.Trigger == NamespaceEvent::UsingDirective)
970       return;
971     // Do not qualify the global namespace.
972     if (!Event.Payload.empty())
973       Event.Payload.append("::");
974 
975     std::string CurrentNamespace;
976     if (Event.Trigger == NamespaceEvent::BeginNamespace) {
977       Enclosing.emplace_back(std::move(Event.Payload));
978       CurrentNamespace = Enclosing.back();
979       // parseNameSpaceEvents reports the beginning position of a token; we want
980       // to insert after '{', so increment by one.
981       ++Event.Pos.character;
982     } else {
983       // Event.Payload points to outer namespace when exiting a scope, so use
984       // the namespace we've last entered instead.
985       CurrentNamespace = std::move(Enclosing.back());
986       Enclosing.pop_back();
987       assert(Enclosing.back() == Event.Payload);
988     }
989 
990     // Ignore namespaces that are not a prefix of the target.
991     if (!FullyQualifiedName.startswith(CurrentNamespace))
992       return;
993 
994     // Prefer the namespace that shares the longest prefix with target.
995     if (CurrentNamespace.size() > ER.EnclosingNamespace.size()) {
996       ER.EligiblePoints.clear();
997       ER.EnclosingNamespace = CurrentNamespace;
998     }
999     if (CurrentNamespace.size() == ER.EnclosingNamespace.size())
1000       ER.EligiblePoints.emplace_back(std::move(Event.Pos));
1001   });
1002   // If there were no shared namespaces just return EOF.
1003   if (ER.EligiblePoints.empty()) {
1004     assert(ER.EnclosingNamespace.empty());
1005     ER.EligiblePoints.emplace_back(offsetToPosition(Code, Code.size()));
1006   }
1007   return ER;
1008 }
1009 
1010 bool isHeaderFile(llvm::StringRef FileName,
1011                   llvm::Optional<LangOptions> LangOpts) {
1012   // Respect the langOpts, for non-file-extension cases, e.g. standard library
1013   // files.
1014   if (LangOpts && LangOpts->IsHeaderFile)
1015     return true;
1016   namespace types = clang::driver::types;
1017   auto Lang = types::lookupTypeForExtension(
1018       llvm::sys::path::extension(FileName).substr(1));
1019   return Lang != types::TY_INVALID && types::onlyPrecompileType(Lang);
1020 }
1021 
1022 bool isProtoFile(SourceLocation Loc, const SourceManager &SM) {
1023   auto FileName = SM.getFilename(Loc);
1024   if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
1025     return false;
1026   auto FID = SM.getFileID(Loc);
1027   // All proto generated headers should start with this line.
1028   static const char *PROTO_HEADER_COMMENT =
1029       "// Generated by the protocol buffer compiler.  DO NOT EDIT!";
1030   // Double check that this is an actual protobuf header.
1031   return SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT);
1032 }
1033 
1034 } // namespace clangd
1035 } // namespace clang
1036