1use std::fmt;
2use std::rc::Rc;
3use std::str::FromStr;
4
5use log::trace;
6use semver::ReqParseError;
7use semver::VersionReq;
8use serde::ser;
9use serde::Serialize;
10use url::Url;
11
12use crate::core::interning::InternedString;
13use crate::core::{PackageId, SourceId, Summary};
14use crate::util::errors::{CargoResult, CargoResultExt};
15use crate::util::{Cfg, CfgExpr, Config};
16
17#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
20pub struct Dependency {
21 inner: Rc<Inner>,
22}
23
24#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug)]
26struct Inner {
27 name: InternedString,
28 source_id: SourceId,
29 registry_id: Option<SourceId>,
36 req: VersionReq,
37 specified_req: bool,
38 kind: Kind,
39 only_match_name: bool,
40 explicit_name_in_toml: Option<InternedString>,
41
42 optional: bool,
43 default_features: bool,
44 features: Vec<InternedString>,
45
46 platform: Option<Platform>,
49}
50
51#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Debug)]
52pub enum Platform {
53 Name(String),
54 Cfg(CfgExpr),
55}
56
57#[derive(Serialize)]
58struct SerializedDependency<'a> {
59 name: &'a str,
60 source: SourceId,
61 req: String,
62 kind: Kind,
63 rename: Option<&'a str>,
64
65 optional: bool,
66 uses_default_features: bool,
67 features: &'a [InternedString],
68 target: Option<&'a Platform>,
69 #[serde(with = "url_serde")]
72 registry: Option<Url>,
73}
74
75impl ser::Serialize for Dependency {
76 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
77 where
78 S: ser::Serializer,
79 {
80 SerializedDependency {
81 name: &*self.package_name(),
82 source: self.source_id(),
83 req: self.version_req().to_string(),
84 kind: self.kind(),
85 optional: self.is_optional(),
86 uses_default_features: self.uses_default_features(),
87 features: self.features(),
88 target: self.platform(),
89 rename: self.explicit_name_in_toml().map(|s| s.as_str()),
90 registry: self.registry_id().map(|sid| sid.url().clone()),
91 }
92 .serialize(s)
93 }
94}
95
96#[derive(PartialEq, Eq, Hash, Ord, PartialOrd, Clone, Debug, Copy)]
97pub enum Kind {
98 Normal,
99 Development,
100 Build,
101}
102
103fn parse_req_with_deprecated(
104 name: &str,
105 req: &str,
106 extra: Option<(PackageId, &Config)>,
107) -> CargoResult<VersionReq> {
108 match VersionReq::parse(req) {
109 Err(ReqParseError::DeprecatedVersionRequirement(requirement)) => {
110 let (inside, config) = match extra {
111 Some(pair) => pair,
112 None => return Err(ReqParseError::DeprecatedVersionRequirement(requirement).into()),
113 };
114 let msg = format!(
115 "\
116parsed version requirement `{}` is no longer valid
117
118Previous versions of Cargo accepted this malformed requirement,
119but it is being deprecated. This was found when parsing the manifest
120of {} {}, and the correct version requirement is `{}`.
121
122This will soon become a hard error, so it's either recommended to
123update to a fixed version or contact the upstream maintainer about
124this warning.
125",
126 req,
127 inside.name(),
128 inside.version(),
129 requirement
130 );
131 config.shell().warn(&msg)?;
132
133 Ok(requirement)
134 }
135 Err(e) => {
136 let err: CargoResult<VersionReq> = Err(e.into());
137 let v: VersionReq = err.chain_err(|| {
138 format!(
139 "failed to parse the version requirement `{}` for dependency `{}`",
140 req, name
141 )
142 })?;
143 Ok(v)
144 }
145 Ok(v) => Ok(v),
146 }
147}
148
149impl ser::Serialize for Kind {
150 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
151 where
152 S: ser::Serializer,
153 {
154 match *self {
155 Kind::Normal => None,
156 Kind::Development => Some("dev"),
157 Kind::Build => Some("build"),
158 }
159 .serialize(s)
160 }
161}
162
163impl Dependency {
164 pub fn parse(
166 name: &str,
167 version: Option<&str>,
168 source_id: SourceId,
169 inside: PackageId,
170 config: &Config,
171 ) -> CargoResult<Dependency> {
172 let arg = Some((inside, config));
173 let (specified_req, version_req) = match version {
174 Some(v) => (true, parse_req_with_deprecated(name, v, arg)?),
175 None => (false, VersionReq::any()),
176 };
177
178 let mut ret = Dependency::new_override(name, source_id);
179 {
180 let ptr = Rc::make_mut(&mut ret.inner);
181 ptr.only_match_name = false;
182 ptr.req = version_req;
183 ptr.specified_req = specified_req;
184 }
185 Ok(ret)
186 }
187
188 pub fn parse_no_deprecated(
190 name: &str,
191 version: Option<&str>,
192 source_id: SourceId,
193 ) -> CargoResult<Dependency> {
194 let (specified_req, version_req) = match version {
195 Some(v) => (true, parse_req_with_deprecated(name, v, None)?),
196 None => (false, VersionReq::any()),
197 };
198
199 let mut ret = Dependency::new_override(name, source_id);
200 {
201 let ptr = Rc::make_mut(&mut ret.inner);
202 ptr.only_match_name = false;
203 ptr.req = version_req;
204 ptr.specified_req = specified_req;
205 }
206 Ok(ret)
207 }
208
209 pub fn new_override(name: &str, source_id: SourceId) -> Dependency {
210 assert!(!name.is_empty());
211 Dependency {
212 inner: Rc::new(Inner {
213 name: InternedString::new(name),
214 source_id,
215 registry_id: None,
216 req: VersionReq::any(),
217 kind: Kind::Normal,
218 only_match_name: true,
219 optional: false,
220 features: Vec::new(),
221 default_features: true,
222 specified_req: false,
223 platform: None,
224 explicit_name_in_toml: None,
225 }),
226 }
227 }
228
229 pub fn version_req(&self) -> &VersionReq {
230 &self.inner.req
231 }
232
233 pub fn name_in_toml(&self) -> InternedString {
254 self.explicit_name_in_toml().unwrap_or(self.inner.name)
255 }
256
257 pub fn package_name(&self) -> InternedString {
276 self.inner.name
277 }
278
279 pub fn source_id(&self) -> SourceId {
280 self.inner.source_id
281 }
282
283 pub fn registry_id(&self) -> Option<SourceId> {
284 self.inner.registry_id
285 }
286
287 pub fn set_registry_id(&mut self, registry_id: SourceId) -> &mut Dependency {
288 Rc::make_mut(&mut self.inner).registry_id = Some(registry_id);
289 self
290 }
291
292 pub fn kind(&self) -> Kind {
293 self.inner.kind
294 }
295
296 pub fn specified_req(&self) -> bool {
297 self.inner.specified_req
298 }
299
300 pub fn platform(&self) -> Option<&Platform> {
303 self.inner.platform.as_ref()
304 }
305
306 pub fn explicit_name_in_toml(&self) -> Option<InternedString> {
311 self.inner.explicit_name_in_toml
312 }
313
314 pub fn set_kind(&mut self, kind: Kind) -> &mut Dependency {
315 Rc::make_mut(&mut self.inner).kind = kind;
316 self
317 }
318
319 pub fn set_features(
321 &mut self,
322 features: impl IntoIterator<Item = impl AsRef<str>>,
323 ) -> &mut Dependency {
324 Rc::make_mut(&mut self.inner).features = features
325 .into_iter()
326 .map(|s| InternedString::new(s.as_ref()))
327 .collect();
328 self
329 }
330
331 pub fn set_default_features(&mut self, default_features: bool) -> &mut Dependency {
333 Rc::make_mut(&mut self.inner).default_features = default_features;
334 self
335 }
336
337 pub fn set_optional(&mut self, optional: bool) -> &mut Dependency {
339 Rc::make_mut(&mut self.inner).optional = optional;
340 self
341 }
342
343 pub fn set_source_id(&mut self, id: SourceId) -> &mut Dependency {
345 Rc::make_mut(&mut self.inner).source_id = id;
346 self
347 }
348
349 pub fn set_version_req(&mut self, req: VersionReq) -> &mut Dependency {
351 Rc::make_mut(&mut self.inner).req = req;
352 self
353 }
354
355 pub fn set_platform(&mut self, platform: Option<Platform>) -> &mut Dependency {
356 Rc::make_mut(&mut self.inner).platform = platform;
357 self
358 }
359
360 pub fn set_explicit_name_in_toml(&mut self, name: &str) -> &mut Dependency {
361 Rc::make_mut(&mut self.inner).explicit_name_in_toml = Some(InternedString::new(name));
362 self
363 }
364
365 pub fn lock_to(&mut self, id: PackageId) -> &mut Dependency {
367 assert_eq!(self.inner.source_id, id.source_id());
368 assert!(self.inner.req.matches(id.version()));
369 trace!(
370 "locking dep from `{}` with `{}` at {} to {}",
371 self.package_name(),
372 self.version_req(),
373 self.source_id(),
374 id
375 );
376 self.set_version_req(VersionReq::exact(id.version()))
377 .set_source_id(id.source_id())
378 }
379
380 pub fn is_locked(&self) -> bool {
383 self.inner.req.to_string().starts_with('=')
385 }
386
387 pub fn is_transitive(&self) -> bool {
389 match self.inner.kind {
390 Kind::Normal | Kind::Build => true,
391 Kind::Development => false,
392 }
393 }
394
395 pub fn is_build(&self) -> bool {
396 match self.inner.kind {
397 Kind::Build => true,
398 _ => false,
399 }
400 }
401
402 pub fn is_optional(&self) -> bool {
403 self.inner.optional
404 }
405
406 pub fn uses_default_features(&self) -> bool {
408 self.inner.default_features
409 }
410 pub fn features(&self) -> &[InternedString] {
412 &self.inner.features
413 }
414
415 pub fn matches(&self, sum: &Summary) -> bool {
417 self.matches_id(sum.package_id())
418 }
419
420 pub fn matches_ignoring_source(&self, id: PackageId) -> bool {
422 self.package_name() == id.name() && self.version_req().matches(id.version())
423 }
424
425 pub fn matches_id(&self, id: PackageId) -> bool {
427 self.inner.name == id.name()
428 && (self.inner.only_match_name
429 || (self.inner.req.matches(id.version()) && self.inner.source_id == id.source_id()))
430 }
431
432 pub fn map_source(mut self, to_replace: SourceId, replace_with: SourceId) -> Dependency {
433 if self.source_id() != to_replace {
434 self
435 } else {
436 self.set_source_id(replace_with);
437 self
438 }
439 }
440}
441
442impl Platform {
443 pub fn matches(&self, name: &str, cfg: Option<&[Cfg]>) -> bool {
444 match *self {
445 Platform::Name(ref p) => p == name,
446 Platform::Cfg(ref p) => match cfg {
447 Some(cfg) => p.matches(cfg),
448 None => false,
449 },
450 }
451 }
452}
453
454impl ser::Serialize for Platform {
455 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
456 where
457 S: ser::Serializer,
458 {
459 self.to_string().serialize(s)
460 }
461}
462
463impl FromStr for Platform {
464 type Err = failure::Error;
465
466 fn from_str(s: &str) -> CargoResult<Platform> {
467 if s.starts_with("cfg(") && s.ends_with(')') {
468 let s = &s[4..s.len() - 1];
469 let p = s.parse().map(Platform::Cfg).chain_err(|| {
470 failure::format_err!("failed to parse `{}` as a cfg expression", s)
471 })?;
472 Ok(p)
473 } else {
474 Ok(Platform::Name(s.to_string()))
475 }
476 }
477}
478
479impl fmt::Display for Platform {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 match *self {
482 Platform::Name(ref n) => n.fmt(f),
483 Platform::Cfg(ref e) => write!(f, "cfg({})", e),
484 }
485 }
486}