Skip to content

Commit a7294ad

Browse files
committed
Add support for boolean literals in target cfgs
1 parent 3aac2b8 commit a7294ad

File tree

8 files changed

+124
-49
lines changed

8 files changed

+124
-49
lines changed

Diff for: crates/cargo-platform/src/cfg.rs

+12-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ pub enum CfgExpr {
1010
All(Vec<CfgExpr>),
1111
Any(Vec<CfgExpr>),
1212
Value(Cfg),
13+
True,
14+
False,
1315
}
1416

1517
/// A cfg value.
@@ -87,6 +89,8 @@ impl CfgExpr {
8789
CfgExpr::All(ref e) => e.iter().all(|e| e.matches(cfg)),
8890
CfgExpr::Any(ref e) => e.iter().any(|e| e.matches(cfg)),
8991
CfgExpr::Value(ref e) => cfg.contains(e),
92+
CfgExpr::True => true,
93+
CfgExpr::False => false,
9094
}
9195
}
9296

@@ -106,7 +110,7 @@ impl CfgExpr {
106110
}
107111
Ok(())
108112
}
109-
CfgExpr::Value(_) => Ok(()),
113+
CfgExpr::Value(_) | CfgExpr::True | CfgExpr::False => Ok(()),
110114
}
111115
}
112116

@@ -137,6 +141,8 @@ impl fmt::Display for CfgExpr {
137141
CfgExpr::All(ref e) => write!(f, "all({})", CommaSep(e)),
138142
CfgExpr::Any(ref e) => write!(f, "any({})", CommaSep(e)),
139143
CfgExpr::Value(ref e) => write!(f, "{}", e),
144+
CfgExpr::True => write!(f, "true"),
145+
CfgExpr::False => write!(f, "false"),
140146
}
141147
}
142148
}
@@ -191,7 +197,11 @@ impl<'a> Parser<'a> {
191197
self.eat(&Token::RightParen)?;
192198
Ok(CfgExpr::Not(Box::new(e)))
193199
}
194-
Some(Ok(..)) => self.cfg().map(CfgExpr::Value),
200+
Some(Ok(..)) => self.cfg().map(|v| match v {
201+
Cfg::Name(n) if n == "true" => CfgExpr::True,
202+
Cfg::Name(n) if n == "false" => CfgExpr::False,
203+
v => CfgExpr::Value(v),
204+
}),
195205
Some(Err(..)) => Err(self.t.next().unwrap().err().unwrap()),
196206
None => Err(ParseError::new(
197207
self.t.orig,

Diff for: crates/cargo-platform/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ impl Platform {
9797
))
9898
},
9999
}
100+
CfgExpr::True | CfgExpr::False => {},
100101
}
101102
}
102103

Diff for: src/cargo/core/features.rs

+5
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,9 @@ features! {
517517

518518
/// Allow paths that resolve relatively to a base specified in the config.
519519
(unstable, path_bases, "", "reference/unstable.html#path-bases"),
520+
521+
/// Allow boolean literals in `[target.'cfg(<true/false>)']`
522+
(unstable, cfg_boolean_literals, "", "reference/unstable.html#cfg-boolean-literals"),
520523
}
521524

