Skip to content

Commit 7248f4b

Browse files
committed
add support for artifact dependencies (#9096)
Tracking issue: #9096 Original PR: #9992 Add 'bindeps' -Z flag for later use A test to validate artifact dependencies aren't currently parsed. Parse 'artifact' and 'lib' fields. Note that this isn't behind a feature toggle so 'unused' messages will disappear. Transfer artifact dependencies from toml- into manifest-dependencies There are a few premises governing the operation. - if unstable features are not set, warn when 'artifact' or 'lib' is encountered. - bail if 'lib' is encountered alone, but warn that this WOULD happen with nightly. - artifact parsing checks for all invariants, but some aren't tested. Assure serialization of 'artifact' and 'lib' fields produces suitable values during publishing This should be the only place were these fields matter and where a cargo manifest is actually produced. These are only for internal use, no user is typically going to see or edit them. Place all artifact dependency tests inta their own module This facilitates deduplication later and possibly redistribution into other modules if there is a better fit. Represent artifacts that are rust libraries as another ArtifactKind This is more consistent and probably simpler for later use. No need to reflect the TOML data structure. Add tests to assure only 'lib = true' artifact deps are documented RFC-3028 doesn't talk about documentation, but for lib=true it's clear what the desired behaviour should be. If an artifact isn't a library though, then for now, it's transparent, maybe. Many more tests, more documentation, mild `Artifact` refactor The latter seems to be a better fit for what being an artifact really means within cargo, as it literally turns being a library on or off, and thus only optionally becoming a normal library. refactor to prepare for artifact related checks Don't show a no-lib warning for artifact dependencies (with lib = false) Tests for more artifact dependency invariants These are merely a proof of concept to show that we are not in a position to actually figure out everything about artifacts right after resolution. However, the error message looks more like a fatal error and less like something that can happen with a more elaborate error message with causes. This might show that these kind of checks might be better done later right before trying to use the information for create compile units. Validate that artifact deps with lib=true still trigger no-lib warnings This triggers the same warning as before, for now without any customization to indicate it's an artifact dependency. Use warnings instead of errors ------------------------------ This avoids the kind of harsh end of compilation in favor of something that can be recovered from. Since warnings are annoying, users will probably avoid re-declaring artifact dependencies. Hook in artifact dependencies into build script runs Even though we would still have to see what happens if they have a lib as well. Is it built twice? Also ---- - fly-by refactor: fix typo; use ? in method returning option - Propagate artifact information into Units; put artifacts into place This means artifacts now have their own place in the 'artifact' directory and uplifts won't happen for them. - refactor and fix cippy suggestion - fix build after rebasing onto master Create directories when executing the job, and not when preparing it. also: Get CI to work on windows the easy way, for now. Set directories for artifact dependencies in build script runtimes Test remaining kinds of build-script runtime environment variables Also ---- - Fix windows tests, the quick way. - Try to fix windows assertions, and generalize them - Fix second test for windows, hopefully test for available library dependency in build scripts with lib = true probably generally exclude all artifact dependencies with lib=false. Pass renamed dep names along with unit deps to allow proper artifact env names Test for selective bin:<name> syntax, as well as binaries with dashes Test to assure dependency names are transformed correctly assure advertised binaries and directories are actually present This wouldn't be the case if dependencies are not setup correctly, for instance. Also ---- - make it easier to see actual values even on failure This should help figure out why on CI something fails that works locally no matter what. Turns out this is a race condition, with my machine being on the good side of it so it doesn't show in testing. Fortunately it still can be reproduced and easily tested for. - refactor test; the race condition is still present though - Force CI to pass here by avoiding checks triggering race. - Fix windows build, maybe? More tolerant is_file() checks to account for delay on CI This _should_ help CI to test for the presence which is better than not testing at all. This appears to be needed as the output file isn't ready/present in time for some reason. The root cause of this issue is unknown, but it's definitely a race as it rarely happens locally. When it happened, the file was always present after the run. Now we will learn if it is truly not present, ever, or if it's maybe something very else. Validate libs also don't see artifact dependencies as libraries with lib=false Also ---- - Add prelimiary test for validating build-time artifacts - Try to fix CI on gnu windows Which apparently generates paths similar to linux, but with .exe suffix. The current linux patterns should match that. - refactor Help sharing code across modules allow rustc to use artifact dep environment variables, but… …it needs some adjustments to actually setup the unit dependency graph with artifacts as well. Right now it will only setup dependencies for artifacts that are libs, but not the artifacts themselves, completely ignoring them when they are not libs. Make artifact dependencies available in main loop This is the commit message #2: ------------------------------ rough cut of support for artifact dependencies at build time… …which unfortunately already shows that the binary it is supposed to include is reproducibly not ready in time even though the path is correct and it's present right after the run. Could it be related to rmeta? This is the commit message #3: ------------------------------ Fix test expectations as failure is typical than the warning we had before… …and add some tolerance to existing test to avoid occasional failures. This doesn't change the issue that it also doens't work at all for libraries, which is nicely reproducable and hopefully helps to fix this issue. This is the commit message #4: ------------------------------ Probably the fix for the dependency issue in the scheduler This means that bin() targets are now properly added to the job graph to cause proper syncing, whereas previously apparently it would still schedule binaries, but somehow consider them rmeta and thus start their dependents too early, leading to races. This is the commit message #5: ------------------------------ Don't accidentally include non-gnu windows tests in gnu windows. Support cargo doc and cargo check The major changes here are… - always compile artifacts in build mode, as we literally want the build output, always, which the dependent might rely on being present. - share code between the rather similar looking paths for rustdoc and rustc. Make artifact messages appear more in line with cargo by using backticks Also: Add first test for static lib support in build scripts build-scripts with support for cdylib and staticlib - Fix windows msvc build No need to speculate why the staticlib has hashes in the name even though nothing else. staticlib and cdylib support for libraries test staticlib and cdylibs for rustdoc as well. Also catch a seemingly untested special case/warning about the lack of linkable items, which probably shouldn't be an issue for artifacts as they are not linkable in the traditional sense. more useful test for 'cargo check' `cargo check` isn't used very consistently in tests, so when we use it we should be sure to actually try to use an artifact based feature to gain some coverage. verify that multiple versions are allowed for artifact deps as well. also: remove redundant test This is the commit message #2: ------------------------------ Properly choose which dependencies take part in artifact handling Previously it would include them very generously without considering the compatible dependency types. This is the commit message #3: ------------------------------ a more complex test which includes dev-dependencies It also shows that doc-tests don't yet work as rustdoc is run outside of the system into which we integrate right now. It should be possible to write our environment variable configuration in terms of this 'finished compilation' though, hopefully with most code reused. This is the commit message #4: ------------------------------ A first stab at storing artifact environment variables for packages… …however, it seems like the key for this isn't necessarily correct under all circumstances. Maybe it should be something more specific, don't know. This is the commit message #5: ------------------------------ Adjust key for identifying units to Metadata This one is actually unique and feels much better. This is the commit message #6: ------------------------------ Attempt to make use of artifact environment information… …but fail as the metadata won't match as the doctest unit is, of course, its separate unit. Now I wonder if its possible to find the artifact units in question that have the metadata. Properly use metadata to use artifact environment variables in doctests This is the commit message #2: ------------------------------ Add test for resolver = "2" and build dependencies Interestingly the 'host-features' flag must be set (as is seemingly documented in the flags documentation as well), even though I am not quite sure if this is the 100% correct solution. Should it rather have an entry with this flag being false in its map? Probably not… but I am not quite certain. This is the commit message #3: ------------------------------ set most if not all tests to use resolver = "2" This allows to keep it working with the most recent version while allowing to quickly test with "1" as well (which thus far was working fine). All tests I could imagine (excluding target and profiles) are working now Crossplatform tests now run on architecture aarm64 as well. More stringent negative testing Fix incorrect handling of dependency directory computation Previously it would just 'hack' the deps-dir to become something very different for artifacts. This could easily be fixed by putting the logic for artifact output directories into the right spot. A test for cargo-tree to indicate artifacts aren't handled specifically Assure build-scripts can't access artifacts at build time Actual doc-tests with access to artifact env vars All relevant parsing of `target = [..]` Next step is to actually take it into consideration. A failing test for adjusting the target for build script artifacts using --target Check for unknown artifact target triple in a place that exists for a year The first test showing that `target="target"` deps seemingly work For now only tested for build scripts, but it won't be much different for non-build dependencies. build scripts accept custom targets unconditionally Support target setting for non-build dependencies This is the commit message #2: ------------------------------ Add doc-test cross compile related test Even though there is no artifact code specific to doc testing, it's worth to try testing it with different target settings to validate it still works despite doc tests having some special caseing around target settings. This is the commit message #3: ------------------------------ A test to validate profiles work as expected for build-deps and non-build deps No change is required to make this work and artifact dependencies 'just work' based on the typical rules of their non-artifact counterarts. This is the commit message #4: ------------------------------ Adjust `cargo metadata` to deal with artifact dependencies This commit was squashed and there is probably more that changed. This is the commit message #5: ------------------------------ Show bin-only artifacts in "resolve" of metadata as well. This is the commit message #6: ------------------------------ minor refactoring during research for RFC-3176 This will soon need to return multiple extern-name/dep-name pairs. This is the commit message #7: ------------------------------ See if opt-level 3 works on win-msvc in basic profile test for artifacts This is the same value as is used in the other test of the same name, which certainly runs on windows. This is the commit message #8: ------------------------------ refactor Assure the type for targets reflect that they cannot be the host target, which removes a few unreachable!() expressions. Put `root_unit_compile_kind` into `UnitFor` Previously that wasn't done because of the unused `all_values()` method which has now been deleted as its not being used anyomre. This allows for the root unit compile kind to be passed as originally intended, instead of working around the previous lack of extendability of UnitFor due to ::all_values(). This is also the basis for better/correct feature handling once feature resolution can be depending on the artifact target as well, resulting in another extension to UnitFor for that matter. Also ---- - Fix ordering Previously the re-created target_mode was used due to the reordering in code, and who knows what kind of effects that might have (despite the test suite being OK with it). Let's put it back in place. - Deactivate test with filename collision on MSVC until RFC-3176 lands Avoid clashes with binaries called 'artifact' by putting 'artifact/' into './deps/' This commit addresses review comment #9992 (comment) Don't rely on operator precedence for boolean operations Now it should be clear that no matter what the first term is, if the unit is an artifact, we should enqueue it. Replace boolean and `/*artifact*/ <bool>` with `IsArtifact::(Yes/No)` fix `doc::doc_lib_false()` test It broke due to major breakage in the way dependencies are calculated. Now we differentiate between deps computation for docs and for building. Avoid testing for doctest cross-compilation message It seems to be present on my machine, but isn't on linux and it's probably better to leave it out entirely and focus on the portions of consecutive output that we want to see at least. A test to validate features are unified across libraries and those in artifact deps in the same target Allow aarch64 MacOS to crosscompile to an easily executable alternative target That way more tests can run locally. Support for feature resolution per target The implementation is taken directly from RFC-3176 and notably lacks the 'multidep' part. Doing this definitely has the benefit of making entirely clear 'what is what' and helps to greatly reduce the scope of RFC-3176 when it's rebuilt based on the latest RF-3028, what we are implementing right now. Also ---- - A test which prooves that artifact deps with different target don't have a feature namespace yet - Add a test to validate features are namespaced by target Previously it didn't work because it relies on resolver = "2". - 'cargo metadata' test to see how artifact-deps are presented - Missed an opportunity for using the newly introduced `PackageFeaturesKey` - Use a HashMap to store name->value relations for artifact environment variables This is semantically closer to what's intended. also: Remove a by now misleading comment Prevent resolver crash if `target = "target"` is encountered in non-build dependencies A warning was emitted before, now we also apply a fix. Previously the test didn't fail as it accidentally used the old resolver, which now has been removed. Abort in parsing stage if nightly flag is not set and 'artifact' is used There is no good reason to delay errors to a later stage when code tries to use artifacts via environment variables which are not present. Change wording of warning message into what's expected for an error message remove unnecessary `Result` in `collect()` call Improve logic to warn if dependencie are ignored due to missing libraries The improvement here is to trigger correctly if any dependency of a crate is potentially a library, without having an actual library target as part of the package specification. Due to artifact dependencies it's also possible to have a dependency to the same crate of the same version, hence the package name isn't necessarily a unique name anymore. Now the name of the actual dependency in the toml file is used to alleviate this. Various small changes for readability and consistency A failing test to validate artifacts work in published crates as well Originally this should have been a test to see target acquisition works but this more pressing issue surfaced instead. Make artifacts known to the registry data (backwards compatible) Now artifacts are serialized into the registry on publish (at least if this code is actually used in the real crates-io registry) which allows the resolve stage to contain artifact information. This seems to be in line with the idea to provide cargo with all information it needs to do package resolution without downloading the actual manifest. Pick up all artifact targets into target info once resolve data is available Even though this works in the test at hand, it clearly shows there is a cyclic dependency between the resolve and the target data. In theory, one would have to repeat resolution until it settles while avoiding cycles. Maybe there is a better way. Add `bindeps`/artifact dependencies to `unstsable.md` with examples Fix tests Various small improvements Greatly simplify artifact environment propagation to commands Remove all adjustments to cargo-metadata, but leave tests The tests are to record the status quo with the current code when artifact dependencies are present and assure the information is not entirely non-sensical. Revert "Make artifacts known to the registry data (backwards compatible)" This reverts commit adc5f8ad04840af9fd06c964cfcdffb8c30769b0. Ideally we are able to make it work without altering the registry storage format. This could work if information from the package set is added to the resolve information. Enrich resolves information with additional information from downloaded manifests Resolve information comes from the registry, and it's only as rich as needed to know which packages take part in the build. Artifacts, however, don't influence dependency resolution, hence it shouldn't be part of it. For artifact information being present nonetheless when it matters, we port it back to the resolve graph where it will be needed later. Collect 'forced-target' information from non-workspace members as well This is needed as these targets aren't present in the registry and thus can't be picked up by traversing non-workspce members. The mechanism used to pick up artifact targets can also be used to pick up these targets. Remove unnecessary adjustment of doc test refactor `State::deps()` to have filter; re-enable accidentally disabled test The initial rebasing started out with a separted `deps_filtered()` method to retain the original capabilities while minimizing the chance for surprises. It turned out that the all changes combined in this PR make heavy use of filtering capabilities to the point where `deps(<without filter>)` was unused. This suggested that it's required to keep it as is without a way to inline portions of it. For the original change that triggered this rebase, see bd45ac8 The fix originally made was reapplied by allowing to re-use the required filter, but without inlining it. Always error on invalid artifact setup, with or without enabled bindeps feature Clarify how critical resolver code around artifact is working Remove workaround in favor of deferring a proper implementation See #9992 (comment) for reference and the TODO in the ignored test for more information. truncate comments at 80-90c; cleanup - remove unused method - remove '-Z unstable-options' - improve error message - improve the way MSVC special cases are targetted in tests - improve how executables are found on non MSVC Avoid depending on output of rustc There is cyclic dependency between rustc and cargo which makes it impossible to adjust cargo's expectations on rustc without leaving broken commits in rustc and cargo. Add missing documentation fix incorrect removal of non-artifact libs This is also the first step towards cleaning up the filtering logic which is still making some logic harder to understand than needs be. The goal is to get it to be closer to what's currently on master. Another test was added to have more safety regarding the overall library inclusion logic. inline `build_artifact_requirements_to_units()` Simplify filtering This adds a default filter to `state.deps(…)` making it similar to what's currently in master, while creating another version of it to allow setting a custom filter. This is needed as the default filter won't allow build dependencies, which we need in this particular case. `calc_artifact_deps(…)` now hard-codes the default filter which is needed due to the use of `any` here: https://github.com/rust-lang/cargo/blob/c0e6abe384c2c6282bdd631e2f2a3b092043e6c6/src/cargo/core/compiler/unit_dependencies.rs#L1119 . Simplify filtering.
1 parent 86376c8 commit 7248f4b

36 files changed

+4330
-411
lines changed

crates/cargo-test-support/src/cross_compile.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ pub fn native_arch() -> &'static str {
191191
.expect("Target triple has unexpected format")
192192
{
193193
"x86_64" => "x86_64",
194+
"aarch64" => "aarch64",
194195
"i686" => "x86",
195196
_ => panic!("This test should be gated on cross_compile::disabled."),
196197
}
@@ -200,7 +201,9 @@ pub fn native_arch() -> &'static str {
200201
///
201202
/// Only use this function on tests that check `cross_compile::disabled`.
202203
pub fn alternate() -> &'static str {
203-
if cfg!(target_os = "macos") {
204+
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
205+
"x86_64-apple-darwin"
206+
} else if cfg!(target_os = "macos") {
204207
"x86_64-apple-ios"
205208
} else if cfg!(target_os = "linux") {
206209
"i686-unknown-linux-gnu"

crates/cargo-test-support/src/registry.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ pub struct Dependency {
331331
name: String,
332332
vers: String,
333333
kind: String,
334+
artifact: Option<(String, Option<String>)>,
334335
target: Option<String>,
335336
features: Vec<String>,
336337
registry: Option<String>,
@@ -591,6 +592,7 @@ impl Package {
591592
"features": dep.features,
592593
"default_features": true,
593594
"target": dep.target,
595+
"artifact": dep.artifact,
594596
"optional": dep.optional,
595597
"kind": dep.kind,
596598
"registry": registry_url,
@@ -744,6 +746,12 @@ impl Package {
744746
"#,
745747
target, kind, dep.name, dep.vers
746748
));
749+
if let Some((artifact, target)) = &dep.artifact {
750+
manifest.push_str(&format!("artifact = \"{}\"\n", artifact));
751+
if let Some(target) = &target {
752+
manifest.push_str(&format!("target = \"{}\"\n", target))
753+
}
754+
}
747755
if let Some(registry) = &dep.registry {
748756
assert_eq!(registry, "alternative");
749757
manifest.push_str(&format!("registry-index = \"{}\"", alt_registry_url()));
@@ -799,6 +807,7 @@ impl Dependency {
799807
name: name.to_string(),
800808
vers: vers.to_string(),
801809
kind: "normal".to_string(),
810+
artifact: None,
802811
target: None,
803812
features: Vec::new(),
804813
package: None,
@@ -825,6 +834,13 @@ impl Dependency {
825834
self
826835
}
827836

837+
/// Change the artifact to be of the given kind, like "bin", or "staticlib",
838+
/// along with a specific target triple if provided.
839+
pub fn artifact(&mut self, kind: &str, target: Option<String>) -> &mut Self {
840+
self.artifact = Some((kind.to_string(), target));
841+
self
842+
}
843+
828844
/// Adds `registry = $registry` to this dependency.
829845
pub fn registry(&mut self, registry: &str) -> &mut Self {
830846
self.registry = Some(registry.to_string());

src/cargo/core/compiler/artifact.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/// Generate artifact information from unit dependencies for configuring the compiler environment.
2+
use crate::core::compiler::unit_graph::UnitDep;
3+
use crate::core::compiler::{Context, CrateType, FileFlavor, Unit};
4+
use crate::core::TargetKind;
5+
use crate::CargoResult;
6+
use std::collections::HashMap;
7+
use std::ffi::OsString;
8+
9+
/// Return all environment variables for the given unit-dependencies
10+
/// if artifacts are present.
11+
pub fn get_env(
12+
cx: &Context<'_, '_>,
13+
dependencies: &[UnitDep],
14+
) -> CargoResult<HashMap<String, OsString>> {
15+
let mut env = HashMap::new();
16+
for unit_dep in dependencies.iter().filter(|d| d.unit.artifact.is_true()) {
17+
for artifact_path in cx
18+
.outputs(&unit_dep.unit)?
19+
.iter()
20+
.filter_map(|f| (f.flavor == FileFlavor::Normal).then(|| &f.path))
21+
{
22+
let artifact_type_upper = unit_artifact_type_name_upper(&unit_dep.unit);
23+
let dep_name = unit_dep.dep_name.unwrap_or(unit_dep.unit.pkg.name());
24+
let dep_name_upper = dep_name.to_uppercase().replace("-", "_");
25+
26+
let var = format!("CARGO_{}_DIR_{}", artifact_type_upper, dep_name_upper);
27+
let path = artifact_path.parent().expect("parent dir for artifacts");
28+
env.insert(var, path.to_owned().into());
29+
30+
let var = format!(
31+
"CARGO_{}_FILE_{}_{}",
32+
artifact_type_upper,
33+
dep_name_upper,
34+
unit_dep.unit.target.name()
35+
);
36+
env.insert(var, artifact_path.to_owned().into());
37+
38+
if unit_dep.unit.target.name() == dep_name.as_str() {
39+
let var = format!("CARGO_{}_FILE_{}", artifact_type_upper, dep_name_upper,);
40+
env.insert(var, artifact_path.to_owned().into());
41+
}
42+
}
43+
}
44+
Ok(env)
45+
}
46+
47+
fn unit_artifact_type_name_upper(unit: &Unit) -> &'static str {
48+
match unit.target.kind() {
49+
TargetKind::Lib(kinds) => match kinds.as_slice() {
50+
&[CrateType::Cdylib] => "CDYLIB",
51+
&[CrateType::Staticlib] => "STATICLIB",
52+
invalid => unreachable!("BUG: artifacts cannot be of type {:?}", invalid),
53+
},
54+
TargetKind::Bin => "BIN",
55+
invalid => unreachable!("BUG: artifacts cannot be of type {:?}", invalid),
56+
}
57+
}

src/cargo/core/compiler/build_context/target_info.rs

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::core::compiler::{
22
BuildOutput, CompileKind, CompileMode, CompileTarget, Context, CrateType,
33
};
4-
use crate::core::{Dependency, Target, TargetKind, Workspace};
4+
use crate::core::{Dependency, Package, Target, TargetKind, Workspace};
55
use crate::util::config::{Config, StringList, TargetConfig};
66
use crate::util::{CargoResult, Rustc};
77
use anyhow::Context as _;
@@ -748,11 +748,17 @@ impl<'cfg> RustcTargetData<'cfg> {
748748
// Get all kinds we currently know about.
749749
//
750750
// For now, targets can only ever come from the root workspace
751-
// units as artifact dependencies are not a thing yet, so this
752-
// correctly represents all the kinds that can happen. When we
753-
// have artifact dependencies or other ways for targets to
754-
// appear at places that are not the root units, we may have
755-
// to revisit this.
751+
// units and artifact dependencies, so this
752+
// correctly represents all the kinds that can happen. When we have
753+
// other ways for targets to appear at places that are not the root units,
754+
// we may have to revisit this.
755+
fn artifact_targets(package: &Package) -> impl Iterator<Item = CompileKind> + '_ {
756+
package
757+
.manifest()
758+
.dependencies()
759+
.iter()
760+
.filter_map(|d| d.artifact()?.target()?.to_compile_kind())
761+
}
756762
let all_kinds = requested_kinds
757763
.iter()
758764
.copied()
@@ -761,25 +767,32 @@ impl<'cfg> RustcTargetData<'cfg> {
761767
.default_kind()
762768
.into_iter()
763769
.chain(p.manifest().forced_kind())
770+
.chain(artifact_targets(p))
764771
}));
765772
for kind in all_kinds {
766-
if let CompileKind::Target(target) = kind {
767-
if !res.target_config.contains_key(&target) {
768-
res.target_config
769-
.insert(target, res.config.target_cfg_triple(target.short_name())?);
770-
}
771-
if !res.target_info.contains_key(&target) {
772-
res.target_info.insert(
773-
target,
774-
TargetInfo::new(res.config, &res.requested_kinds, &res.rustc, kind)?,
775-
);
776-
}
777-
}
773+
res.merge_compile_kind(kind)?;
778774
}
779775

780776
Ok(res)
781777
}
782778

779+
/// Insert `kind` into our `target_info` and `target_config` members if it isn't present yet.
780+
fn merge_compile_kind(&mut self, kind: CompileKind) -> CargoResult<()> {
781+
if let CompileKind::Target(target) = kind {
782+
if !self.target_config.contains_key(&target) {
783+
self.target_config
784+
.insert(target, self.config.target_cfg_triple(target.short_name())?);
785+
}
786+
if !self.target_info.contains_key(&target) {
787+
self.target_info.insert(
788+
target,
789+
TargetInfo::new(self.config, &self.requested_kinds, &self.rustc, kind)?,
790+
);
791+
}
792+
}
793+
Ok(())
794+
}
795+
783796
/// Returns a "short" name for the given kind, suitable for keying off
784797
/// configuration in Cargo or presenting to users.
785798
pub fn short_name<'a>(&'a self, kind: &'a CompileKind) -> &'a str {

src/cargo/core/compiler/compilation.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ pub struct Doctest {
2525
///
2626
/// This is used for indexing [`Compilation::extra_env`].
2727
pub script_meta: Option<Metadata>,
28+
29+
/// Environment variables to set in the rustdoc process.
30+
pub env: HashMap<String, OsString>,
2831
}
2932

3033
/// Information about the output of a unit.
@@ -190,14 +193,14 @@ impl<'cfg> Compilation<'cfg> {
190193
) -> CargoResult<ProcessBuilder> {
191194
let rustdoc = ProcessBuilder::new(&*self.config.rustdoc()?);
192195
let cmd = fill_rustc_tool_env(rustdoc, unit);
193-
let mut p = self.fill_env(cmd, &unit.pkg, script_meta, unit.kind, true)?;
194-
unit.target.edition().cmd_edition_arg(&mut p);
196+
let mut cmd = self.fill_env(cmd, &unit.pkg, script_meta, unit.kind, true)?;
197+
unit.target.edition().cmd_edition_arg(&mut cmd);
195198

196199
for crate_type in unit.target.rustc_crate_types() {
197-
p.arg("--crate-type").arg(crate_type.as_str());
200+
cmd.arg("--crate-type").arg(crate_type.as_str());
198201
}
199202

200-
Ok(p)
203+
Ok(cmd)
201204
}
202205

203206
/// Returns a [`ProcessBuilder`] appropriate for running a process for the

src/cargo/core/compiler/compile_kind.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,8 @@ impl CompileTarget {
158158
/// Typically this is pretty much the same as `short_name`, but for the case
159159
/// of JSON target files this will be a full canonicalized path name for the
160160
/// current filesystem.
161-
pub fn rustc_target(&self) -> &str {
162-
&self.name
161+
pub fn rustc_target(&self) -> InternedString {
162+
self.name
163163
}
164164

165165
/// Returns a "short" version of the target name suitable for usage within

src/cargo/core/compiler/context/compilation_files.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ impl<'a, 'cfg: 'a> CompilationFiles<'a, 'cfg> {
201201
self.build_script_dir(unit)
202202
} else if unit.target.is_example() {
203203
self.layout(unit.kind).examples().to_path_buf()
204+
} else if unit.artifact.is_true() {
205+
self.artifact_dir(unit)
204206
} else {
205207
self.deps_dir(unit).to_path_buf()
206208
}
@@ -287,6 +289,30 @@ impl<'a, 'cfg: 'a> CompilationFiles<'a, 'cfg> {
287289
self.layout(CompileKind::Host).build().join(dir)
288290
}
289291

292+
/// Returns the directory for compiled artifacts files.
293+
/// `/path/to/target/{debug,release}/deps/artifact/KIND/PKG-HASH`
294+
fn artifact_dir(&self, unit: &Unit) -> PathBuf {
295+
assert!(self.metas.contains_key(unit));
296+
assert!(unit.artifact.is_true());
297+
let dir = self.pkg_dir(unit);
298+
let kind = match unit.target.kind() {
299+
TargetKind::Bin => "bin",
300+
TargetKind::Lib(lib_kinds) => match lib_kinds.as_slice() {
301+
&[CrateType::Cdylib] => "cdylib",
302+
&[CrateType::Staticlib] => "staticlib",
303+
invalid => unreachable!(
304+
"BUG: unexpected artifact library type(s): {:?} - these should have been split",
305+
invalid
306+
),
307+
},
308+
invalid => unreachable!(
309+
"BUG: {:?} are not supposed to be used as artifacts",
310+
invalid
311+
),
312+
};
313+
self.layout(unit.kind).artifact().join(dir).join(kind)
314+
}
315+
290316
/// Returns the directory where information about running a build script
291317
/// is stored.
292318
/// `/path/to/target/{debug,release}/build/PKG-HASH`
@@ -354,7 +380,12 @@ impl<'a, 'cfg: 'a> CompilationFiles<'a, 'cfg> {
354380
if unit.mode != CompileMode::Build || file_type.flavor == FileFlavor::Rmeta {
355381
return None;
356382
}
357-
// Only uplift:
383+
384+
// Artifact dependencies are never uplifted.
385+
if unit.artifact.is_true() {
386+
return None;
387+
}
388+
358389
// - Binaries: The user always wants to see these, even if they are
359390
// implicitly built (for example for integration tests).
360391
// - dylibs: This ensures that the dynamic linker pulls in all the

src/cargo/core/compiler/context/mod.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};
33
use std::sync::{Arc, Mutex};
44

55
use crate::core::compiler::compilation::{self, UnitOutput};
6-
use crate::core::compiler::{self, Unit};
6+
use crate::core::compiler::{self, artifact, Unit};
77
use crate::core::PackageId;
88
use crate::util::errors::CargoResult;
99
use crate::util::profile;
@@ -133,7 +133,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
133133

134134
// We need to make sure that if there were any previous docs
135135
// already compiled, they were compiled with the same Rustc version that we're currently
136-
// using. Otherways we must remove the `doc/` folder and compile again forcing a rebuild.
136+
// using. Otherwise we must remove the `doc/` folder and compile again forcing a rebuild.
137137
//
138138
// This is important because the `.js`/`.html` & `.css` files that are generated by Rustc don't have
139139
// any versioning (See https://github.com/rust-lang/cargo/issues/8461).
@@ -262,6 +262,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
262262
unstable_opts,
263263
linker: self.bcx.linker(unit.kind),
264264
script_meta,
265+
env: artifact::get_env(&self, self.unit_deps(unit))?,
265266
});
266267
}
267268

