blob: 724dbd01fe21007953c2db4d78dce134aa7d74ad [file] [log] [blame]
Brian Silvermancc09f182022-03-09 15:40:20 -08001use std::collections::{BTreeMap, BTreeSet, HashMap};
2
3use anyhow::{anyhow, Context, Result};
4use cfg_expr::targets::{get_builtin_target_by_triple, TargetInfo};
5use cfg_expr::{Expression, Predicate};
6
7use crate::context::CrateContext;
8use crate::utils::starlark::Select;
9
10/// Walk through all dependencies in a [CrateContext] list for all configuration specific
11/// dependencies to produce a mapping of configuration to compatible platform triples.
12pub fn resolve_cfg_platforms(
13 crates: Vec<&CrateContext>,
14 supported_platform_triples: &BTreeSet<String>,
15) -> Result<BTreeMap<String, BTreeSet<String>>> {
16 // Collect all unique configurations from all dependencies into a single set
17 let configurations: BTreeSet<String> = crates
18 .iter()
19 .flat_map(|ctx| {
20 let attr = &ctx.common_attrs;
21 attr.deps
22 .configurations()
23 .into_iter()
24 .chain(attr.deps_dev.configurations().into_iter())
25 .chain(attr.proc_macro_deps.configurations().into_iter())
26 .chain(attr.proc_macro_deps_dev.configurations().into_iter())
27 // Chain the build dependencies if some are defined
28 .chain(if let Some(attr) = &ctx.build_script_attrs {
29 attr.deps
30 .configurations()
31 .into_iter()
32 .chain(attr.proc_macro_deps.configurations().into_iter())
33 .collect::<BTreeSet<Option<&String>>>()
34 .into_iter()
35 } else {
36 BTreeSet::new().into_iter()
37 })
38 .flatten()
39 })
40 .cloned()
41 .collect();
42
43 // Generate target information for each triple string
44 let target_infos = supported_platform_triples
45 .iter()
46 .map(|t| match get_builtin_target_by_triple(t) {
47 Some(info) => Ok(info),
48 None => Err(anyhow!(
49 "Invalid platform triple in supported platforms: {}",
50 t
51 )),
52 })
53 .collect::<Result<Vec<&'static TargetInfo>>>()?;
54
55 // `cfg-expr` does not understand configurations that are simply platform triples
56 // (`x86_64-unknown-linux-gun` vs `cfg(target = "x86_64-unkonwn-linux-gnu")`). So
57 // in order to parse configurations, the text is renamed for the check but the
58 // original is retained for comaptibility with the manifest.
59 let rename = |cfg: &str| -> String { format!("cfg(target = \"{}\")", cfg) };
60 let original_cfgs: HashMap<String, String> = configurations
61 .iter()
62 .filter(|cfg| !cfg.starts_with("cfg("))
63 .map(|cfg| (rename(cfg), cfg.clone()))
64 .collect();
65
66 configurations
67 .into_iter()
68 // `cfg-expr` requires that the expressions be actual `cfg` expressions. Any time
69 // there's a target triple (which is a valid constraint), convert it to a cfg expression.
70 .map(|cfg| match cfg.starts_with("cfg(") {
71 true => cfg.to_string(),
72 false => rename(&cfg),
73 })
74 // Check the current configuration with against each supported triple
75 .map(|cfg| {
76 let expression = Expression::parse(&cfg)
77 .context(format!("Failed to parse expression: '{}'", cfg))?;
78
79 let triples = target_infos
80 .iter()
81 .filter(|info| {
82 expression.eval(|p| match p {
83 Predicate::Target(tp) => tp.matches(**info),
84 Predicate::KeyValue { key, val } => {
85 *key == "target" && val == &info.triple.as_str()
86 }
87 // For now there is no other kind of matching
88 _ => false,
89 })
90 })
91 .map(|info| info.triple.to_string())
92 .collect();
93
94 // Map any renamed configurations back to their original IDs
95 let cfg = match original_cfgs.get(&cfg) {
96 Some(orig) => orig.clone(),
97 None => cfg,
98 };
99
100 Ok((cfg, triples))
101 })
102 .collect()
103}
104
105#[cfg(test)]
106mod test {
107 use crate::config::CrateId;
108 use crate::context::crate_context::CrateDependency;
109 use crate::context::CommonAttributes;
110 use crate::utils::starlark::SelectList;
111
112 use super::*;
113
114 fn supported_platform_triples() -> BTreeSet<String> {
115 BTreeSet::from([
116 "aarch64-apple-darwin".to_owned(),
117 "aarch64-apple-ios".to_owned(),
118 "aarch64-linux-android".to_owned(),
119 "aarch64-unknown-linux-gnu".to_owned(),
120 "arm-unknown-linux-gnueabi".to_owned(),
121 "armv7-unknown-linux-gnueabi".to_owned(),
122 "i686-apple-darwin".to_owned(),
123 "i686-linux-android".to_owned(),
124 "i686-pc-windows-msvc".to_owned(),
125 "i686-unknown-freebsd".to_owned(),
126 "i686-unknown-linux-gnu".to_owned(),
127 "powerpc-unknown-linux-gnu".to_owned(),
128 "s390x-unknown-linux-gnu".to_owned(),
129 "wasm32-unknown-unknown".to_owned(),
130 "wasm32-wasi".to_owned(),
131 "x86_64-apple-darwin".to_owned(),
132 "x86_64-apple-ios".to_owned(),
133 "x86_64-linux-android".to_owned(),
134 "x86_64-pc-windows-msvc".to_owned(),
135 "x86_64-unknown-freebsd".to_owned(),
136 "x86_64-unknown-linux-gnu".to_owned(),
137 ])
138 }
139
140 #[test]
141 fn resolve_no_targeted() {
142 let mut deps = SelectList::default();
143 deps.insert(
144 CrateDependency {
145 id: CrateId::new("mock_crate_b".to_owned(), "0.1.0".to_owned()),
146 target: "mock_crate_b".to_owned(),
147 alias: None,
148 },
149 None,
150 );
151
152 let context = CrateContext {
153 name: "mock_crate_a".to_owned(),
154 version: "0.1.0".to_owned(),
155 common_attrs: CommonAttributes {
156 deps,
157 ..CommonAttributes::default()
158 },
159 ..CrateContext::default()
160 };
161
162 let configurations =
163 resolve_cfg_platforms(vec![&context], &supported_platform_triples()).unwrap();
164
165 assert_eq!(configurations, BTreeMap::new(),)
166 }
167
168 #[test]
169 fn resolve_targeted() {
170 let configuration = r#"cfg(target = "x86_64-unknown-linux-gnu")"#.to_owned();
171 let mut deps = SelectList::default();
172 deps.insert(
173 CrateDependency {
174 id: CrateId::new("mock_crate_b".to_owned(), "0.1.0".to_owned()),
175 target: "mock_crate_b".to_owned(),
176 alias: None,
177 },
178 Some(configuration.clone()),
179 );
180
181 let context = CrateContext {
182 name: "mock_crate_a".to_owned(),
183 version: "0.1.0".to_owned(),
184 common_attrs: CommonAttributes {
185 deps,
186 ..CommonAttributes::default()
187 },
188 ..CrateContext::default()
189 };
190
191 let configurations =
192 resolve_cfg_platforms(vec![&context], &supported_platform_triples()).unwrap();
193
194 assert_eq!(
195 configurations,
196 BTreeMap::from([(
197 configuration,
198 BTreeSet::from(["x86_64-unknown-linux-gnu".to_owned()])
199 )])
200 );
201 }
202
203 #[test]
204 fn resolve_platforms() {
205 let configuration = r#"x86_64-unknown-linux-gnu"#.to_owned();
206 let mut deps = SelectList::default();
207 deps.insert(
208 CrateDependency {
209 id: CrateId::new("mock_crate_b".to_owned(), "0.1.0".to_owned()),
210 target: "mock_crate_b".to_owned(),
211 alias: None,
212 },
213 Some(configuration.clone()),
214 );
215
216 let context = CrateContext {
217 name: "mock_crate_a".to_owned(),
218 version: "0.1.0".to_owned(),
219 common_attrs: CommonAttributes {
220 deps,
221 ..CommonAttributes::default()
222 },
223 ..CrateContext::default()
224 };
225
226 let configurations =
227 resolve_cfg_platforms(vec![&context], &supported_platform_triples()).unwrap();
228
229 assert_eq!(
230 configurations,
231 BTreeMap::from([(
232 configuration,
233 BTreeSet::from(["x86_64-unknown-linux-gnu".to_owned()])
234 )])
235 );
236 }
237
238 #[test]
239 fn resolve_unsupported_targeted() {
240 let configuration = r#"cfg(target = "x86_64-unknown-unknown")"#.to_owned();
241 let mut deps = SelectList::default();
242 deps.insert(
243 CrateDependency {
244 id: CrateId::new("mock_crate_b".to_owned(), "0.1.0".to_owned()),
245 target: "mock_crate_b".to_owned(),
246 alias: None,
247 },
248 Some(configuration.clone()),
249 );
250
251 let context = CrateContext {
252 name: "mock_crate_a".to_owned(),
253 version: "0.1.0".to_owned(),
254 common_attrs: CommonAttributes {
255 deps,
256 ..CommonAttributes::default()
257 },
258 ..CrateContext::default()
259 };
260
261 let configurations =
262 resolve_cfg_platforms(vec![&context], &supported_platform_triples()).unwrap();
263
264 assert_eq!(
265 configurations,
266 BTreeMap::from([(configuration, BTreeSet::new())])
267 );
268 }
269}