Skip to main content

cargo/compiler/
unit_dependencies.rs

1//! Constructs the dependency graph for compilation.
2//!
3//! Rust code is typically organized as a set of Cargo packages. The
4//! dependencies between the packages themselves are stored in the
5//! [`Resolve`] struct. However, we can't use that information as is for
6//! compilation! A package typically contains several targets, or crates,
7//! and these targets has inter-dependencies. For example, you need to
8//! compile the `lib` target before the `bin` one, and you need to compile
9//! `build.rs` before either of those.
10//!
11//! So, we need to lower the `Resolve`, which specifies dependencies between
12//! *packages*, to a graph of dependencies between their *targets*, and this
13//! is exactly what this module is doing! Well, almost exactly: another
14//! complication is that we might want to compile the same target several times
15//! (for example, with and without tests), so we actually build a dependency
16//! graph of [`Unit`]s, which capture these properties.
17
18use cargo_util::collections::{HashMap, HashSet};
19
20use cargo_util_schemas::core::CrateType;
21use tracing::trace;
22
23use crate::CargoResult;
24use crate::compiler::UserIntent;
25use crate::compiler::artifact::match_artifacts_kind_with_targets;
26use crate::compiler::unit_graph::{UnitDep, UnitGraph};
27use crate::compiler::{CompileKind, CompileMode, RustcTargetData, Unit, UnitInterner};
28use crate::ops::resolve_all_features;
29use crate::resolver::features::{FeaturesFor, ResolvedFeatures};
30use crate::resolver::{ForceAllTargets, HasDevUnits, Resolve};
31use crate::util::GlobalContext;
32use crate::util::Unhashed;
33use crate::util::interning::InternedString;
34use crate::workspace::dependency::{Artifact, ArtifactKind, ArtifactTarget, DepKind};
35use crate::workspace::profiles::{Profile, Profiles, UnitFor};
36use crate::workspace::{
37    Dependency, Feature, Package, PackageId, PackageSet, Target, TargetKind, Workspace,
38};
39
40const IS_NO_ARTIFACT_DEP: Option<&'static Artifact> = None;
41
42/// Collection of stuff used while creating the [`UnitGraph`].
43struct State<'a, 'gctx> {
44    ws: &'a Workspace<'gctx>,
45    gctx: &'gctx GlobalContext,
46    /// Stores the result of building the [`UnitGraph`].
47    unit_dependencies: UnitGraph,
48    package_set: &'a PackageSet<'gctx>,
49    usr_resolve: &'a Resolve,
50    usr_features: &'a ResolvedFeatures,
51    /// Like `usr_resolve` but for building standard library (`-Zbuild-std`).
52    std_resolve: Option<&'a Resolve>,
53    /// Like `usr_features` but for building standard library (`-Zbuild-std`).
54    std_features: Option<&'a ResolvedFeatures>,
55    /// `true` while generating the dependencies for the standard library.
56    is_std: bool,
57    /// The high-level operation requested by the user.
58    /// Used for preventing from building lib thrice.
59    intent: UserIntent,
60    target_data: &'a RustcTargetData<'gctx>,
61    profiles: &'a Profiles,
62    interner: &'a UnitInterner,
63    // Units for `-Zrustdoc-scrape-examples`.
64    scrape_units: &'a [Unit],
65
66    /// A set of edges in `unit_dependencies` where (a, b) means that the
67    /// dependency from a to b was added purely because it was a dev-dependency.
68    /// This is used during `connect_run_custom_build_deps`.
69    dev_dependency_edges: HashSet<(Unit, Unit)>,
70}
71
72/// A boolean-like to indicate if a `Unit` is an artifact or not.
73#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
74pub enum IsArtifact {
75    Yes,
76    No,
77}
78
79impl IsArtifact {
80    pub fn is_true(&self) -> bool {
81        matches!(self, IsArtifact::Yes)
82    }
83}
84
85/// Then entry point for building a dependency graph of compilation units.
86///
87/// You can find some information for arguments from doc of [`State`].
88#[tracing::instrument(skip_all)]
89pub fn build_unit_dependencies<'a, 'gctx>(
90    ws: &'a Workspace<'gctx>,
91    package_set: &'a PackageSet<'gctx>,
92    resolve: &'a Resolve,
93    features: &'a ResolvedFeatures,
94    std_resolve: Option<&'a (Resolve, ResolvedFeatures)>,
95    roots: &[Unit],
96    scrape_units: &[Unit],
97    std_roots: &HashMap<CompileKind, Vec<Unit>>,
98    intent: UserIntent,
99    target_data: &'a RustcTargetData<'gctx>,
100    profiles: &'a Profiles,
101    interner: &'a UnitInterner,
102) -> CargoResult<UnitGraph> {
103    if roots.is_empty() {
104        // If -Zbuild-std, don't attach units if there is nothing to build.
105        // Otherwise, other parts of the code may be confused by seeing units
106        // in the dep graph without a root.
107        return Ok(HashMap::default());
108    }
109    let (std_resolve, std_features) = match std_resolve {
110        Some((r, f)) => (Some(r), Some(f)),
111        None => (None, None),
112    };
113    let mut state = State {
114        ws,
115        gctx: ws.gctx(),
116        unit_dependencies: HashMap::default(),
117        package_set,
118        usr_resolve: resolve,
119        usr_features: features,
120        std_resolve,
121        std_features,
122        is_std: false,
123        intent,
124        target_data,
125        profiles,
126        interner,
127        scrape_units,
128        dev_dependency_edges: HashSet::default(),
129    };
130
131    let std_unit_deps = calc_deps_of_std(&mut state, std_roots)?;
132
133    deps_of_roots(roots, &mut state)?;
134    super::links::validate_links(state.resolve(), &state.unit_dependencies)?;
135    // Hopefully there aren't any links conflicts with the standard library?
136
137    if let Some(std_unit_deps) = std_unit_deps {
138        attach_std_deps(&mut state, std_roots, std_unit_deps);
139    }
140
141    connect_run_custom_build_deps(&mut state);
142
143    // Dependencies are used in tons of places throughout the backend, many of
144    // which affect the determinism of the build itself. As a result be sure
145    // that dependency lists are always sorted to ensure we've always got a
146    // deterministic output.
147    for (unit, list) in &mut state.unit_dependencies {
148        let is_multiple_build_scripts_enabled = unit
149            .pkg
150            .manifest()
151            .unstable_features()
152            .require(Feature::multiple_build_scripts())
153            .is_ok();
154
155        if is_multiple_build_scripts_enabled {
156            list.sort_by_key(|unit_dep| {
157                if unit_dep.unit.target.is_custom_build() {
158                    // We do not sort build scripts to preserve the user-defined order.
159                    // In terms of determinism, we are assuming nothing interferes with order from when the user set it in `Cargo.toml` to here
160                    (0, None)
161                } else {
162                    (1, Some(unit_dep.clone()))
163                }
164            });
165        } else {
166            list.sort();
167        }
168    }
169
170    log_unit_deps_graph(ws.gctx(), &state.unit_dependencies);
171
172    Ok(state.unit_dependencies)
173}
174
175fn log_unit_deps_graph(gctx: &GlobalContext, graph: &UnitGraph) {
176    // For workspaces with large dependency graphs, the act of logging graph can actually take
177    // hundreds of milliseconds, skewing the profiling timings. By default, we do not dump the
178    // entire graph to avoid skewing the timings.
179    let graph_to_log = if gctx.get_env("__CARGO_DUMP_UNIT_DEP_GRAPH").unwrap_or("0") == "1" {
180        Some(graph)
181    } else {
182        None
183    };
184
185    trace!(
186        count = graph.len(),
187        graph = format!("{graph_to_log:#?}"),
188        "ALL UNIT DEPENDENCIES",
189    );
190}
191
192/// Compute all the dependencies for the standard library.
193fn calc_deps_of_std(
194    state: &mut State<'_, '_>,
195    std_roots: &HashMap<CompileKind, Vec<Unit>>,
196) -> CargoResult<Option<UnitGraph>> {
197    if std_roots.is_empty() {
198        return Ok(None);
199    }
200    // Compute dependencies for the standard library.
201    state.is_std = true;
202    for roots in std_roots.values() {
203        deps_of_roots(roots, state)?;
204    }
205    state.is_std = false;
206    Ok(Some(std::mem::take(&mut state.unit_dependencies)))
207}
208
209/// Add the standard library units to the `unit_dependencies`.
210fn attach_std_deps(
211    state: &mut State<'_, '_>,
212    std_roots: &HashMap<CompileKind, Vec<Unit>>,
213    std_unit_deps: UnitGraph,
214) {
215    // Attach the standard library as a dependency of every target unit.
216    let mut found = false;
217    for (unit, deps) in state.unit_dependencies.iter_mut() {
218        if !unit.kind.is_host() && !unit.mode.is_run_custom_build() {
219            deps.extend(std_roots[&unit.kind].iter().map(|unit| UnitDep {
220                unit: unit.clone(),
221                unit_for: UnitFor::new_normal(unit.kind),
222                extern_crate_name: unit.pkg.name(),
223                dep_name: None,
224                // TODO: Does this `public` make sense?
225                public: true,
226                noprelude: true,
227                nounused: true,
228                // Artificial dependency
229                manifest_deps: Unhashed(None),
230            }));
231            found = true;
232        }
233    }
234    // And also include the dependencies of the standard library itself. Don't
235    // include these if no units actually needed the standard library.
236    if found {
237        for (unit, deps) in std_unit_deps.into_iter() {
238            if let Some(other_unit) = state.unit_dependencies.insert(unit, deps) {
239                panic!("std unit collision with existing unit: {:?}", other_unit);
240            }
241        }
242    }
243}
244
245/// Compute all the dependencies of the given root units.
246/// The result is stored in `state.unit_dependencies`.
247fn deps_of_roots(roots: &[Unit], state: &mut State<'_, '_>) -> CargoResult<()> {
248    for unit in roots.iter() {
249        // Dependencies of tests/benches should not have `panic` set.
250        // We check the user intent to see if we are running in `cargo test` in
251        // which case we ensure all dependencies have `panic` cleared, and
252        // avoid building the lib thrice (once with `panic`, once without, once
253        // for `--test`). In particular, the lib included for Doc tests and
254        // examples are `Build` mode here.
255        let root_compile_kind = unit.kind;
256        let unit_for = if unit.mode.is_any_test() || state.intent.is_rustc_test() {
257            if unit.target.proc_macro() {
258                // Special-case for proc-macros, which are forced to for-host
259                // since they need to link with the proc_macro crate.
260                UnitFor::new_host_test(state.gctx, root_compile_kind)
261            } else {
262                UnitFor::new_test(state.gctx, root_compile_kind)
263            }
264        } else if unit.target.is_custom_build() {
265            // This normally doesn't happen, except `clean` aggressively
266            // generates all units.
267            UnitFor::new_host(false, root_compile_kind)
268        } else if unit.target.proc_macro() {
269            UnitFor::new_host(true, root_compile_kind)
270        } else if unit.target.for_host() {
271            // Plugin should never have panic set.
272            UnitFor::new_compiler(root_compile_kind)
273        } else {
274            UnitFor::new_normal(root_compile_kind)
275        };
276        deps_of(unit, state, unit_for)?;
277    }
278
279    Ok(())
280}
281
282/// Compute the dependencies of a single unit, recursively computing all
283/// transitive dependencies.
284///
285/// The result is stored in `state.unit_dependencies`.
286fn deps_of(unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor) -> CargoResult<()> {
287    // Currently the `unit_dependencies` map does not include `unit_for`. This should
288    // be safe for now. `TestDependency` only exists to clear the `panic`
289    // flag, and you'll never ask for a `unit` with `panic` set as a
290    // `TestDependency`. `CustomBuild` should also be fine since if the
291    // requested unit's settings are the same as `Any`, `CustomBuild` can't
292    // affect anything else in the hierarchy.
293    if !state.unit_dependencies.contains_key(unit) {
294        let unit_deps = compute_deps(unit, state, unit_for)?;
295        state
296            .unit_dependencies
297            .insert(unit.clone(), unit_deps.clone());
298        for unit_dep in unit_deps {
299            deps_of(&unit_dep.unit, state, unit_dep.unit_for)?;
300        }
301    }
302    Ok(())
303}
304
305/// Returns the direct unit dependencies for the given `Unit`.
306fn compute_deps(
307    unit: &Unit,
308    state: &mut State<'_, '_>,
309    unit_for: UnitFor,
310) -> CargoResult<Vec<UnitDep>> {
311    if unit.mode.is_run_custom_build() {
312        return compute_deps_custom_build(unit, unit_for, state);
313    } else if unit.mode.is_doc() {
314        // Note: this does not include doc test.
315        return compute_deps_doc(unit, state, unit_for);
316    }
317
318    let mut ret = Vec::new();
319    let mut dev_deps = Vec::new();
320    for (dep_pkg_id, deps) in state.deps(unit, unit_for) {
321        let Some(dep_lib) = calc_artifact_deps(unit, unit_for, dep_pkg_id, &deps, state, &mut ret)?
322        else {
323            continue;
324        };
325        let dep_pkg = state.get(dep_pkg_id);
326        let mode = check_or_build_mode(unit.mode, dep_lib);
327        let dep_unit_for = unit_for.with_dependency(unit, dep_lib, unit_for.root_compile_kind());
328
329        let manifest_deps = deps.iter().map(|d| (*d).clone()).collect::<Vec<_>>();
330
331        let start = ret.len();
332        if state.gctx.cli_unstable().dual_proc_macros
333            && dep_lib.proc_macro()
334            && !unit.kind.is_host()
335        {
336            let unit_dep = new_unit_dep(
337                state,
338                unit,
339                dep_pkg,
340                dep_lib,
341                Some(manifest_deps.clone()),
342                dep_unit_for,
343                unit.kind,
344                mode,
345                IS_NO_ARTIFACT_DEP,
346            )?;
347            ret.push(unit_dep);
348            let unit_dep = new_unit_dep(
349                state,
350                unit,
351                dep_pkg,
352                dep_lib,
353                Some(manifest_deps),
354                dep_unit_for,
355                CompileKind::Host,
356                mode,
357                IS_NO_ARTIFACT_DEP,
358            )?;
359            ret.push(unit_dep);
360        } else {
361            let unit_dep = new_unit_dep(
362                state,
363                unit,
364                dep_pkg,
365                dep_lib,
366                Some(manifest_deps),
367                dep_unit_for,
368                unit.kind.for_target(dep_lib),
369                mode,
370                IS_NO_ARTIFACT_DEP,
371            )?;
372            ret.push(unit_dep);
373        }
374
375        // If the unit added was a dev-dependency unit, then record that in the
376        // dev-dependencies array. We'll add this to
377        // `state.dev_dependency_edges` at the end and process it later in
378        // `connect_run_custom_build_deps`.
379        if deps.iter().all(|d| !d.is_transitive()) {
380            for dep in ret[start..].iter() {
381                dev_deps.push((unit.clone(), dep.unit.clone()));
382            }
383        }
384    }
385    state.dev_dependency_edges.extend(dev_deps);
386
387    // If this target is a build script, then what we've collected so far is
388    // all we need. If this isn't a build script, then it depends on the
389    // build script if there is one.
390    if unit.target.is_custom_build() {
391        return Ok(ret);
392    }
393    ret.extend(
394        dep_build_script(unit, unit_for, state)?
395            .into_iter()
396            .flatten(),
397    );
398
399    // If this target is a binary, test, example, etc, then it depends on
400    // the library of the same package. The call to `resolve.deps` above
401    // didn't include `pkg` in the return values, so we need to special case
402    // it here and see if we need to push `(pkg, pkg_lib_target)`.
403    if unit.target.is_lib() && unit.mode != CompileMode::Doctest {
404        return Ok(ret);
405    }
406    ret.extend(maybe_lib(unit, state, unit_for)?);
407
408    // If any integration tests/benches are being run, make sure that
409    // binaries are built as well.
410    if !unit.mode.is_check()
411        && unit.mode.is_any_test()
412        && (unit.target.is_test() || unit.target.is_bench())
413    {
414        let id = unit.pkg.package_id();
415        ret.extend(
416            unit.pkg
417                .targets()
418                .iter()
419                .filter(|t| {
420                    // Skip binaries with required features that have not been selected.
421                    match t.required_features() {
422                        Some(rf) if t.is_bin() => {
423                            let features = resolve_all_features(
424                                state.resolve(),
425                                state.features(),
426                                state.package_set,
427                                id,
428                                HasDevUnits::No,
429                                &[unit.kind],
430                                state.target_data,
431                                ForceAllTargets::No,
432                            );
433                            rf.iter().all(|f| features.contains(f))
434                        }
435                        None if t.is_bin() => true,
436                        _ => false,
437                    }
438                })
439                .map(|t| {
440                    new_unit_dep(
441                        state,
442                        unit,
443                        &unit.pkg,
444                        t,
445                        None, // artificial
446                        UnitFor::new_normal(unit_for.root_compile_kind()),
447                        unit.kind.for_target(t),
448                        CompileMode::Build,
449                        IS_NO_ARTIFACT_DEP,
450                    )
451                })
452                .collect::<CargoResult<Vec<UnitDep>>>()?,
453        );
454    }
455
456    Ok(ret)
457}
458
459/// Find artifacts for all `deps` of `unit` and add units that build these artifacts
460/// to `ret`.
461fn calc_artifact_deps<'a>(
462    unit: &Unit,
463    unit_for: UnitFor,
464    dep_id: PackageId,
465    deps: &[&Dependency],
466    state: &State<'a, '_>,
467    ret: &mut Vec<UnitDep>,
468) -> CargoResult<Option<&'a Target>> {
469    let mut has_artifact_lib = false;
470    let mut maybe_non_artifact_lib = false;
471    let artifact_pkg = state.get(dep_id);
472    for dep in deps {
473        let Some(artifact) = dep.artifact() else {
474            maybe_non_artifact_lib = true;
475            continue;
476        };
477        has_artifact_lib |= artifact.is_lib();
478        // Custom build scripts (build/compile) never get artifact dependencies,
479        // but the run-build-script step does (where it is handled).
480        if !unit.target.is_custom_build() {
481            debug_assert!(
482                !unit.mode.is_run_custom_build(),
483                "BUG: This should be handled in a separate branch"
484            );
485            ret.extend(artifact_targets_to_unit_deps(
486                unit,
487                unit_for.with_artifact_features(artifact),
488                state,
489                artifact
490                    .target()
491                    .and_then(|t| match t {
492                        ArtifactTarget::BuildDependencyAssumeTarget => None,
493                        ArtifactTarget::Force(kind) => Some(CompileKind::Target(kind)),
494                    })
495                    .unwrap_or(unit.kind),
496                artifact_pkg,
497                dep,
498            )?);
499        }
500    }
501    if has_artifact_lib || maybe_non_artifact_lib {
502        Ok(artifact_pkg.targets().iter().find(|t| t.is_lib()))
503    } else {
504        Ok(None)
505    }
506}
507
508/// Returns the dependencies needed to run a build script.
509///
510/// The `unit` provided must represent an execution of a build script, and
511/// the returned set of units must all be run before `unit` is run.
512fn compute_deps_custom_build(
513    unit: &Unit,
514    unit_for: UnitFor,
515    state: &State<'_, '_>,
516) -> CargoResult<Vec<UnitDep>> {
517    if let Some(links) = unit.pkg.manifest().links() {
518        if unit.links_overrides.get(links).is_some() {
519            // Overridden build scripts don't have any dependencies.
520            return Ok(Vec::new());
521        }
522    }
523    // All dependencies of this unit should use profiles for custom builds.
524    // If this is a build script of a proc macro, make sure it uses host
525    // features.
526    let script_unit_for = unit_for.for_custom_build();
527    // When not overridden, then the dependencies to run a build script are:
528    //
529    // 1. Compiling the build script itself.
530    // 2. For each immediate dependency of our package which has a `links`
531    //    key, the execution of that build script.
532    //
533    // We don't have a great way of handling (2) here right now so this is
534    // deferred until after the graph of all unit dependencies has been
535    // constructed.
536    let compile_script_unit = new_unit_dep(
537        state,
538        unit,
539        &unit.pkg,
540        &unit.target,
541        None, // artificial
542        script_unit_for,
543        // Build scripts always compiled for the host.
544        CompileKind::Host,
545        CompileMode::Build,
546        IS_NO_ARTIFACT_DEP,
547    )?;
548
549    let mut result = vec![compile_script_unit];
550
551    // Include any artifact dependencies.
552    //
553    // This is essentially the same as `calc_artifact_deps`, but there are some
554    // subtle differences that require this to be implemented differently.
555    //
556    // Produce units that build all required artifact kinds (like binaries,
557    // static libraries, etc) with the correct compile target.
558    //
559    // Computing the compile target for artifact units is more involved as it has to handle
560    // various target configurations specific to artifacts, like `target = "target"` and
561    // `target = "<tuple>"`, which makes knowing the root units compile target
562    // `root_unit_compile_target` necessary.
563    let root_unit_compile_target = unit_for.root_compile_kind();
564    let unit_for = UnitFor::new_host(/*host_features*/ true, root_unit_compile_target);
565    for (dep_pkg_id, deps) in state.deps(unit, script_unit_for) {
566        for dep in deps {
567            if dep.kind() != DepKind::Build || dep.artifact().is_none() {
568                continue;
569            }
570            let artifact_pkg = state.get(dep_pkg_id);
571            let artifact = dep.artifact().expect("artifact dep");
572            let resolved_artifact_compile_kind = artifact
573                .target()
574                .map(|target| target.to_resolved_compile_kind(root_unit_compile_target));
575
576            result.extend(artifact_targets_to_unit_deps(
577                unit,
578                unit_for.with_artifact_features_from_resolved_compile_kind(
579                    resolved_artifact_compile_kind,
580                ),
581                state,
582                resolved_artifact_compile_kind.unwrap_or(CompileKind::Host),
583                artifact_pkg,
584                dep,
585            )?);
586        }
587    }
588
589    Ok(result)
590}
591
592/// Given a `parent` unit containing a dependency `dep` whose package is `artifact_pkg`,
593/// find all targets in `artifact_pkg` which refer to the `dep`s artifact declaration
594/// and turn them into units.
595/// Due to the nature of artifact dependencies, a single dependency in a manifest can
596/// cause one or more targets to be build, for instance with
597/// `artifact = ["bin:a", "bin:b", "staticlib"]`, which is very different from normal
598/// dependencies which cause only a single unit to be created.
599///
600/// `compile_kind` is the computed kind for the future artifact unit
601/// dependency, only the caller can pick the correct one.
602fn artifact_targets_to_unit_deps(
603    parent: &Unit,
604    parent_unit_for: UnitFor,
605    state: &State<'_, '_>,
606    compile_kind: CompileKind,
607    artifact_pkg: &Package,
608    dep: &Dependency,
609) -> CargoResult<Vec<UnitDep>> {
610    let ret =
611        match_artifacts_kind_with_targets(dep, artifact_pkg.targets(), parent.pkg.name().as_str())?
612            .into_iter()
613            .flat_map(|(artifact_kind, target)| {
614                // We split target libraries into individual units, even though rustc is able
615                // to produce multiple kinds in a single invocation for the sole reason that
616                // each artifact kind has its own output directory, something we can't easily
617                // teach rustc for now.
618                match target.kind() {
619                    TargetKind::Lib(kinds) => Box::new(
620                        kinds
621                            .iter()
622                            .filter(move |tk| match (tk, artifact_kind) {
623                                (CrateType::Cdylib, ArtifactKind::Cdylib) => true,
624                                (CrateType::Staticlib, ArtifactKind::Staticlib) => true,
625                                _ => false,
626                            })
627                            .map(|target_kind| {
628                                new_unit_dep(
629                                    state,
630                                    parent,
631                                    artifact_pkg,
632                                    target
633                                        .clone()
634                                        .set_kind(TargetKind::Lib(vec![target_kind.clone()])),
635                                    None, // TBD
636                                    parent_unit_for,
637                                    compile_kind,
638                                    CompileMode::Build,
639                                    dep.artifact(),
640                                )
641                            }),
642                    ) as Box<dyn Iterator<Item = _>>,
643                    _ => Box::new(std::iter::once(new_unit_dep(
644                        state,
645                        parent,
646                        artifact_pkg,
647                        target,
648                        None, // TBD
649                        parent_unit_for,
650                        compile_kind,
651                        CompileMode::Build,
652                        dep.artifact(),
653                    ))),
654                }
655            })
656            .collect::<Result<Vec<_>, _>>()?;
657    Ok(ret)
658}
659
660/// Returns the dependencies necessary to document a package.
661fn compute_deps_doc(
662    unit: &Unit,
663    state: &mut State<'_, '_>,
664    unit_for: UnitFor,
665) -> CargoResult<Vec<UnitDep>> {
666    // To document a library, we depend on dependencies actually being
667    // built. If we're documenting *all* libraries, then we also depend on
668    // the documentation of the library being built.
669    let mut ret = Vec::new();
670    for (id, deps) in state.deps(unit, unit_for) {
671        let Some(dep_lib) = calc_artifact_deps(unit, unit_for, id, &deps, state, &mut ret)? else {
672            continue;
673        };
674        let dep_pkg = state.get(id);
675        // Rustdoc only needs rmeta files for regular dependencies.
676        // However, for plugins/proc macros, deps should be built like normal.
677        let mode = check_or_build_mode(unit.mode, dep_lib);
678        let dep_unit_for = unit_for.with_dependency(unit, dep_lib, unit_for.root_compile_kind());
679        let lib_unit_dep = new_unit_dep(
680            state,
681            unit,
682            dep_pkg,
683            dep_lib,
684            None, // not checking unused deps
685            dep_unit_for,
686            unit.kind.for_target(dep_lib),
687            mode,
688            IS_NO_ARTIFACT_DEP,
689        )?;
690        ret.push(lib_unit_dep);
691        if dep_lib.documented() && state.intent.wants_deps_docs() {
692            // Document this lib as well.
693            let doc_unit_dep = new_unit_dep(
694                state,
695                unit,
696                dep_pkg,
697                dep_lib,
698                None, // not checking unused deps
699                dep_unit_for,
700                unit.kind.for_target(dep_lib),
701                unit.mode,
702                IS_NO_ARTIFACT_DEP,
703            )?;
704            ret.push(doc_unit_dep);
705        }
706    }
707
708    // Be sure to build/run the build script for documented libraries.
709    ret.extend(
710        dep_build_script(unit, unit_for, state)?
711            .into_iter()
712            .flatten(),
713    );
714
715    // If we document a binary/example, we need the library available.
716    if unit.target.is_bin() || unit.target.is_example() {
717        // build the lib
718        ret.extend(maybe_lib(unit, state, unit_for)?);
719        // and also the lib docs for intra-doc links
720        if let Some(lib) = unit
721            .pkg
722            .targets()
723            .iter()
724            .find(|t| t.is_linkable() && t.documented())
725        {
726            let dep_unit_for = unit_for.with_dependency(unit, lib, unit_for.root_compile_kind());
727            let lib_doc_unit = new_unit_dep(
728                state,
729                unit,
730                &unit.pkg,
731                lib,
732                None, // not checking unused deps
733                dep_unit_for,
734                unit.kind.for_target(lib),
735                unit.mode,
736                IS_NO_ARTIFACT_DEP,
737            )?;
738            ret.push(lib_doc_unit);
739        }
740    }
741
742    // Add all units being scraped for examples as a dependency of top-level Doc units.
743    if state.ws.unit_needs_doc_scrape(unit) {
744        for scrape_unit in state.scrape_units.iter() {
745            let scrape_unit_for = UnitFor::new_normal(scrape_unit.kind);
746            deps_of(scrape_unit, state, scrape_unit_for)?;
747            ret.push(new_unit_dep(
748                state,
749                scrape_unit,
750                &scrape_unit.pkg,
751                &scrape_unit.target,
752                None, // not checking unused deps
753                scrape_unit_for,
754                scrape_unit.kind,
755                scrape_unit.mode,
756                IS_NO_ARTIFACT_DEP,
757            )?);
758        }
759    }
760
761    Ok(ret)
762}
763
764fn maybe_lib(
765    unit: &Unit,
766    state: &mut State<'_, '_>,
767    unit_for: UnitFor,
768) -> CargoResult<Option<UnitDep>> {
769    unit.pkg
770        .targets()
771        .iter()
772        .find(|t| t.is_linkable())
773        .map(|t| {
774            let mode = check_or_build_mode(unit.mode, t);
775            let dep_unit_for = unit_for.with_dependency(unit, t, unit_for.root_compile_kind());
776            new_unit_dep(
777                state,
778                unit,
779                &unit.pkg,
780                t,
781                None,
782                dep_unit_for,
783                unit.kind.for_target(t),
784                mode,
785                IS_NO_ARTIFACT_DEP,
786            )
787        })
788        .transpose()
789}
790
791/// If a build script is scheduled to be run for the package specified by
792/// `unit`, this function will return the unit to run that build script.
793///
794/// Overriding a build script simply means that the running of the build
795/// script itself doesn't have any dependencies, so even in that case a unit
796/// of work is still returned. `None` is only returned if the package has no
797/// build script.
798fn dep_build_script(
799    unit: &Unit,
800    unit_for: UnitFor,
801    state: &State<'_, '_>,
802) -> CargoResult<Option<Vec<UnitDep>>> {
803    Some(
804        unit.pkg
805            .targets()
806            .iter()
807            .filter(|t| t.is_custom_build())
808            .map(|t| {
809                // The profile stored in the Unit is the profile for the thing
810                // the custom build script is running for.
811                let profile = state.profiles.get_profile_run_custom_build(&unit.profile);
812                // UnitFor::for_custom_build is used because we want the `host` flag set
813                // for all of our build dependencies (so they all get
814                // build-override profiles), including compiling the build.rs
815                // script itself.
816                //
817                // If `is_for_host_features` here is `false`, that means we are a
818                // build.rs script for a normal dependency and we want to set the
819                // CARGO_FEATURE_* environment variables to the features as a
820                // normal dep.
821                //
822                // If `is_for_host_features` here is `true`, that means that this
823                // package is being used as a build dependency or proc-macro, and
824                // so we only want to set CARGO_FEATURE_* variables for the host
825                // side of the graph.
826                //
827                // Keep in mind that the RunCustomBuild unit and the Compile
828                // build.rs unit use the same features. This is because some
829                // people use `cfg!` and `#[cfg]` expressions to check for enabled
830                // features instead of just checking `CARGO_FEATURE_*` at runtime.
831                // In the case with the new feature resolver (decoupled host
832                // deps), and a shared dependency has different features enabled
833                // for normal vs. build, then the build.rs script will get
834                // compiled twice. I believe it is not feasible to only build it
835                // once because it would break a large number of scripts (they
836                // would think they have the wrong set of features enabled).
837                let script_unit_for = unit_for.for_custom_build();
838                new_unit_dep_with_profile(
839                    state,
840                    unit,
841                    &unit.pkg,
842                    t,
843                    None, // artificial
844                    script_unit_for,
845                    unit.kind,
846                    CompileMode::RunCustomBuild,
847                    profile,
848                    IS_NO_ARTIFACT_DEP,
849                )
850            })
851            .collect(),
852    )
853    .transpose()
854}
855
856/// Choose the correct mode for dependencies.
857fn check_or_build_mode(mode: CompileMode, target: &Target) -> CompileMode {
858    match mode {
859        CompileMode::Check { .. } | CompileMode::Doc { .. } | CompileMode::Docscrape => {
860            if target.for_host() {
861                // Plugin and proc macro targets should be compiled like
862                // normal.
863                CompileMode::Build
864            } else {
865                // Regular dependencies should not be checked with --test.
866                // Regular dependencies of doc targets should emit rmeta only.
867                CompileMode::Check { test: false }
868            }
869        }
870        _ => CompileMode::Build,
871    }
872}
873
874/// Create a new Unit for a dependency from `parent` to `pkg` and `target`.
875fn new_unit_dep(
876    state: &State<'_, '_>,
877    parent: &Unit,
878    pkg: &Package,
879    target: &Target,
880    manifest_deps: Option<Vec<Dependency>>,
881    unit_for: UnitFor,
882    kind: CompileKind,
883    mode: CompileMode,
884    artifact: Option<&Artifact>,
885) -> CargoResult<UnitDep> {
886    let is_local = pkg.package_id().source_id().is_path() && !state.is_std;
887    let profile = state.profiles.get_profile(
888        pkg.package_id(),
889        pkg.hints(),
890        state.ws.is_member(pkg),
891        is_local,
892        unit_for,
893        kind,
894    );
895    new_unit_dep_with_profile(
896        state,
897        parent,
898        pkg,
899        target,
900        manifest_deps,
901        unit_for,
902        kind,
903        mode,
904        profile,
905        artifact,
906    )
907}
908
909fn new_unit_dep_with_profile(
910    state: &State<'_, '_>,
911    parent: &Unit,
912    pkg: &Package,
913    target: &Target,
914    manifest_deps: Option<Vec<Dependency>>,
915    unit_for: UnitFor,
916    kind: CompileKind,
917    mode: CompileMode,
918    profile: Profile,
919    artifact: Option<&Artifact>,
920) -> CargoResult<UnitDep> {
921    let (extern_crate_name, dep_name) = state.resolve().extern_crate_name_and_dep_name(
922        parent.pkg.package_id(),
923        pkg.package_id(),
924        target,
925    )?;
926    let public = state
927        .resolve()
928        .is_public_dep(parent.pkg.package_id(), pkg.package_id());
929    let features_for = unit_for.map_to_features_for(artifact);
930    let artifact_target = match features_for {
931        FeaturesFor::ArtifactDep(target) => Some(target),
932        _ => None,
933    };
934    let features = state.activated_features(pkg.package_id(), features_for);
935    let unit = state.interner.intern(
936        pkg,
937        target,
938        profile,
939        kind,
940        mode,
941        features,
942        state.target_data.info(kind).rustflags.clone(),
943        state.target_data.info(kind).rustdocflags.clone(),
944        state
945            .target_data
946            .target_config(kind)
947            .links_overrides
948            .clone(),
949        state.is_std,
950        /*dep_hash*/ 0,
951        artifact.map_or(IsArtifact::No, |_| IsArtifact::Yes),
952        artifact_target,
953        false,
954    );
955    Ok(UnitDep {
956        unit,
957        unit_for,
958        extern_crate_name,
959        dep_name,
960        public,
961        noprelude: false,
962        nounused: false,
963        manifest_deps: Unhashed(manifest_deps),
964    })
965}
966
967/// Fill in missing dependencies for units of the `RunCustomBuild`
968///
969/// As mentioned above in `compute_deps_custom_build` each build script
970/// execution has two dependencies. The first is compiling the build script
971/// itself (already added) and the second is that all crates the package of the
972/// build script depends on with `links` keys, their build script execution. (a
973/// bit confusing eh?)
974///
975/// Here we take the entire `deps` map and add more dependencies from execution
976/// of one build script to execution of another build script.
977fn connect_run_custom_build_deps(state: &mut State<'_, '_>) {
978    let mut new_deps = Vec::new();
979
980    {
981        let state = &*state;
982        // First up build a reverse dependency map. This is a mapping of all
983        // `RunCustomBuild` known steps to the unit which depends on them. For
984        // example a library might depend on a build script, so this map will
985        // have the build script as the key and the library would be in the
986        // value's set.
987        let mut reverse_deps_map = HashMap::default();
988        for (unit, deps) in state.unit_dependencies.iter() {
989            for dep in deps {
990                if dep.unit.mode == CompileMode::RunCustomBuild {
991                    reverse_deps_map
992                        .entry(dep.unit.clone())
993                        .or_insert_with(HashSet::default)
994                        .insert(unit);
995                }
996            }
997        }
998
999        // Next, we take a look at all build scripts executions listed in the
1000        // dependency map. Our job here is to take everything that depends on
1001        // this build script (from our reverse map above) and look at the other
1002        // package dependencies of these parents.
1003        //
1004        // If we depend on a linkable target and the build script mentions
1005        // `links`, then we depend on that package's build script! Here we use
1006        // `dep_build_script` to manufacture an appropriate build script unit to
1007        // depend on.
1008        for unit in state
1009            .unit_dependencies
1010            .keys()
1011            .filter(|k| k.mode == CompileMode::RunCustomBuild)
1012        {
1013            // This list of dependencies all depend on `unit`, an execution of
1014            // the build script.
1015            let Some(reverse_deps) = reverse_deps_map.get(unit) else {
1016                continue;
1017            };
1018
1019            let to_add = reverse_deps
1020                .iter()
1021                // Get all sibling dependencies of `unit`
1022                .flat_map(|reverse_dep| {
1023                    state.unit_dependencies[reverse_dep]
1024                        .iter()
1025                        .map(move |a| (reverse_dep, a))
1026                })
1027                // Exclude ourself
1028                .filter(|(_parent, other)| other.unit.pkg != unit.pkg)
1029                // Only deps with `links`.
1030                .filter(|(_parent, other)| {
1031                    state.gctx.cli_unstable().any_build_script_metadata
1032                        || (other.unit.target.is_linkable()
1033                            && other.unit.pkg.manifest().links().is_some())
1034                })
1035                // Avoid cycles when using the doc --scrape-examples feature:
1036                // Say a workspace has crates A and B where A has a build-dependency on B.
1037                // The Doc units for A and B will have a dependency on the Docscrape for both A and B.
1038                // So this would add a dependency from B-build to A-build, causing a cycle:
1039                //   B (build) -> A (build) -> B(build)
1040                // See the test scrape_examples_avoid_build_script_cycle for a concrete example.
1041                // To avoid this cycle, we filter out the B -> A (docscrape) dependency.
1042                .filter(|(_parent, other)| !other.unit.mode.is_doc_scrape())
1043                // Skip dependencies induced via dev-dependencies since
1044                // connections between `links` and build scripts only happens
1045                // via normal dependencies. Otherwise since dev-dependencies can
1046                // be cyclic we could have cyclic build-script executions.
1047                .filter_map(move |(parent, other)| {
1048                    if state
1049                        .dev_dependency_edges
1050                        .contains(&((*parent).clone(), other.unit.clone()))
1051                    {
1052                        None
1053                    } else {
1054                        Some(other)
1055                    }
1056                })
1057                // Get the RunCustomBuild for other lib.
1058                .filter_map(|other| {
1059                    state.unit_dependencies[&other.unit]
1060                        .iter()
1061                        .find(|other_dep| other_dep.unit.mode == CompileMode::RunCustomBuild)
1062                        .map(|other_dep| {
1063                            let mut dep = other_dep.clone();
1064                            let dep_name = other.dep_name.unwrap_or(other.unit.pkg.name());
1065                            // Propagate the manifest dep name from the sibling edge.
1066                            // The RunCustomBuild-RustCustomBuild edge is synthetic
1067                            // and doesn't carry a usable dep name, but build script
1068                            // metadata needs one for `CARGO_DEP_<dep_name>_*` env var
1069                            dep.dep_name = Some(dep_name);
1070                            dep
1071                        })
1072                })
1073                .collect::<HashSet<_>>();
1074
1075            if !to_add.is_empty() {
1076                // (RunCustomBuild, set(other RunCustomBuild))
1077                new_deps.push((unit.clone(), to_add));
1078            }
1079        }
1080    }
1081
1082    // And finally, add in all the missing dependencies!
1083    for (unit, new_deps) in new_deps {
1084        state
1085            .unit_dependencies
1086            .get_mut(&unit)
1087            .unwrap()
1088            .extend(new_deps);
1089    }
1090}
1091
1092impl<'a, 'gctx> State<'a, 'gctx> {
1093    /// Gets `std_resolve` during building std, otherwise `usr_resolve`.
1094    fn resolve(&self) -> &'a Resolve {
1095        if self.is_std {
1096            self.std_resolve.unwrap()
1097        } else {
1098            self.usr_resolve
1099        }
1100    }
1101
1102    /// Gets `std_features` during building std, otherwise `usr_features`.
1103    fn features(&self) -> &'a ResolvedFeatures {
1104        if self.is_std {
1105            self.std_features.unwrap()
1106        } else {
1107            self.usr_features
1108        }
1109    }
1110
1111    fn activated_features(
1112        &self,
1113        pkg_id: PackageId,
1114        features_for: FeaturesFor,
1115    ) -> Vec<InternedString> {
1116        let features = self.features();
1117        features.activated_features(pkg_id, features_for)
1118    }
1119
1120    fn is_dep_activated(
1121        &self,
1122        pkg_id: PackageId,
1123        features_for: FeaturesFor,
1124        dep_name: InternedString,
1125    ) -> bool {
1126        self.features()
1127            .is_dep_activated(pkg_id, features_for, dep_name)
1128    }
1129
1130    fn get(&self, id: PackageId) -> &'a Package {
1131        self.package_set
1132            .get_one(id)
1133            .unwrap_or_else(|_| panic!("expected {} to be downloaded", id))
1134    }
1135
1136    /// Returns a filtered set of dependencies for the given unit.
1137    fn deps(&self, unit: &Unit, unit_for: UnitFor) -> Vec<(PackageId, Vec<&Dependency>)> {
1138        let pkg_id = unit.pkg.package_id();
1139        let kind = unit.kind;
1140        self.resolve()
1141            .deps(pkg_id)
1142            .filter_map(|(id, deps)| {
1143                assert!(!deps.is_empty());
1144                let deps: Vec<_> = deps
1145                    .iter()
1146                    .filter(|dep| {
1147                        // If this target is a build command, then we only want build
1148                        // dependencies, otherwise we want everything *other than* build
1149                        // dependencies.
1150                        if unit.target.is_custom_build() != dep.is_build() {
1151                            return false;
1152                        }
1153
1154                        // If this dependency is **not** a transitive dependency, then it
1155                        // only applies to test/example targets.
1156                        if !dep.is_transitive()
1157                            && !unit.target.is_test()
1158                            && !unit.target.is_example()
1159                            && !unit.mode.is_any_test()
1160                        {
1161                            return false;
1162                        }
1163
1164                        // If this dependency is only available for certain platforms,
1165                        // make sure we're only enabling it for that platform.
1166                        if !self.target_data.dep_platform_activated(dep, kind) {
1167                            return false;
1168                        }
1169
1170                        // If this is an optional dependency, and the new feature resolver
1171                        // did not enable it, don't include it.
1172                        if dep.is_optional() {
1173                            // This `unit_for` is from parent dep and *SHOULD* contains its own
1174                            // artifact dep information inside `artifact_target_for_features`.
1175                            // So, no need to map any artifact info from an incorrect `dep.artifact()`.
1176                            let features_for = unit_for.map_to_features_for(IS_NO_ARTIFACT_DEP);
1177                            if !self.is_dep_activated(pkg_id, features_for, dep.name_in_toml()) {
1178                                return false;
1179                            }
1180                        }
1181
1182                        // If we've gotten past all that, then this dependency is
1183                        // actually used!
1184                        true
1185                    })
1186                    .collect();
1187                if deps.is_empty() {
1188                    None
1189                } else {
1190                    Some((id, deps))
1191                }
1192            })
1193            .collect()
1194    }
1195}