Skip to main content

cargo/core/resolver/
mod.rs

1//! Resolution of the entire dependency graph for a crate.
2//!
3//! This module implements the core logic in taking the world of crates and
4//! constraints and creating a resolved graph with locked versions for all
5//! crates and their dependencies. This is separate from the registry module
6//! which is more worried about discovering crates from various sources, this
7//! module just uses the Registry trait as a source to learn about crates from.
8//!
9//! Actually solving a constraint graph is an NP-hard problem. This algorithm
10//! is basically a nice heuristic to make sure we get roughly the best answer
11//! most of the time. The constraints that we're working with are:
12//!
13//! 1. Each crate can have any number of dependencies. Each dependency can
14//!    declare a version range that it is compatible with.
15//! 2. Crates can be activated with multiple version (e.g., show up in the
16//!    dependency graph twice) so long as each pairwise instance have
17//!    semver-incompatible versions.
18//!
19//! The algorithm employed here is fairly simple, we simply do a DFS, activating
20//! the "newest crate" (highest version) first and then going to the next
21//! option. The heuristics we employ are:
22//!
23//! * Never try to activate a crate version which is incompatible. This means we
24//!   only try crates which will actually satisfy a dependency and we won't ever
25//!   try to activate a crate that's semver compatible with something else
26//!   activated (as we're only allowed to have one) nor try to activate a crate
27//!   that has the same links attribute as something else
28//!   activated.
29//! * Always try to activate the highest version crate first. The default
30//!   dependency in Cargo (e.g., when you write `foo = "0.1.2"`) is
31//!   semver-compatible, so selecting the highest version possible will allow us
32//!   to hopefully satisfy as many dependencies at once.
33//!
34//! Beyond that, what's implemented below is just a naive backtracking version
35//! which should in theory try all possible combinations of dependencies and
36//! versions to see if one works. The first resolution that works causes
37//! everything to bail out immediately and return success, and only if *nothing*
38//! works do we actually return an error up the stack.
39//!
40//! Resolution is currently performed twice
41//! 1. With all features enabled (this is what gets saved to `Cargo.lock`)
42//! 2. With only the specific features the user selected on the command-line. Ideally this
43//!    run will get removed in the future when transitioning to the new feature resolver.
44//!
45//! A new feature-specific resolver was added in 2020 which adds more sophisticated feature
46//! resolution. It is located in the [`features`] module. The original dependency resolver still
47//! performs feature unification, as it can help reduce the dependencies it has to consider during
48//! resolution (rather than assuming every optional dependency of every package is enabled).
49//! Checking if a feature is enabled must go through the new feature resolver.
50//!
51//! ## Performance
52//!
53//! Note that this is a relatively performance-critical portion of Cargo. The
54//! data that we're processing is proportional to the size of the dependency
55//! graph, which can often be quite large (e.g., take a look at Servo). To make
56//! matters worse the DFS algorithm we're implemented is inherently quite
57//! inefficient. When we add the requirement of backtracking on top it means
58//! that we're implementing something that probably shouldn't be allocating all
59//! over the place.
60
61use std::collections::{BTreeMap, HashMap, HashSet};
62use std::rc::Rc;
63use std::time::{Duration, Instant};
64
65use tracing::{debug, trace};
66
67use crate::core::PackageIdSpec;
68use crate::core::{Dependency, PackageId, Registry, Summary};
69use crate::util::context::GlobalContext;
70use crate::util::errors::CargoResult;
71use crate::util::network::PollExt;
72
73use self::context::ResolverContext;
74use self::dep_cache::RegistryQueryer;
75use self::features::RequestedFeatures;
76use self::types::{ConflictMap, ConflictReason, DepsFrame};
77use self::types::{FeaturesSet, RcVecIter, RemainingDeps, ResolverProgress};
78
79pub use self::errors::{ActivateError, ActivateResult, ResolveError};
80pub use self::features::{CliFeatures, ForceAllTargets, HasDevUnits};
81pub use self::resolve::{Resolve, ResolveVersion};
82pub use self::types::{ResolveBehavior, ResolveOpts};
83pub use self::version_prefs::{VersionOrdering, VersionPreferences};
84
85mod conflict_cache;
86mod context;
87mod dep_cache;
88pub(crate) mod encode;
89pub(crate) mod errors;
90pub mod features;
91mod resolve;
92mod types;
93mod version_prefs;
94
95/// Builds the list of all packages required to build the first argument.
96///
97/// * `summaries` - the list of package summaries along with how to resolve
98///   their features. This is a list of all top-level packages that are intended
99///   to be part of the lock file (resolve output). These typically are a list
100///   of all workspace members.
101///
102/// * `replacements` - this is a list of `[replace]` directives found in the
103///   root of the workspace. The list here is a `PackageIdSpec` of what to
104///   replace and a `Dependency` to replace that with. In general it's not
105///   recommended to use `[replace]` any more and use `[patch]` instead, which
106///   is supported elsewhere.
107///
108/// * `registry` - this is the source from which all package summaries are
109///   loaded. It's expected that this is extensively configured ahead of time
110///   and is idempotent with our requests to it (aka returns the same results
111///   for the same query every time). Typically this is an instance of a
112///   `PackageRegistry`.
113///
114/// * `version_prefs` - this represents a preference for some versions over others,
115///   based on the lock file or other reasons such as `[patch]`es.
116///
117/// * `resolve_version` - this controls how the lockfile will be serialized.
118///
119/// * `config` - a location to print warnings and such, or `None` if no warnings
120///   should be printed
121#[tracing::instrument(skip_all)]
122pub fn resolve(
123    summaries: &[(Summary, ResolveOpts)],
124    replacements: &[(PackageIdSpec, Dependency)],
125    registry: &impl Registry,
126    version_prefs: &VersionPreferences,
127    resolve_version: ResolveVersion,
128    gctx: Option<&GlobalContext>,
129) -> CargoResult<Resolve> {
130    let first_version = match gctx {
131        Some(config) if config.cli_unstable().direct_minimal_versions => {
132            Some(VersionOrdering::MinimumVersionsFirst)
133        }
134        _ => None,
135    };
136    let mut registry = RegistryQueryer::new(registry, replacements, version_prefs);
137
138    // Global cache of the reasons for each time we backtrack.
139    let mut past_conflicting_activations = conflict_cache::ConflictCache::new();
140
141    let resolver_ctx = loop {
142        let resolver_ctx = activate_deps_loop(
143            &mut registry,
144            summaries,
145            first_version,
146            gctx,
147            &mut past_conflicting_activations,
148        )?;
149        if registry.wait()? {
150            break resolver_ctx;
151        }
152    };
153
154    let mut cksums = HashMap::new();
155    for (summary, _) in resolver_ctx.activations.values() {
156        let cksum = summary.checksum().map(|s| s.to_string());
157        cksums.insert(summary.package_id(), cksum);
158    }
159    let graph = resolver_ctx.graph();
160    let replacements = resolver_ctx.resolve_replacements(&registry);
161    let features = resolver_ctx
162        .resolve_features
163        .iter()
164        .map(|(k, v)| (*k, v.iter().cloned().collect()))
165        .collect();
166    let summaries = resolver_ctx
167        .activations
168        .into_iter()
169        .map(|(_key, (summary, _age))| (summary.package_id(), summary))
170        .collect();
171    let resolve = Resolve::new(
172        graph,
173        replacements,
174        features,
175        cksums,
176        BTreeMap::new(),
177        Vec::new(),
178        resolve_version,
179        summaries,
180    );
181
182    check_cycles(&resolve)?;
183    check_duplicate_pkgs_in_lockfile(&resolve)?;
184    trace!("resolved: {:?}", resolve);
185
186    Ok(resolve)
187}
188
189/// Recursively activates the dependencies for `summaries`, in depth-first order,
190/// backtracking across possible candidates for each dependency as necessary.
191///
192/// If all dependencies can be activated and resolved to a version in the
193/// dependency graph, `cx` is returned.
194fn activate_deps_loop(
195    registry: &mut RegistryQueryer<'_, impl Registry>,
196    summaries: &[(Summary, ResolveOpts)],
197    first_version: Option<VersionOrdering>,
198    gctx: Option<&GlobalContext>,
199    past_conflicting_activations: &mut conflict_cache::ConflictCache,
200) -> CargoResult<ResolverContext> {
201    let mut resolver_ctx = ResolverContext::new();
202    let mut backtrack_stack = Vec::new();
203    let mut remaining_deps = RemainingDeps::new();
204
205    // Activate all the initial summaries to kick off some work.
206    for (summary, opts) in summaries {
207        debug!("initial activation: {}", summary.package_id());
208        let res = activate(
209            &mut resolver_ctx,
210            registry,
211            None,
212            summary.clone(),
213            first_version,
214            opts,
215        );
216        match res {
217            Ok(Some((frame, _))) => remaining_deps.push(frame),
218            Ok(None) => (),
219            Err(ActivateError::Fatal(e)) => return Err(e),
220            Err(ActivateError::Conflict(_, _)) => panic!("bad error from activate"),
221        }
222    }
223
224    let mut printed = ResolverProgress::new();
225
226    // Main resolution loop, this is the workhorse of the resolution algorithm.
227    //
228    // You'll note that a few stacks are maintained on the side, which might
229    // seem odd when this algorithm looks like it could be implemented
230    // recursively. While correct, this is implemented iteratively to avoid
231    // blowing the stack (the recursion depth is proportional to the size of the
232    // input).
233    //
234    // The general sketch of this loop is to run until there are no dependencies
235    // left to activate, and for each dependency to attempt to activate all of
236    // its own dependencies in turn. The `backtrack_stack` is a side table of
237    // backtracking states where if we hit an error we can return to in order to
238    // attempt to continue resolving.
239    while let Some((just_here_for_the_error_messages, frame)) =
240        remaining_deps.pop_most_constrained()
241    {
242        let (mut parent, (mut dep, candidates, mut features)) = frame;
243
244        // If we spend a lot of time here (we shouldn't in most cases) then give
245        // a bit of a visual indicator as to what we're doing.
246        printed.shell_status(gctx)?;
247
248        trace!(
249            "{}[{}]>{} {} candidates",
250            parent.name(),
251            resolver_ctx.age,
252            dep.package_name(),
253            candidates.len()
254        );
255
256        let just_here_for_the_error_messages = just_here_for_the_error_messages
257            && past_conflicting_activations
258                .conflicting(&resolver_ctx, &dep)
259                .is_some();
260
261        let mut remaining_candidates = RemainingCandidates::new(&candidates);
262
263        // `conflicting_activations` stores all the reasons we were unable to
264        // activate candidates. One of these reasons will have to go away for
265        // backtracking to find a place to restart. It is also the list of
266        // things to explain in the error message if we fail to resolve.
267        //
268        // This is a map of package ID to a reason why that packaged caused a
269        // conflict for us.
270        let mut conflicting_activations = ConflictMap::new();
271
272        // When backtracking we don't fully update `conflicting_activations`
273        // especially for the cases that we didn't make a backtrack frame in the
274        // first place. This `backtracked` var stores whether we are continuing
275        // from a restored backtrack frame so that we can skip caching
276        // `conflicting_activations` in `past_conflicting_activations`
277        let mut backtracked = false;
278
279        loop {
280            let next = remaining_candidates.next(&mut conflicting_activations, &resolver_ctx);
281
282            let (candidate, has_another) = next.ok_or(()).or_else(|_| {
283                // If we get here then our `remaining_candidates` was just
284                // exhausted, so `dep` failed to activate.
285                //
286                // It's our job here to backtrack, if possible, and find a
287                // different candidate to activate. If we can't find any
288                // candidates whatsoever then it's time to bail entirely.
289                trace!(
290                    "{}[{}]>{} -- no candidates",
291                    parent.name(),
292                    resolver_ctx.age,
293                    dep.package_name()
294                );
295
296                // Use our list of `conflicting_activations` to add to our
297                // global list of past conflicting activations, effectively
298                // globally poisoning `dep` if `conflicting_activations` ever
299                // shows up again. We'll use the `past_conflicting_activations`
300                // below to determine if a dependency is poisoned and skip as
301                // much work as possible.
302                //
303                // If we're only here for the error messages then there's no
304                // need to try this as this dependency is already known to be
305                // bad.
306                //
307                // As we mentioned above with the `backtracked` variable if this
308                // local is set to `true` then our `conflicting_activations` may
309                // not be right, so we can't push into our global cache.
310                let mut generalize_conflicting_activations = None;
311                if !just_here_for_the_error_messages && !backtracked {
312                    past_conflicting_activations.insert(&dep, &conflicting_activations);
313                    if let Some(c) = generalize_conflicting(
314                        &resolver_ctx,
315                        registry,
316                        past_conflicting_activations,
317                        &parent,
318                        &dep,
319                        &conflicting_activations,
320                    ) {
321                        generalize_conflicting_activations = Some(c);
322                    }
323                }
324
325                match find_candidate(
326                    &resolver_ctx,
327                    &mut backtrack_stack,
328                    &parent,
329                    backtracked,
330                    generalize_conflicting_activations
331                        .as_ref()
332                        .unwrap_or(&conflicting_activations),
333                ) {
334                    Some((candidate, has_another, frame)) => {
335                        // Reset all of our local variables used with the
336                        // contents of `frame` to complete our backtrack.
337                        resolver_ctx = frame.context;
338                        remaining_deps = frame.remaining_deps;
339                        remaining_candidates = frame.remaining_candidates;
340                        parent = frame.parent;
341                        dep = frame.dep;
342                        features = frame.features;
343                        conflicting_activations = frame.conflicting_activations;
344                        backtracked = true;
345                        Ok((candidate, has_another))
346                    }
347                    None => {
348                        debug!("no candidates found");
349                        Err(errors::activation_error(
350                            &resolver_ctx,
351                            registry.registry(),
352                            &parent,
353                            &dep,
354                            &conflicting_activations,
355                            &candidates,
356                            gctx,
357                        ))
358                    }
359                }
360            })?;
361
362            // If we're only here for the error messages then we know that this
363            // activation will fail one way or another. To that end if we've got
364            // more candidates we want to fast-forward to the last one as
365            // otherwise we'll just backtrack here anyway (helping us to skip
366            // some work).
367            if just_here_for_the_error_messages && !backtracked && has_another {
368                continue;
369            }
370
371            // We have a `candidate`. Create a `BacktrackFrame` so we can add it
372            // to the `backtrack_stack` later if activation succeeds.
373            //
374            // Note that if we don't actually have another candidate then there
375            // will be nothing to backtrack to so we skip construction of the
376            // frame. This is a relatively important optimization as a number of
377            // the `clone` calls below can be quite expensive, so we avoid them
378            // if we can.
379            let backtrack = if has_another {
380                Some(BacktrackFrame {
381                    context: ResolverContext::clone(&resolver_ctx),
382                    remaining_deps: remaining_deps.clone(),
383                    remaining_candidates: remaining_candidates.clone(),
384                    parent: Summary::clone(&parent),
385                    dep: Dependency::clone(&dep),
386                    features: Rc::clone(&features),
387                    conflicting_activations: conflicting_activations.clone(),
388                })
389            } else {
390                None
391            };
392
393            let pid = candidate.package_id();
394            let opts = ResolveOpts {
395                dev_deps: false,
396                features: RequestedFeatures::DepFeatures {
397                    features: Rc::clone(&features),
398                    uses_default_features: dep.uses_default_features(),
399                },
400            };
401            trace!(
402                "{}[{}]>{} trying {}",
403                parent.name(),
404                resolver_ctx.age,
405                dep.package_name(),
406                candidate.version()
407            );
408            let first_version = None; // this is an indirect dependency
409            let res = activate(
410                &mut resolver_ctx,
411                registry,
412                Some((&parent, &dep)),
413                candidate,
414                first_version,
415                &opts,
416            );
417
418            let successfully_activated = match res {
419                // Success! We've now activated our `candidate` in our context
420                // and we're almost ready to move on. We may want to scrap this
421                // frame in the end if it looks like it's not going to end well,
422                // so figure that out here.
423                Ok(Some((mut frame, dur))) => {
424                    printed.elapsed(dur);
425
426                    // Our `frame` here is a new package with its own list of
427                    // dependencies. Do a sanity check here of all those
428                    // dependencies by cross-referencing our global
429                    // `past_conflicting_activations`. Recall that map is a
430                    // global cache which lists sets of packages where, when
431                    // activated, the dependency is unresolvable.
432                    //
433                    // If any our frame's dependencies fit in that bucket,
434                    // aka known unresolvable, then we extend our own set of
435                    // conflicting activations with theirs. We can do this
436                    // because the set of conflicts we found implies the
437                    // dependency can't be activated which implies that we
438                    // ourselves can't be activated, so we know that they
439                    // conflict with us.
440                    let mut has_past_conflicting_dep = just_here_for_the_error_messages;
441                    if !has_past_conflicting_dep {
442                        if let Some(conflicting) =
443                            frame
444                                .remaining_siblings
445                                .remaining()
446                                .find_map(|(new_dep, _, _)| {
447                                    past_conflicting_activations.conflicting(&resolver_ctx, new_dep)
448                                })
449                        {
450                            // If one of our deps is known unresolvable
451                            // then we will not succeed.
452                            // How ever if we are part of the reason that
453                            // one of our deps conflicts then
454                            // we can make a stronger statement
455                            // because we will definitely be activated when
456                            // we try our dep.
457                            conflicting_activations.extend(
458                                conflicting
459                                    .iter()
460                                    .filter(|&(p, _)| p != &pid)
461                                    .map(|(&p, r)| (p, r.clone())),
462                            );
463
464                            has_past_conflicting_dep = true;
465                        }
466                    }
467                    // If any of `remaining_deps` are known unresolvable with
468                    // us activated, then we extend our own set of
469                    // conflicting activations with theirs and its parent. We can do this
470                    // because the set of conflicts we found implies the
471                    // dependency can't be activated which implies that we
472                    // ourselves are incompatible with that dep, so we know that deps
473                    // parent conflict with us.
474                    if !has_past_conflicting_dep {
475                        if let Some(known_related_bad_deps) =
476                            past_conflicting_activations.dependencies_conflicting_with(pid)
477                        {
478                            if let Some((other_parent, conflict)) = remaining_deps
479                                .iter()
480                                // for deps related to us
481                                .filter(|(_, other_dep)| known_related_bad_deps.contains(other_dep))
482                                .filter_map(|(other_parent, other_dep)| {
483                                    past_conflicting_activations
484                                        .find_conflicting(&resolver_ctx, &other_dep, Some(pid))
485                                        .map(|con| (other_parent, con))
486                                })
487                                .next()
488                            {
489                                let rel = conflict.get(&pid).unwrap().clone();
490
491                                // The conflict we found is
492                                // "other dep will not succeed if we are activated."
493                                // We want to add
494                                // "our dep will not succeed if other dep is in remaining_deps"
495                                // but that is not how the cache is set up.
496                                // So we add the less general but much faster,
497                                // "our dep will not succeed if other dep's parent is activated".
498                                conflicting_activations.extend(
499                                    conflict
500                                        .iter()
501                                        .filter(|&(p, _)| p != &pid)
502                                        .map(|(&p, r)| (p, r.clone())),
503                                );
504                                conflicting_activations.insert(other_parent, rel);
505                                has_past_conflicting_dep = true;
506                            }
507                        }
508                    }
509
510                    // Ok if we're in a "known failure" state for this frame we
511                    // may want to skip it altogether though. We don't want to
512                    // skip it though in the case that we're displaying error
513                    // messages to the user!
514                    //
515                    // Here we need to figure out if the user will see if we
516                    // skipped this candidate (if it's known to fail, aka has a
517                    // conflicting dep and we're the last candidate). If we're
518                    // here for the error messages, we can't skip it (but we can
519                    // prune extra work). If we don't have any candidates in our
520                    // backtrack stack then we're the last line of defense, so
521                    // we'll want to present an error message for sure.
522                    let activate_for_error_message = has_past_conflicting_dep && !has_another && {
523                        just_here_for_the_error_messages || {
524                            find_candidate(
525                                &resolver_ctx,
526                                &mut backtrack_stack.clone(),
527                                &parent,
528                                backtracked,
529                                &conflicting_activations,
530                            )
531                            .is_none()
532                        }
533                    };
534
535                    // If we're only here for the error messages then we know
536                    // one of our candidate deps will fail, meaning we will
537                    // fail and that none of the backtrack frames will find a
538                    // candidate that will help. Consequently let's clean up the
539                    // no longer needed backtrack frames.
540                    if activate_for_error_message {
541                        backtrack_stack.clear();
542                    }
543
544                    // If we don't know for a fact that we'll fail or if we're
545                    // just here for the error message then we push this frame
546                    // onto our list of to-be-resolve, which will generate more
547                    // work for us later on.
548                    //
549                    // Otherwise we're guaranteed to fail and were not here for
550                    // error messages, so we skip work and don't push anything
551                    // onto our stack.
552                    frame.just_for_error_messages = has_past_conflicting_dep;
553                    if !has_past_conflicting_dep || activate_for_error_message {
554                        remaining_deps.push(frame);
555                        true
556                    } else {
557                        trace!(
558                            "{}[{}]>{} skipping {} ",
559                            parent.name(),
560                            resolver_ctx.age,
561                            dep.package_name(),
562                            pid.version()
563                        );
564                        false
565                    }
566                }
567
568                // This candidate's already activated, so there's no extra work
569                // for us to do. Let's keep going.
570                Ok(None) => true,
571
572                // We failed with a super fatal error (like a network error), so
573                // bail out as quickly as possible as we can't reliably
574                // backtrack from errors like these
575                Err(ActivateError::Fatal(e)) => return Err(e),
576
577                // We failed due to a bland conflict, bah! Record this in our
578                // frame's list of conflicting activations as to why this
579                // candidate failed, and then move on.
580                Err(ActivateError::Conflict(id, reason)) => {
581                    conflicting_activations.insert(id, reason);
582                    false
583                }
584            };
585
586            // If we've successfully activated then save off the backtrack frame
587            // if one was created, and otherwise break out of the inner
588            // activation loop as we're ready to move to the next dependency
589            if successfully_activated {
590                backtrack_stack.extend(backtrack);
591                break;
592            }
593
594            // We've failed to activate this dependency, oh dear! Our call to
595            // `activate` above may have altered our `cx` local variable, so
596            // restore it back if we've got a backtrack frame.
597            //
598            // If we don't have a backtrack frame then we're just using the `cx`
599            // for error messages anyway so we can live with a little
600            // imprecision.
601            if let Some(b) = backtrack {
602                resolver_ctx = b.context;
603            }
604        }
605
606        // Ok phew, that loop was a big one! If we've broken out then we've
607        // successfully activated a candidate. Our stacks are all in place that
608        // we're ready to move on to the next dependency that needs activation,
609        // so loop back to the top of the function here.
610    }
611
612    Ok(resolver_ctx)
613}
614
615/// Attempts to activate the summary `candidate` in the context `cx`.
616///
617/// This function will pull dependency summaries from the registry provided, and
618/// the dependencies of the package will be determined by the `opts` provided.
619/// If `candidate` was activated, this function returns the dependency frame to
620/// iterate through next.
621fn activate(
622    cx: &mut ResolverContext,
623    registry: &mut RegistryQueryer<'_, impl Registry>,
624    parent: Option<(&Summary, &Dependency)>,
625    candidate: Summary,
626    first_version: Option<VersionOrdering>,
627    opts: &ResolveOpts,
628) -> ActivateResult<Option<(DepsFrame, Duration)>> {
629    let candidate_pid = candidate.package_id();
630    cx.age += 1;
631    if let Some((parent, dep)) = parent {
632        let parent_pid = parent.package_id();
633        // add an edge from candidate to parent in the parents graph
634        cx.parents
635            .link(candidate_pid, parent_pid)
636            // and associate dep with that edge
637            .insert(dep.clone());
638    }
639
640    let activated = cx.flag_activated(&candidate, opts, parent)?;
641
642    let candidate = match registry.replacement_summary(candidate_pid) {
643        Some(replace) => {
644            // Note the `None` for parent here since `[replace]` is a bit wonky
645            // and doesn't activate the same things that `[patch]` typically
646            // does. TBH it basically cause panics in the test suite if
647            // `parent` is passed through here and `[replace]` is otherwise
648            // on life support so it's not critical to fix bugs anyway per se.
649            if cx.flag_activated(&replace, opts, None)? && activated {
650                return Ok(None);
651            }
652            trace!(
653                "activating {} (replacing {})",
654                replace.package_id(),
655                candidate_pid
656            );
657            replace.clone()
658        }
659        None => {
660            if activated {
661                return Ok(None);
662            }
663            trace!("activating {}", candidate_pid);
664            candidate
665        }
666    };
667
668    let now = Instant::now();
669    let (used_features, deps) = &*registry.build_deps(
670        cx,
671        parent.map(|p| p.0.package_id()),
672        &candidate,
673        opts,
674        first_version,
675    )?;
676
677    // Record what list of features is active for this package.
678    if !used_features.is_empty() {
679        Rc::make_mut(
680            cx.resolve_features
681                .entry(candidate.package_id())
682                .or_default(),
683        )
684        .extend(used_features);
685    }
686
687    let frame = DepsFrame {
688        parent: candidate,
689        just_for_error_messages: false,
690        remaining_siblings: RcVecIter::new(Rc::clone(deps)),
691    };
692    Ok(Some((frame, now.elapsed())))
693}
694
695#[derive(Clone)]
696struct BacktrackFrame {
697    context: ResolverContext,
698    remaining_deps: RemainingDeps,
699    remaining_candidates: RemainingCandidates,
700    parent: Summary,
701    dep: Dependency,
702    features: FeaturesSet,
703    conflicting_activations: ConflictMap,
704}
705
706/// A helper "iterator" used to extract candidates within a current `Context` of
707/// a dependency graph.
708///
709/// This struct doesn't literally implement the `Iterator` trait (requires a few
710/// more inputs) but in general acts like one. Each `RemainingCandidates` is
711/// created with a list of candidates to choose from. When attempting to iterate
712/// over the list of candidates only *valid* candidates are returned. Validity
713/// is defined within a `Context`.
714///
715/// Candidates passed to `new` may not be returned from `next` as they could be
716/// filtered out, and as they are filtered the causes will be added to `conflicting_prev_active`.
717#[derive(Clone)]
718struct RemainingCandidates {
719    remaining: RcVecIter<Summary>,
720    // This is an inlined peekable generator
721    has_another: Option<Summary>,
722}
723
724impl RemainingCandidates {
725    fn new(candidates: &Rc<Vec<Summary>>) -> RemainingCandidates {
726        RemainingCandidates {
727            remaining: RcVecIter::new(Rc::clone(candidates)),
728            has_another: None,
729        }
730    }
731
732    /// Attempts to find another candidate to check from this list.
733    ///
734    /// This method will attempt to move this iterator forward, returning a
735    /// candidate that's possible to activate. The `cx` argument is the current
736    /// context which determines validity for candidates returned, and the `dep`
737    /// is the dependency listing that we're activating for.
738    ///
739    /// If successful a `(Candidate, bool)` pair will be returned. The
740    /// `Candidate` is the candidate to attempt to activate, and the `bool` is
741    /// an indicator of whether there are remaining candidates to try of if
742    /// we've reached the end of iteration.
743    ///
744    /// If we've reached the end of the iterator here then `Err` will be
745    /// returned. The error will contain a map of package ID to conflict reason,
746    /// where each package ID caused a candidate to be filtered out from the
747    /// original list for the reason listed.
748    fn next(
749        &mut self,
750        conflicting_prev_active: &mut ConflictMap,
751        cx: &ResolverContext,
752    ) -> Option<(Summary, bool)> {
753        for b in self.remaining.iter() {
754            let b_id = b.package_id();
755
756            // The condition for being a valid candidate relies on
757            // semver. Cargo dictates that you can't duplicate multiple
758            // semver-compatible versions of a crate. For example we can't
759            // simultaneously activate `foo 1.0.2` and `foo 1.2.0`. We can,
760            // however, activate `1.0.2` and `2.0.0`.
761            //
762            // Here we throw out our candidate if it's *compatible*, yet not
763            // equal, to all previously activated versions.
764            if let Some((a, _)) = cx.activations.get(&b_id.as_activations_key()) {
765                if a != b {
766                    conflicting_prev_active
767                        .entry(a.package_id())
768                        .or_insert(ConflictReason::Semver);
769                    continue;
770                }
771            }
772
773            // Otherwise the `links` key in the manifest dictates that there's only one
774            // package in a dependency graph, globally, with that particular
775            // `links` key. If this candidate links to something that's already
776            // linked to by a different package then we've gotta skip this.
777            if let Some(link) = b.links() {
778                if let Some(&a) = cx.links.get(&link) {
779                    if a != b_id {
780                        conflicting_prev_active
781                            .entry(a)
782                            .or_insert_with(|| ConflictReason::Links(link));
783                        continue;
784                    }
785                }
786            }
787
788            // Well if we made it this far then we've got a valid dependency. We
789            // want this iterator to be inherently "peekable" so we don't
790            // necessarily return the item just yet. Instead we stash it away to
791            // get returned later, and if we replaced something then that was
792            // actually the candidate to try first so we return that.
793            if let Some(r) = self.has_another.replace(b.clone()) {
794                return Some((r, true));
795            }
796        }
797
798        // Alright we've entirely exhausted our list of candidates. If we've got
799        // something stashed away return that here (also indicating that there's
800        // nothing else).
801        self.has_another.take().map(|r| (r, false))
802    }
803}
804
805/// Attempts to find a new conflict that allows a `find_candidate` better then the input one.
806/// It will add the new conflict to the cache if one is found.
807fn generalize_conflicting(
808    cx: &ResolverContext,
809    registry: &mut RegistryQueryer<'_, impl Registry>,
810    past_conflicting_activations: &mut conflict_cache::ConflictCache,
811    parent: &Summary,
812    dep: &Dependency,
813    conflicting_activations: &ConflictMap,
814) -> Option<ConflictMap> {
815    // We need to determine the `ContextAge` that this `conflicting_activations` will jump to, and why.
816    let (backtrack_critical_age, backtrack_critical_id) = shortcircuit_max(
817        conflicting_activations
818            .keys()
819            .map(|&c| cx.is_active(c).map(|a| (a, c))),
820    )?;
821    let backtrack_critical_reason: ConflictReason =
822        conflicting_activations[&backtrack_critical_id].clone();
823
824    if cx
825        .parents
826        .is_path_from_to(&parent.package_id(), &backtrack_critical_id)
827    {
828        // We are a descendant of the trigger of the problem.
829        // The best generalization of this is to let things bubble up
830        // and let `backtrack_critical_id` figure this out.
831        return None;
832    }
833    // What parents does that critical activation have
834    for (critical_parent, critical_parents_deps) in
835        cx.parents.edges(&backtrack_critical_id).filter(|(p, _)| {
836            // it will only help backjump further if it is older then the critical_age
837            cx.is_active(**p).expect("parent not currently active!?") < backtrack_critical_age
838        })
839    {
840        for critical_parents_dep in critical_parents_deps.iter() {
841            // We only want `first_version.is_some()` for direct dependencies of workspace
842            // members which isn't the case here as this has a `parent`
843            let first_version = None;
844            // A dep is equivalent to one of the things it can resolve to.
845            // Thus, if all the things it can resolve to have already ben determined
846            // to be conflicting, then we can just say that we conflict with the parent.
847            if let Some(others) = registry
848                .query(critical_parents_dep, first_version)
849                .expect("an already used dep now pending!?")
850                .expect("an already used dep now error!?")
851                .iter()
852                .rev() // the last one to be tried is the least likely to be in the cache, so start with that.
853                .map(|other| {
854                    past_conflicting_activations
855                        .find(
856                            dep,
857                            &|id| {
858                                if id == other.package_id() {
859                                    // we are imagining that we used other instead
860                                    Some(backtrack_critical_age)
861                                } else {
862                                    cx.is_active(id)
863                                }
864                            },
865                            Some(other.package_id()),
866                            // we only care about things that are newer then critical_age
867                            backtrack_critical_age,
868                        )
869                        .map(|con| (other.package_id(), con))
870                })
871                .collect::<Option<Vec<(PackageId, &ConflictMap)>>>()
872            {
873                let mut con = conflicting_activations.clone();
874                // It is always valid to combine previously inserted conflicts.
875                // A, B are both known bad states each that can never be activated.
876                // A + B is redundant but can't be activated, as if
877                // A + B is active then A is active and we know that is not ok.
878                for (_, other) in &others {
879                    con.extend(other.iter().map(|(&id, re)| (id, re.clone())));
880                }
881                // Now that we have this combined conflict, we can do a substitution:
882                // A dep is equivalent to one of the things it can resolve to.
883                // So we can remove all the things that it resolves to and replace with the parent.
884                for (other_id, _) in &others {
885                    con.remove(other_id);
886                }
887                con.insert(*critical_parent, backtrack_critical_reason);
888
889                if cfg!(debug_assertions) {
890                    // the entire point is to find an older conflict, so let's make sure we did
891                    let new_age = con
892                        .keys()
893                        .map(|&c| cx.is_active(c).expect("not currently active!?"))
894                        .max()
895                        .unwrap();
896                    assert!(
897                        new_age < backtrack_critical_age,
898                        "new_age {} < backtrack_critical_age {}",
899                        new_age,
900                        backtrack_critical_age
901                    );
902                }
903                past_conflicting_activations.insert(dep, &con);
904                return Some(con);
905            }
906        }
907    }
908    None
909}
910
911/// Returns Some of the largest item in the iterator.
912/// Returns None if any of the items are None or the iterator is empty.
913fn shortcircuit_max<I: Ord>(iter: impl Iterator<Item = Option<I>>) -> Option<I> {
914    let mut out = None;
915    for i in iter {
916        if i.is_none() {
917            return None;
918        }
919        out = std::cmp::max(out, i);
920    }
921    out
922}
923
924/// Looks through the states in `backtrack_stack` for dependencies with
925/// remaining candidates. For each one, also checks if rolling back
926/// could change the outcome of the failed resolution that caused backtracking
927/// in the first place. Namely, if we've backtracked past the parent of the
928/// failed dep, or any of the packages flagged as giving us trouble in
929/// `conflicting_activations`.
930///
931/// Read <https://github.com/rust-lang/cargo/pull/4834>
932/// For several more detailed explanations of the logic here.
933fn find_candidate(
934    cx: &ResolverContext,
935    backtrack_stack: &mut Vec<BacktrackFrame>,
936    parent: &Summary,
937    backtracked: bool,
938    conflicting_activations: &ConflictMap,
939) -> Option<(Summary, bool, BacktrackFrame)> {
940    // When we're calling this method we know that `parent` failed to
941    // activate. That means that some dependency failed to get resolved for
942    // whatever reason. Normally, that means that all of those reasons
943    // (plus maybe some extras) are listed in `conflicting_activations`.
944    //
945    // The abnormal situations are things that do not put all of the reasons in `conflicting_activations`:
946    // If we backtracked we do not know how our `conflicting_activations` related to
947    // the cause of that backtrack, so we do not update it.
948    let age = if !backtracked {
949        // we don't have abnormal situations. So we can ask `cx` for how far back we need to go.
950        // If the `conflicting_activations` does not apply to `cx`,
951        // we will just fall back to laboriously trying all possibilities witch
952        // will give us the correct answer.
953        cx.is_conflicting(Some(parent.package_id()), conflicting_activations)
954    } else {
955        None
956    };
957    let mut new_frame = None;
958    if let Some(age) = age {
959        while let Some(frame) = backtrack_stack.pop() {
960            // If all members of `conflicting_activations` are still
961            // active in this back up we know that we're guaranteed to not actually
962            // make any progress. As a result if we hit this condition we can
963            // completely skip this backtrack frame and move on to the next.
964
965            // Above we use `cx` to determine if this is going to be conflicting.
966            // But lets just double check if the `pop`ed frame agrees.
967            let frame_too_new = frame.context.age >= age;
968            debug_assert!(
969                frame
970                    .context
971                    .is_conflicting(Some(parent.package_id()), conflicting_activations)
972                    == frame_too_new.then_some(age)
973            );
974
975            if !frame_too_new {
976                new_frame = Some(frame);
977                break;
978            }
979            trace!(
980                "{} = \"{}\" skip as not solving {}: {:?}",
981                frame.dep.package_name(),
982                frame.dep.version_req(),
983                parent.package_id(),
984                conflicting_activations
985            );
986        }
987    } else {
988        // If we're here then we are in abnormal situations and need to just go one frame at a time.
989        new_frame = backtrack_stack.pop();
990    }
991
992    new_frame.map(|mut frame| {
993        let (candidate, has_another) = frame
994            .remaining_candidates
995            .next(&mut frame.conflicting_activations, &frame.context)
996            .expect("why did we save a frame that has no next?");
997        (candidate, has_another, frame)
998    })
999}
1000
1001fn check_cycles(resolve: &Resolve) -> CargoResult<()> {
1002    // Perform a simple cycle check by visiting all nodes.
1003    // We visit each node at most once and we keep
1004    // track of the path through the graph as we walk it. If we walk onto the
1005    // same node twice that's a cycle.
1006    let mut checked = HashSet::with_capacity(resolve.len());
1007    let mut path = Vec::with_capacity(4);
1008    let mut visited = HashSet::with_capacity(4);
1009    for pkg in resolve.iter() {
1010        if !checked.contains(&pkg) {
1011            visit(&resolve, pkg, &mut visited, &mut path, &mut checked)?
1012        }
1013    }
1014    return Ok(());
1015
1016    fn visit(
1017        resolve: &Resolve,
1018        id: PackageId,
1019        visited: &mut HashSet<PackageId>,
1020        path: &mut Vec<PackageId>,
1021        checked: &mut HashSet<PackageId>,
1022    ) -> CargoResult<()> {
1023        if !visited.insert(id) {
1024            // We found a cycle and need to construct an error. Performance is no longer top priority.
1025            let iter = path.iter().rev().scan(id, |child, parent| {
1026                let dep = resolve.transitive_deps_not_replaced(*parent).find_map(
1027                    |(dep_id, transitive_dep)| {
1028                        (*child == dep_id || Some(*child) == resolve.replacement(dep_id))
1029                            .then_some(transitive_dep)
1030                    },
1031                );
1032                *child = *parent;
1033                Some((parent, dep))
1034            });
1035            let iter = std::iter::once((&id, None)).chain(iter);
1036            let describe_path = errors::describe_path(iter);
1037            anyhow::bail!(
1038                "cyclic package dependency: package `{id}` depends on itself. Cycle:\n{describe_path}"
1039            );
1040        }
1041
1042        if checked.insert(id) {
1043            path.push(id);
1044            for (dep_id, _transitive_dep) in resolve.transitive_deps_not_replaced(id) {
1045                visit(resolve, dep_id, visited, path, checked)?;
1046                if let Some(replace_id) = resolve.replacement(dep_id) {
1047                    visit(resolve, replace_id, visited, path, checked)?;
1048                }
1049            }
1050            path.pop();
1051        }
1052
1053        visited.remove(&id);
1054        Ok(())
1055    }
1056}
1057
1058/// Checks that packages are unique when written to lock file.
1059///
1060/// When writing package ID's to lock file, we apply lossy encoding. In
1061/// particular, we don't store paths of path dependencies. That means that
1062/// *different* packages may collide in the lock file, hence this check.
1063fn check_duplicate_pkgs_in_lockfile(resolve: &Resolve) -> CargoResult<()> {
1064    let mut unique_pkg_ids = HashMap::new();
1065    let state = encode::EncodeState::new(resolve);
1066    for pkg_id in resolve.iter() {
1067        let encodable_pkd_id = encode::encodable_package_id(pkg_id, &state, resolve.version());
1068        if let Some(prev_pkg_id) = unique_pkg_ids.insert(encodable_pkd_id, pkg_id) {
1069            anyhow::bail!(
1070                "package collision in the lockfile: packages {} and {} are different, \
1071                 but only one can be written to lockfile unambiguously",
1072                prev_pkg_id,
1073                pkg_id
1074            )
1075        }
1076    }
1077    Ok(())
1078}