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

Add crate type flag to rustc command #10093

Merged
merged 3 commits into from
Nov 26, 2021
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
20 changes: 18 additions & 2 deletions src/bin/cargo/commands/rustc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use cargo::ops;
use cargo::util::interning::InternedString;

const PRINT_ARG_NAME: &str = "print";
const CRATE_TYPE_ARG_NAME: &str = "crate-type";

pub fn cli() -> App {
subcommand("rustc")
Expand Down Expand Up @@ -35,6 +36,11 @@ pub fn cli() -> App {
)
.value_name("INFO"),
)
.arg(multi_opt(
CRATE_TYPE_ARG_NAME,
"CRATE-TYPE",
"Comma separated list of types of crates for the compiler to emit (unstable)",
))
.arg_target_dir()
.arg_manifest_path()
.arg_message_format()
Expand Down Expand Up @@ -75,8 +81,18 @@ pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
.cli_unstable()
.fail_if_stable_opt(PRINT_ARG_NAME, 9357)?;
ops::print(&ws, &compile_opts, opt_value)?;
} else {
ops::compile(&ws, &compile_opts)?;
return Ok(());
}
let crate_types = values(args, CRATE_TYPE_ARG_NAME);
compile_opts.target_rustc_crate_types = if crate_types.is_empty() {
None
} else {
config
.cli_unstable()
.fail_if_stable_opt(CRATE_TYPE_ARG_NAME, 10083)?;
Some(crate_types)
};
ops::compile(&ws, &compile_opts)?;

Ok(())
}
9 changes: 9 additions & 0 deletions src/cargo/core/compiler/build_context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ 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 @@ -61,6 +64,7 @@ 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 @@ -80,6 +84,7 @@ 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 @@ -127,4 +132,8 @@ 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: 13 additions & 2 deletions src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,9 +861,20 @@ fn build_base_args(
add_error_format_and_color(cx, cmd, cx.rmeta_required(unit));
add_allow_features(cx, cmd);

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.as_str());
cmd.arg("--crate-type").arg(crate_type);
if crate_type == CrateType::Dylib.as_str() {
contains_dy_lib = true;
}
}
}

Expand All @@ -879,7 +890,7 @@ fn build_base_args(
}

let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
|| (crate_types.contains(&CrateType::Dylib) && !cx.is_primary_package(unit));
|| (contains_dy_lib && !cx.is_primary_package(unit));
if prefer_dynamic {
cmd.arg("-C").arg("prefer-dynamic");
}
Expand Down
27 changes: 27 additions & 0 deletions src/cargo/ops/cargo_compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ pub struct CompileOptions {
/// The specified target will be compiled with all the available arguments,
/// note that this only accounts for the *final* invocation of rustc
pub target_rustc_args: Option<Vec<String>>,
/// Crate types to be passed to rustc (single target only)
pub target_rustc_crate_types: Option<Vec<String>>,
Rustin170506 marked this conversation as resolved.
Show resolved Hide resolved
/// Extra arguments passed to all selected targets for rustdoc.
pub local_rustdoc_args: Option<Vec<String>>,
/// Whether the `--document-private-items` flags was specified and should
Expand All @@ -92,6 +94,7 @@ impl<'a> CompileOptions {
},
target_rustdoc_args: None,
target_rustc_args: None,
target_rustc_crate_types: None,
local_rustdoc_args: None,
rustdoc_document_private_items: false,
honor_rust_version: true,
Expand Down Expand Up @@ -332,6 +335,7 @@ pub fn create_bcx<'a, 'cfg>(
ref filter,
ref target_rustdoc_args,
ref target_rustc_args,
ref target_rustc_crate_types,
ref local_rustdoc_args,
rustdoc_document_private_items,
honor_rust_version,
Expand Down Expand Up @@ -644,6 +648,28 @@ 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 @@ -680,6 +706,7 @@ pub fn create_bcx<'a, 'cfg>(
build_config,
profiles,
extra_compiler_args,
crate_types,
target_data,
units,
unit_graph,
Expand Down
1 change: 1 addition & 0 deletions src/cargo/ops/cargo_package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,7 @@ fn run_verify(
},
target_rustdoc_args: None,
target_rustc_args: rustc_args,
target_rustc_crate_types: None,
local_rustdoc_args: None,
rustdoc_document_private_items: false,
honor_rust_version: true,
Expand Down
1 change: 1 addition & 0 deletions src/cargo/util/command_prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,7 @@ pub trait ArgMatchesExt {
),
target_rustdoc_args: None,
target_rustc_args: None,
target_rustc_crate_types: None,
local_rustdoc_args: None,
rustdoc_document_private_items: false,
honor_rust_version: !self._is_present("ignore-rust-version"),
Expand Down
18 changes: 18 additions & 0 deletions src/doc/src/reference/unstable.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Each new feature described below should explain how to use it.
* [build-std-features](#build-std-features) — Sets features to use with the standard library.
* [binary-dep-depinfo](#binary-dep-depinfo) — Causes the dep-info file to track binary dependencies.
* [panic-abort-tests](#panic-abort-tests) — Allows running tests with the "abort" panic strategy.
* [crate-type](#crate-type) - Supports passing crate types to the compiler.
* rustdoc
* [`doctest-in-workspace`](#doctest-in-workspace) — Fixes workspace-relative paths when running doctests.
* [rustdoc-map](#rustdoc-map) — Provides mappings for documentation to link to external sites like [docs.rs](https://docs.rs/).
Expand Down Expand Up @@ -555,6 +556,23 @@ like to stabilize it somehow!

[rust-lang/rust#64158]: https://github.com/rust-lang/rust/pull/64158

### crate-type
* Tracking Issue: [#10083](https://github.com/rust-lang/cargo/issues/10083)
* RFC: [#3180](https://github.com/rust-lang/rfcs/pull/3180)
* Original Pull Request: [#10093](https://github.com/rust-lang/cargo/pull/10093)

`cargo rustc --crate-type=lib,cdylib` forwards the `--crate-type` flag to `rustc`.
This runs `rustc` with the corresponding
[`--crate-type`](https://doc.rust-lang.org/rustc/command-line-arguments.html#--crate-type-a-list-of-types-of-crates-for-the-compiler-to-emit)
flag, and compiling.

When using it, it requires the `-Z unstable-options`
command-line option:

```console
cargo rustc --crate-type lib,cdylib -Z unstable-options
```

### config-cli
* Tracking Issue: [#7722](https://github.com/rust-lang/cargo/issues/7722)

Expand Down
Loading