1 //! Constructs the dependency graph for compilation.
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.
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.
18 use crate::core
::compiler
::Unit
;
19 use crate::core
::compiler
::{BuildContext, CompileMode, Kind}
;
20 use crate::core
::dependency
::Kind
as DepKind
;
21 use crate::core
::package
::Downloads
;
22 use crate::core
::profiles
::{Profile, UnitFor}
;
23 use crate::core
::resolver
::Resolve
;
24 use crate::core
::{InternedString, Package, PackageId, Target}
;
25 use crate::CargoResult
;
27 use std
::collections
::{HashMap, HashSet}
;
29 /// The dependency graph of Units.
30 pub type UnitGraph
<'a
> = HashMap
<Unit
<'a
>, Vec
<UnitDep
<'a
>>>;
32 /// A unit dependency.
33 #[derive(Debug, Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
34 pub struct UnitDep
<'a
> {
35 /// The dependency unit.
37 /// The purpose of this dependency (a dependency for a test, or a build
39 pub unit_for
: UnitFor
,
40 /// The name the parent uses to refer to this dependency.
41 pub extern_crate_name
: InternedString
,
42 /// Whether or not this is a public dependency.
46 /// Collection of stuff used while creating the `UnitGraph`.
47 struct State
<'a
, 'cfg
> {
48 bcx
: &'a BuildContext
<'a
, 'cfg
>,
49 waiting_on_download
: HashSet
<PackageId
>,
50 downloads
: Downloads
<'a
, 'cfg
>,
51 unit_dependencies
: UnitGraph
<'a
>,
52 package_cache
: HashMap
<PackageId
, &'a Package
>,
53 usr_resolve
: &'a Resolve
,
54 std_resolve
: Option
<&'a Resolve
>,
55 /// This flag is `true` while generating the dependencies for the standard
60 pub fn build_unit_dependencies
<'a
, 'cfg
>(
61 bcx
: &'a BuildContext
<'a
, 'cfg
>,
63 std_resolve
: Option
<&'a Resolve
>,
65 std_roots
: &[Unit
<'a
>],
66 ) -> CargoResult
<UnitGraph
<'a
>> {
67 let mut state
= State
{
69 downloads
: bcx
.packages
.enable_download()?
,
70 waiting_on_download
: HashSet
::new(),
71 unit_dependencies
: HashMap
::new(),
72 package_cache
: HashMap
::new(),
78 let std_unit_deps
= calc_deps_of_std(&mut state
, std_roots
)?
;
80 deps_of_roots(roots
, &mut state
)?
;
81 super::links
::validate_links(state
.resolve(), &state
.unit_dependencies
)?
;
82 // Hopefully there aren't any links conflicts with the standard library?
84 if let Some(std_unit_deps
) = std_unit_deps
{
85 attach_std_deps(&mut state
, std_roots
, std_unit_deps
);
88 connect_run_custom_build_deps(&mut state
.unit_dependencies
);
90 // Dependencies are used in tons of places throughout the backend, many of
91 // which affect the determinism of the build itself. As a result be sure
92 // that dependency lists are always sorted to ensure we've always got a
93 // deterministic output.
94 for list
in state
.unit_dependencies
.values_mut() {
97 trace
!("ALL UNIT DEPENDENCIES {:#?}", state
.unit_dependencies
);
99 Ok(state
.unit_dependencies
)
102 /// Compute all the dependencies for the standard library.
103 fn calc_deps_of_std
<'a
, 'cfg
>(
104 mut state
: &mut State
<'a
, 'cfg
>,
105 std_roots
: &[Unit
<'a
>],
106 ) -> CargoResult
<Option
<UnitGraph
<'a
>>> {
107 if std_roots
.is_empty() {
110 // Compute dependencies for the standard library.
112 deps_of_roots(std_roots
, &mut state
)?
;
113 state
.is_std
= false;
114 Ok(Some(std
::mem
::replace(
115 &mut state
.unit_dependencies
,
120 /// Add the standard library units to the `unit_dependencies`.
121 fn attach_std_deps
<'a
, 'cfg
>(
122 state
: &mut State
<'a
, 'cfg
>,
123 std_roots
: &[Unit
<'a
>],
124 std_unit_deps
: UnitGraph
<'a
>,
126 // Attach the standard library as a dependency of every target unit.
127 for (unit
, deps
) in state
.unit_dependencies
.iter_mut() {
128 if unit
.kind
== Kind
::Target
&& !unit
.mode
.is_run_custom_build() {
129 deps
.extend(std_roots
.iter().map(|unit
| UnitDep
{
131 unit_for
: UnitFor
::new_normal(),
132 extern_crate_name
: unit
.pkg
.name(),
133 // TODO: Does this `public` make sense?
138 // And also include the dependencies of the standard library itself.
139 for (unit
, deps
) in std_unit_deps
.into_iter() {
140 if let Some(other_unit
) = state
.unit_dependencies
.insert(unit
, deps
) {
141 panic
!("std unit collision with existing unit: {:?}", other_unit
);
146 /// Compute all the dependencies of the given root units.
147 /// The result is stored in state.unit_dependencies.
148 fn deps_of_roots
<'a
, 'cfg
>(roots
: &[Unit
<'a
>], mut state
: &mut State
<'a
, 'cfg
>) -> CargoResult
<()> {
149 // Loop because we are downloading while building the dependency graph.
150 // The partially-built unit graph is discarded through each pass of the
151 // loop because it is incomplete because not all required Packages have
154 for unit
in roots
.iter() {
155 state
.get(unit
.pkg
.package_id())?
;
157 // Dependencies of tests/benches should not have `panic` set.
158 // We check the global test mode to see if we are running in `cargo
159 // test` in which case we ensure all dependencies have `panic`
160 // cleared, and avoid building the lib thrice (once with `panic`, once
161 // without, once for `--test`). In particular, the lib included for
162 // Doc tests and examples are `Build` mode here.
163 let unit_for
= if unit
.mode
.is_any_test() || state
.bcx
.build_config
.test() {
165 } else if unit
.target
.is_custom_build() {
166 // This normally doesn't happen, except `clean` aggressively
167 // generates all units.
169 } else if unit
.target
.for_host() {
170 // Proc macro / plugin should never have panic set.
171 UnitFor
::new_compiler()
173 UnitFor
::new_normal()
175 deps_of(unit
, &mut state
, unit_for
)?
;
178 if !state
.waiting_on_download
.is_empty() {
179 state
.finish_some_downloads()?
;
180 state
.unit_dependencies
.clear();
188 /// Compute the dependencies of a single unit.
189 fn deps_of
<'a
, 'cfg
>(
191 state
: &mut State
<'a
, 'cfg
>,
193 ) -> CargoResult
<()> {
194 // Currently the `unit_dependencies` map does not include `unit_for`. This should
195 // be safe for now. `TestDependency` only exists to clear the `panic`
196 // flag, and you'll never ask for a `unit` with `panic` set as a
197 // `TestDependency`. `CustomBuild` should also be fine since if the
198 // requested unit's settings are the same as `Any`, `CustomBuild` can't
199 // affect anything else in the hierarchy.
200 if !state
.unit_dependencies
.contains_key(unit
) {
201 let unit_deps
= compute_deps(unit
, state
, unit_for
)?
;
202 state
.unit_dependencies
.insert(*unit
, unit_deps
.clone());
203 for unit_dep
in unit_deps
{
204 deps_of(&unit_dep
.unit
, state
, unit_dep
.unit_for
)?
;
210 /// For a package, returns all targets that are registered as dependencies
211 /// for that package.
212 /// This returns a `Vec` of `(Unit, UnitFor)` pairs. The `UnitFor`
213 /// is the profile type that should be used for dependencies of the unit.
214 fn compute_deps
<'a
, 'cfg
>(
216 state
: &mut State
<'a
, 'cfg
>,
218 ) -> CargoResult
<Vec
<UnitDep
<'a
>>> {
219 if unit
.mode
.is_run_custom_build() {
220 return compute_deps_custom_build(unit
, state
);
221 } else if unit
.mode
.is_doc() {
222 // Note: this does not include doc test.
223 return compute_deps_doc(unit
, state
);
227 let id
= unit
.pkg
.package_id();
228 let deps
= state
.resolve().deps(id
).filter(|&(_id
, deps
)| {
229 assert
!(!deps
.is_empty());
230 deps
.iter().any(|dep
| {
231 // If this target is a build command, then we only want build
232 // dependencies, otherwise we want everything *other than* build
234 if unit
.target
.is_custom_build() != dep
.is_build() {
238 // If this dependency is **not** a transitive dependency, then it
239 // only applies to test/example targets.
240 if !dep
.is_transitive()
241 && !unit
.target
.is_test()
242 && !unit
.target
.is_example()
243 && !unit
.mode
.is_any_test()
248 // If this dependency is only available for certain platforms,
249 // make sure we're only enabling it for that platform.
250 if !bcx
.dep_platform_activated(dep
, unit
.kind
) {
254 // If we've gotten past all that, then this dependency is
260 let mut ret
= Vec
::new();
261 for (id
, _
) in deps
{
262 let pkg
= match state
.get(id
)?
{
266 let lib
= match pkg
.targets().iter().find(|t
| t
.is_lib()) {
270 let mode
= check_or_build_mode(unit
.mode
, lib
);
271 let dep_unit_for
= unit_for
.with_for_host(lib
.for_host());
273 if bcx
.config
.cli_unstable().dual_proc_macros
275 && unit
.kind
== Kind
::Target
277 let unit_dep
= new_unit_dep(state
, unit
, pkg
, lib
, dep_unit_for
, Kind
::Target
, mode
)?
;
279 let unit_dep
= new_unit_dep(state
, unit
, pkg
, lib
, dep_unit_for
, Kind
::Host
, mode
)?
;
282 let unit_dep
= new_unit_dep(
288 unit
.kind
.for_target(lib
),
295 // If this target is a build script, then what we've collected so far is
296 // all we need. If this isn't a build script, then it depends on the
297 // build script if there is one.
298 if unit
.target
.is_custom_build() {
301 ret
.extend(dep_build_script(unit
, state
)?
);
303 // If this target is a binary, test, example, etc, then it depends on
304 // the library of the same package. The call to `resolve.deps` above
305 // didn't include `pkg` in the return values, so we need to special case
306 // it here and see if we need to push `(pkg, pkg_lib_target)`.
307 if unit
.target
.is_lib() && unit
.mode
!= CompileMode
::Doctest
{
310 ret
.extend(maybe_lib(unit
, state
, unit_for
)?
);
312 // If any integration tests/benches are being run, make sure that
313 // binaries are built as well.
314 if !unit
.mode
.is_check()
315 && unit
.mode
.is_any_test()
316 && (unit
.target
.is_test() || unit
.target
.is_bench())
323 let no_required_features
= Vec
::new();
326 // Skip binaries with required features that have not been selected.
327 t
.required_features().unwrap_or(&no_required_features
).iter().all(|f
| {
328 unit
.features
.contains(&f
.as_str())
337 UnitFor
::new_normal(),
338 unit
.kind
.for_target(t
),
342 .collect
::<CargoResult
<Vec
<UnitDep
<'a
>>>>()?
,
349 /// Returns the dependencies needed to run a build script.
351 /// The `unit` provided must represent an execution of a build script, and
352 /// the returned set of units must all be run before `unit` is run.
353 fn compute_deps_custom_build
<'a
, 'cfg
>(
355 state
: &mut State
<'a
, 'cfg
>,
356 ) -> CargoResult
<Vec
<UnitDep
<'a
>>> {
357 if let Some(links
) = unit
.pkg
.manifest().links() {
358 if state
.bcx
.script_override(links
, unit
.kind
).is_some() {
359 // Overridden build scripts don't have any dependencies.
360 return Ok(Vec
::new());
363 // When not overridden, then the dependencies to run a build script are:
365 // 1. Compiling the build script itself.
366 // 2. For each immediate dependency of our package which has a `links`
367 // key, the execution of that build script.
369 // We don't have a great way of handling (2) here right now so this is
370 // deferred until after the graph of all unit dependencies has been
372 let unit_dep
= new_unit_dep(
377 // All dependencies of this unit should use profiles for custom
379 UnitFor
::new_build(),
380 // Build scripts always compiled for the host.
387 /// Returns the dependencies necessary to document a package.
388 fn compute_deps_doc
<'a
, 'cfg
>(
390 state
: &mut State
<'a
, 'cfg
>,
391 ) -> CargoResult
<Vec
<UnitDep
<'a
>>> {
395 .deps(unit
.pkg
.package_id())
396 .filter(|&(_id
, deps
)| {
397 deps
.iter().any(|dep
| match dep
.kind() {
398 DepKind
::Normal
=> bcx
.dep_platform_activated(dep
, unit
.kind
),
403 // To document a library, we depend on dependencies actually being
404 // built. If we're documenting *all* libraries, then we also depend on
405 // the documentation of the library being built.
406 let mut ret
= Vec
::new();
407 for (id
, _deps
) in deps
{
408 let dep
= match state
.get(id
)?
{
412 let lib
= match dep
.targets().iter().find(|t
| t
.is_lib()) {
416 // Rustdoc only needs rmeta files for regular dependencies.
417 // However, for plugins/proc macros, deps should be built like normal.
418 let mode
= check_or_build_mode(unit
.mode
, lib
);
419 let dep_unit_for
= UnitFor
::new_normal().with_for_host(lib
.for_host());
420 let lib_unit_dep
= new_unit_dep(
426 unit
.kind
.for_target(lib
),
429 ret
.push(lib_unit_dep
);
430 if let CompileMode
::Doc { deps: true }
= unit
.mode
{
431 // Document this lib as well.
432 let doc_unit_dep
= new_unit_dep(
438 unit
.kind
.for_target(lib
),
441 ret
.push(doc_unit_dep
);
445 // Be sure to build/run the build script for documented libraries.
446 ret
.extend(dep_build_script(unit
, state
)?
);
448 // If we document a binary/example, we need the library available.
449 if unit
.target
.is_bin() || unit
.target
.is_example() {
450 ret
.extend(maybe_lib(unit
, state
, UnitFor
::new_normal())?
);
457 state
: &mut State
<'a
, '_
>,
459 ) -> CargoResult
<Option
<UnitDep
<'a
>>> {
463 .find(|t
| t
.linkable())
465 let mode
= check_or_build_mode(unit
.mode
, t
);
472 unit
.kind
.for_target(t
),
479 /// If a build script is scheduled to be run for the package specified by
480 /// `unit`, this function will return the unit to run that build script.
482 /// Overriding a build script simply means that the running of the build
483 /// script itself doesn't have any dependencies, so even in that case a unit
484 /// of work is still returned. `None` is only returned if the package has no
486 fn dep_build_script
<'a
>(
488 state
: &State
<'a
, '_
>,
489 ) -> CargoResult
<Option
<UnitDep
<'a
>>> {
493 .find(|t
| t
.is_custom_build())
495 // The profile stored in the Unit is the profile for the thing
496 // the custom build script is running for.
500 .get_profile_run_custom_build(&unit
.profile
);
501 new_unit_dep_with_profile(
506 UnitFor
::new_build(),
508 CompileMode
::RunCustomBuild
,
515 /// Choose the correct mode for dependencies.
516 fn check_or_build_mode(mode
: CompileMode
, target
: &Target
) -> CompileMode
{
518 CompileMode
::Check { .. }
| CompileMode
::Doc { .. }
=> {
519 if target
.for_host() {
520 // Plugin and proc macro targets should be compiled like
524 // Regular dependencies should not be checked with --test.
525 // Regular dependencies of doc targets should emit rmeta only.
526 CompileMode
::Check { test: false }
529 _
=> CompileMode
::Build
,
533 /// Create a new Unit for a dependency from `parent` to `pkg` and `target`.
535 state
: &State
<'a
, '_
>,
542 ) -> CargoResult
<UnitDep
<'a
>> {
543 let profile
= state
.bcx
.profiles
.get_profile(
545 state
.bcx
.ws
.is_member(pkg
),
548 state
.bcx
.build_config
.release
,
550 new_unit_dep_with_profile(state
, parent
, pkg
, target
, unit_for
, kind
, mode
, profile
)
553 fn new_unit_dep_with_profile
<'a
>(
554 state
: &State
<'a
, '_
>,
562 ) -> CargoResult
<UnitDep
<'a
>> {
563 // TODO: consider making extern_crate_name return InternedString?
564 let extern_crate_name
= InternedString
::new(&state
.resolve().extern_crate_name(
565 parent
.pkg
.package_id(),
571 .is_public_dep(parent
.pkg
.package_id(), pkg
.package_id());
572 let features
= state
.resolve().features_sorted(pkg
.package_id());
576 .intern(pkg
, target
, profile
, kind
, mode
, features
, state
.is_std
);
585 /// Fill in missing dependencies for units of the `RunCustomBuild`
587 /// As mentioned above in `compute_deps_custom_build` each build script
588 /// execution has two dependencies. The first is compiling the build script
589 /// itself (already added) and the second is that all crates the package of the
590 /// build script depends on with `links` keys, their build script execution. (a
591 /// bit confusing eh?)
593 /// Here we take the entire `deps` map and add more dependencies from execution
594 /// of one build script to execution of another build script.
595 fn connect_run_custom_build_deps(unit_dependencies
: &mut UnitGraph
<'_
>) {
596 let mut new_deps
= Vec
::new();
599 // First up build a reverse dependency map. This is a mapping of all
600 // `RunCustomBuild` known steps to the unit which depends on them. For
601 // example a library might depend on a build script, so this map will
602 // have the build script as the key and the library would be in the
604 let mut reverse_deps_map
= HashMap
::new();
605 for (unit
, deps
) in unit_dependencies
.iter() {
607 if dep
.unit
.mode
== CompileMode
::RunCustomBuild
{
610 .or_insert_with(HashSet
::new
)
616 // Next, we take a look at all build scripts executions listed in the
617 // dependency map. Our job here is to take everything that depends on
618 // this build script (from our reverse map above) and look at the other
619 // package dependencies of these parents.
621 // If we depend on a linkable target and the build script mentions
622 // `links`, then we depend on that package's build script! Here we use
623 // `dep_build_script` to manufacture an appropriate build script unit to
625 for unit
in unit_dependencies
627 .filter(|k
| k
.mode
== CompileMode
::RunCustomBuild
)
629 // This is the lib that runs this custom build.
630 let reverse_deps
= match reverse_deps_map
.get(unit
) {
635 let to_add
= reverse_deps
637 // Get all deps for lib.
638 .flat_map(|reverse_dep
| unit_dependencies
[reverse_dep
].iter())
639 // Only deps with `links`.
641 other
.unit
.pkg
!= unit
.pkg
642 && other
.unit
.target
.linkable()
643 && other
.unit
.pkg
.manifest().links().is_some()
645 // Get the RunCustomBuild for other lib.
646 .filter_map(|other
| {
647 unit_dependencies
[&other
.unit
]
649 .find(|other_dep
| other_dep
.unit
.mode
== CompileMode
::RunCustomBuild
)
652 .collect
::<HashSet
<_
>>();
654 if !to_add
.is_empty() {
655 // (RunCustomBuild, set(other RunCustomBuild))
656 new_deps
.push((*unit
, to_add
));
661 // And finally, add in all the missing dependencies!
662 for (unit
, new_deps
) in new_deps
{
663 unit_dependencies
.get_mut(&unit
).unwrap().extend(new_deps
);
667 impl<'a
, 'cfg
> State
<'a
, 'cfg
> {
668 fn resolve(&self) -> &'a Resolve
{
670 self.std_resolve
.unwrap()
676 fn get(&mut self, id
: PackageId
) -> CargoResult
<Option
<&'a Package
>> {
677 if let Some(pkg
) = self.package_cache
.get(&id
) {
678 return Ok(Some(pkg
));
680 if !self.waiting_on_download
.insert(id
) {
683 if let Some(pkg
) = self.downloads
.start(id
)?
{
684 self.package_cache
.insert(id
, pkg
);
685 self.waiting_on_download
.remove(&id
);
686 return Ok(Some(pkg
));
691 /// Completes at least one downloading, maybe waiting for more to complete.
693 /// This function will block the current thread waiting for at least one
694 /// crate to finish downloading. The function may continue to download more
695 /// crates if it looks like there's a long enough queue of crates to keep
696 /// downloading. When only a handful of packages remain this function
697 /// returns, and it's hoped that by returning we'll be able to push more
698 /// packages to download into the queue.
699 fn finish_some_downloads(&mut self) -> CargoResult
<()> {
700 assert
!(self.downloads
.remaining() > 0);
702 let pkg
= self.downloads
.wait()?
;
703 self.waiting_on_download
.remove(&pkg
.package_id());
704 self.package_cache
.insert(pkg
.package_id(), pkg
);
706 // Arbitrarily choose that 5 or more packages concurrently download
707 // is a good enough number to "fill the network pipe". If we have
708 // less than this let's recompute the whole unit dependency graph
709 // again and try to find some more packages to download.
710 if self.downloads
.remaining() < 5 {