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 
18 use crate::core::compiler::unit_graph::{UnitDep, UnitGraph};
19 use crate::core::compiler::UnitInterner;
20 use crate::core::compiler::{CompileKind, CompileMode, RustcTargetData, Unit};
21 use crate::core::dependency::DepKind;
22 use crate::core::profiles::{Profile, Profiles, UnitFor};
23 use crate::core::resolver::features::{FeaturesFor, ResolvedFeatures};
24 use crate::core::resolver::Resolve;
25 use crate::core::{Dependency, Package, PackageId, PackageSet, Target, Workspace};
26 use crate::ops::resolve_all_features;
27 use crate::util::interning::InternedString;
28 use crate::util::Config;
29 use crate::CargoResult;
30 use log::trace;
31 use std::collections::{HashMap, HashSet};
32 
33 /// Collection of stuff used while creating the `UnitGraph`.
34 struct State<'a, 'cfg> {
35     ws: &'a Workspace<'cfg>,
36     config: &'cfg Config,
37     unit_dependencies: UnitGraph,
38     package_set: &'a PackageSet<'cfg>,
39     usr_resolve: &'a Resolve,
40     usr_features: &'a ResolvedFeatures,
41     std_resolve: Option<&'a Resolve>,
42     std_features: Option<&'a ResolvedFeatures>,
43     /// This flag is `true` while generating the dependencies for the standard
44     /// library.
45     is_std: bool,
46     global_mode: CompileMode,
47     target_data: &'a RustcTargetData<'cfg>,
48     profiles: &'a Profiles,
49     interner: &'a UnitInterner,
50 
51     /// A set of edges in `unit_dependencies` where (a, b) means that the
52     /// dependency from a to b was added purely because it was a dev-dependency.
53     /// This is used during `connect_run_custom_build_deps`.
54     dev_dependency_edges: HashSet<(Unit, Unit)>,
55 }
56 
build_unit_dependencies<'a, 'cfg>( ws: &'a Workspace<'cfg>, package_set: &'a PackageSet<'cfg>, resolve: &'a Resolve, features: &'a ResolvedFeatures, std_resolve: Option<&'a (Resolve, ResolvedFeatures)>, roots: &[Unit], std_roots: &HashMap<CompileKind, Vec<Unit>>, global_mode: CompileMode, target_data: &'a RustcTargetData<'cfg>, profiles: &'a Profiles, interner: &'a UnitInterner, ) -> CargoResult<UnitGraph>57 pub fn build_unit_dependencies<'a, 'cfg>(
58     ws: &'a Workspace<'cfg>,
59     package_set: &'a PackageSet<'cfg>,
60     resolve: &'a Resolve,
61     features: &'a ResolvedFeatures,
62     std_resolve: Option<&'a (Resolve, ResolvedFeatures)>,
63     roots: &[Unit],
64     std_roots: &HashMap<CompileKind, Vec<Unit>>,
65     global_mode: CompileMode,
66     target_data: &'a RustcTargetData<'cfg>,
67     profiles: &'a Profiles,
68     interner: &'a UnitInterner,
69 ) -> CargoResult<UnitGraph> {
70     if roots.is_empty() {
71         // If -Zbuild-std, don't attach units if there is nothing to build.
72         // Otherwise, other parts of the code may be confused by seeing units
73         // in the dep graph without a root.
74         return Ok(HashMap::new());
75     }
76     let (std_resolve, std_features) = match std_resolve {
77         Some((r, f)) => (Some(r), Some(f)),
78         None => (None, None),
79     };
80     let mut state = State {
81         ws,
82         config: ws.config(),
83         unit_dependencies: HashMap::new(),
84         package_set,
85         usr_resolve: resolve,
86         usr_features: features,
87         std_resolve,
88         std_features,
89         is_std: false,
90         global_mode,
91         target_data,
92         profiles,
93         interner,
94         dev_dependency_edges: HashSet::new(),
95     };
96 
97     let std_unit_deps = calc_deps_of_std(&mut state, std_roots)?;
98 
99     deps_of_roots(roots, &mut state)?;
100     super::links::validate_links(state.resolve(), &state.unit_dependencies)?;
101     // Hopefully there aren't any links conflicts with the standard library?
102 
103     if let Some(std_unit_deps) = std_unit_deps {
104         attach_std_deps(&mut state, std_roots, std_unit_deps);
105     }
106 
107     connect_run_custom_build_deps(&mut state);
108 
109     // Dependencies are used in tons of places throughout the backend, many of
110     // which affect the determinism of the build itself. As a result be sure
111     // that dependency lists are always sorted to ensure we've always got a
112     // deterministic output.
113     for list in state.unit_dependencies.values_mut() {
114         list.sort();
115     }
116     trace!("ALL UNIT DEPENDENCIES {:#?}", state.unit_dependencies);
117 
118     Ok(state.unit_dependencies)
119 }
120 
121 /// Compute all the dependencies for the standard library.
calc_deps_of_std( mut state: &mut State<'_, '_>, std_roots: &HashMap<CompileKind, Vec<Unit>>, ) -> CargoResult<Option<UnitGraph>>122 fn calc_deps_of_std(
123     mut state: &mut State<'_, '_>,
124     std_roots: &HashMap<CompileKind, Vec<Unit>>,
125 ) -> CargoResult<Option<UnitGraph>> {
126     if std_roots.is_empty() {
127         return Ok(None);
128     }
129     // Compute dependencies for the standard library.
130     state.is_std = true;
131     for roots in std_roots.values() {
132         deps_of_roots(roots, &mut state)?;
133     }
134     state.is_std = false;
135     Ok(Some(std::mem::take(&mut state.unit_dependencies)))
136 }
137 
138 /// Add the standard library units to the `unit_dependencies`.
attach_std_deps( state: &mut State<'_, '_>, std_roots: &HashMap<CompileKind, Vec<Unit>>, std_unit_deps: UnitGraph, )139 fn attach_std_deps(
140     state: &mut State<'_, '_>,
141     std_roots: &HashMap<CompileKind, Vec<Unit>>,
142     std_unit_deps: UnitGraph,
143 ) {
144     // Attach the standard library as a dependency of every target unit.
145     let mut found = false;
146     for (unit, deps) in state.unit_dependencies.iter_mut() {
147         if !unit.kind.is_host() && !unit.mode.is_run_custom_build() {
148             deps.extend(std_roots[&unit.kind].iter().map(|unit| UnitDep {
149                 unit: unit.clone(),
150                 unit_for: UnitFor::new_normal(),
151                 extern_crate_name: unit.pkg.name(),
152                 // TODO: Does this `public` make sense?
153                 public: true,
154                 noprelude: true,
155             }));
156             found = true;
157         }
158     }
159     // And also include the dependencies of the standard library itself. Don't
160     // include these if no units actually needed the standard library.
161     if found {
162         for (unit, deps) in std_unit_deps.into_iter() {
163             if let Some(other_unit) = state.unit_dependencies.insert(unit, deps) {
164                 panic!("std unit collision with existing unit: {:?}", other_unit);
165             }
166         }
167     }
168 }
169 
170 /// Compute all the dependencies of the given root units.
171 /// The result is stored in state.unit_dependencies.
deps_of_roots(roots: &[Unit], mut state: &mut State<'_, '_>) -> CargoResult<()>172 fn deps_of_roots(roots: &[Unit], mut state: &mut State<'_, '_>) -> CargoResult<()> {
173     for unit in roots.iter() {
174         // Dependencies of tests/benches should not have `panic` set.
175         // We check the global test mode to see if we are running in `cargo
176         // test` in which case we ensure all dependencies have `panic`
177         // cleared, and avoid building the lib thrice (once with `panic`, once
178         // without, once for `--test`). In particular, the lib included for
179         // Doc tests and examples are `Build` mode here.
180         let unit_for = if unit.mode.is_any_test() || state.global_mode.is_rustc_test() {
181             if unit.target.proc_macro() {
182                 // Special-case for proc-macros, which are forced to for-host
183                 // since they need to link with the proc_macro crate.
184                 UnitFor::new_host_test(state.config)
185             } else {
186                 UnitFor::new_test(state.config)
187             }
188         } else if unit.target.is_custom_build() {
189             // This normally doesn't happen, except `clean` aggressively
190             // generates all units.
191             UnitFor::new_host(false)
192         } else if unit.target.proc_macro() {
193             UnitFor::new_host(true)
194         } else if unit.target.for_host() {
195             // Plugin should never have panic set.
196             UnitFor::new_compiler()
197         } else {
198             UnitFor::new_normal()
199         };
200         deps_of(unit, &mut state, unit_for)?;
201     }
202 
203     Ok(())
204 }
205 
206 /// Compute the dependencies of a single unit.
deps_of(unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor) -> CargoResult<()>207 fn deps_of(unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor) -> CargoResult<()> {
208     // Currently the `unit_dependencies` map does not include `unit_for`. This should
209     // be safe for now. `TestDependency` only exists to clear the `panic`
210     // flag, and you'll never ask for a `unit` with `panic` set as a
211     // `TestDependency`. `CustomBuild` should also be fine since if the
212     // requested unit's settings are the same as `Any`, `CustomBuild` can't
213     // affect anything else in the hierarchy.
214     if !state.unit_dependencies.contains_key(unit) {
215         let unit_deps = compute_deps(unit, state, unit_for)?;
216         state
217             .unit_dependencies
218             .insert(unit.clone(), unit_deps.clone());
219         for unit_dep in unit_deps {
220             deps_of(&unit_dep.unit, state, unit_dep.unit_for)?;
221         }
222     }
223     Ok(())
224 }
225 
226 /// For a package, returns all targets that are registered as dependencies
227 /// for that package.
228 /// This returns a `Vec` of `(Unit, UnitFor)` pairs. The `UnitFor`
229 /// is the profile type that should be used for dependencies of the unit.
compute_deps( unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor, ) -> CargoResult<Vec<UnitDep>>230 fn compute_deps(
231     unit: &Unit,
232     state: &mut State<'_, '_>,
233     unit_for: UnitFor,
234 ) -> CargoResult<Vec<UnitDep>> {
235     if unit.mode.is_run_custom_build() {
236         return compute_deps_custom_build(unit, unit_for, state);
237     } else if unit.mode.is_doc() {
238         // Note: this does not include doc test.
239         return compute_deps_doc(unit, state, unit_for);
240     }
241 
242     let id = unit.pkg.package_id();
243     let filtered_deps = state.deps(unit, unit_for, &|dep| {
244         // If this target is a build command, then we only want build
245         // dependencies, otherwise we want everything *other than* build
246         // dependencies.
247         if unit.target.is_custom_build() != dep.is_build() {
248             return false;
249         }
250 
251         // If this dependency is **not** a transitive dependency, then it
252         // only applies to test/example targets.
253         if !dep.is_transitive()
254             && !unit.target.is_test()
255             && !unit.target.is_example()
256             && !unit.mode.is_any_test()
257         {
258             return false;
259         }
260 
261         // If we've gotten past all that, then this dependency is
262         // actually used!
263         true
264     });
265 
266     let mut ret = Vec::new();
267     let mut dev_deps = Vec::new();
268     for (id, deps) in filtered_deps {
269         let pkg = state.get(id);
270         let lib = match pkg.targets().iter().find(|t| t.is_lib()) {
271             Some(t) => t,
272             None => continue,
273         };
274         let mode = check_or_build_mode(unit.mode, lib);
275         let dep_unit_for = unit_for.with_dependency(unit, lib);
276 
277         let start = ret.len();
278         if state.config.cli_unstable().dual_proc_macros && lib.proc_macro() && !unit.kind.is_host()
279         {
280             let unit_dep = new_unit_dep(state, unit, pkg, lib, dep_unit_for, unit.kind, mode)?;
281             ret.push(unit_dep);
282             let unit_dep =
283                 new_unit_dep(state, unit, pkg, lib, dep_unit_for, CompileKind::Host, mode)?;
284             ret.push(unit_dep);
285         } else {
286             let unit_dep = new_unit_dep(
287                 state,
288                 unit,
289                 pkg,
290                 lib,
291                 dep_unit_for,
292                 unit.kind.for_target(lib),
293                 mode,
294             )?;
295             ret.push(unit_dep);
296         }
297 
298         // If the unit added was a dev-dependency unit, then record that in the
299         // dev-dependencies array. We'll add this to
300         // `state.dev_dependency_edges` at the end and process it later in
301         // `connect_run_custom_build_deps`.
302         if deps.iter().all(|d| !d.is_transitive()) {
303             for dep in ret[start..].iter() {
304                 dev_deps.push((unit.clone(), dep.unit.clone()));
305             }
306         }
307     }
308     state.dev_dependency_edges.extend(dev_deps);
309 
310     // If this target is a build script, then what we've collected so far is
311     // all we need. If this isn't a build script, then it depends on the
312     // build script if there is one.
313     if unit.target.is_custom_build() {
314         return Ok(ret);
315     }
316     ret.extend(dep_build_script(unit, unit_for, state)?);
317 
318     // If this target is a binary, test, example, etc, then it depends on
319     // the library of the same package. The call to `resolve.deps` above
320     // didn't include `pkg` in the return values, so we need to special case
321     // it here and see if we need to push `(pkg, pkg_lib_target)`.
322     if unit.target.is_lib() && unit.mode != CompileMode::Doctest {
323         return Ok(ret);
324     }
325     ret.extend(maybe_lib(unit, state, unit_for)?);
326 
327     // If any integration tests/benches are being run, make sure that
328     // binaries are built as well.
329     if !unit.mode.is_check()
330         && unit.mode.is_any_test()
331         && (unit.target.is_test() || unit.target.is_bench())
332     {
333         ret.extend(
334             unit.pkg
335                 .targets()
336                 .iter()
337                 .filter(|t| {
338                     // Skip binaries with required features that have not been selected.
339                     match t.required_features() {
340                         Some(rf) if t.is_bin() => {
341                             let features = resolve_all_features(
342                                 state.resolve(),
343                                 state.features(),
344                                 state.package_set,
345                                 id,
346                             );
347                             rf.iter().all(|f| features.contains(f))
348                         }
349                         None if t.is_bin() => true,
350                         _ => false,
351                     }
352                 })
353                 .map(|t| {
354                     new_unit_dep(
355                         state,
356                         unit,
357                         &unit.pkg,
358                         t,
359                         UnitFor::new_normal(),
360                         unit.kind.for_target(t),
361                         CompileMode::Build,
362                     )
363                 })
364                 .collect::<CargoResult<Vec<UnitDep>>>()?,
365         );
366     }
367 
368     Ok(ret)
369 }
370 
371 /// Returns the dependencies needed to run a build script.
372 ///
373 /// The `unit` provided must represent an execution of a build script, and
374 /// the returned set of units must all be run before `unit` is run.
compute_deps_custom_build( unit: &Unit, unit_for: UnitFor, state: &mut State<'_, '_>, ) -> CargoResult<Vec<UnitDep>>375 fn compute_deps_custom_build(
376     unit: &Unit,
377     unit_for: UnitFor,
378     state: &mut State<'_, '_>,
379 ) -> CargoResult<Vec<UnitDep>> {
380     if let Some(links) = unit.pkg.manifest().links() {
381         if state
382             .target_data
383             .script_override(links, unit.kind)
384             .is_some()
385         {
386             // Overridden build scripts don't have any dependencies.
387             return Ok(Vec::new());
388         }
389     }
390     // All dependencies of this unit should use profiles for custom builds.
391     // If this is a build script of a proc macro, make sure it uses host
392     // features.
393     let script_unit_for = UnitFor::new_host(unit_for.is_for_host_features());
394     // When not overridden, then the dependencies to run a build script are:
395     //
396     // 1. Compiling the build script itself.
397     // 2. For each immediate dependency of our package which has a `links`
398     //    key, the execution of that build script.
399     //
400     // We don't have a great way of handling (2) here right now so this is
401     // deferred until after the graph of all unit dependencies has been
402     // constructed.
403     let unit_dep = new_unit_dep(
404         state,
405         unit,
406         &unit.pkg,
407         &unit.target,
408         script_unit_for,
409         // Build scripts always compiled for the host.
410         CompileKind::Host,
411         CompileMode::Build,
412     )?;
413     Ok(vec![unit_dep])
414 }
415 
416 /// Returns the dependencies necessary to document a package.
compute_deps_doc( unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor, ) -> CargoResult<Vec<UnitDep>>417 fn compute_deps_doc(
418     unit: &Unit,
419     state: &mut State<'_, '_>,
420     unit_for: UnitFor,
421 ) -> CargoResult<Vec<UnitDep>> {
422     let deps = state.deps(unit, unit_for, &|dep| dep.kind() == DepKind::Normal);
423 
424     // To document a library, we depend on dependencies actually being
425     // built. If we're documenting *all* libraries, then we also depend on
426     // the documentation of the library being built.
427     let mut ret = Vec::new();
428     for (id, _deps) in deps {
429         let dep = state.get(id);
430         let lib = match dep.targets().iter().find(|t| t.is_lib()) {
431             Some(lib) => lib,
432             None => continue,
433         };
434         // Rustdoc only needs rmeta files for regular dependencies.
435         // However, for plugins/proc macros, deps should be built like normal.
436         let mode = check_or_build_mode(unit.mode, lib);
437         let dep_unit_for = unit_for.with_dependency(unit, lib);
438         let lib_unit_dep = new_unit_dep(
439             state,
440             unit,
441             dep,
442             lib,
443             dep_unit_for,
444             unit.kind.for_target(lib),
445             mode,
446         )?;
447         ret.push(lib_unit_dep);
448         if let CompileMode::Doc { deps: true } = unit.mode {
449             // Document this lib as well.
450             let doc_unit_dep = new_unit_dep(
451                 state,
452                 unit,
453                 dep,
454                 lib,
455                 dep_unit_for,
456                 unit.kind.for_target(lib),
457                 unit.mode,
458             )?;
459             ret.push(doc_unit_dep);
460         }
461     }
462 
463     // Be sure to build/run the build script for documented libraries.
464     ret.extend(dep_build_script(unit, unit_for, state)?);
465 
466     // If we document a binary/example, we need the library available.
467     if unit.target.is_bin() || unit.target.is_example() {
468         ret.extend(maybe_lib(unit, state, unit_for)?);
469     }
470     Ok(ret)
471 }
472 
maybe_lib( unit: &Unit, state: &mut State<'_, '_>, unit_for: UnitFor, ) -> CargoResult<Option<UnitDep>>473 fn maybe_lib(
474     unit: &Unit,
475     state: &mut State<'_, '_>,
476     unit_for: UnitFor,
477 ) -> CargoResult<Option<UnitDep>> {
478     unit.pkg
479         .targets()
480         .iter()
481         .find(|t| t.is_linkable())
482         .map(|t| {
483             let mode = check_or_build_mode(unit.mode, t);
484             let dep_unit_for = unit_for.with_dependency(unit, t);
485             new_unit_dep(
486                 state,
487                 unit,
488                 &unit.pkg,
489                 t,
490                 dep_unit_for,
491                 unit.kind.for_target(t),
492                 mode,
493             )
494         })
495         .transpose()
496 }
497 
498 /// If a build script is scheduled to be run for the package specified by
499 /// `unit`, this function will return the unit to run that build script.
500 ///
501 /// Overriding a build script simply means that the running of the build
502 /// script itself doesn't have any dependencies, so even in that case a unit
503 /// of work is still returned. `None` is only returned if the package has no
504 /// build script.
dep_build_script( unit: &Unit, unit_for: UnitFor, state: &State<'_, '_>, ) -> CargoResult<Option<UnitDep>>505 fn dep_build_script(
506     unit: &Unit,
507     unit_for: UnitFor,
508     state: &State<'_, '_>,
509 ) -> CargoResult<Option<UnitDep>> {
510     unit.pkg
511         .targets()
512         .iter()
513         .find(|t| t.is_custom_build())
514         .map(|t| {
515             // The profile stored in the Unit is the profile for the thing
516             // the custom build script is running for.
517             let profile = state.profiles.get_profile_run_custom_build(&unit.profile);
518             // UnitFor::new_host is used because we want the `host` flag set
519             // for all of our build dependencies (so they all get
520             // build-override profiles), including compiling the build.rs
521             // script itself.
522             //
523             // If `is_for_host_features` here is `false`, that means we are a
524             // build.rs script for a normal dependency and we want to set the
525             // CARGO_FEATURE_* environment variables to the features as a
526             // normal dep.
527             //
528             // If `is_for_host_features` here is `true`, that means that this
529             // package is being used as a build dependency or proc-macro, and
530             // so we only want to set CARGO_FEATURE_* variables for the host
531             // side of the graph.
532             //
533             // Keep in mind that the RunCustomBuild unit and the Compile
534             // build.rs unit use the same features. This is because some
535             // people use `cfg!` and `#[cfg]` expressions to check for enabled
536             // features instead of just checking `CARGO_FEATURE_*` at runtime.
537             // In the case with the new feature resolver (decoupled host
538             // deps), and a shared dependency has different features enabled
539             // for normal vs. build, then the build.rs script will get
540             // compiled twice. I believe it is not feasible to only build it
541             // once because it would break a large number of scripts (they
542             // would think they have the wrong set of features enabled).
543             let script_unit_for = UnitFor::new_host(unit_for.is_for_host_features());
544             new_unit_dep_with_profile(
545                 state,
546                 unit,
547                 &unit.pkg,
548                 t,
549                 script_unit_for,
550                 unit.kind,
551                 CompileMode::RunCustomBuild,
552                 profile,
553             )
554         })
555         .transpose()
556 }
557 
558 /// Choose the correct mode for dependencies.
check_or_build_mode(mode: CompileMode, target: &Target) -> CompileMode559 fn check_or_build_mode(mode: CompileMode, target: &Target) -> CompileMode {
560     match mode {
561         CompileMode::Check { .. } | CompileMode::Doc { .. } => {
562             if target.for_host() {
563                 // Plugin and proc macro targets should be compiled like
564                 // normal.
565                 CompileMode::Build
566             } else {
567                 // Regular dependencies should not be checked with --test.
568                 // Regular dependencies of doc targets should emit rmeta only.
569                 CompileMode::Check { test: false }
570             }
571         }
572         _ => CompileMode::Build,
573     }
574 }
575 
576 /// Create a new Unit for a dependency from `parent` to `pkg` and `target`.
new_unit_dep( state: &State<'_, '_>, parent: &Unit, pkg: &Package, target: &Target, unit_for: UnitFor, kind: CompileKind, mode: CompileMode, ) -> CargoResult<UnitDep>577 fn new_unit_dep(
578     state: &State<'_, '_>,
579     parent: &Unit,
580     pkg: &Package,
581     target: &Target,
582     unit_for: UnitFor,
583     kind: CompileKind,
584     mode: CompileMode,
585 ) -> CargoResult<UnitDep> {
586     let is_local = pkg.package_id().source_id().is_path() && !state.is_std;
587     let profile = state.profiles.get_profile(
588         pkg.package_id(),
589         state.ws.is_member(pkg),
590         is_local,
591         unit_for,
592         mode,
593         kind,
594     );
595     new_unit_dep_with_profile(state, parent, pkg, target, unit_for, kind, mode, profile)
596 }
597 
new_unit_dep_with_profile( state: &State<'_, '_>, parent: &Unit, pkg: &Package, target: &Target, unit_for: UnitFor, kind: CompileKind, mode: CompileMode, profile: Profile, ) -> CargoResult<UnitDep>598 fn new_unit_dep_with_profile(
599     state: &State<'_, '_>,
600     parent: &Unit,
601     pkg: &Package,
602     target: &Target,
603     unit_for: UnitFor,
604     kind: CompileKind,
605     mode: CompileMode,
606     profile: Profile,
607 ) -> CargoResult<UnitDep> {
608     // TODO: consider making extern_crate_name return InternedString?
609     let extern_crate_name = InternedString::new(&state.resolve().extern_crate_name(
610         parent.pkg.package_id(),
611         pkg.package_id(),
612         target,
613     )?);
614     let public = state
615         .resolve()
616         .is_public_dep(parent.pkg.package_id(), pkg.package_id());
617     let features_for = unit_for.map_to_features_for();
618     let features = state.activated_features(pkg.package_id(), features_for);
619     let unit = state
620         .interner
621         .intern(pkg, target, profile, kind, mode, features, state.is_std, 0);
622     Ok(UnitDep {
623         unit,
624         unit_for,
625         extern_crate_name,
626         public,
627         noprelude: false,
628     })
629 }
630 
631 /// Fill in missing dependencies for units of the `RunCustomBuild`
632 ///
633 /// As mentioned above in `compute_deps_custom_build` each build script
634 /// execution has two dependencies. The first is compiling the build script
635 /// itself (already added) and the second is that all crates the package of the
636 /// build script depends on with `links` keys, their build script execution. (a
637 /// bit confusing eh?)
638 ///
639 /// Here we take the entire `deps` map and add more dependencies from execution
640 /// of one build script to execution of another build script.
connect_run_custom_build_deps(state: &mut State<'_, '_>)641 fn connect_run_custom_build_deps(state: &mut State<'_, '_>) {
642     let mut new_deps = Vec::new();
643 
644     {
645         let state = &*state;
646         // First up build a reverse dependency map. This is a mapping of all
647         // `RunCustomBuild` known steps to the unit which depends on them. For
648         // example a library might depend on a build script, so this map will
649         // have the build script as the key and the library would be in the
650         // value's set.
651         let mut reverse_deps_map = HashMap::new();
652         for (unit, deps) in state.unit_dependencies.iter() {
653             for dep in deps {
654                 if dep.unit.mode == CompileMode::RunCustomBuild {
655                     reverse_deps_map
656                         .entry(dep.unit.clone())
657                         .or_insert_with(HashSet::new)
658                         .insert(unit);
659                 }
660             }
661         }
662 
663         // Next, we take a look at all build scripts executions listed in the
664         // dependency map. Our job here is to take everything that depends on
665         // this build script (from our reverse map above) and look at the other
666         // package dependencies of these parents.
667         //
668         // If we depend on a linkable target and the build script mentions
669         // `links`, then we depend on that package's build script! Here we use
670         // `dep_build_script` to manufacture an appropriate build script unit to
671         // depend on.
672         for unit in state
673             .unit_dependencies
674             .keys()
675             .filter(|k| k.mode == CompileMode::RunCustomBuild)
676         {
677             // This list of dependencies all depend on `unit`, an execution of
678             // the build script.
679             let reverse_deps = match reverse_deps_map.get(unit) {
680                 Some(set) => set,
681                 None => continue,
682             };
683 
684             let to_add = reverse_deps
685                 .iter()
686                 // Get all sibling dependencies of `unit`
687                 .flat_map(|reverse_dep| {
688                     state.unit_dependencies[reverse_dep]
689                         .iter()
690                         .map(move |a| (reverse_dep, a))
691                 })
692                 // Only deps with `links`.
693                 .filter(|(_parent, other)| {
694                     other.unit.pkg != unit.pkg
695                         && other.unit.target.is_linkable()
696                         && other.unit.pkg.manifest().links().is_some()
697                 })
698                 // Skip dependencies induced via dev-dependencies since
699                 // connections between `links` and build scripts only happens
700                 // via normal dependencies. Otherwise since dev-dependencies can
701                 // be cyclic we could have cyclic build-script executions.
702                 .filter_map(move |(parent, other)| {
703                     if state
704                         .dev_dependency_edges
705                         .contains(&((*parent).clone(), other.unit.clone()))
706                     {
707                         None
708                     } else {
709                         Some(other)
710                     }
711                 })
712                 // Get the RunCustomBuild for other lib.
713                 .filter_map(|other| {
714                     state.unit_dependencies[&other.unit]
715                         .iter()
716                         .find(|other_dep| other_dep.unit.mode == CompileMode::RunCustomBuild)
717                         .cloned()
718                 })
719                 .collect::<HashSet<_>>();
720 
721             if !to_add.is_empty() {
722                 // (RunCustomBuild, set(other RunCustomBuild))
723                 new_deps.push((unit.clone(), to_add));
724             }
725         }
726     }
727 
728     // And finally, add in all the missing dependencies!
729     for (unit, new_deps) in new_deps {
730         state
731             .unit_dependencies
732             .get_mut(&unit)
733             .unwrap()
734             .extend(new_deps);
735     }
736 }
737 
738 impl<'a, 'cfg> State<'a, 'cfg> {
resolve(&self) -> &'a Resolve739     fn resolve(&self) -> &'a Resolve {
740         if self.is_std {
741             self.std_resolve.unwrap()
742         } else {
743             self.usr_resolve
744         }
745     }
746 
features(&self) -> &'a ResolvedFeatures747     fn features(&self) -> &'a ResolvedFeatures {
748         if self.is_std {
749             self.std_features.unwrap()
750         } else {
751             self.usr_features
752         }
753     }
754 
activated_features( &self, pkg_id: PackageId, features_for: FeaturesFor, ) -> Vec<InternedString>755     fn activated_features(
756         &self,
757         pkg_id: PackageId,
758         features_for: FeaturesFor,
759     ) -> Vec<InternedString> {
760         let features = self.features();
761         features.activated_features(pkg_id, features_for)
762     }
763 
is_dep_activated( &self, pkg_id: PackageId, features_for: FeaturesFor, dep_name: InternedString, ) -> bool764     fn is_dep_activated(
765         &self,
766         pkg_id: PackageId,
767         features_for: FeaturesFor,
768         dep_name: InternedString,
769     ) -> bool {
770         self.features()
771             .is_dep_activated(pkg_id, features_for, dep_name)
772     }
773 
get(&self, id: PackageId) -> &'a Package774     fn get(&self, id: PackageId) -> &'a Package {
775         self.package_set
776             .get_one(id)
777             .unwrap_or_else(|_| panic!("expected {} to be downloaded", id))
778     }
779 
780     /// Returns a filtered set of dependencies for the given unit.
deps( &self, unit: &Unit, unit_for: UnitFor, filter: &dyn Fn(&Dependency) -> bool, ) -> Vec<(PackageId, &HashSet<Dependency>)>781     fn deps(
782         &self,
783         unit: &Unit,
784         unit_for: UnitFor,
785         filter: &dyn Fn(&Dependency) -> bool,
786     ) -> Vec<(PackageId, &HashSet<Dependency>)> {
787         let pkg_id = unit.pkg.package_id();
788         let kind = unit.kind;
789         self.resolve()
790             .deps(pkg_id)
791             .filter(|&(_id, deps)| {
792                 assert!(!deps.is_empty());
793                 deps.iter().any(|dep| {
794                     if !filter(dep) {
795                         return false;
796                     }
797                     // If this dependency is only available for certain platforms,
798                     // make sure we're only enabling it for that platform.
799                     if !self.target_data.dep_platform_activated(dep, kind) {
800                         return false;
801                     }
802 
803                     // If this is an optional dependency, and the new feature resolver
804                     // did not enable it, don't include it.
805                     if dep.is_optional() {
806                         let features_for = unit_for.map_to_features_for();
807                         if !self.is_dep_activated(pkg_id, features_for, dep.name_in_toml()) {
808                             return false;
809                         }
810                     }
811 
812                     true
813                 })
814             })
815             .collect()
816     }
817 }
818