]> git.proxmox.com Git - cargo.git/blob - src/cargo/core/manifest.rs
Migrate from the `failure` crate to `anyhow`
[cargo.git] / src / cargo / core / manifest.rs
1 use std::collections::{BTreeMap, HashMap};
2 use std::fmt;
3 use std::hash::{Hash, Hasher};
4 use std::path::{Path, PathBuf};
5 use std::rc::Rc;
6
7 use semver::Version;
8 use serde::ser;
9 use serde::Serialize;
10 use url::Url;
11
12 use crate::core::interning::InternedString;
13 use crate::core::profiles::Profiles;
14 use crate::core::{Dependency, PackageId, PackageIdSpec, SourceId, Summary};
15 use crate::core::{Edition, Feature, Features, WorkspaceConfig};
16 use crate::util::errors::*;
17 use crate::util::toml::TomlManifest;
18 use crate::util::{short_hash, Config, Filesystem};
19
20 pub enum EitherManifest {
21 Real(Manifest),
22 Virtual(VirtualManifest),
23 }
24
25 /// Contains all the information about a package, as loaded from a `Cargo.toml`.
26 #[derive(Clone, Debug)]
27 pub struct Manifest {
28 summary: Summary,
29 targets: Vec<Target>,
30 links: Option<String>,
31 warnings: Warnings,
32 exclude: Vec<String>,
33 include: Vec<String>,
34 metadata: ManifestMetadata,
35 custom_metadata: Option<toml::Value>,
36 profiles: Profiles,
37 publish: Option<Vec<String>>,
38 publish_lockfile: bool,
39 replace: Vec<(PackageIdSpec, Dependency)>,
40 patch: HashMap<Url, Vec<Dependency>>,
41 workspace: WorkspaceConfig,
42 original: Rc<TomlManifest>,
43 features: Features,
44 edition: Edition,
45 im_a_teapot: Option<bool>,
46 default_run: Option<String>,
47 metabuild: Option<Vec<String>>,
48 }
49
50 /// When parsing `Cargo.toml`, some warnings should silenced
51 /// if the manifest comes from a dependency. `ManifestWarning`
52 /// allows this delayed emission of warnings.
53 #[derive(Clone, Debug)]
54 pub struct DelayedWarning {
55 pub message: String,
56 pub is_critical: bool,
57 }
58
59 #[derive(Clone, Debug)]
60 pub struct Warnings(Vec<DelayedWarning>);
61
62 #[derive(Clone, Debug)]
63 pub struct VirtualManifest {
64 replace: Vec<(PackageIdSpec, Dependency)>,
65 patch: HashMap<Url, Vec<Dependency>>,
66 workspace: WorkspaceConfig,
67 profiles: Profiles,
68 warnings: Warnings,
69 features: Features,
70 }
71
72 /// General metadata about a package which is just blindly uploaded to the
73 /// registry.
74 ///
75 /// Note that many of these fields can contain invalid values such as the
76 /// homepage, repository, documentation, or license. These fields are not
77 /// validated by cargo itself, but rather it is up to the registry when uploaded
78 /// to validate these fields. Cargo will itself accept any valid TOML
79 /// specification for these values.
80 #[derive(PartialEq, Clone, Debug)]
81 pub struct ManifestMetadata {
82 pub authors: Vec<String>,
83 pub keywords: Vec<String>,
84 pub categories: Vec<String>,
85 pub license: Option<String>,
86 pub license_file: Option<String>,
87 pub description: Option<String>, // Not in Markdown
88 pub readme: Option<String>, // File, not contents
89 pub homepage: Option<String>, // URL
90 pub repository: Option<String>, // URL
91 pub documentation: Option<String>, // URL
92 pub badges: BTreeMap<String, BTreeMap<String, String>>,
93 pub links: Option<String>,
94 }
95
96 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
97 pub enum LibKind {
98 Lib,
99 Rlib,
100 Dylib,
101 ProcMacro,
102 Other(String),
103 }
104
105 impl LibKind {
106 /// Returns the argument suitable for `--crate-type` to pass to rustc.
107 pub fn crate_type(&self) -> &str {
108 match *self {
109 LibKind::Lib => "lib",
110 LibKind::Rlib => "rlib",
111 LibKind::Dylib => "dylib",
112 LibKind::ProcMacro => "proc-macro",
113 LibKind::Other(ref s) => s,
114 }
115 }
116
117 pub fn linkable(&self) -> bool {
118 match *self {
119 LibKind::Lib | LibKind::Rlib | LibKind::Dylib | LibKind::ProcMacro => true,
120 LibKind::Other(..) => false,
121 }
122 }
123
124 pub fn requires_upstream_objects(&self) -> bool {
125 match *self {
126 // "lib" == "rlib" and is a compilation that doesn't actually
127 // require upstream object files to exist, only upstream metadata
128 // files. As a result, it doesn't require upstream artifacts
129 LibKind::Lib | LibKind::Rlib => false,
130
131 // Everything else, however, is some form of "linkable output" or
132 // something that requires upstream object files.
133 _ => true,
134 }
135 }
136 }
137
138 impl fmt::Debug for LibKind {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 self.crate_type().fmt(f)
141 }
142 }
143
144 impl<'a> From<&'a String> for LibKind {
145 fn from(string: &'a String) -> Self {
146 match string.as_ref() {
147 "lib" => LibKind::Lib,
148 "rlib" => LibKind::Rlib,
149 "dylib" => LibKind::Dylib,
150 "proc-macro" => LibKind::ProcMacro,
151 s => LibKind::Other(s.to_string()),
152 }
153 }
154 }
155
156 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
157 pub enum TargetKind {
158 Lib(Vec<LibKind>),
159 Bin,
160 Test,
161 Bench,
162 ExampleLib(Vec<LibKind>),
163 ExampleBin,
164 CustomBuild,
165 }
166
167 impl ser::Serialize for TargetKind {
168 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
169 where
170 S: ser::Serializer,
171 {
172 use self::TargetKind::*;
173 match *self {
174 Lib(ref kinds) => s.collect_seq(kinds.iter().map(LibKind::crate_type)),
175 Bin => ["bin"].serialize(s),
176 ExampleBin | ExampleLib(_) => ["example"].serialize(s),
177 Test => ["test"].serialize(s),
178 CustomBuild => ["custom-build"].serialize(s),
179 Bench => ["bench"].serialize(s),
180 }
181 }
182 }
183
184 impl fmt::Debug for TargetKind {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 use self::TargetKind::*;
187 match *self {
188 Lib(ref kinds) => kinds.fmt(f),
189 Bin => "bin".fmt(f),
190 ExampleBin | ExampleLib(_) => "example".fmt(f),
191 Test => "test".fmt(f),
192 CustomBuild => "custom-build".fmt(f),
193 Bench => "bench".fmt(f),
194 }
195 }
196 }
197
198 impl TargetKind {
199 pub fn description(&self) -> &'static str {
200 match self {
201 TargetKind::Lib(..) => "lib",
202 TargetKind::Bin => "bin",
203 TargetKind::Test => "integration-test",
204 TargetKind::ExampleBin | TargetKind::ExampleLib(..) => "example",
205 TargetKind::Bench => "bench",
206 TargetKind::CustomBuild => "build-script",
207 }
208 }
209
210 /// Returns whether production of this artifact requires the object files
211 /// from dependencies to be available.
212 ///
213 /// This only returns `false` when all we're producing is an rlib, otherwise
214 /// it will return `true`.
215 pub fn requires_upstream_objects(&self) -> bool {
216 match self {
217 TargetKind::Lib(kinds) | TargetKind::ExampleLib(kinds) => {
218 kinds.iter().any(|k| k.requires_upstream_objects())
219 }
220 _ => true,
221 }
222 }
223 }
224
225 /// Information about a binary, a library, an example, etc. that is part of the
226 /// package.
227 #[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
228 pub struct Target {
229 kind: TargetKind,
230 name: String,
231 // Note that the `src_path` here is excluded from the `Hash` implementation
232 // as it's absolute currently and is otherwise a little too brittle for
233 // causing rebuilds. Instead the hash for the path that we send to the
234 // compiler is handled elsewhere.
235 src_path: TargetSourcePath,
236 required_features: Option<Vec<String>>,
237 tested: bool,
238 benched: bool,
239 doc: bool,
240 doctest: bool,
241 harness: bool, // whether to use the test harness (--test)
242 for_host: bool,
243 proc_macro: bool,
244 edition: Edition,
245 }
246
247 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
248 pub enum TargetSourcePath {
249 Path(PathBuf),
250 Metabuild,
251 }
252
253 impl TargetSourcePath {
254 pub fn path(&self) -> Option<&Path> {
255 match self {
256 TargetSourcePath::Path(path) => Some(path.as_ref()),
257 TargetSourcePath::Metabuild => None,
258 }
259 }
260
261 pub fn is_path(&self) -> bool {
262 match self {
263 TargetSourcePath::Path(_) => true,
264 _ => false,
265 }
266 }
267 }
268
269 impl Hash for TargetSourcePath {
270 fn hash<H: Hasher>(&self, _: &mut H) {
271 // ...
272 }
273 }
274
275 impl fmt::Debug for TargetSourcePath {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 match self {
278 TargetSourcePath::Path(path) => path.fmt(f),
279 TargetSourcePath::Metabuild => "metabuild".fmt(f),
280 }
281 }
282 }
283
284 impl From<PathBuf> for TargetSourcePath {
285 fn from(path: PathBuf) -> Self {
286 assert!(path.is_absolute(), "`{}` is not absolute", path.display());
287 TargetSourcePath::Path(path)
288 }
289 }
290
291 #[derive(Serialize)]
292 struct SerializedTarget<'a> {
293 /// Is this a `--bin bin`, `--lib`, `--example ex`?
294 /// Serialized as a list of strings for historical reasons.
295 kind: &'a TargetKind,
296 /// Corresponds to `--crate-type` compiler attribute.
297 /// See https://doc.rust-lang.org/reference/linkage.html
298 crate_types: Vec<&'a str>,
299 name: &'a str,
300 src_path: Option<&'a PathBuf>,
301 edition: &'a str,
302 #[serde(rename = "required-features", skip_serializing_if = "Option::is_none")]
303 required_features: Option<Vec<&'a str>>,
304 doctest: bool,
305 }
306
307 impl ser::Serialize for Target {
308 fn serialize<S: ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
309 let src_path = match &self.src_path {
310 TargetSourcePath::Path(p) => Some(p),
311 // Unfortunately getting the correct path would require access to
312 // target_dir, which is not available here.
313 TargetSourcePath::Metabuild => None,
314 };
315 SerializedTarget {
316 kind: &self.kind,
317 crate_types: self.rustc_crate_types(),
318 name: &self.name,
319 src_path,
320 edition: &self.edition.to_string(),
321 required_features: self
322 .required_features
323 .as_ref()
324 .map(|rf| rf.iter().map(|s| &**s).collect()),
325 doctest: self.doctest && self.doctestable(),
326 }
327 .serialize(s)
328 }
329 }
330
331 compact_debug! {
332 impl fmt::Debug for Target {
333 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334 let (default, default_name) = {
335 match &self.kind {
336 TargetKind::Lib(kinds) => {
337 (
338 Target::lib_target(
339 &self.name,
340 kinds.clone(),
341 self.src_path().path().unwrap().to_path_buf(),
342 self.edition,
343 ),
344 format!("lib_target({:?}, {:?}, {:?}, {:?})",
345 self.name, kinds, self.src_path, self.edition),
346 )
347 }
348 TargetKind::CustomBuild => {
349 match self.src_path {
350 TargetSourcePath::Path(ref path) => {
351 (
352 Target::custom_build_target(
353 &self.name,
354 path.to_path_buf(),
355 self.edition,
356 ),
357 format!("custom_build_target({:?}, {:?}, {:?})",
358 self.name, path, self.edition),
359 )
360 }
361 TargetSourcePath::Metabuild => {
362 (
363 Target::metabuild_target(&self.name),
364 format!("metabuild_target({:?})", self.name),
365 )
366 }
367 }
368 }
369 _ => (
370 Target::new(self.src_path.clone(), self.edition),
371 format!("with_path({:?}, {:?})", self.src_path, self.edition),
372 ),
373 }
374 };
375 [debug_the_fields(
376 kind
377 name
378 src_path
379 required_features
380 tested
381 benched
382 doc
383 doctest
384 harness
385 for_host
386 proc_macro
387 edition
388 )]
389 }
390 }
391 }
392
393 impl Manifest {
394 pub fn new(
395 summary: Summary,
396 targets: Vec<Target>,
397 exclude: Vec<String>,
398 include: Vec<String>,
399 links: Option<String>,
400 metadata: ManifestMetadata,
401 custom_metadata: Option<toml::Value>,
402 profiles: Profiles,
403 publish: Option<Vec<String>>,
404 publish_lockfile: bool,
405 replace: Vec<(PackageIdSpec, Dependency)>,
406 patch: HashMap<Url, Vec<Dependency>>,
407 workspace: WorkspaceConfig,
408 features: Features,
409 edition: Edition,
410 im_a_teapot: Option<bool>,
411 default_run: Option<String>,
412 original: Rc<TomlManifest>,
413 metabuild: Option<Vec<String>>,
414 ) -> Manifest {
415 Manifest {
416 summary,
417 targets,
418 warnings: Warnings::new(),
419 exclude,
420 include,
421 links,
422 metadata,
423 custom_metadata,
424 profiles,
425 publish,
426 replace,
427 patch,
428 workspace,
429 features,
430 edition,
431 original,
432 im_a_teapot,
433 default_run,
434 publish_lockfile,
435 metabuild,
436 }
437 }
438
439 pub fn dependencies(&self) -> &[Dependency] {
440 self.summary.dependencies()
441 }
442 pub fn exclude(&self) -> &[String] {
443 &self.exclude
444 }
445 pub fn include(&self) -> &[String] {
446 &self.include
447 }
448 pub fn metadata(&self) -> &ManifestMetadata {
449 &self.metadata
450 }
451 pub fn name(&self) -> InternedString {
452 self.package_id().name()
453 }
454 pub fn package_id(&self) -> PackageId {
455 self.summary.package_id()
456 }
457 pub fn summary(&self) -> &Summary {
458 &self.summary
459 }
460 pub fn summary_mut(&mut self) -> &mut Summary {
461 &mut self.summary
462 }
463 pub fn targets(&self) -> &[Target] {
464 &self.targets
465 }
466 pub fn targets_mut(&mut self) -> &mut [Target] {
467 &mut self.targets
468 }
469 pub fn version(&self) -> &Version {
470 self.package_id().version()
471 }
472 pub fn warnings_mut(&mut self) -> &mut Warnings {
473 &mut self.warnings
474 }
475 pub fn warnings(&self) -> &Warnings {
476 &self.warnings
477 }
478 pub fn profiles(&self) -> &Profiles {
479 &self.profiles
480 }
481 pub fn publish(&self) -> &Option<Vec<String>> {
482 &self.publish
483 }
484 pub fn replace(&self) -> &[(PackageIdSpec, Dependency)] {
485 &self.replace
486 }
487 pub fn original(&self) -> &TomlManifest {
488 &self.original
489 }
490 pub fn patch(&self) -> &HashMap<Url, Vec<Dependency>> {
491 &self.patch
492 }
493 pub fn links(&self) -> Option<&str> {
494 self.links.as_ref().map(|s| &s[..])
495 }
496
497 pub fn workspace_config(&self) -> &WorkspaceConfig {
498 &self.workspace
499 }
500
501 pub fn features(&self) -> &Features {
502 &self.features
503 }
504
505 pub fn map_source(self, to_replace: SourceId, replace_with: SourceId) -> Manifest {
506 Manifest {
507 summary: self.summary.map_source(to_replace, replace_with),
508 ..self
509 }
510 }
511
512 pub fn feature_gate(&self) -> CargoResult<()> {
513 if self.im_a_teapot.is_some() {
514 self.features
515 .require(Feature::test_dummy_unstable())
516 .chain_err(|| {
517 anyhow::format_err!(
518 "the `im-a-teapot` manifest key is unstable and may \
519 not work properly in England"
520 )
521 })?;
522 }
523
524 Ok(())
525 }
526
527 // Just a helper function to test out `-Z` flags on Cargo
528 pub fn print_teapot(&self, config: &Config) {
529 if let Some(teapot) = self.im_a_teapot {
530 if config.cli_unstable().print_im_a_teapot {
531 println!("im-a-teapot = {}", teapot);
532 }
533 }
534 }
535
536 pub fn edition(&self) -> Edition {
537 self.edition
538 }
539
540 pub fn custom_metadata(&self) -> Option<&toml::Value> {
541 self.custom_metadata.as_ref()
542 }
543
544 pub fn default_run(&self) -> Option<&str> {
545 self.default_run.as_ref().map(|s| &s[..])
546 }
547
548 pub fn metabuild(&self) -> Option<&Vec<String>> {
549 self.metabuild.as_ref()
550 }
551
552 pub fn metabuild_path(&self, target_dir: Filesystem) -> PathBuf {
553 let hash = short_hash(&self.package_id());
554 target_dir
555 .into_path_unlocked()
556 .join(".metabuild")
557 .join(format!("metabuild-{}-{}.rs", self.name(), hash))
558 }
559 }
560
561 impl VirtualManifest {
562 pub fn new(
563 replace: Vec<(PackageIdSpec, Dependency)>,
564 patch: HashMap<Url, Vec<Dependency>>,
565 workspace: WorkspaceConfig,
566 profiles: Profiles,
567 features: Features,
568 ) -> VirtualManifest {
569 VirtualManifest {
570 replace,
571 patch,
572 workspace,
573 profiles,
574 warnings: Warnings::new(),
575 features,
576 }
577 }
578
579 pub fn replace(&self) -> &[(PackageIdSpec, Dependency)] {
580 &self.replace
581 }
582
583 pub fn patch(&self) -> &HashMap<Url, Vec<Dependency>> {
584 &self.patch
585 }
586
587 pub fn workspace_config(&self) -> &WorkspaceConfig {
588 &self.workspace
589 }
590
591 pub fn profiles(&self) -> &Profiles {
592 &self.profiles
593 }
594
595 pub fn warnings_mut(&mut self) -> &mut Warnings {
596 &mut self.warnings
597 }
598
599 pub fn warnings(&self) -> &Warnings {
600 &self.warnings
601 }
602
603 pub fn features(&self) -> &Features {
604 &self.features
605 }
606 }
607
608 impl Target {
609 fn new(src_path: TargetSourcePath, edition: Edition) -> Target {
610 Target {
611 kind: TargetKind::Bin,
612 name: String::new(),
613 src_path,
614 required_features: None,
615 doc: false,
616 doctest: false,
617 harness: true,
618 for_host: false,
619 proc_macro: false,
620 edition,
621 tested: true,
622 benched: true,
623 }
624 }
625
626 fn with_path(src_path: PathBuf, edition: Edition) -> Target {
627 Target::new(TargetSourcePath::from(src_path), edition)
628 }
629
630 pub fn lib_target(
631 name: &str,
632 crate_targets: Vec<LibKind>,
633 src_path: PathBuf,
634 edition: Edition,
635 ) -> Target {
636 Target {
637 kind: TargetKind::Lib(crate_targets),
638 name: name.to_string(),
639 doctest: true,
640 doc: true,
641 ..Target::with_path(src_path, edition)
642 }
643 }
644
645 pub fn bin_target(
646 name: &str,
647 src_path: PathBuf,
648 required_features: Option<Vec<String>>,
649 edition: Edition,
650 ) -> Target {
651 Target {
652 kind: TargetKind::Bin,
653 name: name.to_string(),
654 required_features,
655 doc: true,
656 ..Target::with_path(src_path, edition)
657 }
658 }
659
660 /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
661 pub fn custom_build_target(name: &str, src_path: PathBuf, edition: Edition) -> Target {
662 Target {
663 kind: TargetKind::CustomBuild,
664 name: name.to_string(),
665 for_host: true,
666 benched: false,
667 tested: false,
668 ..Target::with_path(src_path, edition)
669 }
670 }
671
672 pub fn metabuild_target(name: &str) -> Target {
673 Target {
674 kind: TargetKind::CustomBuild,
675 name: name.to_string(),
676 for_host: true,
677 benched: false,
678 tested: false,
679 ..Target::new(TargetSourcePath::Metabuild, Edition::Edition2018)
680 }
681 }
682
683 pub fn example_target(
684 name: &str,
685 crate_targets: Vec<LibKind>,
686 src_path: PathBuf,
687 required_features: Option<Vec<String>>,
688 edition: Edition,
689 ) -> Target {
690 let kind = if crate_targets.is_empty()
691 || crate_targets
692 .iter()
693 .all(|t| *t == LibKind::Other("bin".into()))
694 {
695 TargetKind::ExampleBin
696 } else {
697 TargetKind::ExampleLib(crate_targets)
698 };
699
700 Target {
701 kind,
702 name: name.to_string(),
703 required_features,
704 tested: false,
705 benched: false,
706 ..Target::with_path(src_path, edition)
707 }
708 }
709
710 pub fn test_target(
711 name: &str,
712 src_path: PathBuf,
713 required_features: Option<Vec<String>>,
714 edition: Edition,
715 ) -> Target {
716 Target {
717 kind: TargetKind::Test,
718 name: name.to_string(),
719 required_features,
720 benched: false,
721 ..Target::with_path(src_path, edition)
722 }
723 }
724
725 pub fn bench_target(
726 name: &str,
727 src_path: PathBuf,
728 required_features: Option<Vec<String>>,
729 edition: Edition,
730 ) -> Target {
731 Target {
732 kind: TargetKind::Bench,
733 name: name.to_string(),
734 required_features,
735 tested: false,
736 ..Target::with_path(src_path, edition)
737 }
738 }
739
740 pub fn name(&self) -> &str {
741 &self.name
742 }
743 pub fn crate_name(&self) -> String {
744 self.name.replace("-", "_")
745 }
746 pub fn src_path(&self) -> &TargetSourcePath {
747 &self.src_path
748 }
749 pub fn set_src_path(&mut self, src_path: TargetSourcePath) {
750 self.src_path = src_path;
751 }
752 pub fn required_features(&self) -> Option<&Vec<String>> {
753 self.required_features.as_ref()
754 }
755 pub fn kind(&self) -> &TargetKind {
756 &self.kind
757 }
758 pub fn kind_mut(&mut self) -> &mut TargetKind {
759 &mut self.kind
760 }
761 pub fn tested(&self) -> bool {
762 self.tested
763 }
764 pub fn harness(&self) -> bool {
765 self.harness
766 }
767 pub fn documented(&self) -> bool {
768 self.doc
769 }
770 // A plugin, proc-macro, or build-script.
771 pub fn for_host(&self) -> bool {
772 self.for_host
773 }
774 pub fn proc_macro(&self) -> bool {
775 self.proc_macro
776 }
777 pub fn edition(&self) -> Edition {
778 self.edition
779 }
780 pub fn benched(&self) -> bool {
781 self.benched
782 }
783 pub fn doctested(&self) -> bool {
784 self.doctest
785 }
786
787 pub fn doctestable(&self) -> bool {
788 match self.kind {
789 TargetKind::Lib(ref kinds) => kinds
790 .iter()
791 .any(|k| *k == LibKind::Rlib || *k == LibKind::Lib || *k == LibKind::ProcMacro),
792 _ => false,
793 }
794 }
795
796 pub fn allows_underscores(&self) -> bool {
797 self.is_bin() || self.is_example() || self.is_custom_build()
798 }
799
800 pub fn is_lib(&self) -> bool {
801 match self.kind {
802 TargetKind::Lib(_) => true,
803 _ => false,
804 }
805 }
806
807 pub fn is_dylib(&self) -> bool {
808 match self.kind {
809 TargetKind::Lib(ref libs) => libs.iter().any(|l| *l == LibKind::Dylib),
810 _ => false,
811 }
812 }
813
814 pub fn is_cdylib(&self) -> bool {
815 let libs = match self.kind {
816 TargetKind::Lib(ref libs) => libs,
817 _ => return false,
818 };
819 libs.iter().any(|l| match *l {
820 LibKind::Other(ref s) => s == "cdylib",
821 _ => false,
822 })
823 }
824
825 /// Returns whether this target produces an artifact which can be linked
826 /// into a Rust crate.
827 ///
828 /// This only returns true for certain kinds of libraries.
829 pub fn linkable(&self) -> bool {
830 match self.kind {
831 TargetKind::Lib(ref kinds) => kinds.iter().any(|k| k.linkable()),
832 _ => false,
833 }
834 }
835
836 pub fn is_bin(&self) -> bool {
837 self.kind == TargetKind::Bin
838 }
839
840 pub fn is_example(&self) -> bool {
841 match self.kind {
842 TargetKind::ExampleBin | TargetKind::ExampleLib(..) => true,
843 _ => false,
844 }
845 }
846
847 /// Returns `true` if it is a binary or executable example.
848 /// NOTE: Tests are `false`!
849 pub fn is_executable(&self) -> bool {
850 self.is_bin() || self.is_exe_example()
851 }
852
853 /// Returns `true` if it is an executable example.
854 pub fn is_exe_example(&self) -> bool {
855 // Needed for --all-examples in contexts where only runnable examples make sense
856 match self.kind {
857 TargetKind::ExampleBin => true,
858 _ => false,
859 }
860 }
861
862 pub fn is_test(&self) -> bool {
863 self.kind == TargetKind::Test
864 }
865 pub fn is_bench(&self) -> bool {
866 self.kind == TargetKind::Bench
867 }
868 pub fn is_custom_build(&self) -> bool {
869 self.kind == TargetKind::CustomBuild
870 }
871
872 /// Returns the arguments suitable for `--crate-type` to pass to rustc.
873 pub fn rustc_crate_types(&self) -> Vec<&str> {
874 match self.kind {
875 TargetKind::Lib(ref kinds) | TargetKind::ExampleLib(ref kinds) => {
876 kinds.iter().map(LibKind::crate_type).collect()
877 }
878 TargetKind::CustomBuild
879 | TargetKind::Bench
880 | TargetKind::Test
881 | TargetKind::ExampleBin
882 | TargetKind::Bin => vec!["bin"],
883 }
884 }
885
886 pub fn can_lto(&self) -> bool {
887 match self.kind {
888 TargetKind::Lib(ref v) => {
889 !v.contains(&LibKind::Rlib)
890 && !v.contains(&LibKind::Dylib)
891 && !v.contains(&LibKind::Lib)
892 }
893 _ => true,
894 }
895 }
896
897 pub fn set_tested(&mut self, tested: bool) -> &mut Target {
898 self.tested = tested;
899 self
900 }
901 pub fn set_benched(&mut self, benched: bool) -> &mut Target {
902 self.benched = benched;
903 self
904 }
905 pub fn set_doctest(&mut self, doctest: bool) -> &mut Target {
906 self.doctest = doctest;
907 self
908 }
909 pub fn set_for_host(&mut self, for_host: bool) -> &mut Target {
910 self.for_host = for_host;
911 self
912 }
913 pub fn set_proc_macro(&mut self, proc_macro: bool) -> &mut Target {
914 self.proc_macro = proc_macro;
915 self
916 }
917 pub fn set_edition(&mut self, edition: Edition) -> &mut Target {
918 self.edition = edition;
919 self
920 }
921 pub fn set_harness(&mut self, harness: bool) -> &mut Target {
922 self.harness = harness;
923 self
924 }
925 pub fn set_doc(&mut self, doc: bool) -> &mut Target {
926 self.doc = doc;
927 self
928 }
929
930 pub fn description_named(&self) -> String {
931 match self.kind {
932 TargetKind::Lib(..) => "lib".to_string(),
933 TargetKind::Bin => format!("bin \"{}\"", self.name()),
934 TargetKind::Test => format!("test \"{}\"", self.name()),
935 TargetKind::Bench => format!("bench \"{}\"", self.name()),
936 TargetKind::ExampleLib(..) | TargetKind::ExampleBin => {
937 format!("example \"{}\"", self.name())
938 }
939 TargetKind::CustomBuild => "custom-build".to_string(),
940 }
941 }
942 }
943
944 impl fmt::Display for Target {
945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946 match self.kind {
947 TargetKind::Lib(..) => write!(f, "Target(lib)"),
948 TargetKind::Bin => write!(f, "Target(bin: {})", self.name),
949 TargetKind::Test => write!(f, "Target(test: {})", self.name),
950 TargetKind::Bench => write!(f, "Target(bench: {})", self.name),
951 TargetKind::ExampleBin | TargetKind::ExampleLib(..) => {
952 write!(f, "Target(example: {})", self.name)
953 }
954 TargetKind::CustomBuild => write!(f, "Target(script)"),
955 }
956 }
957 }
958
959 impl Warnings {
960 fn new() -> Warnings {
961 Warnings(Vec::new())
962 }
963
964 pub fn add_warning(&mut self, s: String) {
965 self.0.push(DelayedWarning {
966 message: s,
967 is_critical: false,
968 })
969 }
970
971 pub fn add_critical_warning(&mut self, s: String) {
972 self.0.push(DelayedWarning {
973 message: s,
974 is_critical: true,
975 })
976 }
977
978 pub fn warnings(&self) -> &[DelayedWarning] {
979 &self.0
980 }
981 }