cargo/ops/
resolve.rs

1//! High-level APIs for executing the resolver.
2//!
3//! This module provides functions for running the resolver given a workspace, including loading
4//! the `Cargo.lock` file and checking if it needs updating.
5//!
6//! There are roughly 3 main functions:
7//!
8//! - [`resolve_ws`]: A simple, high-level function with no options.
9//! - [`resolve_ws_with_opts`]: A medium-level function with options like
10//!   user-provided features. This is the most appropriate function to use in
11//!   most cases.
12//! - [`resolve_with_previous`]: A low-level function for running the resolver,
13//!   providing the most power and flexibility.
14//!
15//! ### Data Structures
16//!
17//! - [`Workspace`]:
18//!   Usually created by [`crate::util::command_prelude::ArgMatchesExt::workspace`] which discovers the root of the
19//!   workspace, and loads all the workspace members as a [`Package`] object
20//!   - [`Package`]
21//!     Corresponds with `Cargo.toml` manifest (deserialized as [`Manifest`]) and its associated files.
22//!     - [`Target`]s are crates such as the library, binaries, integration test, or examples.
23//!       They are what is actually compiled by `rustc`.
24//!       Each `Target` defines a crate root, like `src/lib.rs` or `examples/foo.rs`.
25//!     - [`PackageId`] --- A unique identifier for a package.
26//! - [`PackageRegistry`]:
27//!   The primary interface for how the dependency
28//!   resolver finds packages. It contains the `SourceMap`, and handles things
29//!   like the `[patch]` table. The dependency resolver
30//!   sends a query to the `PackageRegistry` to "get me all packages that match
31//!   this dependency declaration". The `Registry` trait provides a generic interface
32//!   to the `PackageRegistry`, but this is only used for providing an alternate
33//!   implementation of the `PackageRegistry` for testing.
34//! - [`SourceMap`]: Map of all available sources.
35//!   - [`Source`]: An abstraction for something that can fetch packages (a remote
36//!     registry, a git repo, the local filesystem, etc.). Check out the [source
37//!     implementations] for all the details about registries, indexes, git
38//!     dependencies, etc.
39//!       * [`SourceId`]: A unique identifier for a source.
40//!   - [`Summary`]: A of a [`Manifest`], and is essentially
41//!     the information that can be found in a registry index. Queries against the
42//!     `PackageRegistry` yields a `Summary`. The resolver uses the summary
43//!     information to build the dependency graph.
44//! - [`PackageSet`] --- Contains all the `Package` objects. This works with the
45//!   [`Downloads`] struct to coordinate downloading packages. It has a reference
46//!   to the `SourceMap` to get the `Source` objects which tell the `Downloads`
47//!   struct which URLs to fetch.
48//!
49//! [`Package`]: crate::core::package
50//! [`Target`]: crate::core::Target
51//! [`Manifest`]: crate::core::Manifest
52//! [`Source`]: crate::sources::source::Source
53//! [`SourceMap`]: crate::sources::source::SourceMap
54//! [`PackageRegistry`]: crate::core::registry::PackageRegistry
55//! [source implementations]: crate::sources
56//! [`Downloads`]: crate::core::package::Downloads
57
58use crate::core::Dependency;
59use crate::core::GitReference;
60use crate::core::PackageId;
61use crate::core::PackageIdSpec;
62use crate::core::PackageIdSpecQuery;
63use crate::core::PackageSet;
64use crate::core::SourceId;
65use crate::core::Workspace;
66use crate::core::compiler::{CompileKind, RustcTargetData};
67use crate::core::registry::{LockedPatchDependency, PackageRegistry};
68use crate::core::resolver::features::{
69    CliFeatures, FeatureOpts, FeatureResolver, ForceAllTargets, RequestedFeatures, ResolvedFeatures,
70};
71use crate::core::resolver::{
72    self, HasDevUnits, Resolve, ResolveOpts, ResolveVersion, VersionOrdering, VersionPreferences,
73};
74use crate::core::summary::Summary;
75use crate::ops;
76use crate::sources::RecursivePathSource;
77use crate::util::CanonicalUrl;
78use crate::util::cache_lock::CacheLockMode;
79use crate::util::context::FeatureUnification;
80use crate::util::errors::CargoResult;
81use annotate_snippets::Group;
82use annotate_snippets::Level;
83use anyhow::Context as _;
84use cargo_util::paths;
85use cargo_util_schemas::core::PartialVersion;
86use std::borrow::Cow;
87use std::collections::{HashMap, HashSet};
88use std::rc::Rc;
89use tracing::{debug, trace};
90
91/// Filter for keep using Package ID from previous lockfile.
92type Keep<'a> = &'a dyn Fn(&PackageId) -> bool;
93
94/// Result for `resolve_ws_with_opts`.
95pub struct WorkspaceResolve<'gctx> {
96    /// Packages to be downloaded.
97    pub pkg_set: PackageSet<'gctx>,
98    /// The resolve for the entire workspace.
99    ///
100    /// This may be `None` for things like `cargo install` and `-Zavoid-dev-deps`.
101    /// This does not include `paths` overrides.
102    pub workspace_resolve: Option<Resolve>,
103    /// The narrowed resolve, with the specific features enabled.
104    pub targeted_resolve: Resolve,
105    /// Package specs requested for compilation along with specific features enabled. This usually
106    /// has the length of one but there may be more specs with different features when using the
107    /// `package` feature resolver.
108    pub specs_and_features: Vec<SpecsAndResolvedFeatures>,
109}
110
111/// Pair of package specs requested for compilation along with enabled features.
112pub struct SpecsAndResolvedFeatures {
113    /// Packages that are supposed to be built.
114    pub specs: Vec<PackageIdSpec>,
115    /// The features activated per package.
116    pub resolved_features: ResolvedFeatures,
117}
118
119const UNUSED_PATCH_WARNING: &str = "\
120Check that the patched package version and available features are compatible
121with the dependency requirements. If the patch has a different version from
122what is locked in the Cargo.lock file, run `cargo update` to use the new
123version. This may also occur with an optional dependency that is not enabled.";
124
125/// Resolves all dependencies for the workspace using the previous
126/// lock file as a guide if present.
127///
128/// This function will also write the result of resolution as a new lock file
129/// (unless it is an ephemeral workspace such as `cargo install` or `cargo
130/// package`).
131///
132/// This is a simple interface used by commands like `clean`, `fetch`, and
133/// `package`, which don't specify any options or features.
134pub fn resolve_ws<'a>(ws: &Workspace<'a>, dry_run: bool) -> CargoResult<(PackageSet<'a>, Resolve)> {
135    let mut registry = ws.package_registry()?;
136    let resolve = resolve_with_registry(ws, &mut registry, dry_run)?;
137    let packages = get_resolved_packages(&resolve, registry)?;
138    Ok((packages, resolve))
139}
140
141/// Resolves dependencies for some packages of the workspace,
142/// taking into account `paths` overrides and activated features.
143///
144/// This function will also write the result of resolution as a new lock file
145/// (unless `Workspace::require_optional_deps` is false, such as `cargo
146/// install` or `-Z avoid-dev-deps`), or it is an ephemeral workspace (`cargo
147/// install` or `cargo package`).
148///
149/// `specs` may be empty, which indicates it should resolve all workspace
150/// members. In this case, `opts.all_features` must be `true`.
151pub fn resolve_ws_with_opts<'gctx>(
152    ws: &Workspace<'gctx>,
153    target_data: &mut RustcTargetData<'gctx>,
154    requested_targets: &[CompileKind],
155    cli_features: &CliFeatures,
156    specs: &[PackageIdSpec],
157    has_dev_units: HasDevUnits,
158    force_all_targets: ForceAllTargets,
159    dry_run: bool,
160) -> CargoResult<WorkspaceResolve<'gctx>> {
161    let feature_unification = ws.resolve_feature_unification();
162    let individual_specs = match feature_unification {
163        FeatureUnification::Selected => vec![specs.to_owned()],
164        FeatureUnification::Workspace => {
165            vec![ops::Packages::All(Vec::new()).to_package_id_specs(ws)?]
166        }
167        FeatureUnification::Package => specs.iter().map(|spec| vec![spec.clone()]).collect(),
168    };
169    let specs: Vec<_> = individual_specs
170        .iter()
171        .map(|specs| specs.iter())
172        .flatten()
173        .cloned()
174        .collect();
175    let specs = &specs[..];
176    let mut registry = ws.package_registry()?;
177    let (resolve, resolved_with_overrides) = if ws.ignore_lock() {
178        let add_patches = true;
179        let resolve = None;
180        let resolved_with_overrides = resolve_with_previous(
181            &mut registry,
182            ws,
183            cli_features,
184            has_dev_units,
185            resolve.as_ref(),
186            None,
187            specs,
188            add_patches,
189        )?;
190        ops::print_lockfile_changes(ws, None, &resolved_with_overrides, &mut registry)?;
191        (resolve, resolved_with_overrides)
192    } else if ws.require_optional_deps() {
193        // First, resolve the root_package's *listed* dependencies, as well as
194        // downloading and updating all remotes and such.
195        let resolve = resolve_with_registry(ws, &mut registry, dry_run)?;
196        // No need to add patches again, `resolve_with_registry` has done it.
197        let add_patches = false;
198
199        // Second, resolve with precisely what we're doing. Filter out
200        // transitive dependencies if necessary, specify features, handle
201        // overrides, etc.
202        add_overrides(&mut registry, ws)?;
203
204        for (replace_spec, dep) in ws.root_replace() {
205            if !resolve
206                .iter()
207                .any(|r| replace_spec.matches(r) && !dep.matches_id(r))
208            {
209                ws.gctx()
210                    .shell()
211                    .warn(format!("package replacement is not used: {}", replace_spec))?
212            }
213
214            let mut unused_fields = Vec::new();
215            if dep.features().len() != 0 {
216                unused_fields.push("`features`");
217            }
218            if !dep.uses_default_features() {
219                unused_fields.push("`default-features`")
220            }
221            if !unused_fields.is_empty() {
222                ws.gctx().shell().print_report(
223                    &[Level::WARNING
224                        .secondary_title(format!(
225                            "unused field in replacement for `{}`: {}",
226                            dep.package_name(),
227                            unused_fields.join(", ")
228                        ))
229                        .element(Level::NOTE.message(format!(
230                            "configure {} in the `dependencies` entry",
231                            unused_fields.join(", ")
232                        )))],
233                    false,
234                )?;
235            }
236        }
237
238        let resolved_with_overrides = resolve_with_previous(
239            &mut registry,
240            ws,
241            cli_features,
242            has_dev_units,
243            Some(&resolve),
244            None,
245            specs,
246            add_patches,
247        )?;
248        (Some(resolve), resolved_with_overrides)
249    } else {
250        let add_patches = true;
251        let resolve = ops::load_pkg_lockfile(ws)?;
252        let resolved_with_overrides = resolve_with_previous(
253            &mut registry,
254            ws,
255            cli_features,
256            has_dev_units,
257            resolve.as_ref(),
258            None,
259            specs,
260            add_patches,
261        )?;
262        // Skipping `print_lockfile_changes` as there are cases where this prints irrelevant
263        // information
264        (resolve, resolved_with_overrides)
265    };
266
267    let pkg_set = get_resolved_packages(&resolved_with_overrides, registry)?;
268
269    let members_with_features = ws.members_with_features(specs, cli_features)?;
270    let member_ids = members_with_features
271        .iter()
272        .map(|(p, _fts)| p.package_id())
273        .collect::<Vec<_>>();
274    pkg_set.download_accessible(
275        &resolved_with_overrides,
276        &member_ids,
277        has_dev_units,
278        requested_targets,
279        target_data,
280        force_all_targets,
281    )?;
282
283    let mut specs_and_features = Vec::new();
284
285    for specs in individual_specs {
286        let feature_opts = FeatureOpts::new(ws, has_dev_units, force_all_targets)?;
287
288        // We want to narrow the features to the current specs so that stuff like `cargo check -p a
289        // -p b -F a/a,b/b` works and the resolver does not contain that `a` does not have feature
290        // `b` and vice-versa. However, resolver v1 needs to see even features of unselected
291        // packages turned on if it was because of working directory being inside the unselected
292        // package, because they might turn on a feature of a selected package.
293        let narrowed_features = match feature_unification {
294            FeatureUnification::Package => {
295                let mut narrowed_features = cli_features.clone();
296                let enabled_features = members_with_features
297                    .iter()
298                    .filter_map(|(package, cli_features)| {
299                        specs
300                            .iter()
301                            .any(|spec| spec.matches(package.package_id()))
302                            .then_some(cli_features.features.iter())
303                    })
304                    .flatten()
305                    .cloned()
306                    .collect();
307                narrowed_features.features = Rc::new(enabled_features);
308                Cow::Owned(narrowed_features)
309            }
310            FeatureUnification::Selected | FeatureUnification::Workspace => {
311                Cow::Borrowed(cli_features)
312            }
313        };
314
315        let resolved_features = FeatureResolver::resolve(
316            ws,
317            target_data,
318            &resolved_with_overrides,
319            &pkg_set,
320            &*narrowed_features,
321            &specs,
322            requested_targets,
323            feature_opts,
324        )?;
325
326        pkg_set.warn_no_lib_packages_and_artifact_libs_overlapping_deps(
327            ws,
328            &resolved_with_overrides,
329            &member_ids,
330            has_dev_units,
331            requested_targets,
332            target_data,
333            force_all_targets,
334        )?;
335
336        specs_and_features.push(SpecsAndResolvedFeatures {
337            specs,
338            resolved_features,
339        });
340    }
341
342    Ok(WorkspaceResolve {
343        pkg_set,
344        workspace_resolve: resolve,
345        targeted_resolve: resolved_with_overrides,
346        specs_and_features,
347    })
348}
349
350#[tracing::instrument(skip_all)]
351fn resolve_with_registry<'gctx>(
352    ws: &Workspace<'gctx>,
353    registry: &mut PackageRegistry<'gctx>,
354    dry_run: bool,
355) -> CargoResult<Resolve> {
356    let prev = ops::load_pkg_lockfile(ws)?;
357    let mut resolve = resolve_with_previous(
358        registry,
359        ws,
360        &CliFeatures::new_all(true),
361        HasDevUnits::Yes,
362        prev.as_ref(),
363        None,
364        &[],
365        true,
366    )?;
367
368    let print = if !ws.is_ephemeral() && ws.require_optional_deps() {
369        if !dry_run {
370            ops::write_pkg_lockfile(ws, &mut resolve)?
371        } else {
372            true
373        }
374    } else {
375        // This mostly represents
376        // - `cargo install --locked` and the only change is the package is no longer local but
377        //   from the registry which is noise
378        // - publish of libraries
379        false
380    };
381    if print {
382        ops::print_lockfile_changes(ws, prev.as_ref(), &resolve, registry)?;
383    }
384    Ok(resolve)
385}
386
387/// Resolves all dependencies for a package using an optional previous instance
388/// of resolve to guide the resolution process.
389///
390/// This also takes an optional filter `keep_previous`, which informs the `registry`
391/// which package ID should be locked to the previous instance of resolve
392/// (often used in pairings with updates). See comments in [`register_previous_locks`]
393/// for scenarios that might override this.
394///
395/// The previous resolve normally comes from a lock file. This function does not
396/// read or write lock files from the filesystem.
397///
398/// `specs` may be empty, which indicates it should resolve all workspace
399/// members. In this case, `opts.all_features` must be `true`.
400///
401/// If `register_patches` is true, then entries from the `[patch]` table in
402/// the manifest will be added to the given `PackageRegistry`.
403#[tracing::instrument(skip_all)]
404pub fn resolve_with_previous<'gctx>(
405    registry: &mut PackageRegistry<'gctx>,
406    ws: &Workspace<'gctx>,
407    cli_features: &CliFeatures,
408    has_dev_units: HasDevUnits,
409    previous: Option<&Resolve>,
410    keep_previous: Option<Keep<'_>>,
411    specs: &[PackageIdSpec],
412    register_patches: bool,
413) -> CargoResult<Resolve> {
414    // We only want one Cargo at a time resolving a crate graph since this can
415    // involve a lot of frobbing of the global caches.
416    let _lock = ws
417        .gctx()
418        .acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
419
420    // Some packages are already loaded when setting up a workspace. This
421    // makes it so anything that was already loaded will not be loaded again.
422    // Without this there were cases where members would be parsed multiple times
423    ws.preload(registry);
424
425    // In case any members were not already loaded or the Workspace is_ephemeral.
426    for member in ws.members() {
427        registry.add_sources(Some(member.package_id().source_id()))?;
428    }
429
430    // Try to keep all from previous resolve if no instruction given.
431    let keep_previous = keep_previous.unwrap_or(&|_| true);
432
433    // While registering patches, we will record preferences for particular versions
434    // of various packages.
435    let mut version_prefs = VersionPreferences::default();
436    if ws.gctx().cli_unstable().minimal_versions {
437        version_prefs.version_ordering(VersionOrdering::MinimumVersionsFirst)
438    }
439    if ws.resolve_honors_rust_version() {
440        let mut rust_versions: Vec<_> = ws
441            .members()
442            .filter_map(|p| p.rust_version().map(|rv| rv.as_partial().clone()))
443            .collect();
444        if rust_versions.is_empty() {
445            let rustc = ws.gctx().load_global_rustc(Some(ws))?;
446            let rust_version: PartialVersion = rustc.version.clone().into();
447            rust_versions.push(rust_version);
448        }
449        version_prefs.rust_versions(rust_versions);
450    }
451
452    let avoid_patch_ids = if register_patches {
453        register_patch_entries(registry, ws, previous, &mut version_prefs, keep_previous)?
454    } else {
455        HashSet::new()
456    };
457
458    // Refine `keep` with patches that should avoid locking.
459    let keep = |p: &PackageId| keep_previous(p) && !avoid_patch_ids.contains(p);
460
461    let dev_deps = ws.require_optional_deps() || has_dev_units == HasDevUnits::Yes;
462
463    if let Some(r) = previous {
464        trace!("previous: {:?}", r);
465
466        // In the case where a previous instance of resolve is available, we
467        // want to lock as many packages as possible to the previous version
468        // without disturbing the graph structure.
469        register_previous_locks(ws, registry, r, &keep, dev_deps);
470
471        // Prefer to use anything in the previous lock file, aka we want to have conservative updates.
472        let _span = tracing::span!(tracing::Level::TRACE, "prefer_package_id").entered();
473        for id in r.iter().filter(keep) {
474            debug!("attempting to prefer {}", id);
475            version_prefs.prefer_package_id(id);
476        }
477    }
478
479    if register_patches {
480        registry.lock_patches();
481    }
482
483    let summaries: Vec<(Summary, ResolveOpts)> = {
484        let _span = tracing::span!(tracing::Level::TRACE, "registry.lock").entered();
485        ws.members_with_features(specs, cli_features)?
486            .into_iter()
487            .map(|(member, features)| {
488                let summary = registry.lock(member.summary().clone());
489                (
490                    summary,
491                    ResolveOpts {
492                        dev_deps,
493                        features: RequestedFeatures::CliFeatures(features),
494                    },
495                )
496            })
497            .collect()
498    };
499
500    let replace = lock_replacements(ws, previous, &keep);
501
502    let mut resolved = resolver::resolve(
503        &summaries,
504        &replace,
505        registry,
506        &version_prefs,
507        ResolveVersion::with_rust_version(ws.lowest_rust_version()),
508        Some(ws.gctx()),
509    )?;
510
511    let patches = registry.patches().values().flat_map(|v| v.iter());
512    resolved.register_used_patches(patches);
513
514    if register_patches && !resolved.unused_patches().is_empty() {
515        emit_warnings_of_unused_patches(ws, &resolved, registry)?;
516    }
517
518    if let Some(previous) = previous {
519        resolved.merge_from(previous)?;
520    }
521    let gctx = ws.gctx();
522    let mut deferred = gctx.deferred_global_last_use()?;
523    deferred.save_no_error(gctx);
524    Ok(resolved)
525}
526
527/// Read the `paths` configuration variable to discover all path overrides that
528/// have been configured.
529#[tracing::instrument(skip_all)]
530pub fn add_overrides<'a>(
531    registry: &mut PackageRegistry<'a>,
532    ws: &Workspace<'a>,
533) -> CargoResult<()> {
534    let gctx = ws.gctx();
535    let Some(paths) = gctx.paths_overrides()? else {
536        return Ok(());
537    };
538
539    let paths = paths.val.iter().map(|(s, def)| {
540        // The path listed next to the string is the config file in which the
541        // key was located, so we want to pop off the `.cargo/config` component
542        // to get the directory containing the `.cargo` folder.
543        (paths::normalize_path(&def.root(gctx).join(s)), def)
544    });
545
546    for (path, definition) in paths {
547        let id = SourceId::for_path(&path)?;
548        let mut source = RecursivePathSource::new(&path, id, ws.gctx());
549        source.load().with_context(|| {
550            format!(
551                "failed to update path override `{}` \
552                 (defined in `{}`)",
553                path.display(),
554                definition
555            )
556        })?;
557        registry.add_override(Box::new(source));
558    }
559    Ok(())
560}
561
562pub fn get_resolved_packages<'gctx>(
563    resolve: &Resolve,
564    registry: PackageRegistry<'gctx>,
565) -> CargoResult<PackageSet<'gctx>> {
566    let ids: Vec<PackageId> = resolve.iter().collect();
567    registry.get(&ids)
568}
569
570/// In this function we're responsible for informing the `registry` of all
571/// locked dependencies from the previous lock file we had, `resolve`.
572///
573/// This gets particularly tricky for a couple of reasons. The first is that we
574/// want all updates to be conservative, so we actually want to take the
575/// `resolve` into account (and avoid unnecessary registry updates and such).
576/// the second, however, is that we want to be resilient to updates of
577/// manifests. For example if a dependency is added or a version is changed we
578/// want to make sure that we properly re-resolve (conservatively) instead of
579/// providing an opaque error.
580///
581/// The logic here is somewhat subtle, but there should be more comments below to
582/// clarify things.
583///
584/// Note that this function, at the time of this writing, is basically the
585/// entire fix for issue #4127.
586#[tracing::instrument(skip_all)]
587fn register_previous_locks(
588    ws: &Workspace<'_>,
589    registry: &mut PackageRegistry<'_>,
590    resolve: &Resolve,
591    keep: Keep<'_>,
592    dev_deps: bool,
593) {
594    let path_pkg = |id: SourceId| {
595        if !id.is_path() {
596            return None;
597        }
598        if let Ok(path) = id.url().to_file_path() {
599            if let Ok(pkg) = ws.load(&path.join("Cargo.toml")) {
600                return Some(pkg);
601            }
602        }
603        None
604    };
605
606    // Ok so we've been passed in a `keep` function which basically says "if I
607    // return `true` then this package wasn't listed for an update on the command
608    // line". That is, if we run `cargo update foo` then `keep(bar)` will return
609    // `true`, whereas `keep(foo)` will return `false` (roughly speaking).
610    //
611    // This isn't actually quite what we want, however. Instead we want to
612    // further refine this `keep` function with *all transitive dependencies* of
613    // the packages we're not keeping. For example, consider a case like this:
614    //
615    // * There's a crate `log`.
616    // * There's a crate `serde` which depends on `log`.
617    //
618    // Let's say we then run `cargo update serde`. This may *also* want to
619    // update the `log` dependency as our newer version of `serde` may have a
620    // new minimum version required for `log`. Now this isn't always guaranteed
621    // to work. What'll happen here is we *won't* lock the `log` dependency nor
622    // the `log` crate itself, but we will inform the registry "please prefer
623    // this version of `log`". That way if our newer version of serde works with
624    // the older version of `log`, we conservatively won't update `log`. If,
625    // however, nothing else in the dependency graph depends on `log` and the
626    // newer version of `serde` requires a new version of `log` it'll get pulled
627    // in (as we didn't accidentally lock it to an old version).
628    let mut avoid_locking = HashSet::new();
629    registry.add_to_yanked_whitelist(resolve.iter().filter(keep));
630    for node in resolve.iter() {
631        if !keep(&node) {
632            add_deps(resolve, node, &mut avoid_locking);
633        }
634    }
635
636    // Ok, but the above loop isn't the entire story! Updates to the dependency
637    // graph can come from two locations, the `cargo update` command or
638    // manifests themselves. For example a manifest on the filesystem may
639    // have been updated to have an updated version requirement on `serde`. In
640    // this case both `keep(serde)` and `keep(log)` return `true` (the `keep`
641    // that's an argument to this function). We, however, don't want to keep
642    // either of those! Otherwise we'll get obscure resolve errors about locked
643    // versions.
644    //
645    // To solve this problem we iterate over all packages with path sources
646    // (aka ones with manifests that are changing) and take a look at all of
647    // their dependencies. If any dependency does not match something in the
648    // previous lock file, then we're guaranteed that the main resolver will
649    // update the source of this dependency no matter what. Knowing this we
650    // poison all packages from the same source, forcing them all to get
651    // updated.
652    //
653    // This may seem like a heavy hammer, and it is! It means that if you change
654    // anything from crates.io then all of crates.io becomes unlocked. Note,
655    // however, that we still want conservative updates. This currently happens
656    // because the first candidate the resolver picks is the previously locked
657    // version, and only if that fails to activate to we move on and try
658    // a different version. (giving the guise of conservative updates)
659    //
660    // For example let's say we had `serde = "0.1"` written in our lock file.
661    // When we later edit this to `serde = "0.1.3"` we don't want to lock serde
662    // at its old version, 0.1.1. Instead we want to allow it to update to
663    // `0.1.3` and update its own dependencies (like above). To do this *all
664    // crates from crates.io* are not locked (aka added to `avoid_locking`).
665    // For dependencies like `log` their previous version in the lock file will
666    // come up first before newer version, if newer version are available.
667    {
668        let _span = tracing::span!(tracing::Level::TRACE, "poison").entered();
669        let mut path_deps = ws.members().cloned().collect::<Vec<_>>();
670        let mut visited = HashSet::new();
671        while let Some(member) = path_deps.pop() {
672            if !visited.insert(member.package_id()) {
673                continue;
674            }
675            let is_ws_member = ws.is_member(&member);
676            for dep in member.dependencies() {
677                // If this dependency didn't match anything special then we may want
678                // to poison the source as it may have been added. If this path
679                // dependencies is **not** a workspace member, however, and it's an
680                // optional/non-transitive dependency then it won't be necessarily
681                // be in our lock file. If this shows up then we avoid poisoning
682                // this source as otherwise we'd repeatedly update the registry.
683                //
684                // TODO: this breaks adding an optional dependency in a
685                // non-workspace member and then simultaneously editing the
686                // dependency on that crate to enable the feature. For now,
687                // this bug is better than the always-updating registry though.
688                if !is_ws_member && (dep.is_optional() || !dep.is_transitive()) {
689                    continue;
690                }
691
692                // If dev-dependencies aren't being resolved, skip them.
693                if !dep.is_transitive() && !dev_deps {
694                    continue;
695                }
696
697                // If this is a path dependency, then try to push it onto our
698                // worklist.
699                if let Some(pkg) = path_pkg(dep.source_id()) {
700                    path_deps.push(pkg);
701                    continue;
702                }
703
704                // If we match *anything* in the dependency graph then we consider
705                // ourselves all ok, and assume that we'll resolve to that.
706                if resolve.iter().any(|id| dep.matches_ignoring_source(id)) {
707                    continue;
708                }
709
710                // Ok if nothing matches, then we poison the source of these
711                // dependencies and the previous lock file.
712                debug!(
713                    "poisoning {} because {} looks like it changed {}",
714                    dep.source_id(),
715                    member.package_id(),
716                    dep.package_name()
717                );
718                for id in resolve
719                    .iter()
720                    .filter(|id| id.source_id() == dep.source_id())
721                {
722                    add_deps(resolve, id, &mut avoid_locking);
723                }
724            }
725        }
726    }
727
728    // Additionally, here we process all path dependencies listed in the previous
729    // resolve. They can not only have their dependencies change but also
730    // the versions of the package change as well. If this ends up happening
731    // then we want to make sure we don't lock a package ID node that doesn't
732    // actually exist. Note that we don't do transitive visits of all the
733    // package's dependencies here as that'll be covered below to poison those
734    // if they changed.
735    //
736    // This must come after all other `add_deps` calls to ensure it recursively walks the tree when
737    // called.
738    for node in resolve.iter() {
739        if let Some(pkg) = path_pkg(node.source_id()) {
740            if pkg.package_id() != node {
741                avoid_locking.insert(node);
742            }
743        }
744    }
745
746    // Alright now that we've got our new, fresh, shiny, and refined `keep`
747    // function let's put it to action. Take a look at the previous lock file,
748    // filter everything by this callback, and then shove everything else into
749    // the registry as a locked dependency.
750    let keep = |id: &PackageId| keep(id) && !avoid_locking.contains(id);
751
752    registry.clear_lock();
753    {
754        let _span = tracing::span!(tracing::Level::TRACE, "register_lock").entered();
755        for node in resolve.iter().filter(keep) {
756            let deps = resolve
757                .deps_not_replaced(node)
758                .map(|p| p.0)
759                .filter(keep)
760                .collect::<Vec<_>>();
761
762            // In the v2 lockfile format and prior the `branch=master` dependency
763            // directive was serialized the same way as the no-branch-listed
764            // directive. Nowadays in Cargo, however, these two directives are
765            // considered distinct and are no longer represented the same way. To
766            // maintain compatibility with older lock files we register locked nodes
767            // for *both* the master branch and the default branch.
768            //
769            // Note that this is only applicable for loading older resolves now at
770            // this point. All new lock files are encoded as v3-or-later, so this is
771            // just compat for loading an old lock file successfully.
772            if let Some(node) = master_branch_git_source(node, resolve) {
773                registry.register_lock(node, deps.clone());
774            }
775
776            registry.register_lock(node, deps);
777        }
778    }
779
780    /// Recursively add `node` and all its transitive dependencies to `set`.
781    fn add_deps(resolve: &Resolve, node: PackageId, set: &mut HashSet<PackageId>) {
782        if !set.insert(node) {
783            return;
784        }
785        debug!("ignoring any lock pointing directly at {}", node);
786        for (dep, _) in resolve.deps_not_replaced(node) {
787            add_deps(resolve, dep, set);
788        }
789    }
790}
791
792fn master_branch_git_source(id: PackageId, resolve: &Resolve) -> Option<PackageId> {
793    if resolve.version() <= ResolveVersion::V2 {
794        let source = id.source_id();
795        if let Some(GitReference::DefaultBranch) = source.git_reference() {
796            let new_source =
797                SourceId::for_git(source.url(), GitReference::Branch("master".to_string()))
798                    .unwrap()
799                    .with_precise_from(source);
800            return Some(id.with_source_id(new_source));
801        }
802    }
803    None
804}
805
806/// Emits warnings of unused patches case by case.
807///
808/// This function does its best to provide more targeted and helpful
809/// (such as showing close candidates that failed to match). However, that's
810/// not terribly easy to do, so just show a general help message if we cannot.
811fn emit_warnings_of_unused_patches(
812    ws: &Workspace<'_>,
813    resolve: &Resolve,
814    registry: &PackageRegistry<'_>,
815) -> CargoResult<()> {
816    const MESSAGE: &str = "was not used in the crate graph";
817
818    // Patch package with the source URLs being patch
819    let mut patch_pkgid_to_urls = HashMap::new();
820    for (url, summaries) in registry.patches().iter() {
821        for summary in summaries.iter() {
822            patch_pkgid_to_urls
823                .entry(summary.package_id())
824                .or_insert_with(HashSet::new)
825                .insert(url);
826        }
827    }
828
829    // pkg name -> all source IDs of under the same pkg name
830    let mut source_ids_grouped_by_pkg_name = HashMap::new();
831    for pkgid in resolve.iter() {
832        source_ids_grouped_by_pkg_name
833            .entry(pkgid.name())
834            .or_insert_with(HashSet::new)
835            .insert(pkgid.source_id());
836    }
837
838    let mut unemitted_unused_patches = Vec::new();
839    for unused in resolve.unused_patches().iter() {
840        // Show alternative source URLs if the source URLs being patched
841        // cannot be found in the crate graph.
842        match (
843            source_ids_grouped_by_pkg_name.get(&unused.name()),
844            patch_pkgid_to_urls.get(unused),
845        ) {
846            (Some(ids), Some(patched_urls))
847                if ids
848                    .iter()
849                    .all(|id| !patched_urls.contains(id.canonical_url())) =>
850            {
851                let mut help = "perhaps you meant one of the following:".to_owned();
852                for id in ids {
853                    help.push_str("\n\t");
854                    help.push_str(&id.display_registry_name());
855                }
856                ws.gctx().shell().print_report(
857                    &[Level::WARNING
858                        .secondary_title(format!("patch `{unused}` {MESSAGE}"))
859                        .element(Level::HELP.message(help))],
860                    false,
861                )?;
862            }
863            _ => unemitted_unused_patches.push(unused),
864        }
865    }
866
867    // Show general help message.
868    if !unemitted_unused_patches.is_empty() {
869        let mut warnings: Vec<_> = unemitted_unused_patches
870            .iter()
871            .map(|pkgid| {
872                Group::with_title(
873                    Level::WARNING.secondary_title(format!("patch `{pkgid}` {MESSAGE}")),
874                )
875            })
876            .collect();
877        warnings.push(Group::with_title(
878            Level::HELP.secondary_title(UNUSED_PATCH_WARNING),
879        ));
880        ws.gctx().shell().print_report(&warnings, false)?;
881    }
882
883    return Ok(());
884}
885
886/// Informs `registry` and `version_pref` that `[patch]` entries are available
887/// and preferable for the dependency resolution.
888///
889/// This returns a set of PackageIds of `[patch]` entries, and some related
890/// locked PackageIds, for which locking should be avoided (but which will be
891/// preferred when searching dependencies, via [`VersionPreferences::prefer_patch_deps`]).
892#[tracing::instrument(level = "debug", skip_all, ret)]
893fn register_patch_entries(
894    registry: &mut PackageRegistry<'_>,
895    ws: &Workspace<'_>,
896    previous: Option<&Resolve>,
897    version_prefs: &mut VersionPreferences,
898    keep_previous: Keep<'_>,
899) -> CargoResult<HashSet<PackageId>> {
900    let mut avoid_patch_ids = HashSet::new();
901    for (url, patches) in ws.root_patch()?.iter() {
902        for patch in patches {
903            version_prefs.prefer_dependency(patch.clone());
904        }
905        let Some(previous) = previous else {
906            let patches: Vec<_> = patches.iter().map(|p| (p, None)).collect();
907            let unlock_ids = registry.patch(url, &patches)?;
908            // Since nothing is locked, this shouldn't possibly return anything.
909            assert!(unlock_ids.is_empty());
910            continue;
911        };
912
913        // This is a list of pairs where the first element of the pair is
914        // the raw `Dependency` which matches what's listed in `Cargo.toml`.
915        // The second element is, if present, the "locked" version of
916        // the `Dependency` as well as the `PackageId` that it previously
917        // resolved to. This second element is calculated by looking at the
918        // previous resolve graph, which is primarily what's done here to
919        // build the `registrations` list.
920        let mut registrations = Vec::new();
921        for dep in patches {
922            let candidates = || {
923                previous
924                    .iter()
925                    .chain(previous.unused_patches().iter().cloned())
926                    .filter(&keep_previous)
927            };
928
929            let lock = match candidates().find(|id| dep.matches_id(*id)) {
930                // If we found an exactly matching candidate in our list of
931                // candidates, then that's the one to use.
932                Some(package_id) => {
933                    let mut locked_dep = dep.clone();
934                    locked_dep.lock_to(package_id);
935                    Some(LockedPatchDependency {
936                        dependency: locked_dep,
937                        package_id,
938                        alt_package_id: None,
939                    })
940                }
941                None => {
942                    // If the candidate does not have a matching source id
943                    // then we may still have a lock candidate. If we're
944                    // loading a v2-encoded resolve graph and `dep` is a
945                    // git dep with `branch = 'master'`, then this should
946                    // also match candidates without `branch = 'master'`
947                    // (which is now treated separately in Cargo).
948                    //
949                    // In this scenario we try to convert candidates located
950                    // in the resolve graph to explicitly having the
951                    // `master` branch (if they otherwise point to
952                    // `DefaultBranch`). If this works and our `dep`
953                    // matches that then this is something we'll lock to.
954                    match candidates().find(|&id| match master_branch_git_source(id, previous) {
955                        Some(id) => dep.matches_id(id),
956                        None => false,
957                    }) {
958                        Some(id_using_default) => {
959                            let id_using_master = id_using_default.with_source_id(
960                                dep.source_id()
961                                    .with_precise_from(id_using_default.source_id()),
962                            );
963
964                            let mut locked_dep = dep.clone();
965                            locked_dep.lock_to(id_using_master);
966                            Some(LockedPatchDependency {
967                                dependency: locked_dep,
968                                package_id: id_using_master,
969                                // Note that this is where the magic
970                                // happens, where the resolve graph
971                                // probably has locks pointing to
972                                // DefaultBranch sources, and by including
973                                // this here those will get transparently
974                                // rewritten to Branch("master") which we
975                                // have a lock entry for.
976                                alt_package_id: Some(id_using_default),
977                            })
978                        }
979
980                        // No locked candidate was found
981                        None => None,
982                    }
983                }
984            };
985
986            registrations.push((dep, lock));
987        }
988
989        let canonical = CanonicalUrl::new(url)?;
990        for (orig_patch, unlock_id) in registry.patch(url, &registrations)? {
991            // Avoid the locked patch ID.
992            avoid_patch_ids.insert(unlock_id);
993            // Also avoid the thing it is patching.
994            avoid_patch_ids.extend(previous.iter().filter(|id| {
995                orig_patch.matches_ignoring_source(*id)
996                    && *id.source_id().canonical_url() == canonical
997            }));
998        }
999    }
1000
1001    Ok(avoid_patch_ids)
1002}
1003
1004/// Locks each `[replace]` entry to a specific Package ID
1005/// if the lockfile contains any corresponding previous replacement.
1006fn lock_replacements(
1007    ws: &Workspace<'_>,
1008    previous: Option<&Resolve>,
1009    keep: Keep<'_>,
1010) -> Vec<(PackageIdSpec, Dependency)> {
1011    let root_replace = ws.root_replace();
1012    let replace = match previous {
1013        Some(r) => root_replace
1014            .iter()
1015            .map(|(spec, dep)| {
1016                for (&key, &val) in r.replacements().iter() {
1017                    if spec.matches(key) && dep.matches_id(val) && keep(&val) {
1018                        let mut dep = dep.clone();
1019                        dep.lock_to(val);
1020                        return (spec.clone(), dep);
1021                    }
1022                }
1023                (spec.clone(), dep.clone())
1024            })
1025            .collect::<Vec<_>>(),
1026        None => root_replace.to_vec(),
1027    };
1028    replace
1029}