Skip to main content

cargo/core/
manifest.rs

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