Skip to main content

cargo/core/resolver/
resolve.rs

1use std::borrow::Borrow;
2use std::collections::{HashMap, HashSet};
3use std::fmt;
4use std::hash::Hash;
5use std::iter::FromIterator;
6
7use url::Url;
8
9use crate::core::{Dependency, PackageId, PackageIdSpec, Summary, Target};
10use crate::util::errors::CargoResult;
11use crate::util::Graph;
12
13use super::encode::Metadata;
14
15/// Represents a fully resolved package dependency graph. Each node in the graph
16/// is a package and edges represent dependencies between packages.
17///
18/// Each instance of `Resolve` also understands the full set of features used
19/// for each package.
20#[derive(PartialEq)]
21pub struct Resolve {
22    /// A graph, whose vertices are packages and edges are dependency specifications
23    /// from Cargo.toml. We need a `Vec` here because the same package
24    /// might be present in both `[dependencies]` and `[build-dependencies]`.
25    graph: Graph<PackageId, Vec<Dependency>>,
26    replacements: HashMap<PackageId, PackageId>,
27    reverse_replacements: HashMap<PackageId, PackageId>,
28    empty_features: HashSet<String>,
29    features: HashMap<PackageId, HashSet<String>>,
30    checksums: HashMap<PackageId, Option<String>>,
31    metadata: Metadata,
32    unused_patches: Vec<PackageId>,
33}
34
35impl Resolve {
36    pub fn new(
37        graph: Graph<PackageId, Vec<Dependency>>,
38        replacements: HashMap<PackageId, PackageId>,
39        features: HashMap<PackageId, HashSet<String>>,
40        checksums: HashMap<PackageId, Option<String>>,
41        metadata: Metadata,
42        unused_patches: Vec<PackageId>,
43    ) -> Resolve {
44        let reverse_replacements = replacements.iter().map(|(&p, &r)| (r, p)).collect();
45        Resolve {
46            graph,
47            replacements,
48            features,
49            checksums,
50            metadata,
51            unused_patches,
52            empty_features: HashSet::new(),
53            reverse_replacements,
54        }
55    }
56
57    /// Resolves one of the paths from the given dependent package up to
58    /// the root.
59    pub fn path_to_top<'a>(&'a self, pkg: &'a PackageId) -> Vec<&'a PackageId> {
60        self.graph.path_to_top(pkg)
61    }
62
63    pub fn register_used_patches(&mut self, patches: &HashMap<Url, Vec<Summary>>) {
64        for summary in patches.values().flat_map(|v| v) {
65            if self.iter().any(|id| id == summary.package_id()) {
66                continue;
67            }
68            self.unused_patches.push(summary.package_id());
69        }
70    }
71
72    pub fn merge_from(&mut self, previous: &Resolve) -> CargoResult<()> {
73        // Given a previous instance of resolve, it should be forbidden to ever
74        // have a checksums which *differ*. If the same package id has differing
75        // checksums, then something has gone wrong such as:
76        //
77        // * Something got seriously corrupted
78        // * A "mirror" isn't actually a mirror as some changes were made
79        // * A replacement source wasn't actually a replacment, some changes
80        //   were made
81        //
82        // In all of these cases, we want to report an error to indicate that
83        // something is awry. Normal execution (esp just using crates.io) should
84        // never run into this.
85        for (id, cksum) in previous.checksums.iter() {
86            if let Some(mine) = self.checksums.get(id) {
87                if mine == cksum {
88                    continue;
89                }
90
91                // If the previous checksum wasn't calculated, the current
92                // checksum is `Some`. This may indicate that a source was
93                // erroneously replaced or was replaced with something that
94                // desires stronger checksum guarantees than can be afforded
95                // elsewhere.
96                if cksum.is_none() {
97                    failure::bail!(
98                        "\
99checksum for `{}` was not previously calculated, but a checksum could now \
100be calculated
101
102this could be indicative of a few possible situations:
103
104    * the source `{}` did not previously support checksums,
105      but was replaced with one that does
106    * newer Cargo implementations know how to checksum this source, but this
107      older implementation does not
108    * the lock file is corrupt
109",
110                        id,
111                        id.source_id()
112                    )
113
114                // If our checksum hasn't been calculated, then it could mean
115                // that future Cargo figured out how to checksum something or
116                // more realistically we were overridden with a source that does
117                // not have checksums.
118                } else if mine.is_none() {
119                    failure::bail!(
120                        "\
121checksum for `{}` could not be calculated, but a checksum is listed in \
122the existing lock file
123
124this could be indicative of a few possible situations:
125
126    * the source `{}` supports checksums,
127      but was replaced with one that doesn't
128    * the lock file is corrupt
129
130unable to verify that `{0}` is the same as when the lockfile was generated
131",
132                        id,
133                        id.source_id()
134                    )
135
136                // If the checksums aren't equal, and neither is None, then they
137                // must both be Some, in which case the checksum now differs.
138                // That's quite bad!
139                } else {
140                    failure::bail!(
141                        "\
142checksum for `{}` changed between lock files
143
144this could be indicative of a few possible errors:
145
146    * the lock file is corrupt
147    * a replacement source in use (e.g. a mirror) returned a different checksum
148    * the source itself may be corrupt in one way or another
149
150unable to verify that `{0}` is the same as when the lockfile was generated
151",
152                        id
153                    );
154                }
155            }
156        }
157
158        // Be sure to just copy over any unknown metadata.
159        self.metadata = previous.metadata.clone();
160        Ok(())
161    }
162
163    pub fn contains<Q: ?Sized>(&self, k: &Q) -> bool
164    where
165        PackageId: Borrow<Q>,
166        Q: Hash + Eq,
167    {
168        self.graph.contains(k)
169    }
170
171    pub fn sort(&self) -> Vec<PackageId> {
172        self.graph.sort()
173    }
174
175    pub fn iter<'a>(&'a self) -> impl Iterator<Item = PackageId> + 'a {
176        self.graph.iter().cloned()
177    }
178
179    pub fn deps(&self, pkg: PackageId) -> impl Iterator<Item = (PackageId, &[Dependency])> {
180        self.graph
181            .edges(&pkg)
182            .map(move |(&id, deps)| (self.replacement(id).unwrap_or(id), deps.as_slice()))
183    }
184
185    pub fn deps_not_replaced<'a>(&'a self, pkg: PackageId) -> impl Iterator<Item = PackageId> + 'a {
186        self.graph.edges(&pkg).map(|(&id, _)| id)
187    }
188
189    pub fn replacement(&self, pkg: PackageId) -> Option<PackageId> {
190        self.replacements.get(&pkg).cloned()
191    }
192
193    pub fn replacements(&self) -> &HashMap<PackageId, PackageId> {
194        &self.replacements
195    }
196
197    pub fn features(&self, pkg: PackageId) -> &HashSet<String> {
198        self.features.get(&pkg).unwrap_or(&self.empty_features)
199    }
200
201    pub fn features_sorted(&self, pkg: PackageId) -> Vec<&str> {
202        let mut v = Vec::from_iter(self.features(pkg).iter().map(|s| s.as_ref()));
203        v.sort_unstable();
204        v
205    }
206
207    pub fn query(&self, spec: &str) -> CargoResult<PackageId> {
208        PackageIdSpec::query_str(spec, self.iter())
209    }
210
211    pub fn unused_patches(&self) -> &[PackageId] {
212        &self.unused_patches
213    }
214
215    pub fn checksums(&self) -> &HashMap<PackageId, Option<String>> {
216        &self.checksums
217    }
218
219    pub fn metadata(&self) -> &Metadata {
220        &self.metadata
221    }
222
223    pub fn extern_crate_name(
224        &self,
225        from: PackageId,
226        to: PackageId,
227        to_target: &Target,
228    ) -> CargoResult<String> {
229        let deps = if from == to {
230            &[]
231        } else {
232            self.dependencies_listed(from, to)
233        };
234
235        let crate_name = to_target.crate_name();
236        let mut names = deps.iter().map(|d| {
237            d.explicit_name_in_toml()
238                .map(|s| s.as_str().replace("-", "_"))
239                .unwrap_or_else(|| crate_name.clone())
240        });
241        let name = names.next().unwrap_or_else(|| crate_name.clone());
242        for n in names {
243            if n == name {
244                continue;
245            }
246            failure::bail!(
247                "multiple dependencies listed for the same crate must \
248                 all have the same name, but the dependency on `{}` \
249                 is listed as having different names",
250                to
251            );
252        }
253        Ok(name)
254    }
255
256    fn dependencies_listed(&self, from: PackageId, to: PackageId) -> &[Dependency] {
257        // We've got a dependency on `from` to `to`, but this dependency edge
258        // may be affected by [replace]. If the `to` package is listed as the
259        // target of a replacement (aka the key of a reverse replacement map)
260        // then we try to find our dependency edge through that. If that fails
261        // then we go down below assuming it's not replaced.
262        //
263        // Note that we don't treat `from` as if it's been replaced because
264        // that's where the dependency originates from, and we only replace
265        // targets of dependencies not the originator.
266        if let Some(replace) = self.reverse_replacements.get(&to) {
267            if let Some(deps) = self.graph.edge(&from, replace) {
268                return deps;
269            }
270        }
271        match self.graph.edge(&from, &to) {
272            Some(ret) => ret,
273            None => panic!("no Dependency listed for `{}` => `{}`", from, to),
274        }
275    }
276}
277
278impl fmt::Debug for Resolve {
279    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
280        writeln!(fmt, "graph: {:?}", self.graph)?;
281        writeln!(fmt, "\nfeatures: {{")?;
282        for (pkg, features) in &self.features {
283            writeln!(fmt, "  {}: {:?}", pkg, features)?;
284        }
285        write!(fmt, "}}")
286    }
287}