blob: 7bac25167074feb4b75be97a3ab5c265fd78d97a [file] [log] [blame]
Sam McCall3f0243f2018-07-03 08:09:29 +00001//===--- FileDistance.cpp - File contents container -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The FileDistance structure allows calculating the minimum distance to paths
11// in a single tree.
12// We simply walk up the path's ancestors until we find a node whose cost is
13// known, and add the cost of walking back down. Initialization ensures this
14// gives the correct path to the roots.
15// We cache the results, so that the runtime is O(|A|), where A is the set of
16// all distinct ancestors of visited paths.
17//
18// Example after initialization with /=2, /bar=0, DownCost = 1:
19// / = 2
20// /bar = 0
21//
22// After querying /foo/bar and /bar/foo:
23// / = 2
24// /bar = 0
25// /bar/foo = 1
26// /foo = 3
27// /foo/bar = 4
28//
29// URIDistance creates FileDistance lazily for each URI scheme encountered. In
30// practice this is a small constant factor.
31//
32//===-------------------------------------------------------------------------//
33
34#include "FileDistance.h"
35#include "Logger.h"
36#include "llvm/ADT/STLExtras.h"
37#include <queue>
Sam McCall3f0243f2018-07-03 08:09:29 +000038
39namespace clang {
40namespace clangd {
Sam McCall3f0243f2018-07-03 08:09:29 +000041
42// Convert a path into the canonical form.
43// Canonical form is either "/", or "/segment" * N:
44// C:\foo\bar --> /c:/foo/bar
45// /foo/ --> /foo
46// a/b/c --> /a/b/c
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000047static llvm::SmallString<128> canonicalize(llvm::StringRef Path) {
48 llvm::SmallString<128> Result = Path.rtrim('/');
49 native(Result, llvm::sys::path::Style::posix);
Sam McCall3f0243f2018-07-03 08:09:29 +000050 if (Result.empty() || Result.front() != '/')
51 Result.insert(Result.begin(), '/');
52 return Result;
53}
54
Kirill Bobyrevc38b3f02018-08-31 08:29:48 +000055constexpr const unsigned FileDistance::Unreachable;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000056const llvm::hash_code FileDistance::RootHash =
57 llvm::hash_value(llvm::StringRef("/"));
Sam McCall3f0243f2018-07-03 08:09:29 +000058
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000059FileDistance::FileDistance(llvm::StringMap<SourceParams> Sources,
Sam McCall3f0243f2018-07-03 08:09:29 +000060 const FileDistanceOptions &Opts)
61 : Opts(Opts) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000062 llvm::DenseMap<llvm::hash_code, llvm::SmallVector<llvm::hash_code, 4>>
63 DownEdges;
Sam McCall3f0243f2018-07-03 08:09:29 +000064 // Compute the best distance following only up edges.
65 // Keep track of down edges, in case we can use them to improve on this.
66 for (const auto &S : Sources) {
67 auto Canonical = canonicalize(S.getKey());
Sam McCallbed58852018-07-11 10:35:11 +000068 dlog("Source {0} = {1}, MaxUp = {2}", Canonical, S.second.Cost,
69 S.second.MaxUpTraversals);
Sam McCall3f0243f2018-07-03 08:09:29 +000070 // Walk up to ancestors of this source, assigning cost.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000071 llvm::StringRef Rest = Canonical;
72 llvm::hash_code Hash = llvm::hash_value(Rest);
Sam McCall3f0243f2018-07-03 08:09:29 +000073 for (unsigned I = 0; !Rest.empty(); ++I) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000074 Rest = parent_path(Rest, llvm::sys::path::Style::posix);
75 auto NextHash = llvm::hash_value(Rest);
Sam McCall7c96bb62018-07-04 08:27:28 +000076 auto &Down = DownEdges[NextHash];
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000077 if (!llvm::is_contained(Down, Hash))
Fangrui Song8380c9e2018-10-07 17:21:08 +000078 Down.push_back(Hash);
Sam McCall3f0243f2018-07-03 08:09:29 +000079 // We can't just break after MaxUpTraversals, must still set DownEdges.
80 if (I > S.getValue().MaxUpTraversals) {
81 if (Cache.find(Hash) != Cache.end())
82 break;
83 } else {
84 unsigned Cost = S.getValue().Cost + I * Opts.UpCost;
85 auto R = Cache.try_emplace(Hash, Cost);
86 if (!R.second) {
87 if (Cost < R.first->second) {
88 R.first->second = Cost;
89 } else {
90 // If we're not the best way to get to this path, stop assigning.
91 break;
92 }
93 }
94 }
95 Hash = NextHash;
96 }
97 }
98 // Now propagate scores parent -> child if that's an improvement.
99 // BFS ensures we propagate down chains (must visit parents before children).
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000100 std::queue<llvm::hash_code> Next;
101 for (auto Child : DownEdges.lookup(llvm::hash_value(llvm::StringRef(""))))
Sam McCall3f0243f2018-07-03 08:09:29 +0000102 Next.push(Child);
103 while (!Next.empty()) {
Eric Liu0c29722c2018-10-16 10:41:17 +0000104 auto Parent = Next.front();
105 Next.pop();
106 auto ParentCost = Cache.lookup(Parent);
107 for (auto Child : DownEdges.lookup(Parent)) {
108 if (Parent != RootHash || Opts.AllowDownTraversalFromRoot) {
109 auto &ChildCost =
110 Cache.try_emplace(Child, Unreachable).first->getSecond();
111 if (ParentCost + Opts.DownCost < ChildCost)
112 ChildCost = ParentCost + Opts.DownCost;
113 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000114 Next.push(Child);
115 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000116 }
117}
118
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000119unsigned FileDistance::distance(llvm::StringRef Path) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000120 auto Canonical = canonicalize(Path);
Kirill Bobyrevc1bb7b92018-08-31 08:19:50 +0000121 unsigned Cost = Unreachable;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000122 llvm::SmallVector<llvm::hash_code, 16> Ancestors;
Sam McCall3f0243f2018-07-03 08:09:29 +0000123 // Walk up ancestors until we find a path we know the distance for.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000124 for (llvm::StringRef Rest = Canonical; !Rest.empty();
125 Rest = parent_path(Rest, llvm::sys::path::Style::posix)) {
126 auto Hash = llvm::hash_value(Rest);
Eric Liu0c29722c2018-10-16 10:41:17 +0000127 if (Hash == RootHash && !Ancestors.empty() &&
128 !Opts.AllowDownTraversalFromRoot) {
129 Cost = Unreachable;
130 break;
131 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000132 auto It = Cache.find(Hash);
133 if (It != Cache.end()) {
134 Cost = It->second;
135 break;
136 }
137 Ancestors.push_back(Hash);
138 }
139 // Now we know the costs for (known node, queried node].
140 // Fill these in, walking down the directory tree.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 for (llvm::hash_code Hash : llvm::reverse(Ancestors)) {
Kirill Bobyrevc1bb7b92018-08-31 08:19:50 +0000142 if (Cost != Unreachable)
Sam McCall3f0243f2018-07-03 08:09:29 +0000143 Cost += Opts.DownCost;
144 Cache.try_emplace(Hash, Cost);
145 }
Sam McCallbed58852018-07-11 10:35:11 +0000146 dlog("distance({0} = {1})", Path, Cost);
Sam McCall3f0243f2018-07-03 08:09:29 +0000147 return Cost;
148}
149
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000150unsigned URIDistance::distance(llvm::StringRef URI) {
151 auto R = Cache.try_emplace(llvm::hash_value(URI), FileDistance::Unreachable);
Sam McCall3f0243f2018-07-03 08:09:29 +0000152 if (!R.second)
153 return R.first->getSecond();
154 if (auto U = clangd::URI::parse(URI)) {
Sam McCallbed58852018-07-11 10:35:11 +0000155 dlog("distance({0} = {1})", URI, U->body());
Sam McCall3f0243f2018-07-03 08:09:29 +0000156 R.first->second = forScheme(U->scheme()).distance(U->body());
157 } else {
Sam McCallbed58852018-07-11 10:35:11 +0000158 log("URIDistance::distance() of unparseable {0}: {1}", URI, U.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +0000159 }
160 return R.first->second;
161}
162
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000163FileDistance &URIDistance::forScheme(llvm::StringRef Scheme) {
Sam McCall3f0243f2018-07-03 08:09:29 +0000164 auto &Delegate = ByScheme[Scheme];
165 if (!Delegate) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000166 llvm::StringMap<SourceParams> SchemeSources;
Sam McCall3f0243f2018-07-03 08:09:29 +0000167 for (const auto &Source : Sources) {
168 if (auto U = clangd::URI::create(Source.getKey(), Scheme))
169 SchemeSources.try_emplace(U->body(), Source.getValue());
170 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000171 llvm::consumeError(U.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +0000172 }
Sam McCallbed58852018-07-11 10:35:11 +0000173 dlog("FileDistance for scheme {0}: {1}/{2} sources", Scheme,
174 SchemeSources.size(), Sources.size());
Sam McCall3f0243f2018-07-03 08:09:29 +0000175 Delegate.reset(new FileDistance(std::move(SchemeSources), Opts));
176 }
177 return *Delegate;
178}
179
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180static std::pair<std::string, int> scopeToPath(llvm::StringRef Scope) {
181 llvm::SmallVector<llvm::StringRef, 4> Split;
Eric Liu3fac4ef2018-10-17 11:19:02 +0000182 Scope.split(Split, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 return {"/" + llvm::join(Split, "/"), Split.size()};
Eric Liu3fac4ef2018-10-17 11:19:02 +0000184}
185
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000186static FileDistance
187createScopeFileDistance(llvm::ArrayRef<std::string> QueryScopes) {
Eric Liu3fac4ef2018-10-17 11:19:02 +0000188 FileDistanceOptions Opts;
189 Opts.UpCost = 2;
190 Opts.DownCost = 4;
191 Opts.AllowDownTraversalFromRoot = false;
192
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000193 llvm::StringMap<SourceParams> Sources;
194 llvm::StringRef Preferred =
195 QueryScopes.empty() ? "" : QueryScopes.front().c_str();
196 for (llvm::StringRef S : QueryScopes) {
Eric Liu3fac4ef2018-10-17 11:19:02 +0000197 SourceParams Param;
198 // Penalize the global scope even it's preferred, as all projects can define
199 // symbols in it, and there is pattern where using-namespace is used in
200 // place of enclosing namespaces (e.g. in implementation files).
201 if (S == Preferred)
Eric Liu4fac50e2018-11-26 12:12:01 +0000202 Param.Cost = S == "" ? 4 : 0;
Eric Liu3fac4ef2018-10-17 11:19:02 +0000203 else if (Preferred.startswith(S) && !S.empty())
204 continue; // just rely on up-traversals.
205 else
Eric Liu4fac50e2018-11-26 12:12:01 +0000206 Param.Cost = S == "" ? 6 : 2;
Eric Liu3fac4ef2018-10-17 11:19:02 +0000207 auto Path = scopeToPath(S);
208 // The global namespace is not 'near' its children.
209 Param.MaxUpTraversals = std::max(Path.second - 1, 0);
210 Sources[Path.first] = std::move(Param);
211 }
212 return FileDistance(Sources, Opts);
213}
214
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000215ScopeDistance::ScopeDistance(llvm::ArrayRef<std::string> QueryScopes)
Eric Liu3fac4ef2018-10-17 11:19:02 +0000216 : Distance(createScopeFileDistance(QueryScopes)) {}
217
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000218unsigned ScopeDistance::distance(llvm::StringRef SymbolScope) {
Eric Liu3fac4ef2018-10-17 11:19:02 +0000219 return Distance.distance(scopeToPath(SymbolScope).first);
220}
221
Sam McCall3f0243f2018-07-03 08:09:29 +0000222} // namespace clangd
223} // namespace clang