Skip to main content

cargo/core/
summary.rs

1use std::borrow::Borrow;
2use std::collections::{BTreeMap, HashMap};
3use std::fmt::Display;
4use std::mem;
5use std::rc::Rc;
6
7use serde::{Serialize, Serializer};
8
9use crate::core::interning::InternedString;
10use crate::core::{Dependency, PackageId, SourceId};
11use semver::Version;
12
13use crate::util::CargoResult;
14
15/// Subset of a `Manifest`. Contains only the most important information about
16/// a package.
17///
18/// Summaries are cloned, and should not be mutated after creation
19#[derive(Debug, Clone)]
20pub struct Summary {
21    inner: Rc<Inner>,
22}
23
24#[derive(Debug, Clone)]
25struct Inner {
26    package_id: PackageId,
27    dependencies: Vec<Dependency>,
28    features: FeatureMap,
29    checksum: Option<String>,
30    links: Option<InternedString>,
31    namespaced_features: bool,
32}
33
34impl Summary {
35    pub fn new<K>(
36        pkg_id: PackageId,
37        dependencies: Vec<Dependency>,
38        features: &BTreeMap<K, Vec<impl AsRef<str>>>,
39        links: Option<impl AsRef<str>>,
40        namespaced_features: bool,
41    ) -> CargoResult<Summary>
42    where
43        K: Borrow<str> + Ord + Display,
44    {
45        for dep in dependencies.iter() {
46            let feature = dep.name_in_toml();
47            if !namespaced_features && features.get(&*feature).is_some() {
48                failure::bail!(
49                    "Features and dependencies cannot have the \
50                     same name: `{}`",
51                    feature
52                )
53            }
54            if dep.is_optional() && !dep.is_transitive() {
55                failure::bail!(
56                    "Dev-dependencies are not allowed to be optional: `{}`",
57                    feature
58                )
59            }
60        }
61        let feature_map = build_feature_map(&features, &dependencies, namespaced_features)?;
62        Ok(Summary {
63            inner: Rc::new(Inner {
64                package_id: pkg_id,
65                dependencies,
66                features: feature_map,
67                checksum: None,
68                links: links.map(|l| InternedString::new(l.as_ref())),
69                namespaced_features,
70            }),
71        })
72    }
73
74    pub fn package_id(&self) -> PackageId {
75        self.inner.package_id
76    }
77    pub fn name(&self) -> InternedString {
78        self.package_id().name()
79    }
80    pub fn version(&self) -> &Version {
81        self.package_id().version()
82    }
83    pub fn source_id(&self) -> SourceId {
84        self.package_id().source_id()
85    }
86    pub fn dependencies(&self) -> &[Dependency] {
87        &self.inner.dependencies
88    }
89    pub fn features(&self) -> &FeatureMap {
90        &self.inner.features
91    }
92    pub fn checksum(&self) -> Option<&str> {
93        self.inner.checksum.as_ref().map(|s| &s[..])
94    }
95    pub fn links(&self) -> Option<InternedString> {
96        self.inner.links
97    }
98    pub fn namespaced_features(&self) -> bool {
99        self.inner.namespaced_features
100    }
101
102    pub fn override_id(mut self, id: PackageId) -> Summary {
103        Rc::make_mut(&mut self.inner).package_id = id;
104        self
105    }
106
107    pub fn set_checksum(mut self, cksum: String) -> Summary {
108        Rc::make_mut(&mut self.inner).checksum = Some(cksum);
109        self
110    }
111
112    pub fn map_dependencies<F>(mut self, f: F) -> Summary
113    where
114        F: FnMut(Dependency) -> Dependency,
115    {
116        {
117            let slot = &mut Rc::make_mut(&mut self.inner).dependencies;
118            let deps = mem::replace(slot, Vec::new());
119            *slot = deps.into_iter().map(f).collect();
120        }
121        self
122    }
123
124    pub fn map_source(self, to_replace: SourceId, replace_with: SourceId) -> Summary {
125        let me = if self.package_id().source_id() == to_replace {
126            let new_id = self.package_id().with_source_id(replace_with);
127            self.override_id(new_id)
128        } else {
129            self
130        };
131        me.map_dependencies(|dep| dep.map_source(to_replace, replace_with))
132    }
133}
134
135impl PartialEq for Summary {
136    fn eq(&self, other: &Summary) -> bool {
137        self.inner.package_id == other.inner.package_id
138    }
139}
140
141// Checks features for errors, bailing out a CargoResult:Err if invalid,
142// and creates FeatureValues for each feature.
143fn build_feature_map<K>(
144    features: &BTreeMap<K, Vec<impl AsRef<str>>>,
145    dependencies: &[Dependency],
146    namespaced: bool,
147) -> CargoResult<FeatureMap>
148where
149    K: Borrow<str> + Ord + Display,
150{
151    use self::FeatureValue::*;
152    let mut dep_map = HashMap::new();
153    for dep in dependencies.iter() {
154        dep_map
155            .entry(dep.name_in_toml())
156            .or_insert_with(Vec::new)
157            .push(dep);
158    }
159
160    let mut map = BTreeMap::new();
161    for (feature, list) in features.iter() {
162        // If namespaced features is active and the key is the same as that of an
163        // optional dependency, that dependency must be included in the values.
164        // Thus, if a `feature` is found that has the same name as a dependency, we
165        // (a) bail out if the dependency is non-optional, and (b) we track if the
166        // feature requirements include the dependency `crate:feature` in the list.
167        // This is done with the `dependency_found` variable, which can only be
168        // false if features are namespaced and the current feature key is the same
169        // as the name of an optional dependency. If so, it gets set to true during
170        // iteration over the list if the dependency is found in the list.
171        let mut dependency_found = if namespaced {
172            match dep_map.get(feature.borrow()) {
173                Some(ref dep_data) => {
174                    if !dep_data.iter().any(|d| d.is_optional()) {
175                        failure::bail!(
176                            "Feature `{}` includes the dependency of the same name, but this is \
177                             left implicit in the features included by this feature.\n\
178                             Additionally, the dependency must be marked as optional to be \
179                             included in the feature definition.\n\
180                             Consider adding `crate:{}` to this feature's requirements \
181                             and marking the dependency as `optional = true`",
182                            feature,
183                            feature
184                        )
185                    } else {
186                        false
187                    }
188                }
189                None => true,
190            }
191        } else {
192            true
193        };
194
195        let mut values = vec![];
196        for dep in list {
197            let val = FeatureValue::build(
198                InternedString::new(dep.as_ref()),
199                |fs| features.contains_key(fs.as_str()),
200                namespaced,
201            );
202
203            // Find data for the referenced dependency...
204            let dep_data = {
205                match val {
206                    Feature(ref dep_name) | Crate(ref dep_name) | CrateFeature(ref dep_name, _) => {
207                        dep_map.get(dep_name.as_str())
208                    }
209                }
210            };
211            let is_optional_dep = dep_data
212                .iter()
213                .flat_map(|d| d.iter())
214                .any(|d| d.is_optional());
215            if let FeatureValue::Crate(ref dep_name) = val {
216                // If we have a dependency value, check if this is the dependency named
217                // the same as the feature that we were looking for.
218                if !dependency_found && feature.borrow() == dep_name.as_str() {
219                    dependency_found = true;
220                }
221            }
222
223            match (&val, dep_data.is_some(), is_optional_dep) {
224                // The value is a feature. If features are namespaced, this just means
225                // it's not prefixed with `crate:`, so we have to check whether the
226                // feature actually exist. If the feature is not defined *and* an optional
227                // dependency of the same name exists, the feature is defined implicitly
228                // here by adding it to the feature map, pointing to the dependency.
229                // If features are not namespaced, it's been validated as a feature already
230                // while instantiating the `FeatureValue` in `FeatureValue::build()`, so
231                // we don't have to do so here.
232                (&Feature(feat), _, true) => {
233                    if namespaced && !features.contains_key(&*feat) {
234                        map.insert(feat, vec![FeatureValue::Crate(feat)]);
235                    }
236                }
237                // If features are namespaced and the value is not defined as a feature
238                // and there is no optional dependency of the same name, error out.
239                // If features are not namespaced, there must be an existing feature
240                // here (checked by `FeatureValue::build()`), so it will always be defined.
241                (&Feature(feat), dep_exists, false) => {
242                    if namespaced && !features.contains_key(&*feat) {
243                        if dep_exists {
244                            failure::bail!(
245                                "Feature `{}` includes `{}` which is not defined as a feature.\n\
246                                 A non-optional dependency of the same name is defined; consider \
247                                 adding `optional = true` to its definition",
248                                feature,
249                                feat
250                            )
251                        } else {
252                            failure::bail!(
253                                "Feature `{}` includes `{}` which is not defined as a feature",
254                                feature,
255                                feat
256                            )
257                        }
258                    }
259                }
260                // The value is a dependency. If features are namespaced, it is explicitly
261                // tagged as such (`crate:value`). If features are not namespaced, any value
262                // not recognized as a feature is pegged as a `Crate`. Here we handle the case
263                // where the dependency exists but is non-optional. It branches on namespaced
264                // just to provide the correct string for the crate dependency in the error.
265                (&Crate(ref dep), true, false) => {
266                    if namespaced {
267                        failure::bail!(
268                            "Feature `{}` includes `crate:{}` which is not an \
269                             optional dependency.\nConsider adding \
270                             `optional = true` to the dependency",
271                            feature,
272                            dep
273                        )
274                    } else {
275                        failure::bail!(
276                            "Feature `{}` depends on `{}` which is not an \
277                             optional dependency.\nConsider adding \
278                             `optional = true` to the dependency",
279                            feature,
280                            dep
281                        )
282                    }
283                }
284                // If namespaced, the value was tagged as a dependency; if not namespaced,
285                // this could be anything not defined as a feature. This handles the case
286                // where no such dependency is actually defined; again, the branch on
287                // namespaced here is just to provide the correct string in the error.
288                (&Crate(ref dep), false, _) => {
289                    if namespaced {
290                        failure::bail!(
291                            "Feature `{}` includes `crate:{}` which is not a known \
292                             dependency",
293                            feature,
294                            dep
295                        )
296                    } else {
297                        failure::bail!(
298                            "Feature `{}` includes `{}` which is neither a dependency nor \
299                             another feature",
300                            feature,
301                            dep
302                        )
303                    }
304                }
305                (&Crate(_), true, true) => {}
306                // If the value is a feature for one of the dependencies, bail out if no such
307                // dependency is actually defined in the manifest.
308                (&CrateFeature(ref dep, _), false, _) => failure::bail!(
309                    "Feature `{}` requires a feature of `{}` which is not a \
310                     dependency",
311                    feature,
312                    dep
313                ),
314                (&CrateFeature(_, _), true, _) => {}
315            }
316            values.push(val);
317        }
318
319        if !dependency_found {
320            // If we have not found the dependency of the same-named feature, we should
321            // bail here.
322            failure::bail!(
323                "Feature `{}` includes the optional dependency of the \
324                 same name, but this is left implicit in the features \
325                 included by this feature.\nConsider adding \
326                 `crate:{}` to this feature's requirements.",
327                feature,
328                feature
329            )
330        }
331
332        map.insert(InternedString::new(feature.borrow()), values);
333    }
334    Ok(map)
335}
336
337/// FeatureValue represents the types of dependencies a feature can have:
338///
339/// * Another feature
340/// * An optional dependency
341/// * A feature in a dependency
342///
343/// The selection between these 3 things happens as part of the construction of the FeatureValue.
344#[derive(Clone, Debug)]
345pub enum FeatureValue {
346    Feature(InternedString),
347    Crate(InternedString),
348    CrateFeature(InternedString, InternedString),
349}
350
351impl FeatureValue {
352    fn build<T>(feature: InternedString, is_feature: T, namespaced: bool) -> FeatureValue
353    where
354        T: Fn(InternedString) -> bool,
355    {
356        match (feature.find('/'), namespaced) {
357            (Some(pos), _) => {
358                let (dep, dep_feat) = feature.split_at(pos);
359                let dep_feat = &dep_feat[1..];
360                FeatureValue::CrateFeature(InternedString::new(dep), InternedString::new(dep_feat))
361            }
362            (None, true) if feature.starts_with("crate:") => {
363                FeatureValue::Crate(InternedString::new(&feature[6..]))
364            }
365            (None, true) => FeatureValue::Feature(feature),
366            (None, false) if is_feature(feature) => FeatureValue::Feature(feature),
367            (None, false) => FeatureValue::Crate(feature),
368        }
369    }
370
371    pub fn new(feature: InternedString, s: &Summary) -> FeatureValue {
372        Self::build(
373            feature,
374            |fs| s.features().contains_key(&fs),
375            s.namespaced_features(),
376        )
377    }
378
379    pub fn to_string(&self, s: &Summary) -> String {
380        use self::FeatureValue::*;
381        match *self {
382            Feature(ref f) => f.to_string(),
383            Crate(ref c) => {
384                if s.namespaced_features() {
385                    format!("crate:{}", &c)
386                } else {
387                    c.to_string()
388                }
389            }
390            CrateFeature(ref c, ref f) => [c.as_ref(), f.as_ref()].join("/"),
391        }
392    }
393}
394
395impl Serialize for FeatureValue {
396    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
397    where
398        S: Serializer,
399    {
400        use self::FeatureValue::*;
401        match *self {
402            Feature(ref f) => serializer.serialize_str(f),
403            Crate(ref c) => serializer.serialize_str(c),
404            CrateFeature(ref c, ref f) => {
405                serializer.serialize_str(&[c.as_ref(), f.as_ref()].join("/"))
406            }
407        }
408    }
409}
410
411pub type FeatureMap = BTreeMap<InternedString, Vec<FeatureValue>>;