Skip to content

Commit 48e0c53

Browse files
committed
Auto merge of #11562 - weihanglo:issue-11552, r=ehuss
Support `codegen-backend` and `rustflags` in profiles in config file
2 parents 98645f1 + 5c87110 commit 48e0c53

File tree

5 files changed

+142
-14
lines changed

5 files changed

+142
-14
lines changed

src/cargo/core/features.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -667,6 +667,7 @@ unstable_cli_options!(
667667
#[serde(deserialize_with = "deserialize_build_std")]
668668
build_std: Option<Vec<String>> = ("Enable Cargo to compile the standard library itself as part of a crate graph compilation"),
669669
build_std_features: Option<Vec<String>> = ("Configure features enabled for the standard library itself when building the standard library"),
670+
codegen_backend: bool = ("Enable the `codegen-backend` option in profiles in .cargo/config.toml file"),
670671
config_include: bool = ("Enable the `include` key in config files"),
671672
credential_process: bool = ("Add a config setting to fetch registry authentication tokens by calling an external process"),
672673
#[serde(deserialize_with = "deserialize_check_cfg")]
@@ -680,6 +681,7 @@ unstable_cli_options!(
680681
mtime_on_use: bool = ("Configure Cargo to update the mtime of used files"),
681682
no_index_update: bool = ("Do not update the registry index even if the cache is outdated"),
682683
panic_abort_tests: bool = ("Enable support to run tests with -Cpanic=abort"),
684+
profile_rustflags: bool = ("Enable the `rustflags` option in profiles in .cargo/config.toml file"),
683685
host_config: bool = ("Enable the [host] section in the .cargo/config.toml file"),
684686
sparse_registry: bool = ("Support plain-HTTP-based crate registries"),
685687
registry_auth: bool = ("Authentication for alternative registries, and generate registry authentication tokens using asymmetric cryptography"),
@@ -969,6 +971,8 @@ impl CliUnstable {
969971
stabilized_warn(k, "1.59.0", STABILIZED_FUTURE_INCOMPAT_REPORT)
970972
}
971973
"timings" => stabilized_warn(k, "1.60", STABILIZED_TIMINGS),
974+
"codegen-backend" => self.codegen_backend = parse_empty(k, v)?,
975+
"profile-rustflags" => self.profile_rustflags = parse_empty(k, v)?,
972976
_ => bail!("unknown `-Z` flag specified: {}", k),
973977
}
974978

src/cargo/core/profiles.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1115,7 +1115,12 @@ fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult<Option<Toml
11151115
let mut warnings = Vec::new();
11161116
profile
11171117
.val
1118-
.validate(name, ws.unstable_features(), &mut warnings)
1118+
.validate(
1119+
name,
1120+
ws.config().cli_unstable(),
1121+
ws.unstable_features(),
1122+
&mut warnings,
1123+
)
11191124
.with_context(|| {
11201125
format!(
11211126
"config profile `{}` is not valid (defined in `{}`)",

src/cargo/util/toml/mod.rs

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,8 @@ use crate::core::compiler::{CompileKind, CompileTarget};
2222
use crate::core::dependency::{Artifact, ArtifactTarget, DepKind};
2323
use crate::core::manifest::{ManifestMetadata, TargetSourcePath, Warnings};
2424
use crate::core::resolver::ResolveBehavior;
25-
use crate::core::{
26-
find_workspace_root, resolve_relative_path, Dependency, Manifest, PackageId, Summary, Target,
27-
};
25+
use crate::core::{find_workspace_root, resolve_relative_path, CliUnstable};
26+
use crate::core::{Dependency, Manifest, PackageId, Summary, Target};
2827
use crate::core::{Edition, EitherManifest, Feature, Features, VirtualManifest, Workspace};
2928
use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, WorkspaceRootConfig};
3029
use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
@@ -455,9 +454,18 @@ impl TomlProfiles {
455454
self.0.get(name)
456455
}
457456

458-
pub fn validate(&self, features: &Features, warnings: &mut Vec<String>) -> CargoResult<()> {
457+
/// Checks syntax validity and unstable feature gate for each profile.
458+
///
459+
/// It's a bit unfortunate both `-Z` flags and `cargo-features` are required,
460+
/// because profiles can now be set in either `Cargo.toml` or `config.toml`.
461+
pub fn validate(
462+
&self,
463+
cli_unstable: &CliUnstable,
464+
features: &Features,
465+
warnings: &mut Vec<String>,
466+
) -> CargoResult<()> {
459467
for (name, profile) in &self.0 {
460-
profile.validate(name, features, warnings)?;
468+
profile.validate(name, cli_unstable, features, warnings)?;
461469
}
462470
Ok(())
463471
}
@@ -592,21 +600,27 @@ impl fmt::Display for ProfilePackageSpec {
592600
}
593601

594602
impl TomlProfile {
603+
/// Checks stytax validity and unstable feature gate for a given profile.
595604
pub fn validate(
596605
&self,
597606
name: &str,
607+
cli_unstable: &CliUnstable,
598608
features: &Features,
599609
warnings: &mut Vec<String>,
600610
) -> CargoResult<()> {
601-
self.validate_profile(name, features)?;
611+
self.validate_profile(name, cli_unstable, features)?;
602612
if let Some(ref profile) = self.build_override {
603613
profile.validate_override("build-override")?;
604-
profile.validate_profile(&format!("{name}.build-override"), features)?;
614+
profile.validate_profile(&format!("{name}.build-override"), cli_unstable, features)?;
605615
}
606616
if let Some(ref packages) = self.package {
607617
for (override_name, profile) in packages {
608618
profile.validate_override("package")?;
609-
profile.validate_profile(&format!("{name}.package.{override_name}"), features)?;
619+
profile.validate_profile(
620+
&format!("{name}.package.{override_name}"),
621+
cli_unstable,
622+
features,
623+
)?;
610624
}
611625
}
612626

@@ -751,9 +765,21 @@ impl TomlProfile {
751765
/// Validates a profile.
752766
///
753767
/// This is a shallow check, which is reused for the profile itself and any overrides.
754-
fn validate_profile(&self, name: &str, features: &Features) -> CargoResult<()> {
768+
fn validate_profile(
769+
&self,
770+
name: &str,
771+
cli_unstable: &CliUnstable,
772+
features: &Features,
773+
) -> CargoResult<()> {
755774
if let Some(codegen_backend) = &self.codegen_backend {
756-
features.require(Feature::codegen_backend())?;
775+
match (
776+
features.require(Feature::codegen_backend()),
777+
cli_unstable.codegen_backend,
778+
) {
779+
(Err(e), false) => return Err(e),
780+
_ => {}
781+
}
782+
757783
if codegen_backend.contains(|c: char| !c.is_ascii_alphanumeric() && c != '_') {
758784
bail!(
759785
"`profile.{}.codegen-backend` setting of `{}` is not a valid backend name.",
@@ -763,7 +789,13 @@ impl TomlProfile {
763789
}
764790
}
765791
if self.rustflags.is_some() {
766-
features.require(Feature::profile_rustflags())?;
792+
match (
793+
features.require(Feature::profile_rustflags()),
794+
cli_unstable.profile_rustflags,
795+
) {
796+
(Err(e), false) => return Err(e),
797+
_ => {}
798+
}
767799
}
768800
Ok(())
769801
}
@@ -2065,7 +2097,8 @@ impl TomlManifest {
20652097

20662098
let profiles = me.profile.clone();
20672099
if let Some(profiles) = &profiles {
2068-
profiles.validate(&features, &mut warnings)?;
2100+
let cli_unstable = config.cli_unstable();
2101+
profiles.validate(cli_unstable, &features, &mut warnings)?;
20692102
}
20702103

20712104
let publish = package
@@ -2254,7 +2287,7 @@ impl TomlManifest {
22542287
};
22552288
let profiles = me.profile.clone();
22562289
if let Some(profiles) = &profiles {
2257-
profiles.validate(&features, &mut warnings)?;
2290+
profiles.validate(config.cli_unstable(), &features, &mut warnings)?;
22582291
}
22592292
let resolve_behavior = me
22602293
.workspace

src/doc/src/reference/unstable.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ Each new feature described below should explain how to use it.
8585
* [rustdoc-map](#rustdoc-map) — Provides mappings for documentation to link to external sites like [docs.rs](https://docs.rs/).
8686
* `Cargo.toml` extensions
8787
* [Profile `rustflags` option](#profile-rustflags-option) — Passed directly to rustc.
88+
* [codegen-backend](#codegen-backend) — Select the codegen backend used by rustc.
8889
* [per-package-target](#per-package-target) — Sets the `--target` to use for each individual package.
8990
* [artifact dependencies](#artifact-dependencies) - Allow build artifacts to be included into other build artifacts and build them for different targets.
9091
* Information and metadata
@@ -681,6 +682,18 @@ cargo-features = ["profile-rustflags"]
681682
rustflags = [ "-C", "..." ]
682683
```
683684

685+
To set this in a profile in Cargo configuration, you need to use either
686+
`-Z profile-rustflags` or `[unstable]` table to enable it. For example,
687+
688+
```toml
689+
# .cargo/config.toml
690+
[unstable]
691+
profile-rustflags = true
692+
693+
[profile.release]
694+
rustflags = [ "-C", "..." ]
695+
```
696+
684697
### rustdoc-map
685698
* Tracking Issue: [#8296](https://github.com/rust-lang/cargo/issues/8296)
686699

@@ -1378,6 +1391,18 @@ serde = "1.0.117"
13781391
codegen-backend = "cranelift"
13791392
```
13801393

1394+
To set this in a profile in Cargo configuration, you need to use either
1395+
`-Z codegen-backend` or `[unstable]` table to enable it. For example,
1396+
1397+
```toml
1398+
# .cargo/config.toml
1399+
[unstable]
1400+
codegen-backend = true
1401+
1402+
[profile.dev.package.foo]
1403+
codegen-backend = "cranelift"
1404+
```
1405+
13811406
### patch-in-config
13821407

13831408
The `-Z patch-in-config` flag, and the corresponding support for

tests/testsuite/profile_config.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,67 @@ use cargo_test_support::paths::CargoPathExt;
44
use cargo_test_support::registry::Package;
55
use cargo_test_support::{basic_lib_manifest, paths, project};
66

7+
// TODO: this should be remove once -Zprofile-rustflags is stabilized
8+
#[cargo_test]
9+
fn rustflags_works_with_zflag() {
10+
let p = project()
11+
.file(
12+
"Cargo.toml",
13+
r#"
14+
[package]
15+
name = "foo"
16+
version = "0.0.1"
17+
"#,
18+
)
19+
.file("src/main.rs", "fn main() {}")
20+
.file(
21+
".cargo/config.toml",
22+
r#"
23+
[profile.dev]
24+
rustflags = ["-C", "link-dead-code=yes"]
25+
"#,
26+
)
27+
.build();
28+
29+
p.cargo("check -v")
30+
.masquerade_as_nightly_cargo(&["profile-rustflags"])
31+
.with_status(101)
32+
.with_stderr_contains("[..]feature `profile-rustflags` is required[..]")
33+
.run();
34+
35+
p.cargo("check -v -Zprofile-rustflags")
36+
.masquerade_as_nightly_cargo(&["profile-rustflags"])
37+
.with_stderr(
38+
"\
39+
[CHECKING] foo [..]
40+
[RUNNING] `rustc --crate-name foo [..] -C link-dead-code=yes [..]
41+
[FINISHED] [..]
42+
",
43+
)
44+
.run();
45+
46+
p.change_file(
47+
".cargo/config.toml",
48+
r#"
49+
[unstable]
50+
profile-rustflags = true
51+
52+
[profile.dev]
53+
rustflags = ["-C", "link-dead-code=yes"]
54+
"#,
55+
);
56+
57+
p.cargo("check -v")
58+
.masquerade_as_nightly_cargo(&["profile-rustflags"])
59+
.with_stderr(
60+
"\
61+
[FRESH] foo [..]
62+
[FINISHED] [..]
63+
",
64+
)
65+
.run();
66+
}
67+
768
#[cargo_test]
869
fn profile_config_validate_warnings() {
970
let p = project()

0 commit comments

Comments
 (0)