src/cargo/core/compiler/custom_build.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::job::{Freshness, Job, Work};
22
use super::{fingerprint, Context, LinkType, Unit};
3+
use crate::core::compiler::artifact;
34
use crate::core::compiler::context::Metadata;
45
use crate::core::compiler::job_queue::JobState;
56
use crate::core::{profiles::ProfileRoot, PackageId, Target};
@@ -203,6 +204,11 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
203204
.env("RUSTDOC", &*bcx.config.rustdoc()?)
204205
.inherit_jobserver(&cx.jobserver);
205206

207+
// Find all artifact dependencies and make their file and containing directory discoverable using environment variables.
208+
for (var, value) in artifact::get_env(cx, dependencies)? {
209+
cmd.env(&var, value);
210+
}
211+
206212
if let Some(linker) = &bcx.target_data.target_config(unit.kind).linker {
207213
cmd.env(
208214
"RUSTC_LINKER",

src/cargo/core/compiler/job_queue.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,8 @@ impl<'cfg> JobQueue<'cfg> {
395395
.filter(|dep| {
396396
// Binaries aren't actually needed to *compile* tests, just to run
397397
// them, so we don't include this dependency edge in the job graph.
398-
!dep.unit.target.is_test() && !dep.unit.target.is_bin()
398+
(!dep.unit.target.is_test() && !dep.unit.target.is_bin())
399+
|| dep.unit.artifact.is_true()
399400
})
400401
.map(|dep| {
401402
// Handle the case here where our `unit -> dep` dependency may

src/cargo/core/compiler/layout.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@
4747
//! # prevent collisions. One notable exception is dynamic libraries.
4848
//! deps/
4949
//!
50+
//! # Each artifact dependency gets in its own directory.
51+
//! /artifact/$pkgname-$META/$kind
52+
//!
5053
//! # Root directory for all compiled examples.
5154
//! examples/
5255
//!
@@ -117,6 +120,8 @@ pub struct Layout {
117120
deps: PathBuf,
118121
/// The directory for build scripts: `$dest/build`
119122
build: PathBuf,
123+
/// The directory for artifacts, i.e. binaries, cdylibs, staticlibs: `$dest/deps/artifact`
124+
artifact: PathBuf,
120125
/// The directory for incremental files: `$dest/incremental`
121126
incremental: PathBuf,
122127
/// The directory for fingerprints: `$dest/.fingerprint`
@@ -164,10 +169,13 @@ impl Layout {
164169
let lock = dest.open_rw(".cargo-lock", ws.config(), "build directory")?;
165170
let root = root.into_path_unlocked();
166171
let dest = dest.into_path_unlocked();
172+
let deps = dest.join("deps");
173+
let artifact = deps.join("artifact");
167174

168175
Ok(Layout {
169-
deps: dest.join("deps"),
176+
deps,
170177
build: dest.join("build"),
178+
artifact,
171179
incremental: dest.join("incremental"),
172180
fingerprint: dest.join(".fingerprint"),
173181
examples: dest.join("examples"),
@@ -222,6 +230,10 @@ impl Layout {
222230
pub fn build(&self) -> &Path {
223231
&self.build
224232
}
233+
/// Fetch the artifact path.
234+
pub fn artifact(&self) -> &Path {
235+
&self.artifact
236+
}
225237
/// Create and return the tmp path.
226238
pub fn prepare_tmp(&self) -> CargoResult<&Path> {
227239
paths::create_dir_all(&self.tmp)?;

0 commit comments

Comments
 (0)