Skip to main content

cargo/core/
registry.rs

1//! Types that hold source information for a group of packages.
2//!
3//! The primary type you're looking for is [`PackageRegistry`]. It is an
4//! abstraction over multiple [`Source`]s. [`PackageRegistry`] also implements
5//! the [`Registry`] trait, allowing a dependency resolver to query necessary
6//! package metadata (i.e., [Summary]) from it.
7//!
8//! Not to be confused with [`crate::sources::registry`] and [`crate::ops::registry`].
9//! The former is just one kind of source,
10//! while the latter involves operations on the registry Web API.
11
12use std::collections::{HashMap, HashSet};
13use std::task::{Poll, ready};
14
15use crate::core::{Dependency, PackageId, PackageSet, Patch, SourceId, Summary};
16use crate::sources::IndexSummary;
17use crate::sources::config::SourceConfigMap;
18use crate::sources::source::QueryKind;
19use crate::sources::source::Source;
20use crate::sources::source::SourceMap;
21use crate::util::errors::CargoResult;
22use crate::util::interning::InternedString;
23use crate::util::{CanonicalUrl, GlobalContext};
24use annotate_snippets::Level;
25use anyhow::Context as _;
26use itertools::Itertools;
27use tracing::{debug, trace};
28use url::Url;
29
30/// An abstraction provides a set of methods for querying source information
31/// about a group of packages, without leaking too much implementation details
32/// of the actual registry.
33///
34/// As of 2024-04, only [`PackageRegistry`] and `MyRegistry` in resolver-tests
35/// are found implementing this.
36///
37/// See also the [`Source`] trait, as many of the methods here mirror and
38/// abstract over its functionalities.
39pub trait Registry {
40    /// Attempt to find the packages that match a dependency request.
41    fn query(
42        &mut self,
43        dep: &Dependency,
44        kind: QueryKind,
45        f: &mut dyn FnMut(IndexSummary),
46    ) -> Poll<CargoResult<()>>;
47
48    /// Gathers the result from [`Registry::query`] as a list of [`IndexSummary`] items
49    /// when they become available.
50    fn query_vec(
51        &mut self,
52        dep: &Dependency,
53        kind: QueryKind,
54    ) -> Poll<CargoResult<Vec<IndexSummary>>> {
55        let mut ret = Vec::new();
56        self.query(dep, kind, &mut |s| ret.push(s)).map_ok(|()| ret)
57    }
58
59    /// Gets the description of a source, to provide useful messages.
60    fn describe_source(&self, source: SourceId) -> String;
61
62    /// Checks if a source is replaced with some other source.
63    fn is_replaced(&self, source: SourceId) -> bool;
64
65    /// Block until all outstanding [`Poll::Pending`] requests are [`Poll::Ready`].
66    fn block_until_ready(&mut self) -> CargoResult<()>;
67}
68
69/// This structure represents a registry of known packages. It internally
70/// contains a number of [`Source`] instances which are used to load a
71/// [`Package`] from.
72///
73/// The resolution phase of Cargo uses this to drive knowledge about new
74/// packages as well as querying for lists of new packages.
75/// It is here that sources are updated (e.g., network operations) and
76/// overrides/patches are handled.
77///
78/// The general idea behind this registry is that it is centered around the
79/// [`SourceMap`] structure, contained within which is a mapping of a [`SourceId`]
80/// to a [`Source`]. Each [`Source`] in the map has been updated (using network
81/// operations if necessary) and is ready to be queried for packages.
82///
83/// [`Package`]: crate::core::Package
84pub struct PackageRegistry<'gctx> {
85    gctx: &'gctx GlobalContext,
86    sources: SourceMap<'gctx>,
87
88    /// A list of sources which are considered "path-overrides" which take
89    /// precedent when querying for packages.
90    overrides: Vec<SourceId>,
91
92    /// Use for tracking sources that are already loaded into the registry.
93    // Note that each SourceId does not take into account its `precise` field
94    // when hashing or testing for equality. When adding a new `SourceId`, we
95    // want to avoid duplicates in the `SourceMap` (to prevent re-updating the
96    // same git repo twice for example), but we also want to ensure that the
97    // loaded source is always updated.
98    //
99    // Sources with a `precise` field normally don't need to be updated because
100    // their contents are already on disk, but sources without a `precise` field
101    // almost always need to be updated. If we have a cached `Source` for a
102    // precise `SourceId`, then when we add a new `SourceId` that is not precise
103    // we want to ensure that the underlying source is updated.
104    //
105    // This is basically a long-winded way of saying that we want to know
106    // precisely what the keys of `sources` are, so this is a mapping of key to
107    // what exactly the key is.
108    source_ids: HashMap<SourceId, (SourceId, Kind)>,
109
110    /// This is constructed via [`PackageRegistry::register_lock`].
111    /// See also [`LockedMap`].
112    locked: LockedMap,
113    /// Packages allowed to be used, even if they are yanked.
114    yanked_whitelist: HashSet<PackageId>,
115    source_config: SourceConfigMap<'gctx>,
116
117    /// Patches registered during calls to [`PackageRegistry::patch`].
118    ///
119    /// These are available for `query` after calling [`PackageRegistry::lock_patches`],
120    /// which `lock`s them all to specific versions.
121    patches: HashMap<CanonicalUrl, Vec<Summary>>,
122    /// Whether patches are locked. That is, they are available to resolution.
123    ///
124    /// See [`PackageRegistry::lock_patches`] and [`PackageRegistry::patch`] for more.
125    patches_locked: bool,
126    /// Patches available for each source.
127    ///
128    /// This is for determining whether a dependency entry from a lockfile
129    /// happened through `[patch]`, during calls to [`lock`] to rewrite
130    /// summaries to point directly at these patched entries.
131    ///
132    /// This is constructed during calls to [`PackageRegistry::patch`],
133    /// along with the `patches` field, thoough these entries never get locked.
134    patches_available: HashMap<CanonicalUrl, Vec<PackageId>>,
135}
136
137/// A map of all "locked packages" which is filled in when parsing a lock file
138/// and is used to guide dependency resolution by altering summaries as they're
139/// queried from this source.
140///
141/// This map can be thought of as a glorified `Vec<MySummary>` where `MySummary`
142/// has a `PackageId` for which package it represents as well as a list of
143/// `PackageId` for the resolved dependencies. The hash map is otherwise
144/// structured though for easy access throughout this registry.
145type LockedMap = HashMap<
146    // The first level of key-ing done in this hash map is the source that
147    // dependencies come from, identified by a `SourceId`.
148    // The next level is keyed by the name of the package...
149    (SourceId, InternedString),
150    // ... and the value here is a list of tuples. The first element of each
151    // tuple is a package which has the source/name used to get to this
152    // point. The second element of each tuple is the list of locked
153    // dependencies that the first element has.
154    Vec<(PackageId, Vec<PackageId>)>,
155>;
156
157/// Kinds of sources a [`PackageRegistry`] has loaded.
158#[derive(PartialEq, Eq, Clone, Copy)]
159enum Kind {
160    /// A source from a [path override].
161    ///
162    /// [path overrides]: https://doc.rust-lang.org/nightly/cargo/reference/overriding-dependencies.html#paths-overrides
163    Override,
164    /// A source that is locked and not going to change.
165    ///
166    /// For example, sources of workspace members are loaded during the
167    /// workspace initialization, so not allowed to change.
168    Locked,
169    /// A source that is not locked nor a path-override.
170    Normal,
171}
172
173/// This tuple is an argument to [`PackageRegistry::patch`].
174///
175/// * The first element is the patch definition straight from the manifest.
176/// * The second element is an optional variant where the patch has been locked.
177///   It is the patch locked to a specific version found in Cargo.lock.
178///   This will be `None` if `Cargo.lock` doesn't exist,
179///   or the patch did not match any existing entries in `Cargo.lock`.
180pub type PatchDependency<'a> = (&'a Patch, Option<LockedPatchDependency>);
181
182/// Argument to [`PackageRegistry::patch`] which is information about a `[patch]`
183/// directive that we found in a lockfile, if present.
184pub struct LockedPatchDependency {
185    /// The original `Dependency` directive, except "locked" so it's version
186    /// requirement is Locked to `foo` and its `SourceId` has a "precise" listed.
187    pub dependency: Dependency,
188    /// The `PackageId` that was previously found in a lock file which
189    /// `dependency` matches.
190    pub package_id: PackageId,
191    /// Something only used for backwards compatibility with the v2 lock file
192    /// format where `branch=master` is considered the same as `DefaultBranch`.
193    /// For more comments on this see the code in `ops/resolve.rs`.
194    pub alt_package_id: Option<PackageId>,
195}
196
197impl<'gctx> PackageRegistry<'gctx> {
198    pub fn new_with_source_config(
199        gctx: &'gctx GlobalContext,
200        source_config: SourceConfigMap<'gctx>,
201    ) -> CargoResult<PackageRegistry<'gctx>> {
202        Ok(PackageRegistry {
203            gctx,
204            sources: SourceMap::new(),
205            source_ids: HashMap::new(),
206            overrides: Vec::new(),
207            source_config,
208            locked: HashMap::new(),
209            yanked_whitelist: HashSet::new(),
210            patches: HashMap::new(),
211            patches_locked: false,
212            patches_available: HashMap::new(),
213        })
214    }
215
216    pub fn get(self, package_ids: &[PackageId]) -> CargoResult<PackageSet<'gctx>> {
217        trace!("getting packages; sources={}", self.sources.len());
218        PackageSet::new(package_ids, self.sources, self.gctx)
219    }
220
221    /// Ensures the [`Source`] of the given [`SourceId`] is loaded.
222    /// If not, this will block until the source is ready.
223    fn ensure_loaded(&mut self, namespace: SourceId, kind: Kind) -> CargoResult<()> {
224        match self.source_ids.get(&namespace) {
225            // We've previously loaded this source, and we've already locked it,
226            // so we're not allowed to change it even if `namespace` has a
227            // slightly different precise version listed.
228            Some((_, Kind::Locked)) => {
229                debug!("load/locked   {}", namespace);
230                return Ok(());
231            }
232
233            // If the previous source was not a precise source, then we can be
234            // sure that it's already been updated if we've already loaded it.
235            Some((previous, _)) if !previous.has_precise() => {
236                debug!("load/precise  {}", namespace);
237                return Ok(());
238            }
239
240            // If the previous source has the same precise version as we do,
241            // then we're done, otherwise we need to move forward
242            // updating this source.
243            Some((previous, _)) => {
244                if previous.has_same_precise_as(namespace) {
245                    debug!("load/match    {}", namespace);
246                    return Ok(());
247                }
248                debug!("load/mismatch {}", namespace);
249            }
250            None => {
251                debug!("load/missing  {}", namespace);
252            }
253        }
254
255        self.load(namespace, kind)?;
256
257        // This isn't strictly necessary since it will be called later.
258        // However it improves error messages for sources that issue errors
259        // in `block_until_ready` because the callers here have context about
260        // which deps are being resolved.
261        self.block_until_ready()?;
262        Ok(())
263    }
264
265    pub fn add_sources(&mut self, ids: impl IntoIterator<Item = SourceId>) -> CargoResult<()> {
266        for id in ids {
267            self.ensure_loaded(id, Kind::Locked)?;
268        }
269        Ok(())
270    }
271
272    /// Adds a source which will be locked.
273    /// Useful for path sources such as the source of a workspace member.
274    pub fn add_preloaded(&mut self, source: Box<dyn Source + 'gctx>) {
275        self.add_source(source, Kind::Locked);
276    }
277
278    /// Adds a source to the registry.
279    fn add_source(&mut self, source: Box<dyn Source + 'gctx>, kind: Kind) {
280        let id = source.source_id();
281        self.sources.insert(source);
282        self.source_ids.insert(id, (id, kind));
283    }
284
285    /// Adds a source from a [path override].
286    ///
287    /// [path override]: https://doc.rust-lang.org/nightly/cargo/reference/overriding-dependencies.html#paths-overrides
288    pub fn add_override(&mut self, source: Box<dyn Source + 'gctx>) {
289        self.overrides.push(source.source_id());
290        self.add_source(source, Kind::Override);
291    }
292
293    /// Allows a group of package to be available to query even if they are yanked.
294    pub fn add_to_yanked_whitelist(&mut self, iter: impl Iterator<Item = PackageId>) {
295        let pkgs = iter.collect::<Vec<_>>();
296        for (_, source) in self.sources.sources_mut() {
297            source.add_to_yanked_whitelist(&pkgs);
298        }
299        self.yanked_whitelist.extend(pkgs);
300    }
301
302    /// remove all residual state from previous lock files.
303    pub fn clear_lock(&mut self) {
304        trace!("clear_lock");
305        self.locked = HashMap::new();
306    }
307
308    /// Registers one "locked package" to the registry, for guiding the
309    /// dependency resolution. See [`LockedMap`] for more.
310    pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) {
311        trace!("register_lock: {}", id);
312        for dep in deps.iter() {
313            trace!("\t-> {}", dep);
314        }
315        let sub_vec = self
316            .locked
317            .entry((id.source_id(), id.name()))
318            .or_insert_with(Vec::new);
319        sub_vec.push((id, deps));
320    }
321
322    /// Insert a `[patch]` section into this registry.
323    ///
324    /// This method will insert a `[patch]` section for the `url` specified,
325    /// with the given list of dependencies. The `url` specified is the URL of
326    /// the source to patch (for example this is `crates-io` in the manifest).
327    /// The `deps` is an array of all the entries in the `[patch]` section of
328    /// the manifest.
329    ///
330    /// Here the `patch_deps` will be resolved to a precise version and stored
331    /// internally for future calls to `query` below.
332    ///
333    /// Note that the patch list specified here *will not* be available to
334    /// [`Registry::query`] until [`PackageRegistry::lock_patches`] is called
335    /// below, which should be called once all patches have been added.
336    ///
337    /// The return value is a `Vec` of patches that should *not* be locked.
338    /// This happens when the patch is locked, but the patch has been updated
339    /// so the locked value is no longer correct.
340    #[tracing::instrument(skip(self, patch_deps))]
341    pub fn patch(
342        &mut self,
343        url: &Url,
344        patch_deps: &[PatchDependency<'_>],
345    ) -> CargoResult<Vec<(Patch, PackageId)>> {
346        // NOTE: None of this code is aware of required features. If a patch
347        // is missing a required feature, you end up with an "unused patch"
348        // warning, which is very hard to understand. Ideally the warning
349        // would be tailored to indicate *why* it is unused.
350        let canonical = CanonicalUrl::new(url)?;
351
352        // Return value of patches that shouldn't be locked.
353        let mut unlock_patches = Vec::new();
354
355        // First up we need to actually resolve each `patch_deps` specification
356        // to precisely one summary. We're not using the `query` method below
357        // as it internally uses maps we're building up as part of this method
358        // (`patches_available` and `patches`). Instead we're going straight to
359        // the source to load information from it.
360        //
361        // Remember that each dependency listed in `[patch]` has to resolve to
362        // precisely one package, so that's why we're just creating a flat list
363        // of summaries which should be the same length as `deps` above.
364
365        let mut patch_deps_remaining: Vec<_> = patch_deps.iter().collect();
366        let mut unlocked_summaries = Vec::new();
367        while !patch_deps_remaining.is_empty() {
368            let mut patch_deps_pending = Vec::new();
369            for patch_dep_remaining in patch_deps_remaining {
370                let (orig_patch, locked) = patch_dep_remaining;
371
372                // Use the locked patch if it exists, otherwise use the original.
373                let dep = match locked {
374                    Some(lock) => &lock.dependency,
375                    None => &orig_patch.dep,
376                };
377                debug!(
378                    "registering a patch for `{}` with `{}`",
379                    url,
380                    dep.package_name()
381                );
382
383                let mut unused_fields = Vec::new();
384                if dep.features().len() != 0 {
385                    unused_fields.push("`features`");
386                }
387                if !dep.uses_default_features() {
388                    unused_fields.push("`default-features`")
389                }
390                if !unused_fields.is_empty() {
391                    self.source_config.gctx().shell().print_report(
392                        &[Level::WARNING
393                            .secondary_title(format!(
394                                "unused field in patch for `{}`: {}",
395                                dep.package_name(),
396                                unused_fields.join(", ")
397                            ))
398                            .element(Level::HELP.message(format!(
399                                "configure {} in the `dependencies` entry",
400                                unused_fields.join(", ")
401                            )))],
402                        false,
403                    )?;
404                }
405
406                // Go straight to the source for resolving `dep`. Load it as we
407                // normally would and then ask it directly for the list of summaries
408                // corresponding to this `dep`.
409                self.ensure_loaded(dep.source_id(), Kind::Normal)
410                    .with_context(|| {
411                        format!(
412                            "failed to load source for dependency `{}`",
413                            dep.package_name()
414                        )
415                    })?;
416
417                let source = self
418                    .sources
419                    .get_mut(dep.source_id())
420                    .expect("loaded source not present");
421
422                let summaries = match source.query_vec(dep, QueryKind::Exact)? {
423                    Poll::Ready(deps) => deps,
424                    Poll::Pending => {
425                        patch_deps_pending.push(patch_dep_remaining);
426                        continue;
427                    }
428                };
429
430                let summaries = summaries.into_iter().map(|s| s.into_summary()).collect();
431
432                let (summary, should_unlock) =
433                    match summary_for_patch(&orig_patch, url, &locked, summaries, source) {
434                        Poll::Ready(x) => x,
435                        Poll::Pending => {
436                            patch_deps_pending.push(patch_dep_remaining);
437                            continue;
438                        }
439                    }?;
440
441                debug!(
442                    "patch summary is {:?} should_unlock={:?}",
443                    summary, should_unlock
444                );
445                if let Some(unlock_id) = should_unlock {
446                    unlock_patches.push(((*orig_patch).clone(), unlock_id));
447                }
448
449                if *summary.package_id().source_id().canonical_url() == canonical {
450                    return Err(anyhow::anyhow!(
451                        "patch for `{}` points to the same source, but patches must point to different sources\n\
452                        help: check `{}` patch definition for `{}` in `{}`",
453                        dep.package_name(),
454                        dep.package_name(),
455                        url,
456                        orig_patch.loc
457                    ));
458                }
459                unlocked_summaries.push(summary);
460            }
461
462            patch_deps_remaining = patch_deps_pending;
463            self.block_until_ready()?;
464        }
465
466        let mut name_and_version = HashSet::new();
467        for summary in unlocked_summaries.iter() {
468            let name = summary.package_id().name();
469            let version = summary.package_id().version();
470            if !name_and_version.insert((name, version)) {
471                let duplicate_locations = patch_deps
472                    .iter()
473                    .filter(|&p| p.0.dep.package_name() == name)
474                    .map(|p| format!("`{}`", p.0.loc))
475                    .unique()
476                    .join(", ");
477                return Err(anyhow::anyhow!(
478                    "several `[patch]` entries resolving to same version `{} v{}`\n\
479                    help: check `{}` patch definitions for `{}` in {}",
480                    name,
481                    version,
482                    name,
483                    url,
484                    duplicate_locations
485                ));
486            }
487        }
488
489        // Calculate a list of all patches available for this source.
490        let mut ids = Vec::new();
491        for (summary, (_, lock)) in unlocked_summaries.iter().zip(patch_deps) {
492            ids.push(summary.package_id());
493            // This is subtle where the list of `ids` for a canonical URL is
494            // extend with possibly two ids per summary. This is done to handle
495            // the transition from the v2->v3 lock file format where in v2
496            // DefaultBranch was either DefaultBranch or Branch("master") for
497            // git dependencies. In this case if `summary.package_id()` is
498            // Branch("master") then alt_package_id will be DefaultBranch. This
499            // signifies that there's a patch available for either of those
500            // dependency directives if we see them in the dependency graph.
501            if let Some(lock) = lock {
502                ids.extend(lock.alt_package_id);
503            }
504        }
505        self.patches_available.insert(canonical.clone(), ids);
506
507        // Note that we do not use `lock` here to lock summaries! That step
508        // happens later once `lock_patches` is invoked. In the meantime though
509        // we want to fill in the `patches_available` map (later used in the
510        // `lock` method) and otherwise store the unlocked summaries in
511        // `patches` to get locked in a future call to `lock_patches`.
512        self.patches.insert(canonical, unlocked_summaries);
513
514        Ok(unlock_patches)
515    }
516
517    /// Lock all patch summaries added via [`patch`](Self::patch),
518    /// making them available to resolution via [`Registry::query`].
519    pub fn lock_patches(&mut self) {
520        assert!(!self.patches_locked);
521        for summaries in self.patches.values_mut() {
522            for summary in summaries {
523                debug!("locking patch {:?}", summary);
524                *summary = lock(&self.locked, &self.patches_available, summary.clone());
525            }
526        }
527        self.patches_locked = true;
528    }
529
530    /// Gets all patches grouped by the source URLs they are going to patch.
531    ///
532    /// These patches are mainly collected from [`patch`](Self::patch).
533    /// They might not be the same as patches actually used during dependency resolving.
534    pub fn patches(&self) -> &HashMap<CanonicalUrl, Vec<Summary>> {
535        &self.patches
536    }
537
538    /// Loads the [`Source`] for a given [`SourceId`] to this registry, making
539    /// them available to resolution.
540    fn load(&mut self, source_id: SourceId, kind: Kind) -> CargoResult<()> {
541        debug!("loading source {}", source_id);
542        let source = self
543            .source_config
544            .load(source_id, &self.yanked_whitelist)
545            .with_context(|| format!("Unable to update {}", source_id))?;
546        assert_eq!(source.source_id(), source_id);
547
548        if kind == Kind::Override {
549            self.overrides.push(source_id);
550        }
551        self.add_source(source, kind);
552
553        // If we have an imprecise version then we don't know what we're going
554        // to look for, so we always attempt to perform an update here.
555        //
556        // If we have a precise version, then we'll update lazily during the
557        // querying phase. Note that precise in this case is only
558        // `"locked"` as other values indicate a `cargo update
559        // --precise` request
560        if !source_id.has_locked_precise() {
561            self.sources.get_mut(source_id).unwrap().invalidate_cache();
562        } else {
563            debug!("skipping update due to locked registry");
564        }
565        Ok(())
566    }
567
568    /// Queries path overrides from this registry.
569    fn query_overrides(&mut self, dep: &Dependency) -> Poll<CargoResult<Option<IndexSummary>>> {
570        for &s in self.overrides.iter() {
571            let src = self.sources.get_mut(s).unwrap();
572            let dep = Dependency::new_override(dep.package_name(), s);
573
574            let mut results = None;
575            ready!(src.query(&dep, QueryKind::Exact, &mut |s| results = Some(s)))?;
576            if results.is_some() {
577                return Poll::Ready(Ok(results));
578            }
579        }
580        Poll::Ready(Ok(None))
581    }
582
583    /// This function is used to transform a summary to another locked summary
584    /// if possible. This is where the concept of a lock file comes into play.
585    ///
586    /// If a summary points at a package ID which was previously locked, then we
587    /// override the summary's ID itself, as well as all dependencies, to be
588    /// rewritten to the locked versions. This will transform the summary's
589    /// source to a precise source (listed in the locked version) as well as
590    /// transforming all of the dependencies from range requirements on
591    /// imprecise sources to exact requirements on precise sources.
592    ///
593    /// If a summary does not point at a package ID which was previously locked,
594    /// or if any dependencies were added and don't have a previously listed
595    /// version, we still want to avoid updating as many dependencies as
596    /// possible to keep the graph stable. In this case we map all of the
597    /// summary's dependencies to be rewritten to a locked version wherever
598    /// possible. If we're unable to map a dependency though, we just pass it on
599    /// through.
600    pub fn lock(&self, summary: Summary) -> Summary {
601        assert!(self.patches_locked);
602        lock(&self.locked, &self.patches_available, summary)
603    }
604
605    fn warn_bad_override(
606        &self,
607        override_summary: &Summary,
608        real_summary: &Summary,
609    ) -> CargoResult<()> {
610        let mut real_deps = real_summary.dependencies().iter().collect::<Vec<_>>();
611
612        let boilerplate = "\
613This is currently allowed but is known to produce buggy behavior with spurious
614recompiles and changes to the crate graph. Path overrides unfortunately were
615never intended to support this feature, so for now this message is just a
616warning. In the future, however, this message will become a hard error.
617
618To change the dependency graph via an override it's recommended to use the
619`[patch]` feature of Cargo instead of the path override feature. This is
620documented online at the url below for more information.
621
622https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html
623";
624
625        for dep in override_summary.dependencies() {
626            if let Some(i) = real_deps.iter().position(|d| dep == *d) {
627                real_deps.remove(i);
628                continue;
629            }
630            let msg = format!(
631                "path override for crate `{}` has altered the original list of\n\
632                 dependencies; the dependency on `{}` was either added or\n\
633                 modified to not match the previously resolved version\n\n\
634                 {}",
635                override_summary.package_id().name(),
636                dep.package_name(),
637                boilerplate
638            );
639            self.source_config.gctx().shell().warn(&msg)?;
640            return Ok(());
641        }
642
643        if let Some(dep) = real_deps.get(0) {
644            let msg = format!(
645                "path override for crate `{}` has altered the original list of\n\
646                 dependencies; the dependency on `{}` was removed\n\n\
647                 {}",
648                override_summary.package_id().name(),
649                dep.package_name(),
650                boilerplate
651            );
652            self.source_config.gctx().shell().warn(&msg)?;
653            return Ok(());
654        }
655
656        Ok(())
657    }
658}
659
660impl<'gctx> Registry for PackageRegistry<'gctx> {
661    fn query(
662        &mut self,
663        dep: &Dependency,
664        kind: QueryKind,
665        f: &mut dyn FnMut(IndexSummary),
666    ) -> Poll<CargoResult<()>> {
667        assert!(self.patches_locked);
668        // Look for an override and get ready to query the real source.
669        let override_summary = ready!(self.query_overrides(dep))?;
670
671        // Next up on our list of candidates is to check the `[patch]` section
672        // of the manifest. Here we look through all patches relevant to the
673        // source that `dep` points to, and then we match name/version. Note
674        // that we don't use `dep.matches(..)` because the patches, by definition,
675        // come from a different source. This means that `dep.matches(..)` will
676        // always return false, when what we really care about is the name/version match.
677        let mut patches = Vec::<Summary>::new();
678        if let Some(extra) = self.patches.get(dep.source_id().canonical_url()) {
679            patches.extend(
680                extra
681                    .iter()
682                    .filter(|s| dep.matches_ignoring_source(s.package_id()))
683                    .cloned(),
684            );
685        }
686
687        // A crucial feature of the `[patch]` feature is that we don't query the
688        // actual registry if we have a "locked" dependency. A locked dep basically
689        // just means a version constraint of `=a.b.c`, and because patches take
690        // priority over the actual source then if we have a candidate we're done.
691        if patches.len() == 1 && dep.is_locked() {
692            let patch = patches.remove(0);
693            match override_summary {
694                Some(override_summary) => {
695                    self.warn_bad_override(override_summary.as_summary(), &patch)?;
696                    let override_summary =
697                        override_summary.map_summary(|summary| self.lock(summary));
698                    f(override_summary);
699                }
700                None => f(IndexSummary::Candidate(patch)),
701            }
702
703            return Poll::Ready(Ok(()));
704        }
705
706        if !patches.is_empty() {
707            debug!(
708                "found {} patches with an unlocked dep on `{}` at {} \
709                     with `{}`, \
710                     looking at sources",
711                patches.len(),
712                dep.package_name(),
713                dep.source_id(),
714                dep.version_req()
715            );
716        }
717
718        // Ensure the requested source_id is loaded
719        self.ensure_loaded(dep.source_id(), Kind::Normal)
720            .with_context(|| {
721                format!(
722                    "failed to load source for dependency `{}`",
723                    dep.package_name()
724                )
725            })?;
726
727        let source = self.sources.get_mut(dep.source_id());
728        match (override_summary, source) {
729            (Some(_), None) => {
730                return Poll::Ready(Err(anyhow::anyhow!("override found but no real ones")));
731            }
732            (None, None) => return Poll::Ready(Ok(())),
733
734            // If we don't have an override then we just ship everything upstairs after locking the summary
735            (None, Some(source)) => {
736                for patch in patches.iter() {
737                    f(IndexSummary::Candidate(patch.clone()));
738                }
739
740                // Our sources shouldn't ever come back to us with two summaries
741                // that have the same version. We could, however, have an `[patch]`
742                // section which is in use to override a version in the registry.
743                // This means that if our `summary` in this loop has the same
744                // version as something in `patches` that we've already selected,
745                // then we skip this `summary`.
746                let locked = &self.locked;
747                let all_patches = &self.patches_available;
748                let callback = &mut |summary: IndexSummary| {
749                    for patch in patches.iter() {
750                        let patch = patch.package_id().version();
751                        if summary.package_id().version() == patch {
752                            return;
753                        }
754                    }
755                    let summary = summary.map_summary(|summary| lock(locked, all_patches, summary));
756                    f(summary)
757                };
758                return source.query(dep, kind, callback);
759            }
760
761            // If we have an override summary then we query the source to sanity check its results.
762            // We don't actually use any of the summaries it gives us though.
763            (Some(override_summary), Some(source)) => {
764                if !patches.is_empty() {
765                    return Poll::Ready(Err(anyhow::anyhow!("found patches and a path override")));
766                }
767                let mut n = 0;
768                let mut to_warn = None;
769                let callback = &mut |summary| {
770                    n += 1;
771                    to_warn = Some(summary);
772                };
773                let pend = source.query(dep, kind, callback);
774                if pend.is_pending() {
775                    return Poll::Pending;
776                }
777                if n > 1 {
778                    return Poll::Ready(Err(anyhow::anyhow!(
779                        "found an override with a non-locked list"
780                    )));
781                }
782                if let Some(to_warn) = to_warn {
783                    self.warn_bad_override(override_summary.as_summary(), to_warn.as_summary())?;
784                }
785                let override_summary = override_summary.map_summary(|summary| self.lock(summary));
786                f(override_summary);
787            }
788        }
789
790        Poll::Ready(Ok(()))
791    }
792
793    fn describe_source(&self, id: SourceId) -> String {
794        match self.sources.get(id) {
795            Some(src) => src.describe(),
796            None => id.to_string(),
797        }
798    }
799
800    fn is_replaced(&self, id: SourceId) -> bool {
801        match self.sources.get(id) {
802            Some(src) => src.is_replaced(),
803            None => false,
804        }
805    }
806
807    #[tracing::instrument(skip_all)]
808    fn block_until_ready(&mut self) -> CargoResult<()> {
809        // Ensure `shell` is not already in use,
810        // regardless of which source is used and how it happens to behave this time
811        self.gctx.debug_assert_shell_not_borrowed();
812        for (source_id, source) in self.sources.sources_mut() {
813            source
814                .block_until_ready()
815                .with_context(|| format!("Unable to update {}", source_id))?;
816        }
817        Ok(())
818    }
819}
820
821/// See [`PackageRegistry::lock`].
822fn lock(
823    locked: &LockedMap,
824    patches: &HashMap<CanonicalUrl, Vec<PackageId>>,
825    summary: Summary,
826) -> Summary {
827    let pair = locked
828        .get(&(summary.source_id(), summary.name()))
829        .and_then(|vec| vec.iter().find(|&&(id, _)| id == summary.package_id()));
830
831    trace!("locking summary of {}", summary.package_id());
832
833    // Lock the summary's ID if possible
834    let summary = match pair {
835        Some((precise, _)) => summary.override_id(*precise),
836        None => summary,
837    };
838    summary.map_dependencies(|dep| {
839        trace!(
840            "\t{}/{}/{}",
841            dep.package_name(),
842            dep.version_req(),
843            dep.source_id()
844        );
845
846        // If we've got a known set of overrides for this summary, then
847        // one of a few cases can arise:
848        //
849        // 1. We have a lock entry for this dependency from the same
850        //    source as it's listed as coming from. In this case we make
851        //    sure to lock to precisely the given package ID.
852        //
853        // 2. We have a lock entry for this dependency, but it's from a
854        //    different source than what's listed, or the version
855        //    requirement has changed. In this case we must discard the
856        //    locked version because the dependency needs to be
857        //    re-resolved.
858        //
859        // 3. We have a lock entry for this dependency, but it's from a
860        //    different source than what's listed. This lock though happens
861        //    through `[patch]`, so we want to preserve it.
862        //
863        // 4. We don't have a lock entry for this dependency, in which
864        //    case it was likely an optional dependency which wasn't
865        //    included previously so we just pass it through anyway.
866        //
867        // Cases 1/2 are handled by `matches_id`, case 3 is handled specially,
868        // and case 4 is handled by falling through to the logic below.
869        if let Some((_, locked_deps)) = pair {
870            let locked = locked_deps.iter().find(|&&id| {
871                // If the dependency matches the package id exactly then we've
872                // found a match, this is the id the dependency was previously
873                // locked to.
874                if dep.matches_id(id) {
875                    return true;
876                }
877
878                // If the name/version doesn't match, then we definitely don't
879                // have a match whatsoever. Otherwise we need to check
880                // `[patch]`...
881                if !dep.matches_ignoring_source(id) {
882                    return false;
883                }
884
885                // ... so here we look up the dependency url in the patches
886                // map, and we see if `id` is contained in the list of patches
887                // for that url. If it is then this lock is still valid,
888                // otherwise the lock is no longer valid.
889                match patches.get(dep.source_id().canonical_url()) {
890                    Some(list) => list.contains(&id),
891                    None => false,
892                }
893            });
894
895            if let Some(&locked) = locked {
896                trace!("\tfirst hit on {}", locked);
897                let mut dep = dep;
898
899                // If we found a locked version where the sources match, then
900                // we can `lock_to` to get an exact lock on this dependency.
901                // Otherwise we got a lock via `[patch]` so we only lock the
902                // version requirement, not the source.
903                if locked.source_id() == dep.source_id() {
904                    dep.lock_to(locked);
905                } else {
906                    dep.lock_version(locked.version());
907                }
908                return dep;
909            }
910        }
911
912        // If this dependency did not have a locked version, then we query
913        // all known locked packages to see if they match this dependency.
914        // If anything does then we lock it to that and move on.
915        let v = locked
916            .get(&(dep.source_id(), dep.package_name()))
917            .and_then(|vec| vec.iter().find(|&&(id, _)| dep.matches_id(id)));
918        if let Some(&(id, _)) = v {
919            trace!("\tsecond hit on {}", id);
920            let mut dep = dep;
921            dep.lock_to(id);
922            return dep;
923        }
924
925        trace!("\tnope, unlocked");
926        dep
927    })
928}
929
930/// A helper for selecting the summary, or generating a helpful error message.
931///
932/// Returns a tuple that the first element is the summary selected. The second
933/// is a package ID indicating that the patch entry should be unlocked. This
934/// happens when a match cannot be found with the `locked` one, but found one
935/// via the original patch, so we need to inform the resolver to "unlock" it.
936fn summary_for_patch(
937    original_patch: &Patch,
938    orig_patch_url: &Url,
939    locked: &Option<LockedPatchDependency>,
940    mut summaries: Vec<Summary>,
941    source: &mut dyn Source,
942) -> Poll<CargoResult<(Summary, Option<PackageId>)>> {
943    if summaries.len() == 1 {
944        return Poll::Ready(Ok((summaries.pop().unwrap(), None)));
945    }
946    if summaries.len() > 1 {
947        // TODO: In the future, it might be nice to add all of these
948        // candidates so that version selection would just pick the
949        // appropriate one. However, as this is currently structured, if we
950        // added these all as patches, the unselected versions would end up in
951        // the "unused patch" listing, and trigger a warning. It might take a
952        // fair bit of restructuring to make that work cleanly, and there
953        // isn't any demand at this time to support that.
954        let mut vers: Vec<_> = summaries.iter().map(|summary| summary.version()).collect();
955        vers.sort();
956        let versions: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
957        return Poll::Ready(Err(anyhow::anyhow!(
958            "patch for `{}` in `{}` resolved to more than one candidate\n\
959            note: found versions: {}\n\
960            help: check `{}` patch definition for `{}` in `{}`\n\
961            help: select only one package using `version = \"={}\"`",
962            &original_patch.dep.package_name(),
963            &original_patch.dep.source_id(),
964            versions.join(", "),
965            &original_patch.dep.package_name(),
966            orig_patch_url,
967            original_patch.loc,
968            versions.last().unwrap()
969        )));
970    }
971    assert!(summaries.is_empty());
972    // No summaries found, try to help the user figure out what is wrong.
973    if let Some(locked) = locked {
974        // Since the locked patch did not match anything, try the unlocked one.
975        let orig_matches = ready!(source.query_vec(&original_patch.dep, QueryKind::Exact))
976            .unwrap_or_else(|e| {
977                tracing::warn!(
978                    "could not determine unlocked summaries for dep {:?}: {:?}",
979                    &original_patch.dep,
980                    e
981                );
982                Vec::new()
983            });
984
985        let orig_matches = orig_matches.into_iter().map(|s| s.into_summary()).collect();
986
987        let summary = ready!(summary_for_patch(
988            original_patch,
989            orig_patch_url,
990            &None,
991            orig_matches,
992            source
993        ))?;
994        return Poll::Ready(Ok((summary.0, Some(locked.package_id))));
995    }
996    // Try checking if there are *any* packages that match this by name.
997    let name_only_dep = Dependency::new_override(
998        original_patch.dep.package_name(),
999        original_patch.dep.source_id(),
1000    );
1001
1002    let name_summaries =
1003        ready!(source.query_vec(&name_only_dep, QueryKind::Exact)).unwrap_or_else(|e| {
1004            tracing::warn!(
1005                "failed to do name-only summary query for {:?}: {:?}",
1006                name_only_dep,
1007                e
1008            );
1009            Vec::new()
1010        });
1011    let mut vers = name_summaries
1012        .iter()
1013        .map(|summary| summary.as_summary().version())
1014        .collect::<Vec<_>>();
1015    let found = match vers.len() {
1016        0 => "".to_string(),
1017        1 => format!("version `{}`", vers[0]),
1018        _ => {
1019            vers.sort();
1020            let strs: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
1021            format!("versions `{}`", strs.join(", "))
1022        }
1023    };
1024    Poll::Ready(Err(if found.is_empty() {
1025        anyhow::anyhow!(
1026            "patch location `{}` does not contain packages matching `{}`\n\
1027            help: check `{}` patch definition for `{}` in `{}`",
1028            &original_patch.dep.source_id(),
1029            &original_patch.dep.package_name(),
1030            &original_patch.dep.package_name(),
1031            orig_patch_url,
1032            original_patch.loc
1033        )
1034    } else {
1035        anyhow::anyhow!(
1036            "patch `{}` version mismatch\n\
1037            note: patch location contains {}, but patch definition requires `{}`\n\
1038            help: check patch location `{}`\n\
1039            help: check `{}` patch definition for `{}` in `{}`",
1040            &original_patch.dep.package_name(),
1041            found,
1042            &original_patch.dep.version_req(),
1043            &original_patch.dep.source_id(),
1044            &original_patch.dep.package_name(),
1045            orig_patch_url,
1046            original_patch.loc
1047        )
1048    }))
1049}