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