Debian Codegraph @

src/features.rs

raw symbols SCIP
1 //! Helper for parsing the microsyntax of the `[features]` section and computing implied features from optional dependencies.
2
3 use crate::{Dependency, DepsSet, Manifest, Product, TargetDepsSet};
4 use std::borrow::Cow;
5 use std::collections::hash_map::{Entry, RandomState};
6 use std::collections::{BTreeMap, BTreeSet, HashMap};
7 use std::hash::BuildHasher;
8 use std::marker::PhantomData;
9
10 /// Maximum number of features and dependencies, to protect against DoS
11 /// crates.io limit is 300.
12 const MAX_ITEMS: usize = 2048;
13
14 /// Call [`features::Resolver::new()`](Resolver::new) to get started.
15 ///
16 /// The extra `Hasher` arg is for optionally using [`ahash`](https://lib.rs/ahash).
17 pub struct Resolver<'config, Hasher = RandomState> {
18 always_keep: Option<&'config dyn Fn(&str) -> bool>,
19 _hasher: PhantomData<fn() -> Hasher>,
20 }
21
22 /// Parse result
23 ///
24 /// It's a temporary struct that borrows from the manifest. Copy things out of this if lifetimes get in the way.
25 ///
26 /// The extra `Hasher` arg is for optionally using [`ahash`](https://lib.rs/ahash).
27 #[derive(Debug)]
28 #[non_exhaustive]
29 pub struct Features<'manifest, 'deps, Hasher = RandomState> {
30 /// All features, resolved and normalized
31 ///
32 /// Default features are literally under the "default" key.
33 pub features: HashMap<&'manifest str, Feature<'manifest>, Hasher>,
34 /// FYI, dependencies referenced by the features, keyed by dependencies' name/identifier in TOML (that's not always the crate name)
35 ///
36 /// This doesn't include *all* dependencies. Dependencies unaffected by any features selection are skipped.
37 pub dependencies: HashMap<&'deps str, FeatureDependency<'deps>, Hasher>,
38 /// True if there were features with names staring with `_` and were inlined and merged into other features
39 ///
40 /// See arg of [`new_with_hasher_and_filter`](Resolver::new_with_hasher_and_filter) to disable removal.
41 pub removed_hidden_features: bool,
42
43 /// A redirect from removed feature to its replacements
44 pub hidden_features: HashMap<&'manifest str, BTreeSet<&'manifest str>, Hasher>,
45 }
46
47 /// How an enabled feature affects the dependency
48 #[derive(Debug, PartialEq, Clone)]
49 #[non_exhaustive]
50 pub struct DepAction<'a> {
51 /// Uses `?` syntax, so it doesn't enable the depenency
52 pub is_conditional: bool,
53 /// Uses `dep:` or `?` syntax, so it doesn't imply a feature name
54 pub is_dep_only: bool,
55 /// Features of the dependency to enable (the text after slash, possibly aggregated from multiple items)
56 pub dep_features: BTreeSet<Cow<'a, str>>,
57 }
58
59 /// A feature from `[features]` with all the details
60 #[derive(Debug, Clone)]
61 #[non_exhaustive]
62 pub struct Feature<'a> {
63 /// Name of the feature
64 pub key: &'a str,
65 /// Deps this enables or modifies, by their manifest key (the key isn't always the same as the crate name)
66 ///
67 /// This set is shallow (this feature may also be enabling other features that enable more deps), see [`Feature::enables_recursive`].
68 pub enables_deps: BTreeMap<&'a str, DepAction<'a>>,
69 /// Enables these explicitly named features
70 ///
71 /// This set is shallow, and the features listed here may be enabling more features, see [`Feature::enables_recursive`].
72 /// Note that Cargo permits infinite loops (A enables B, B enables A).
73 pub enables_features: BTreeSet<&'a str>,
74
75 /// Keys of other features that directly enable this feature (this is shallow, not recursive)
76 pub enabled_by: BTreeSet<&'a str>,
77
78 /// Names of binaries that mention this feature in their `required-features = [this feature]`
79 ///
80 /// Name of the default unnamed binary is set to the package name, and not normalized.
81 pub required_by_bins: Vec<&'a str>,
82
83 /// If true, it's from `[features]`. If false, it's from `[dependencies]`.
84 ///
85 /// If it's not explicit, and `is_referenced() == true`, it's probably a mistake and wasn't supposed to be a feature.
86 /// See `is_user_facing`.
87 pub explicit: bool,
88 }
89
90 /// Outer key is the dependency key/name, the `Vec` contains feature names
91 pub type DependenciesEnabledByFeatures<'a, S> = HashMap<&'a str, Vec<(&'a str, &'a DepAction<'a>)>, S>;
92
93 impl<'a> Feature<'a> {
94 /// Heuristic whether this feature should be shown to users
95 ///
96 /// Skips underscore-prefixed features, and possibly unintended features implied by optional dependencies
97 #[inline]
98 #[must_use]
99 pub fn is_user_facing(&self) -> bool {
100 (self.explicit || !self.is_referenced()) && !self.key.starts_with('_')
101 }
102
103 /// Just `enabled_by` except the "default" feature
104 #[inline]
105 pub fn non_default_enabled_by(&self) -> impl Iterator<Item = &str> {
106 self.enabled_by.iter().copied().filter(|&e| e != "default")
107 }
108
109 /// Is any other feature using this one?
110 #[inline]
111 #[must_use]
112 pub fn is_referenced(&self) -> bool {
113 !self.enabled_by.is_empty()
114 }
115
116 /// Finds all features and dependencies that this feature enables, recursively and exhaustively
117 ///
118 /// The first `HashMap` is features by their key, the second is dependencies by their key. It includes only dependencies changed by the features, not all crate dependencies.
119 #[must_use]
120 pub fn enables_recursive<S: BuildHasher + Default>(&'a self, features: &'a HashMap<&'a str, Feature<'a>, S>) -> (HashMap<&'a str, &'a Feature<'a>, S>, DependenciesEnabledByFeatures<'a, S>) {
121 let mut features_set = HashMap::with_capacity_and_hasher(self.enabled_by.len() + self.enabled_by.len()/2, S::default());
122 let mut deps_set = HashMap::with_capacity_and_hasher(self.enables_deps.len() + self.enables_deps.len()/2, S::default());
123 self.add_to_set(features, &mut features_set, &mut deps_set);
124 (features_set, deps_set)
125 }
126
127 #[inline(never)]
128 fn add_to_set<S: BuildHasher>(&'a self, features: &'a HashMap<&'a str, Feature<'a>, S>, features_set: &mut HashMap<&'a str, &'a Feature<'a>, S>, deps_set: &mut DependenciesEnabledByFeatures<'a, S>) {
129 if features_set.insert(self.key, self).is_none() {
130 for (&dep_key, action) in &self.enables_deps {
131 if !action.is_conditional {
132 deps_set.entry(dep_key).or_default().push((self.key, action));
133 }
134 }
135 for &key in &self.enables_features {
136 if let Some(feature) = features.get(key) {
137 feature.add_to_set(features, features_set, deps_set);
138 }
139 }
140 }
141 }
142 }
143
144 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
145 pub struct TargetKey<'a> {
146 pub kind: Kind,
147 /// cfg. None for all targets.
148 pub target: Option<&'a str>,
149 }
150
151 /// A dependency referenced by a feature
152 #[derive(Debug)]
153 #[non_exhaustive]
154 pub struct FeatureDependency<'dep> {
155 /// Actual crate of this dependency. Note that multiple dependencies can be the same crate, in different versions.
156 pub crate_name: &'dep str,
157
158 /// By kind and target
159 pub targets: BTreeMap<TargetKey<'dep>, &'dep Dependency>,
160 }
161
162 impl<'dep> FeatureDependency<'dep> {
163 #[inline]
164 #[must_use]
165 pub fn dep(&self) -> &'dep Dependency {
166 self.detail().0
167 }
168
169 /// Extra metadata for the most common usage (normal > build > dev) of this dependency
170 #[inline]
171 #[must_use]
172 pub fn detail(&self) -> (&'dep Dependency, Kind) {
173 let (k, dep) = self.targets.iter().next().unwrap();
174 (dep, k.kind)
175 }
176 }
177
178 impl Resolver<'static, RandomState> {
179 /// Next step: [`.parse(manifest)`](Resolver::parse).
180 #[inline]
181 #[must_use]
182 pub fn new() -> Self {
183 Self {
184 always_keep: None,
185 _hasher: PhantomData,
186 }
187 }
188 }
189
190 impl<'manifest, 'config, RandomState: BuildHasher + Default> Resolver<'config, RandomState> {
191 /// Use turbofish to configure `RandomState` of a hasher you want this to use.
192 ///
193 /// `should_keep_hidden_feature` is a reference to a closure that will receive feature names starting with `_`, and return whether to keep or hide them.
194 #[must_use]
195 pub fn new_with_hasher_and_filter(should_keep_hidden_feature: &'config dyn Fn(&str) -> bool) -> Self {
196 Self {
197 always_keep: Some(should_keep_hidden_feature),
198 _hasher: PhantomData,
199 }
200 }
201
202 /// Parse features from a Cargo.toml manifest
203 pub fn parse<M>(&self, manifest: &'manifest Manifest<M>) -> Features<'manifest, 'manifest, RandomState> {
204 let mut features = Self::parse_features(
205 manifest.features.iter().take(MAX_ITEMS),
206 manifest.features.contains_key("default"),
207 );
208
209 let dependencies = Self::add_dependencies(
210 &mut features,
211 &manifest.dependencies,
212 &manifest.build_dependencies,
213 &manifest.dev_dependencies,
214 &manifest.target,
215 );
216
217 Self::set_required_by_bins(&mut features, &manifest.bin, manifest.package().name());
218
219 Self::remove_redundant_dep_action_features(&mut features, &dependencies);
220 Self::set_enabled_by(&mut features);
221 let hidden_features = self.remove_hidden_features(&mut features);
222
223 Features {
224 features,
225 dependencies,
226 removed_hidden_features: !hidden_features.is_empty(),
227 hidden_features,
228 }
229 }
230
231 /// Instead of processing a `Cargo.toml` manifest, take bits of information directly instead
232 ///
233 /// It won't fill in `required_by_bins` fields.
234 pub fn parse_custom<'deps, S: BuildHasher>(&self, manifest_features: &'manifest HashMap<String, Vec<String>, S>, deps: impl Iterator<Item=ParseDependency<'manifest, 'deps>>) -> Features<'manifest, 'deps, RandomState> where 'manifest: 'deps {
235 let mut features: HashMap<&'manifest str, Feature<'manifest>, _> = Self::parse_features(
236 manifest_features.iter().take(MAX_ITEMS),
237 manifest_features.contains_key("default"),
238 );
239
240 let named_using_dep_syntax = Self::named_using_dep_syntax(&features);
241
242 // First one wins, so order is important
243 let mut dependencies = HashMap::<&'deps str, FeatureDependency<'deps>, RandomState>::default();
244 for dep in deps {
245 Self::add_dependency(&mut features, &mut dependencies, named_using_dep_syntax.get(dep.key).copied(), dep.kind, dep.target, dep.key, dep.dep);
246 }
247
248 Self::remove_redundant_dep_action_features(&mut features, &dependencies);
249 Self::set_enabled_by(&mut features);
250 let hidden_features = self.remove_hidden_features(&mut features);
251
252 Features {
253 features,
254 dependencies,
255 removed_hidden_features: !hidden_features.is_empty(),
256 hidden_features,
257 }
258 }
259 }
260
261 /// For parsing in `parse_custom`. Can be constructed from the crates.io index, instead of `Cargo.toml`.
262 ///
263 /// Note about lifetimes: it's not possible to make `&Dependency` on the fly.
264 /// You will have to collect *owned* `Dependency` objects to a `Vec` or `HashMap` first.
265 #[derive(Debug, Clone)]
266 pub struct ParseDependency<'a, 'tmp> {
267 /// Name/id of the dependency, not always the crate name
268 pub key: &'a str,
269 pub kind: Kind,
270 /// Name `[target."from here".dependencies]`
271 pub target: Option<&'a str>,
272 /// Possibly more detail
273 pub dep: &'tmp Dependency,
274 }
275
276 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
277 pub enum Kind {
278 #[default]
279 Normal,
280 Build,
281 Dev,
282 }
283
284 impl<'a, 'c, S: BuildHasher + Default> Resolver<'c, S> {
285 fn parse_features(features: impl Iterator<Item = (&'a String, &'a Vec<String>)>, has_explicit_default: bool) -> HashMap<&'a str, Feature<'a>, S> {
286 features
287 .map(|(key, f)| (key.as_str(), f.as_slice()))
288 .chain(if has_explicit_default { None } else { Some(("default", &[][..])) }) // there must always be the default key
289 .map(|(feature_key, actions)| Self::parse_feature(feature_key, actions))
290 .collect()
291 }
292
293 #[inline(never)]
294 fn parse_feature(feature_key: &'a str, actions: &'a [String]) -> (&'a str, Feature<'a>) {
295 // coalesce dep_feature
296 let mut enables_deps = BTreeMap::new();
297 let mut enables_features = BTreeSet::new();
298 actions.iter().take(MAX_ITEMS).for_each(|action| {
299 let mut parts = action.splitn(2, '/');
300 let mut atarget = parts.next().unwrap_or_default();
301 let dep_feature = parts.next();
302
303 let is_dep_prefix = if let Some(k) = atarget.strip_prefix("dep:") { atarget = k; true } else { false };
304 let is_conditional = if let Some(k) = atarget.strip_suffix('?') { atarget = k; true } else { false };
305
306 // dep/feature is old, doesn't actually mean it's dep:only!
307 let is_dep_only = is_dep_prefix;
308 if is_dep_only || dep_feature.is_some() {
309 let action = enables_deps.entry(atarget).or_insert(DepAction {
310 is_conditional,
311 is_dep_only,
312 dep_features: BTreeSet::default(),
313 });
314 if !is_conditional { action.is_conditional = false; }
315 if is_dep_only { action.is_dep_only = true; }
316 if let Some(df) = dep_feature { action.dep_features.insert(Cow::Borrowed(df)); }
317 } else {
318 // dep/foo can be both, and missing enables_deps is added later after checking all for dep:
319 enables_features.insert(atarget);
320 }
321 });
322
323 (feature_key, Feature {
324 key: feature_key,
325 enables_features,
326 required_by_bins: vec![],
327 enables_deps,
328 explicit: true,
329 enabled_by: BTreeSet::new(), // fixed later
330 })
331 }
332
333 fn add_implied_optional_deps(features: &mut HashMap<&'a str, Feature<'a>, S>, deps_for_features: &mut HashMap<&'a str, FeatureDependency<'a>, S>, crate_deps: &'a BTreeMap<String, Dependency>, named_using_dep_syntax: &HashMap<&str, bool, S>, dep_kind: Kind, only_for_target: Option<&'a str>) {
334 for (key, dep) in crate_deps.iter().take(MAX_ITEMS) {
335 let key = key.as_str();
336 Self::add_dependency(features, deps_for_features, named_using_dep_syntax.get(key).copied(), dep_kind, only_for_target, key, dep);
337 }
338 }
339
340 #[inline(never)]
341 fn add_dependency<'d>(features: &mut HashMap<&'a str, Feature<'a>, S>, deps_for_features: &mut HashMap<&'d str, FeatureDependency<'d>, S>, named_using_dep_syntax: Option<bool>, dep_kind: Kind, only_for_target: Option<&'d str>, key: &'a str, dep: &'d Dependency) where 'a: 'd {
342 let is_optional = dep.optional();
343 let entry = deps_for_features.entry(key);
344 if !is_optional && named_using_dep_syntax.is_none() && matches!(entry, Entry::Vacant(_)) {
345 return;
346 }
347
348 let entry = entry.or_insert_with(move || FeatureDependency {
349 crate_name: dep.package().unwrap_or(key),
350 targets: BTreeMap::new(),
351 });
352
353 entry.targets.entry(TargetKey { kind: dep_kind, target: only_for_target }).or_insert(dep);
354
355 // explicit features never overlap with deps, unless using "dep:" syntax.
356
357 // We need to know about all deps referenced by features, or all optional ones.
358 // We won't see optional build or dev dep feature, if there's normal non-optional dep. Not a big deal?
359 // if we added one for normal, then keep adding build and dev.
360 if is_optional && named_using_dep_syntax != Some(true) {
361 features.entry(key).or_insert_with(move || Feature {
362 key,
363 enables_features: BTreeSet::default(),
364 enables_deps: BTreeMap::from_iter([(key, DepAction {
365 is_dep_only: false,
366 is_conditional: false,
367 dep_features: BTreeSet::default(),
368 })]),
369 explicit: false,
370 enabled_by: BTreeSet::new(), // will do later
371 required_by_bins: vec![],
372 });
373 }
374 }
375
376 /// find which names are affected by use of the `dep:` syntax and supress implicit features
377 #[inline(never)]
378 fn named_using_dep_syntax(features: &HashMap<&'a str, Feature<'a>, S>) -> HashMap<&'a str, bool, S> {
379 // explicit features exist, even if their name clashes with a `dep:name`.
380 let mut named_using_dep_syntax: HashMap<_, _, S> = features.keys().map(|&k| (k, false)).collect();
381
382 for f in features.values() {
383 f.enables_deps.iter().for_each(|(&dep_key, a)| {
384 named_using_dep_syntax.entry(dep_key)
385 .and_modify(|v| *v |= a.is_dep_only)
386 .or_insert(a.is_dep_only);
387 });
388 }
389
390 named_using_dep_syntax
391 }
392
393 fn add_dependencies(features: &mut HashMap<&'a str, Feature<'a>, S>, dependencies: &'a DepsSet, build_dependencies: &'a DepsSet, dev_dependencies: &'a DepsSet, target: &'a TargetDepsSet) -> HashMap<&'a str, FeatureDependency<'a>, S> {
394 let named_using_dep_syntax = Self::named_using_dep_syntax(features);
395
396 // First one wins, so order is important
397 let mut all_deps = HashMap::<_, _, S>::default();
398 Self::add_implied_optional_deps(features, &mut all_deps, dependencies, &named_using_dep_syntax, Kind::Normal, None);
399 Self::add_implied_optional_deps(features, &mut all_deps, build_dependencies, &named_using_dep_syntax, Kind::Build, None);
400 for (target_cfg, target_deps) in target {
401 Self::add_implied_optional_deps(features, &mut all_deps, &target_deps.dependencies, &named_using_dep_syntax, Kind::Normal, Some(target_cfg));
402 Self::add_implied_optional_deps(features, &mut all_deps, &target_deps.build_dependencies, &named_using_dep_syntax, Kind::Build, Some(target_cfg));
403 }
404 Self::add_implied_optional_deps(features, &mut all_deps, dev_dependencies, &named_using_dep_syntax, Kind::Dev, None);
405 for (target_cfg, target_deps) in target {
406 Self::add_implied_optional_deps(features, &mut all_deps, &target_deps.dev_dependencies, &named_using_dep_syntax, Kind::Dev, Some(target_cfg));
407 }
408 all_deps
409 }
410
411 #[inline(never)]
412 fn set_required_by_bins(features: &mut HashMap<&'a str, Feature<'a>, S>, bin: &'a [Product], package_name: &'a str) {
413 for bin in bin {
414 for f in &bin.required_features {
415 let bin_name = bin.name.as_deref().unwrap_or(package_name);
416 if let Some(f) = features.get_mut(f.as_str()) {
417 // fallback to package name is not quite accurate, because Cargo normalizes exe names slightly
418 f.required_by_bins.push(bin_name);
419 }
420 }
421 }
422 }
423
424 #[inline(never)]
425 fn remove_redundant_dep_action_features(features: &mut HashMap<&str, Feature<'_>, S>, dependencies: &HashMap<&str, FeatureDependency<'_>, S>) {
426 features.values_mut()
427 .flat_map(|f| &mut f.enables_deps)
428 .filter(|(_, action)| !action.dep_features.is_empty())
429 .for_each(|(dep_key, action)| {
430 if let Some(dep) = dependencies.get(dep_key).and_then(|d| d.dep().detail()) {
431 action.dep_features.retain(move |dep_f| {
432 let dep_f = &**dep_f;
433 (!dep.default_features || dep_f != "default") &&
434 !dep.features.iter().any(|k| k == dep_f)
435 });
436 }
437 });
438 }
439
440 #[inline(never)]
441 fn set_enabled_by(features: &mut HashMap<&'a str, Feature<'a>, S>) {
442 let mut all_enabled_by = HashMap::<_, _, S>::default();
443 for (&feature_key, f) in features.iter() {
444 f.enables_features.iter().copied().for_each(|action_key| if action_key != feature_key {
445 all_enabled_by.entry(action_key).or_insert_with(BTreeSet::new).insert(feature_key);
446 });
447 f.enables_deps.iter().for_each(|(&action_key, action)| if !action.is_conditional && !action.is_dep_only && action_key != feature_key {
448 all_enabled_by.entry(action_key).or_insert_with(BTreeSet::new).insert(feature_key);
449 });
450 }
451
452 for (key, enabled_by) in all_enabled_by {
453 if let Some(f) = features.get_mut(key) {
454 f.enabled_by = enabled_by;
455 }
456 }
457 }
458
459 /// find `__features` and inline them
460 #[inline(never)]
461 fn remove_hidden_features(&self, features: &mut HashMap<&'a str, Feature<'a>, S>) -> HashMap<&'a str, BTreeSet<&'a str>, S> {
462 let features_to_remove: BTreeSet<_> = features.keys().copied().filter(|&k| {
463 k.starts_with('_') && !self.always_keep.is_some_and(|cb| (cb)(k)) // if user thinks that is useful info
464 }).collect();
465
466 let mut removed_mapping = HashMap::<_, _, S>::default();
467
468 if features_to_remove.is_empty() {
469 return removed_mapping;
470 }
471
472 features_to_remove.into_iter().for_each(|key| {
473 let Some(mut janky) = features.remove(key) else { return };
474
475 janky.enabled_by.iter().for_each(|&parent_key| if let Some(parent) = features.get_mut(parent_key) {
476 parent.enabled_by.remove(janky.key); // just in case it's circular
477
478 // the filter tries to avoid adding new redundant enables_features, but it's order-dependent
479 parent.enables_features.extend(&janky.enables_features);
480 parent.enables_features.remove(janky.key);
481
482 janky.enables_deps.iter().for_each(|(&k, ja)| {
483 parent.enables_deps.entry(k)
484 .and_modify(|old| {
485 if !ja.is_conditional { old.is_conditional = false; }
486 if ja.is_dep_only { old.is_dep_only = true; }
487 old.dep_features.extend(ja.dep_features.iter().cloned());
488 })
489 .or_insert_with(|| ja.clone());
490 });
491 });
492
493 janky.enables_features.iter().for_each(|&f| {
494 if let Some(child) = features.get_mut(f) {
495 // this list is sometimes a bit redundant,
496 // but the hidden feature cleanup is not recursive, so it needs to contain all possible places
497 child.enabled_by.extend(&janky.enabled_by);
498 child.enabled_by.remove(janky.key);
499
500 janky.required_by_bins.iter().take(10).for_each(|&bin| {
501 if !child.required_by_bins.contains(&bin) {
502 child.required_by_bins.push(bin);
503 }
504 });
505 }
506 });
507
508 janky.enables_deps.iter().filter(|&(k, a)| !a.is_dep_only && !janky.enables_features.contains(k)).for_each(|(&d, _)| {
509 if let Some(d) = features.get_mut(d) {
510 d.enabled_by.extend(&janky.enabled_by);
511 d.enabled_by.remove(janky.key);
512 }
513 });
514
515 removed_mapping.entry(janky.key).or_default().append(&mut janky.enables_features);
516 });
517 removed_mapping
518 }
519 }
520
521 #[test]
522 fn features_test() {
523 let m = crate::Manifest::from_str(r#"
524 [package]
525 name = "foo"
526
527 [[bin]]
528 name = "thebin"
529 required-features = ["__hidden2", "loop3"]
530
531 [dependencies]
532 not_optional = { path = "..", package = "actual_pkg", features = ["f1", "f2"] }
533 depend = { version = "1.0.0", package = "actual_pkg", optional = true, default-features = false }
534 implied_standalone = { version = "1.0.0", optional = true }
535 implied_referenced = { version = "1.0.0", optional = true }
536 not_relevant = "2"
537 feature_for_hidden = { version = "2", optional = true }
538 __hidden_dep = { version = "2", optional = true }
539
540 [build-dependencies]
541 a_dep = { version = "1.0.0", optional = true }
542
543 [features]
544 default = ["x"]
545 a = []
546 b = ["a", "implied_referenced/with_feature", "depend/default", "depend/default"]
547 c = ["__hidden"]
548 x = ["__hidden", "c", "not_optional/f2", "not_optional/f3", "not_optional/default"]
549 __hidden = ["__hidden2"]
550 __hidden2 = ["dep:depend", "depend/with_x", "depend?/with_y", "__hidden0"]
551 __hidden0 = ["a"]
552 enables_hidden = ["__hidden0"]
553 __feature_for_hidden = ["feature_for_hidden"]
554
555 loop1 = ["loop2"]
556 loop2 = ["loop3", "a_dep?/maybe", "a_dep?/maybe_too", "depend/with_loop"]
557 loop3 = ["loop1", "implied_referenced/from_loop_3"]
558
559 "#).unwrap();
560 let r = Resolver::new().parse(&m);
561 let f = r.features;
562 let d = r.dependencies;
563
564 assert!(r.removed_hidden_features);
565
566 // __hidden completely removed
567 assert!(!f.iter().any(|(&k, f)| {
568 k.starts_with('_') ||
569 f.enables_features.iter().any(|&k| k.starts_with('_')) ||
570 f.enables_deps.iter().any(|(&k, _)| k.starts_with('_')) ||
571 f.enabled_by.iter().any(|&k| k.starts_with('_'))
572 }));
573
574 assert!(!d.keys().any(|&k| k.starts_with('_') && k != "__hidden_dep"));
575 assert!(!f.contains_key("__hidden_dep"));
576
577 assert_eq!(f.len(), 13);
578 assert!(!f.contains_key("depend"));
579
580 assert_eq!(d.len(), 7);
581 assert!(!d.contains_key("not_relevant"));
582 assert!(!f.contains_key("not_relevant"));
583
584 assert!(!f.contains_key("not_optional"));
585 assert_eq!(d["not_optional"].crate_name, "actual_pkg");
586
587 assert_eq!(d["implied_standalone"].crate_name, "implied_standalone");
588 assert!(d["implied_standalone"].detail().0.optional());
589 assert!(d["a_dep"].targets.keys().all(|t| t.kind == Kind::Build));
590 assert!(!f["implied_standalone"].explicit);
591 assert!(!f["implied_referenced"].explicit);
592 assert!(!f["a_dep"].explicit);
593 assert!(!f["feature_for_hidden"].is_referenced());
594
595 assert_eq!(f["x"].enables_deps.keys().copied().collect::<Vec<_>>(), &["depend", "not_optional"]);
596 assert_eq!(f["x"].enables_features.iter().copied().collect::<Vec<_>>(), &["a", "c"]);
597
598 assert_eq!(f["a"].enabled_by.iter().copied().collect::<Vec<_>>(), &["b", "c", "enables_hidden", "x"]);
599 assert!(f["a"].enables_deps.is_empty());
600 assert!(f["a"].enables_features.is_empty());
601
602 assert_eq!(f["loop1"].enabled_by.iter().copied().collect::<Vec<_>>(), &["loop3"]);
603 assert_eq!(f["loop2"].enabled_by.iter().copied().collect::<Vec<_>>(), &["loop1"]);
604 assert_eq!(f["loop3"].enabled_by.iter().copied().collect::<Vec<_>>(), &["loop2"]);
605
606 assert!(f["loop1"].enables_deps.is_empty());
607 assert_eq!(f["loop2"].enables_deps.keys().copied().collect::<Vec<_>>(), &["a_dep", "depend"]);
608 assert!(f["loop2"].enables_deps["a_dep"].is_conditional);
609 assert!(!f["loop2"].enables_deps["depend"].is_conditional);
610 assert_eq!(f["loop3"].enables_deps.keys().copied().collect::<Vec<_>>(), &["implied_referenced"]);
611
612 assert_eq!(f["loop1"].enables_features.iter().copied().collect::<Vec<_>>(), &["loop2"]);
613 assert_eq!(f["loop2"].enables_features.iter().copied().collect::<Vec<_>>(), &["loop3"]);
614 assert_eq!(f["loop3"].enables_features.iter().copied().collect::<Vec<_>>(), &["loop1"]);
615
616 let (rf, rd) = f["loop1"].enables_recursive(&f);
617 assert_eq!(rf["loop1"].key, "loop1");
618 assert_eq!(rf["loop2"].key, "loop2");
619 assert_eq!(rf["loop3"].key, "loop3");
620 assert_eq!(rd["implied_referenced"][0].0, "loop3");
621 assert_eq!(rd["depend"][0].0, "loop2");
622 assert!(!rd.contains_key("a_dep"));
623 }