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#[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
141fn 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 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 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 !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 (&Feature(feat), _, true) => {
233 if namespaced && !features.contains_key(&*feat) {
234 map.insert(feat, vec![FeatureValue::Crate(feat)]);
235 }
236 }
237 (&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 (&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 (&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 (&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 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#[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>>;