cargo/core/resolver/
errors.rs1use std::collections::BTreeMap;
2use std::fmt;
3
4use crate::core::{Dependency, PackageId, Registry, Summary};
5use crate::util::lev_distance::lev_distance;
6use crate::util::Config;
7use failure::{Error, Fail};
8use semver;
9
10use super::context::Context;
11use super::types::{Candidate, ConflictReason};
12
13pub struct ResolveError {
15 cause: Error,
16 package_path: Vec<PackageId>,
17}
18
19impl ResolveError {
20 pub fn new<E: Into<Error>>(cause: E, package_path: Vec<PackageId>) -> Self {
21 Self {
22 cause: cause.into(),
23 package_path,
24 }
25 }
26
27 pub fn package_path(&self) -> &[PackageId] {
30 &self.package_path
31 }
32}
33
34impl Fail for ResolveError {
35 fn cause(&self) -> Option<&dyn Fail> {
36 self.cause.as_fail().cause()
37 }
38}
39
40impl fmt::Debug for ResolveError {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 self.cause.fmt(f)
43 }
44}
45
46impl fmt::Display for ResolveError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 self.cause.fmt(f)
49 }
50}
51
52pub type ActivateResult<T> = Result<T, ActivateError>;
53
54pub enum ActivateError {
55 Fatal(failure::Error),
56 Conflict(PackageId, ConflictReason),
57}
58
59impl From<::failure::Error> for ActivateError {
60 fn from(t: ::failure::Error) -> Self {
61 ActivateError::Fatal(t)
62 }
63}
64
65impl From<(PackageId, ConflictReason)> for ActivateError {
66 fn from(t: (PackageId, ConflictReason)) -> Self {
67 ActivateError::Conflict(t.0, t.1)
68 }
69}
70
71pub(super) fn activation_error(
72 cx: &Context,
73 registry: &mut dyn Registry,
74 parent: &Summary,
75 dep: &Dependency,
76 conflicting_activations: &BTreeMap<PackageId, ConflictReason>,
77 candidates: &[Candidate],
78 config: Option<&Config>,
79) -> ResolveError {
80 let graph = cx.graph();
81 let to_resolve_err = |err| {
82 ResolveError::new(
83 err,
84 graph
85 .path_to_top(&parent.package_id())
86 .into_iter()
87 .cloned()
88 .collect(),
89 )
90 };
91
92 if !candidates.is_empty() {
93 let mut msg = format!("failed to select a version for `{}`.", dep.package_name());
94 msg.push_str("\n ... required by ");
95 msg.push_str(&describe_path(&graph.path_to_top(&parent.package_id())));
96
97 msg.push_str("\nversions that meet the requirements `");
98 msg.push_str(&dep.version_req().to_string());
99 msg.push_str("` are: ");
100 msg.push_str(
101 &candidates
102 .iter()
103 .map(|v| v.summary.version())
104 .map(|v| v.to_string())
105 .collect::<Vec<_>>()
106 .join(", "),
107 );
108
109 let mut conflicting_activations: Vec<_> = conflicting_activations.iter().collect();
110 conflicting_activations.sort_unstable();
111 let (links_errors, mut other_errors): (Vec<_>, Vec<_>) = conflicting_activations
112 .drain(..)
113 .rev()
114 .partition(|&(_, r)| r.is_links());
115
116 for &(p, r) in links_errors.iter() {
117 if let ConflictReason::Links(ref link) = *r {
118 msg.push_str("\n\nthe package `");
119 msg.push_str(&*dep.package_name());
120 msg.push_str("` links to the native library `");
121 msg.push_str(link);
122 msg.push_str("`, but it conflicts with a previous package which links to `");
123 msg.push_str(link);
124 msg.push_str("` as well:\n");
125 }
126 msg.push_str(&describe_path(&graph.path_to_top(p)));
127 }
128
129 let (features_errors, other_errors): (Vec<_>, Vec<_>) = other_errors
130 .drain(..)
131 .partition(|&(_, r)| r.is_missing_features());
132
133 for &(p, r) in features_errors.iter() {
134 if let ConflictReason::MissingFeatures(ref features) = *r {
135 msg.push_str("\n\nthe package `");
136 msg.push_str(&*p.name());
137 msg.push_str("` depends on `");
138 msg.push_str(&*dep.package_name());
139 msg.push_str("`, with features: `");
140 msg.push_str(features);
141 msg.push_str("` but `");
142 msg.push_str(&*dep.package_name());
143 msg.push_str("` does not have these features.\n");
144 }
145 }
147
148 if !other_errors.is_empty() {
149 msg.push_str(
150 "\n\nall possible versions conflict with \
151 previously selected packages.",
152 );
153 }
154
155 for &(p, _) in other_errors.iter() {
156 msg.push_str("\n\n previously selected ");
157 msg.push_str(&describe_path(&graph.path_to_top(p)));
158 }
159
160 msg.push_str("\n\nfailed to select a version for `");
161 msg.push_str(&*dep.package_name());
162 msg.push_str("` which could resolve this conflict");
163
164 return to_resolve_err(failure::format_err!("{}", msg));
165 }
166
167 let all_req = semver::VersionReq::parse("*").unwrap();
174 let mut new_dep = dep.clone();
175 new_dep.set_version_req(all_req);
176 let mut candidates = match registry.query_vec(&new_dep, false) {
177 Ok(candidates) => candidates,
178 Err(e) => return to_resolve_err(e),
179 };
180 candidates.sort_unstable_by(|a, b| b.version().cmp(a.version()));
181
182 let mut msg = if !candidates.is_empty() {
183 let versions = {
184 let mut versions = candidates
185 .iter()
186 .take(3)
187 .map(|cand| cand.version().to_string())
188 .collect::<Vec<_>>();
189
190 if candidates.len() > 3 {
191 versions.push("...".into());
192 }
193
194 versions.join(", ")
195 };
196
197 let mut msg = format!(
198 "failed to select a version for the requirement `{} = \"{}\"`\n \
199 candidate versions found which didn't match: {}\n \
200 location searched: {}\n",
201 dep.package_name(),
202 dep.version_req(),
203 versions,
204 registry.describe_source(dep.source_id()),
205 );
206 msg.push_str("required by ");
207 msg.push_str(&describe_path(&graph.path_to_top(&parent.package_id())));
208
209 if dep.source_id().is_path() && dep.version_req().to_string().starts_with('=') {
213 msg.push_str(
214 "\nconsider running `cargo update` to update \
215 a path dependency's locked version",
216 );
217 }
218
219 if registry.is_replaced(dep.source_id()) {
220 msg.push_str("\nperhaps a crate was updated and forgotten to be re-vendored?");
221 }
222
223 msg
224 } else {
225 let mut candidates = Vec::new();
228 if let Err(e) = registry.query(&new_dep, &mut |s| candidates.push(s.name()), true) {
229 return to_resolve_err(e);
230 };
231 candidates.sort_unstable();
232 candidates.dedup();
233 let mut candidates: Vec<_> = candidates
234 .iter()
235 .map(|n| (lev_distance(&*new_dep.package_name(), &*n), n))
236 .filter(|&(d, _)| d < 4)
237 .collect();
238 candidates.sort_by_key(|o| o.0);
239 let mut msg = format!(
240 "no matching package named `{}` found\n\
241 location searched: {}\n",
242 dep.package_name(),
243 dep.source_id()
244 );
245 if !candidates.is_empty() {
246 let mut names = candidates
247 .iter()
248 .take(3)
249 .map(|c| c.1.as_str())
250 .collect::<Vec<_>>();
251
252 if candidates.len() > 3 {
253 names.push("...");
254 }
255
256 msg.push_str("did you mean: ");
257 msg.push_str(&names.join(", "));
258 msg.push_str("\n");
259 }
260 msg.push_str("required by ");
261 msg.push_str(&describe_path(&graph.path_to_top(&parent.package_id())));
262
263 msg
264 };
265
266 if let Some(config) = config {
267 if config.cli_unstable().offline {
268 msg.push_str(
269 "\nAs a reminder, you're using offline mode (-Z offline) \
270 which can sometimes cause surprising resolution failures, \
271 if this error is too confusing you may with to retry \
272 without the offline flag.",
273 );
274 }
275 }
276
277 to_resolve_err(failure::format_err!("{}", msg))
278}
279
280pub(super) fn describe_path(path: &[&PackageId]) -> String {
282 use std::fmt::Write;
283 let mut dep_path_desc = format!("package `{}`", path[0]);
284 for dep in path[1..].iter() {
285 write!(dep_path_desc, "\n ... which is depended on by `{}`", dep).unwrap();
286 }
287 dep_path_desc
288}