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
.is_host() && !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
&& lib
.proc_macro() && !unit
.kind
.is_host() {
274 let unit_dep
= new_unit_dep(state
, unit
, pkg
, lib
, dep_unit_for
, unit
.kind
, mode
)?
;
276 let unit_dep
= new_unit_dep(state
, unit
, pkg
, lib
, dep_unit_for
, Kind
::Host
, mode
)?
;
279 let unit_dep
= new_unit_dep(
285 unit
.kind
.for_target(lib
),
292 // If this target is a build script, then what we've collected so far is
293 // all we need. If this isn't a build script, then it depends on the
294 // build script if there is one.
295 if unit
.target
.is_custom_build() {
298 ret
.extend(dep_build_script(unit
, state
)?
);
300 // If this target is a binary, test, example, etc, then it depends on
301 // the library of the same package. The call to `resolve.deps` above
302 // didn't include `pkg` in the return values, so we need to special case
303 // it here and see if we need to push `(pkg, pkg_lib_target)`.
304 if unit
.target
.is_lib() && unit
.mode
!= CompileMode
::Doctest
{
307 ret
.extend(maybe_lib(unit
, state
, unit_for
)?
);
309 // If any integration tests/benches are being run, make sure that
310 // binaries are built as well.
311 if !unit
.mode
.is_check()
312 && unit
.mode
.is_any_test()
313 && (unit
.target
.is_test() || unit
.target
.is_bench())
320 let no_required_features
= Vec
::new();
323 // Skip binaries with required features that have not been selected.
324 t
.required_features().unwrap_or(&no_required_features
).iter().all(|f
| {
325 unit
.features
.contains(&f
.as_str())
334 UnitFor
::new_normal(),
335 unit
.kind
.for_target(t
),
339 .collect
::<CargoResult
<Vec
<UnitDep
<'a
>>>>()?
,
346 /// Returns the dependencies needed to run a build script.
348 /// The `unit` provided must represent an execution of a build script, and
349 /// the returned set of units must all be run before `unit` is run.
350 fn compute_deps_custom_build
<'a
, 'cfg
>(
352 state
: &mut State
<'a
, 'cfg
>,
353 ) -> CargoResult
<Vec
<UnitDep
<'a
>>> {
354 if let Some(links
) = unit
.pkg
.manifest().links() {
355 if state
.bcx
.script_override(links
, unit
.kind
).is_some() {
356 // Overridden build scripts don't have any dependencies.
357 return Ok(Vec
::new());
360 // When not overridden, then the dependencies to run a build script are:
362 // 1. Compiling the build script itself.
363 // 2. For each immediate dependency of our package which has a `links`
364 // key, the execution of that build script.
366 // We don't have a great way of handling (2) here right now so this is
367 // deferred until after the graph of all unit dependencies has been
369 let unit_dep
= new_unit_dep(
374 // All dependencies of this unit should use profiles for custom
376 UnitFor
::new_build(),
377 // Build scripts always compiled for the host.
384 /// Returns the dependencies necessary to document a package.
385 fn compute_deps_doc
<'a
, 'cfg
>(
387 state
: &mut State
<'a
, 'cfg
>,
388 ) -> CargoResult
<Vec
<UnitDep
<'a
>>> {
392 .deps(unit
.pkg
.package_id())
393 .filter(|&(_id
, deps
)| {
394 deps
.iter().any(|dep
| match dep
.kind() {
395 DepKind
::Normal
=> bcx
.dep_platform_activated(dep
, unit
.kind
),
400 // To document a library, we depend on dependencies actually being
401 // built. If we're documenting *all* libraries, then we also depend on
402 // the documentation of the library being built.
403 let mut ret
= Vec
::new();
404 for (id
, _deps
) in deps
{
405 let dep
= match state
.get(id
)?
{
409 let lib
= match dep
.targets().iter().find(|t
| t
.is_lib()) {
413 // Rustdoc only needs rmeta files for regular dependencies.
414 // However, for plugins/proc macros, deps should be built like normal.
415 let mode
= check_or_build_mode(unit
.mode
, lib
);
416 let dep_unit_for
= UnitFor
::new_normal().with_for_host(lib
.for_host());
417 let lib_unit_dep
= new_unit_dep(
423 unit
.kind
.for_target(lib
),
426 ret
.push(lib_unit_dep
);
427 if let CompileMode
::Doc { deps: true }
= unit
.mode
{
428 // Document this lib as well.
429 let doc_unit_dep
= new_unit_dep(
435 unit
.kind
.for_target(lib
),
438 ret
.push(doc_unit_dep
);
442 // Be sure to build/run the build script for documented libraries.
443 ret
.extend(dep_build_script(unit
, state
)?
);
445 // If we document a binary/example, we need the library available.
446 if unit
.target
.is_bin() || unit
.target
.is_example() {
447 ret
.extend(maybe_lib(unit
, state
, UnitFor
::new_normal())?
);
454 state
: &mut State
<'a
, '_
>,
456 ) -> CargoResult
<Option
<UnitDep
<'a
>>> {
460 .find(|t
| t
.linkable())
462 let mode
= check_or_build_mode(unit
.mode
, t
);
469 unit
.kind
.for_target(t
),
476 /// If a build script is scheduled to be run for the package specified by
477 /// `unit`, this function will return the unit to run that build script.
479 /// Overriding a build script simply means that the running of the build
480 /// script itself doesn't have any dependencies, so even in that case a unit
481 /// of work is still returned. `None` is only returned if the package has no
483 fn dep_build_script
<'a
>(
485 state
: &State
<'a
, '_
>,
486 ) -> CargoResult
<Option
<UnitDep
<'a
>>> {
490 .find(|t
| t
.is_custom_build())
492 // The profile stored in the Unit is the profile for the thing
493 // the custom build script is running for.
497 .get_profile_run_custom_build(&unit
.profile
);
498 new_unit_dep_with_profile(
503 UnitFor
::new_build(),
505 CompileMode
::RunCustomBuild
,
512 /// Choose the correct mode for dependencies.
513 fn check_or_build_mode(mode
: CompileMode
, target
: &Target
) -> CompileMode
{
515 CompileMode
::Check { .. }
| CompileMode
::Doc { .. }
=> {
516 if target
.for_host() {
517 // Plugin and proc macro targets should be compiled like
521 // Regular dependencies should not be checked with --test.
522 // Regular dependencies of doc targets should emit rmeta only.
523 CompileMode
::Check { test: false }
526 _
=> CompileMode
::Build
,
530 /// Create a new Unit for a dependency from `parent` to `pkg` and `target`.
532 state
: &State
<'a
, '_
>,
539 ) -> CargoResult
<UnitDep
<'a
>> {
540 let profile
= state
.bcx
.profiles
.get_profile(
542 state
.bcx
.ws
.is_member(pkg
),
545 state
.bcx
.build_config
.release
,
547 new_unit_dep_with_profile(state
, parent
, pkg
, target
, unit_for
, kind
, mode
, profile
)
550 fn new_unit_dep_with_profile
<'a
>(
551 state
: &State
<'a
, '_
>,
559 ) -> CargoResult
<UnitDep
<'a
>> {
560 // TODO: consider making extern_crate_name return InternedString?
561 let extern_crate_name
= InternedString
::new(&state
.resolve().extern_crate_name(
562 parent
.pkg
.package_id(),
568 .is_public_dep(parent
.pkg
.package_id(), pkg
.package_id());
569 let features
= state
.resolve().features_sorted(pkg
.package_id());
573 .intern(pkg
, target
, profile
, kind
, mode
, features
, state
.is_std
);
582 /// Fill in missing dependencies for units of the `RunCustomBuild`
584 /// As mentioned above in `compute_deps_custom_build` each build script
585 /// execution has two dependencies. The first is compiling the build script
586 /// itself (already added) and the second is that all crates the package of the
587 /// build script depends on with `links` keys, their build script execution. (a
588 /// bit confusing eh?)
590 /// Here we take the entire `deps` map and add more dependencies from execution
591 /// of one build script to execution of another build script.
592 fn connect_run_custom_build_deps(unit_dependencies
: &mut UnitGraph
<'_
>) {
593 let mut new_deps
= Vec
::new();
596 // First up build a reverse dependency map. This is a mapping of all
597 // `RunCustomBuild` known steps to the unit which depends on them. For
598 // example a library might depend on a build script, so this map will
599 // have the build script as the key and the library would be in the
601 let mut reverse_deps_map
= HashMap
::new();
602 for (unit
, deps
) in unit_dependencies
.iter() {
604 if dep
.unit
.mode
== CompileMode
::RunCustomBuild
{
607 .or_insert_with(HashSet
::new
)
613 // Next, we take a look at all build scripts executions listed in the
614 // dependency map. Our job here is to take everything that depends on
615 // this build script (from our reverse map above) and look at the other
616 // package dependencies of these parents.
618 // If we depend on a linkable target and the build script mentions
619 // `links`, then we depend on that package's build script! Here we use
620 // `dep_build_script` to manufacture an appropriate build script unit to
622 for unit
in unit_dependencies
624 .filter(|k
| k
.mode
== CompileMode
::RunCustomBuild
)
626 // This is the lib that runs this custom build.
627 let reverse_deps
= match reverse_deps_map
.get(unit
) {
632 let to_add
= reverse_deps
634 // Get all deps for lib.
635 .flat_map(|reverse_dep
| unit_dependencies
[reverse_dep
].iter())
636 // Only deps with `links`.
638 other
.unit
.pkg
!= unit
.pkg
639 && other
.unit
.target
.linkable()
640 && other
.unit
.pkg
.manifest().links().is_some()
642 // Get the RunCustomBuild for other lib.
643 .filter_map(|other
| {
644 unit_dependencies
[&other
.unit
]
646 .find(|other_dep
| other_dep
.unit
.mode
== CompileMode
::RunCustomBuild
)
649 .collect
::<HashSet
<_
>>();
651 if !to_add
.is_empty() {
652 // (RunCustomBuild, set(other RunCustomBuild))
653 new_deps
.push((*unit
, to_add
));
658 // And finally, add in all the missing dependencies!
659 for (unit
, new_deps
) in new_deps
{
660 unit_dependencies
.get_mut(&unit
).unwrap().extend(new_deps
);
664 impl<'a
, 'cfg
> State
<'a
, 'cfg
> {
665 fn resolve(&self) -> &'a Resolve
{
667 self.std_resolve
.unwrap()
673 fn get(&mut self, id
: PackageId
) -> CargoResult
<Option
<&'a Package
>> {
674 if let Some(pkg
) = self.package_cache
.get(&id
) {
675 return Ok(Some(pkg
));
677 if !self.waiting_on_download
.insert(id
) {
680 if let Some(pkg
) = self.downloads
.start(id
)?
{
681 self.package_cache
.insert(id
, pkg
);
682 self.waiting_on_download
.remove(&id
);
683 return Ok(Some(pkg
));
688 /// Completes at least one downloading, maybe waiting for more to complete.
690 /// This function will block the current thread waiting for at least one
691 /// crate to finish downloading. The function may continue to download more
692 /// crates if it looks like there's a long enough queue of crates to keep
693 /// downloading. When only a handful of packages remain this function
694 /// returns, and it's hoped that by returning we'll be able to push more
695 /// packages to download into the queue.
696 fn finish_some_downloads(&mut self) -> CargoResult
<()> {
697 assert
!(self.downloads
.remaining() > 0);
699 let pkg
= self.downloads
.wait()?
;
700 self.waiting_on_download
.remove(&pkg
.package_id());
701 self.package_cache
.insert(pkg
.package_id(), pkg
);
703 // Arbitrarily choose that 5 or more packages concurrently download
704 // is a good enough number to "fill the network pipe". If we have
705 // less than this let's recompute the whole unit dependency graph
706 // again and try to find some more packages to download.
707 if self.downloads
.remaining() < 5 {