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