522525
/// Status and metadata for a single unstable feature.
@@ -761,6 +764,7 @@ unstable_cli_options!(
761764
build_std: Option<Vec<String>> = ("Enable Cargo to compile the standard library itself as part of a crate graph compilation"),
762765
build_std_features: Option<Vec<String>> = ("Configure features enabled for the standard library itself when building the standard library"),
763766
cargo_lints: bool = ("Enable the `[lints.cargo]` table"),
767+
cfg_boolean_literals: bool = ("Allow boolean literals in `[target.'cfg(<true/false>)']`"),
764768
checksum_freshness: bool = ("Use a checksum to determine if output is fresh rather than filesystem mtime"),
765769
codegen_backend: bool = ("Enable the `codegen-backend` option in profiles in .cargo/config.toml file"),
766770
config_include: bool = ("Enable the `include` key in config files"),
@@ -1259,6 +1263,7 @@ impl CliUnstable {
12591263
}
12601264
"build-std-features" => self.build_std_features = Some(parse_features(v)),
12611265
"cargo-lints" => self.cargo_lints = parse_empty(k, v)?,
1266+
"cfg-boolean-literals" => self.cfg_boolean_literals = parse_empty(k, v)?,
12621267
"codegen-backend" => self.codegen_backend = parse_empty(k, v)?,
12631268
"config-include" => self.config_include = parse_empty(k, v)?,
12641269
"direct-minimal-versions" => self.direct_minimal_versions = parse_empty(k, v)?,

Diff for: src/cargo/util/context/target.rs

+12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::{ConfigKey, ConfigRelativePath, GlobalContext, OptValue, PathAndArgs, StringList, CV};
22
use crate::core::compiler::{BuildOutput, LinkArgTarget};
33
use crate::util::CargoResult;
4+
use cargo_platform::{CfgExpr, Platform};
45
use serde::Deserialize;
56
use std::collections::{BTreeMap, HashMap};
67
use std::path::PathBuf;
@@ -53,6 +54,17 @@ pub(super) fn load_target_cfgs(
5354
let target: BTreeMap<String, TargetCfgConfig> = gctx.get("target")?;
5455
tracing::debug!("Got all targets {:#?}", target);
5556
for (key, cfg) in target {
57+
// Feature gate `cfg(true)`/`cfg(false)` under `-Zcfg-boolean-literals`
58+
if !gctx.cli_unstable().cfg_boolean_literals {
59+
if let Ok(Platform::Cfg(cfg_expr)) = key.parse() {
60+
cfg_expr.walk_expr(|e| match e {
61+
CfgExpr::True | CfgExpr::False => {
62+
anyhow::bail!("`-Zcfg-boolean-literals` should be used to enable cfg boolean literals in `.cargo/config.toml`")
63+
},
64+
_ => Ok(()),
65+
})?;
66+
}
67+
}
5668
if key.starts_with("cfg(") {
5769
// Unfortunately this is not able to display the location of the
5870
// unused key. Using config::Value<toml::Value> doesn't work. One

Diff for: src/cargo/util/toml/mod.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::str::{self, FromStr};
88
use crate::core::summary::MissingDependencyError;
99
use crate::AlreadyPrintedError;
1010
use anyhow::{anyhow, bail, Context as _};
11-
use cargo_platform::Platform;
11+
use cargo_platform::{CfgExpr, Platform};
1212
use cargo_util::paths;
1313
use cargo_util_schemas::manifest::{
1414
self, PackageName, PathBaseName, TomlDependency, TomlDetailedDependency, TomlManifest,
@@ -1326,6 +1326,12 @@ pub fn to_real_manifest(
13261326
for (name, platform) in original_toml.target.iter().flatten() {
13271327
let platform_kind: Platform = name.parse()?;
13281328
platform_kind.check_cfg_attributes(warnings);
1329+
if let Platform::Cfg(cfg_expr) = &platform_kind {
1330+
cfg_expr.walk_expr(|e| match e {
1331+
CfgExpr::True | CfgExpr::False => features.require(Feature::cfg_boolean_literals()),
1332+
_ => Ok(()),
1333+
})?;
1334+
}
13291335
let platform_kind = Some(platform_kind);
13301336
validate_dependencies(
13311337
platform.dependencies.as_ref(),

Diff for: src/doc/src/reference/unstable.md

+24
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ Each new feature described below should explain how to use it.
121121
* [package-workspace](#package-workspace) --- Allows for packaging and publishing multiple crates in a workspace.
122122
* [native-completions](#native-completions) --- Move cargo shell completions to native completions.
123123
* [warnings](#warnings) --- controls warning behavior; options for allowing or denying warnings.
124+
* [cfg-boolean-literals](#cfg-boolean-literals) --- Allows the use of boolean literals in `[target.'cfg(<true/false>)']`
124125

125126
## allow-features
126127

@@ -1746,6 +1747,29 @@ When in doubt, you can discuss this in [#14520](https://github.com/rust-lang/car
17461747
- powershell:
17471748
Add `CARGO_COMPLETE=powershell cargo +nightly | Invoke-Expression` to `$PROFILE`.
17481749

1750+
## cfg-boolean-literals
1751+
1752+
* Tracking Issue: [#00000](https://github.com/rust-lang/cargo/issues/00000)
1753+
1754+
This feature allows the use of boolean literals in `[target.'cfg(<true/false>)']`.
1755+
1756+
Those boolean literals always evaluate to true and false respectively, they are **not** subject
1757+
to `RUSTFLAGS`.
1758+
1759+
For example, in this example the `b` dependencies is always compiled, while `c` is never:
1760+
1761+
```toml
1762+
cargo-features = ["cfg-boolean-literals"]
1763+
1764+
[target.'cfg(true)'.dependencies]
1765+
b = { path = 'b' }
1766+
1767+
[target.'cfg(false)'.dependencies]
1768+
c = { path = 'c' }
1769+
```
1770+
1771+
For cfgs in `.cargo/config.toml`, `-Zcfg-boolean-literals` must be used.
1772+
17491773
# Stabilized and removed features
17501774

17511775
## Compile progress

Diff for: tests/testsuite/cargo/z_help/stdout.term.svg

+35-33
Loading

0 commit comments

Comments
 (0)