1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate::{errors::ExpressionParseError, Error, Platform, Triple};
use cfg_expr::{Expression, Predicate};
use std::{borrow::Cow, str::FromStr, sync::Arc};
/// A parsed target specification or triple, as found in a `Cargo.toml` file.
///
/// ## Examples
///
/// ```
/// use target_spec::{Platform, TargetFeatures, TargetSpec};
///
/// let i686_windows = Platform::new("i686-pc-windows-gnu", TargetFeatures::Unknown).unwrap();
/// let x86_64_mac = Platform::new("x86_64-apple-darwin", TargetFeatures::none()).unwrap();
/// let i686_linux = Platform::new(
/// "i686-unknown-linux-gnu",
/// TargetFeatures::features(["sse2"].iter().copied()),
/// ).unwrap();
///
/// let spec: TargetSpec = "cfg(any(windows, target_arch = \"x86_64\"))".parse().unwrap();
/// assert_eq!(spec.eval(&i686_windows), Some(true), "i686 Windows");
/// assert_eq!(spec.eval(&x86_64_mac), Some(true), "x86_64 MacOS");
/// assert_eq!(spec.eval(&i686_linux), Some(false), "i686 Linux (should not match)");
///
/// let spec: TargetSpec = "cfg(any(target_feature = \"sse2\", target_feature = \"sse\"))".parse().unwrap();
/// assert_eq!(spec.eval(&i686_windows), None, "i686 Windows features are unknown");
/// assert_eq!(spec.eval(&x86_64_mac), Some(false), "x86_64 MacOS matches no features");
/// assert_eq!(spec.eval(&i686_linux), Some(true), "i686 Linux matches some features");
/// ```
#[derive(Clone, Debug)]
pub enum TargetSpec {
/// An exact target parsed from a triple.
///
/// Parsed from strings like `"i686-pc-windows-gnu"`.
Triple(Triple),
/// A complex expression.
///
/// Parsed from strings like `"cfg(any(windows, target_arch = \"x86_64\"))"`.
Expression(TargetExpression),
}
impl TargetSpec {
/// Creates a new target from a string.
///
/// This constructor covers many, but not all, cases. To customize target spec construction, use
/// [`Self::looks_like_expression`].
pub fn new(input: impl Into<Cow<'static, str>>) -> Result<Self, Error> {
let input = input.into();
if Self::looks_like_expression(&input) {
Ok(TargetSpec::Expression(TargetExpression::new(&input)?))
} else {
match Triple::new(input) {
Ok(triple) => Ok(TargetSpec::Triple(triple)),
Err(parse_err) => Err(Error::UnknownTargetTriple(parse_err)),
}
}
}
/// Returns true if the input resembles a target expression.
///
/// This simply checks that the input begins with `"cfg("`.
///
/// # Examples
///
/// `looks_like_expression` can be used to customize target spec construction. For example, it
/// can be used to resolve custom targets:
///
/// ```
/// use target_spec::{Error, TargetExpression, TargetSpec, Triple};
///
/// # #[cfg(feature = "custom")]
/// fn make_target_spec(input: &str) -> Result<TargetSpec, Error> {
/// if TargetSpec::looks_like_expression(input) {
/// Ok(TargetSpec::Expression(TargetExpression::new(&input)?))
/// } else {
/// let json = "{}"; // perform custom target resolution here
/// let triple = Triple::new_custom(input.to_owned(), json)
/// .map_err(Error::CustomTripleCreate)?;
/// Ok(TargetSpec::Triple(triple))
/// }
/// }
/// ```
pub fn looks_like_expression(input: &str) -> bool {
input.starts_with("cfg(")
}
/// Evaluates this specification against the given platform.
///
/// Returns `Some(true)` if there's a match, `Some(false)` if there's none, or `None` if the
/// result of the evaluation is unknown (typically found if target features are involved).
#[inline]
pub fn eval(&self, platform: &Platform) -> Option<bool> {
match self {
TargetSpec::Triple(triple) => Some(triple.eval(platform)),
TargetSpec::Expression(expr) => expr.eval(platform),
}
}
}
impl FromStr for TargetSpec {
type Err = Error;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Self::new(input.to_owned())
}
}
/// A target expression.
///
/// Parsed from a string beginning with `cfg(`.
#[derive(Clone, Debug)]
pub struct TargetExpression {
inner: Arc<Expression>,
}
impl TargetExpression {
/// Creates a new `TargetExpression` from a string beginning with `cfg(`.
///
/// Returns an error if the string could not be parsed, or if the string contains a predicate
/// that wasn't understood by `target-spec`.
pub fn new(input: &str) -> Result<Self, Error> {
let expr = Expression::parse(input)
.map_err(|err| Error::InvalidExpression(ExpressionParseError::new(input, err)))?;
Ok(Self {
inner: Arc::new(expr),
})
}
/// Returns the string that was parsed into `self`.
#[inline]
pub fn expression_str(&self) -> &str {
self.inner.original()
}
/// Evaluates this expression against the given platform.
///
/// Returns `Some(true)` if there's a match, `Some(false)` if there's none, or `None` if the
/// result of the evaluation is unknown (typically found if target features are involved).
pub fn eval(&self, platform: &Platform) -> Option<bool> {
self.inner.eval(|pred| {
match pred {
Predicate::Target(target) => Some(platform.triple().matches(target)),
Predicate::TargetFeature(feature) => platform.target_features().matches(feature),
Predicate::Test | Predicate::DebugAssertions | Predicate::ProcMacro => {
// Known families that always evaluate to false. See
// https://docs.rs/cargo-platform/0.1.1/src/cargo_platform/lib.rs.html#76.
Some(false)
}
Predicate::Feature(_) => {
// NOTE: This is not supported by Cargo which always evaluates this to false. See
// https://github.com/rust-lang/cargo/issues/7442 for more details.
Some(false)
}
Predicate::Flag(flag) => {
// This returns false by default but true in some cases.
Some(platform.has_flag(flag))
}
Predicate::KeyValue { .. } => {
// This is always interpreted by Cargo as false.
Some(false)
}
}
})
}
}
impl FromStr for TargetExpression {
type Err = Error;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Self::new(input)
}
}
#[cfg(test)]
mod tests {
use super::*;
use cfg_expr::{
targets::{Abi, Arch, Family, Os},
Predicate, TargetPredicate,
};
#[test]
fn test_triple() {
let res = TargetSpec::new("x86_64-apple-darwin");
assert!(matches!(
res,
Ok(TargetSpec::Triple(triple)) if triple.as_str() == "x86_64-apple-darwin"
));
}
#[test]
fn test_single() {
let expr = match TargetSpec::new("cfg(windows)").unwrap() {
TargetSpec::Triple(triple) => {
panic!("expected expression, got triple: {:?}", triple)
}
TargetSpec::Expression(expr) => expr,
};
assert_eq!(
expr.inner.predicates().collect::<Vec<_>>(),
vec![Predicate::Target(TargetPredicate::Family(Family::windows))],
);
}
#[test]
fn test_target_abi() {
let expr =
match TargetSpec::new("cfg(any(target_arch = \"wasm32\", target_abi = \"unknown\"))")
.unwrap()
{
TargetSpec::Triple(triple) => {
panic!("expected expression, got triple: {:?}", triple)
}
TargetSpec::Expression(expr) => expr,
};
assert_eq!(
expr.inner.predicates().collect::<Vec<_>>(),
vec![
Predicate::Target(TargetPredicate::Arch(Arch("wasm32".into()))),
Predicate::Target(TargetPredicate::Abi(Abi("unknown".into()))),
],
);
}
#[test]
fn test_not() {
assert!(matches!(
TargetSpec::new("cfg(not(windows))"),
Ok(TargetSpec::Expression(_))
));
}
#[test]
fn test_testequal() {
let expr = match TargetSpec::new("cfg(target_os = \"windows\")").unwrap() {
TargetSpec::Triple(triple) => {
panic!("expected spec, got triple: {:?}", triple)
}
TargetSpec::Expression(expr) => expr,
};
assert_eq!(
expr.inner.predicates().collect::<Vec<_>>(),
vec![Predicate::Target(TargetPredicate::Os(Os::windows))],
);
}
#[test]
fn test_unknown_triple() {
// This used to be "x86_64-pc-darwin", but target-lexicon can parse that.
let err = TargetSpec::new("cannotbeknown").expect_err("unknown triple");
assert!(matches!(
err,
Error::UnknownTargetTriple(parse_err) if parse_err.triple_str() == "cannotbeknown"
));
}
#[test]
fn test_unknown_flag() {
let expr = match TargetSpec::new("cfg(foo)").unwrap() {
TargetSpec::Triple(triple) => {
panic!("expected spec, got triple: {:?}", triple)
}
TargetSpec::Expression(expr) => expr,
};
assert_eq!(
expr.inner.predicates().collect::<Vec<_>>(),
vec![Predicate::Flag("foo")],
);
}
#[test]
fn test_unknown_predicate() {
let expr = match TargetSpec::new("cfg(bogus_key = \"bogus_value\")")
.expect("unknown predicate should parse")
{
TargetSpec::Triple(triple) => {
panic!("expected spec, got triple: {:?}", triple)
}
TargetSpec::Expression(expr) => expr,
};
assert_eq!(
expr.inner.predicates().collect::<Vec<_>>(),
vec![Predicate::KeyValue {
key: "bogus_key",
val: "bogus_value"
}],
);
let platform = Platform::current().unwrap();
// This should always evaluate to false.
assert_eq!(expr.eval(&platform), Some(false));
let expr = TargetSpec::new("cfg(not(bogus_key = \"bogus_value\"))")
.expect("unknown predicate should parse");
// This is a cfg(not()), so it should always evaluate to true.
assert_eq!(expr.eval(&platform), Some(true));
}
#[test]
fn test_extra() {
let res = TargetSpec::new("cfg(unix)this-is-extra");
res.expect_err("extra content at the end");
}
#[test]
fn test_incomplete() {
// This fails because the ) at the end is missing.
let res = TargetSpec::new("cfg(not(unix)");
res.expect_err("missing ) at the end");
}
}