1//! Platform definition used by Cargo.
2//!
3//! This defines a [`Platform`] type which is used in Cargo to specify a target platform.
4//! There are two kinds, a named target like `x86_64-apple-darwin`, and a "cfg expression"
5//! like `cfg(any(target_os = "macos", target_os = "ios"))`.
6//!
7//! See `examples/matches.rs` for an example of how to match against a `Platform`.
8//!
9//! > This crate is maintained by the Cargo team for use by the wider
10//! > ecosystem. This crate follows semver compatibility for its APIs.
11//!
12//! [`Platform`]: enum.Platform.html
1314use std::str::FromStr;
15use std::{fmt, path::Path};
1617mod cfg;
18mod error;
1920use cfg::KEYWORDS;
21pub use cfg::{Cfg, CfgExpr, Ident};
22pub use error::{ParseError, ParseErrorKind};
2324/// Platform definition.
25#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]
26pub enum Platform {
27/// A named platform, like `x86_64-apple-darwin`.
28Name(String),
29/// A cfg expression, like `cfg(windows)`.
30Cfg(CfgExpr),
31}
3233impl Platform {
34/// Returns whether the Platform matches the given target and cfg.
35 ///
36 /// The named target and cfg values should be obtained from `rustc`.
37pub fn matches(&self, name: &str, cfg: &[Cfg]) -> bool {
38match *self {
39 Platform::Name(ref p) => p == name,
40 Platform::Cfg(ref p) => p.matches(cfg),
41 }
42 }
4344fn validate_named_platform(name: &str) -> Result<(), ParseError> {
45if let Some(ch) = name
46 .chars()
47 .find(|&c| !(c.is_alphanumeric() || c == '_' || c == '-' || c == '.'))
48 {
49if name.chars().any(|c| c == '(') {
50return Err(ParseError::new(
51 name,
52 ParseErrorKind::InvalidTarget(
53"unexpected `(` character, cfg expressions must start with `cfg(`"
54.to_string(),
55 ),
56 ));
57 }
58return Err(ParseError::new(
59 name,
60 ParseErrorKind::InvalidTarget(format!(
61"unexpected character {} in target name",
62 ch
63 )),
64 ));
65 }
66Ok(())
67 }
6869pub fn check_cfg_attributes(&self, warnings: &mut Vec<String>) {
70fn check_cfg_expr(expr: &CfgExpr, warnings: &mut Vec<String>) {
71match *expr {
72 CfgExpr::Not(ref e) => check_cfg_expr(e, warnings),
73 CfgExpr::All(ref e) | CfgExpr::Any(ref e) => {
74for e in e {
75 check_cfg_expr(e, warnings);
76 }
77 }
78 CfgExpr::Value(ref e) => match e {
79 Cfg::Name(name) => match name.as_str() {
80"test" | "debug_assertions" | "proc_macro" =>
81 warnings.push(format!(
82"Found `{}` in `target.'cfg(...)'.dependencies`. \
83 This value is not supported for selecting dependencies \
84 and will not work as expected. \
85 To learn more visit \
86 https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies",
87 name
88 )),
89_ => (),
90 },
91 Cfg::KeyPair(name, _) => if name.as_str() == "feature" {
92 warnings.push(String::from(
93"Found `feature = ...` in `target.'cfg(...)'.dependencies`. \
94 This key is not supported for selecting dependencies \
95 and will not work as expected. \
96 Use the [features] section instead: \
97 https://doc.rust-lang.org/cargo/reference/features.html"
98))
99 },
100 }
101 }
102 }
103104if let Platform::Cfg(cfg) = self {
105 check_cfg_expr(cfg, warnings);
106 }
107 }
108109pub fn check_cfg_keywords(&self, warnings: &mut Vec<String>, path: &Path) {
110fn check_cfg_expr(expr: &CfgExpr, warnings: &mut Vec<String>, path: &Path) {
111match *expr {
112 CfgExpr::Not(ref e) => check_cfg_expr(e, warnings, path),
113 CfgExpr::All(ref e) | CfgExpr::Any(ref e) => {
114for e in e {
115 check_cfg_expr(e, warnings, path);
116 }
117 }
118 CfgExpr::Value(ref e) => match e {
119 Cfg::Name(name) | Cfg::KeyPair(name, _) => {
120if !name.raw && KEYWORDS.contains(&name.as_str()) {
121if name.as_str() == "true" || name.as_str() == "false" {
122 warnings.push(format!(
123"[{}] future-incompatibility: the meaning of `cfg({e})` will change in the future\n \
124 | Cargo is erroneously allowing `cfg(true)` and `cfg(false)`, but both forms are interpreted as false unless manually overridden with `--cfg`.\n \
125 | In the future these will be built-in defines that will have the corresponding true/false value.\n \
126 | It is recommended to avoid using these configs until they are properly supported.\n \
127 | See <https://github.com/rust-lang/rust/issues/131204> for more information.\n \
128 |\n \
129 | help: use raw-idents instead: `cfg(r#{name})`",
130 path.display()
131 ));
132 } else {
133 warnings.push(format!(
134"[{}] future-incompatibility: `cfg({e})` is deprecated as `{name}` is a keyword \
135 and not an identifier and should not have have been accepted in this position.\n \
136 | this was previously accepted by Cargo but is being phased out; it will become a hard error in a future release!\n \
137 |\n \
138 | help: use raw-idents instead: `cfg(r#{name})`",
139 path.display()
140 ));
141 }
142 }
143 }
144 },
145 }
146 }
147148if let Platform::Cfg(cfg) = self {
149 check_cfg_expr(cfg, warnings, path);
150 }
151 }
152}
153154impl serde::Serialize for Platform {
155fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
156where
157S: serde::Serializer,
158 {
159self.to_string().serialize(s)
160 }
161}
162163impl<'de> serde::Deserialize<'de> for Platform {
164fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
165where
166D: serde::Deserializer<'de>,
167 {
168let s = String::deserialize(deserializer)?;
169 FromStr::from_str(&s).map_err(serde::de::Error::custom)
170 }
171}
172173impl FromStr for Platform {
174type Err = ParseError;
175176fn from_str(s: &str) -> Result<Platform, ParseError> {
177if let Some(s) = s.strip_prefix("cfg(").and_then(|s| s.strip_suffix(')')) {
178 s.parse().map(Platform::Cfg)
179 } else {
180 Platform::validate_named_platform(s)?;
181Ok(Platform::Name(s.to_string()))
182 }
183 }
184}
185186impl fmt::Display for Platform {
187fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188match *self {
189 Platform::Name(ref n) => n.fmt(f),
190 Platform::Cfg(ref e) => write!(f, "cfg({})", e),
191 }
192 }
193}