Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override target crate-type for cargo rustc --crate-type #10388

Merged
merged 3 commits into from
Feb 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions src/cargo/core/compiler/build_context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ pub struct BuildContext<'a, 'cfg> {
/// Extra compiler args for either `rustc` or `rustdoc`.
pub extra_compiler_args: HashMap<Unit, Vec<String>>,

// Crate types for `rustc`.
pub target_rustc_crate_types: HashMap<Unit, Vec<String>>,

/// Package downloader.
///
/// This holds ownership of the `Package` objects.
Expand Down Expand Up @@ -64,7 +61,6 @@ impl<'a, 'cfg> BuildContext<'a, 'cfg> {
build_config: &'a BuildConfig,
profiles: Profiles,
extra_compiler_args: HashMap<Unit, Vec<String>>,
target_rustc_crate_types: HashMap<Unit, Vec<String>>,
target_data: RustcTargetData<'cfg>,
roots: Vec<Unit>,
unit_graph: UnitGraph,
Expand All @@ -84,7 +80,6 @@ impl<'a, 'cfg> BuildContext<'a, 'cfg> {
build_config,
profiles,
extra_compiler_args,
target_rustc_crate_types,
target_data,
roots,
unit_graph,
Expand Down Expand Up @@ -132,8 +127,4 @@ impl<'a, 'cfg> BuildContext<'a, 'cfg> {
pub fn extra_args_for(&self, unit: &Unit) -> Option<&Vec<String>> {
self.extra_compiler_args.get(unit)
}

pub fn rustc_crate_types_args_for(&self, unit: &Unit) -> Option<&Vec<String>> {
self.target_rustc_crate_types.get(unit)
}
}
15 changes: 3 additions & 12 deletions src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -890,18 +890,9 @@ fn build_base_args(

let mut contains_dy_lib = false;
if !test {
let mut crate_types = &crate_types
.iter()
.map(|t| t.as_str().to_string())
.collect::<Vec<String>>();
if let Some(types) = cx.bcx.rustc_crate_types_args_for(unit) {
crate_types = types;
}
for crate_type in crate_types.iter() {
cmd.arg("--crate-type").arg(crate_type);
if crate_type == CrateType::Dylib.as_str() {
contains_dy_lib = true;
}
for crate_type in crate_types {
cmd.arg("--crate-type").arg(crate_type.as_str());
contains_dy_lib |= crate_type == &CrateType::Dylib;
}
}

Expand Down
76 changes: 52 additions & 24 deletions src/cargo/ops/cargo_compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use std::sync::Arc;

use crate::core::compiler::unit_dependencies::{build_unit_dependencies, IsArtifact};
use crate::core::compiler::unit_graph::{self, UnitDep, UnitGraph};
use crate::core::compiler::{standard_lib, TargetInfo};
use crate::core::compiler::{standard_lib, CrateType, TargetInfo};
use crate::core::compiler::{BuildConfig, BuildContext, Compilation, Context};
use crate::core::compiler::{CompileKind, CompileMode, CompileTarget, RustcTargetData, Unit};
use crate::core::compiler::{DefaultExecutor, Executor, UnitInterner};
Expand Down Expand Up @@ -505,6 +505,10 @@ pub fn create_bcx<'a, 'cfg>(
interner,
)?;

if let Some(args) = target_rustc_crate_types {
override_rustc_crate_types(&mut units, args, interner)?;
}

let mut scrape_units = match rustdoc_scrape_examples {
Some(arg) => {
let filter = match arg.as_str() {
Expand Down Expand Up @@ -648,28 +652,6 @@ pub fn create_bcx<'a, 'cfg>(
}
}

let mut crate_types = HashMap::new();
if let Some(args) = target_rustc_crate_types {
if units.len() != 1 {
anyhow::bail!(
"crate types to rustc can only be passed to one \
target, consider filtering\nthe package by passing, \
e.g., `--lib` or `--example` to specify a single target"
);
}
match units[0].target.kind() {
TargetKind::Lib(_) | TargetKind::ExampleLib(_) => {
crate_types.insert(units[0].clone(), args.clone());
}
_ => {
anyhow::bail!(
"crate types can only be specified for libraries and example libraries.\n\
Binaries, tests, and benchmarks are always the `bin` crate type"
);
}
}
}

if honor_rust_version {
// Remove any pre-release identifiers for easier comparison
let current_version = &target_data.rustc.version;
Expand Down Expand Up @@ -706,7 +688,6 @@ pub fn create_bcx<'a, 'cfg>(
build_config,
profiles,
extra_compiler_args,
crate_types,
target_data,
units,
unit_graph,
Expand Down Expand Up @@ -1871,3 +1852,50 @@ fn remove_duplicate_doc(
}
unit_graph.retain(|unit, _| visited.contains(unit));
}

/// Override crate types for given units.
///
/// This is primarily used by `cargo rustc --crate-type`.
fn override_rustc_crate_types(
units: &mut [Unit],
args: &[String],
interner: &UnitInterner,
) -> CargoResult<()> {
if units.len() != 1 {
anyhow::bail!(
"crate types to rustc can only be passed to one \
target, consider filtering\nthe package by passing, \
e.g., `--lib` or `--example` to specify a single target"
);
}

let unit = &units[0];
let override_unit = |f: fn(Vec<CrateType>) -> TargetKind| {
let crate_types = args.iter().map(|s| s.into()).collect();
let mut target = unit.target.clone();
target.set_kind(f(crate_types));
interner.intern(
&unit.pkg,
&target,
unit.profile.clone(),
unit.kind,
unit.mode,
unit.features.clone(),
unit.is_std,
unit.dep_hash,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intern API has recently been updated on master, so something similar to this looks to be needed now

Suggested change
unit.dep_hash,
unit.dep_hash,
unit.artifact,

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Just found that and rebased to master

unit.artifact,
)
};
units[0] = match unit.target.kind() {
TargetKind::Lib(_) => override_unit(TargetKind::Lib),
TargetKind::ExampleLib(_) => override_unit(TargetKind::ExampleLib),
_ => {
anyhow::bail!(
"crate types can only be specified for libraries and example libraries.\n\
Binaries, tests, and benchmarks are always the `bin` crate type"
);
}
};

Ok(())
}
52 changes: 43 additions & 9 deletions tests/testsuite/rustc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,17 +217,54 @@ Binaries, tests, and benchmarks are always the `bin` crate type",

#[cargo_test]
fn build_with_crate_type_for_foo() {
let p = project().file("src/lib.rs", "").build();

p.cargo("rustc -v --crate-type cdylib -Zunstable-options")
.masquerade_as_nightly_cargo()
.with_stderr(
"\
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc --crate-name foo src/lib.rs [..]--crate-type cdylib [..]
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
.run();
}

#[cargo_test]
fn build_with_crate_type_for_foo_with_deps() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file("src/lib.rs", r#" "#)
.file(
"src/lib.rs",
r#"
extern crate a;
pub fn foo() { a::hello(); }
"#,
)
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []

[dependencies]
a = { path = "a" }
"#,
)
.file("a/Cargo.toml", &basic_manifest("a", "0.1.0"))
.file("a/src/lib.rs", "pub fn hello() {}")
.build();

p.cargo("rustc -v --lib --crate-type lib -Zunstable-options")
p.cargo("rustc -v --crate-type cdylib -Zunstable-options")
.masquerade_as_nightly_cargo()
.with_stderr(
"\
[COMPILING] a v0.1.0 ([CWD]/a)
[RUNNING] `rustc --crate-name a a/src/lib.rs [..]--crate-type lib [..]
[COMPILING] foo v0.0.1 ([CWD])
[RUNNING] `rustc --crate-name foo src/lib.rs [..]--crate-type lib [..]
[RUNNING] `rustc --crate-name foo src/lib.rs [..]--crate-type cdylib [..]
[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]
",
)
Expand All @@ -236,12 +273,9 @@ fn build_with_crate_type_for_foo() {

#[cargo_test]
fn build_with_crate_types_for_foo() {
let p = project()
.file("src/main.rs", "fn main() {}")
.file("src/lib.rs", r#" "#)
.build();
let p = project().file("src/lib.rs", "").build();

p.cargo("rustc -v --lib --crate-type lib,cdylib -Zunstable-options")
p.cargo("rustc -v --crate-type lib,cdylib -Zunstable-options")
.masquerade_as_nightly_cargo()
.with_stderr(
"\
Expand Down