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