Skip to main content

cargo/workspace/
manifest.rs

1use cargo_util::collections::HashMap;
2use std::borrow::Cow;
3use std::collections::BTreeMap;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6use std::path::{Path, PathBuf};
7use std::rc::Rc;
8use std::sync::Arc;
9
10use anyhow::Context as _;
11use cargo_util_schemas::core::CrateType;
12use cargo_util_schemas::manifest::RustVersion;
13use cargo_util_schemas::manifest::{Hints, TomlManifest, TomlProfiles};
14use semver::Version;
15use serde::Serialize;
16use serde::ser;
17use url::Url;
18
19use crate::compiler::CompileKind;
20use crate::compiler::CrateTypeExt as _;
21use crate::compiler::rustdoc::RustdocScrapeExamples;
22use crate::resolver::ResolveBehavior;
23use crate::util::errors::*;
24use crate::util::interning::InternedString;
25use crate::util::{Filesystem, GlobalContext, short_hash};
26use crate::workspace::{Dependency, PackageId, PackageIdSpec, Patch, SourceId, Summary};
27use crate::workspace::{Edition, Feature, Features, WorkspaceConfig};
28
29pub const MANIFEST_PREAMBLE: &str = "\
30# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
31#
32# When uploading crates to the registry Cargo will automatically
33# \"normalize\" Cargo.toml files for maximal compatibility
34# with all versions of Cargo and also rewrite `path` dependencies
35# to registry (e.g., crates.io) dependencies.
36#
37# If you are reading this file be aware that the original Cargo.toml
38# will likely look very different (and much more reasonable).
39# See Cargo.toml.orig for the original contents.
40";
41
42pub enum EitherManifest {
43    Real(Manifest),
44    Virtual(VirtualManifest),
45}
46
47impl EitherManifest {
48    pub fn warnings_mut(&mut self) -> &mut Warnings {
49        match self {
50            EitherManifest::Real(r) => r.warnings_mut(),
51            EitherManifest::Virtual(v) => v.warnings_mut(),
52        }
53    }
54    pub(crate) fn workspace_config(&self) -> &WorkspaceConfig {
55        match *self {
56            EitherManifest::Real(ref r) => r.workspace_config(),
57            EitherManifest::Virtual(ref v) => v.workspace_config(),
58        }
59    }
60}
61
62/// Contains all the information about a package, as loaded from a `Cargo.toml`.
63///
64/// This is deserialized using the [`TomlManifest`] type.
65#[derive(Clone, Debug)]
66pub struct Manifest {
67    // alternate forms of manifests:
68    contents: Option<Rc<String>>,
69    document: Option<Arc<toml::Spanned<toml::de::DeTable<'static>>>>,
70    original_toml: Option<Rc<TomlManifest>>,
71    normalized_toml: Rc<TomlManifest>,
72    summary: Summary,
73
74    // this form of manifest:
75    targets: Vec<Target>,
76    default_kind: Option<CompileKind>,
77    forced_kind: Option<CompileKind>,
78    links: Option<String>,
79    warnings: Warnings,
80    exclude: Vec<String>,
81    include: Vec<String>,
82    metadata: ManifestMetadata,
83    custom_metadata: Option<toml::Value>,
84    publish: Option<Vec<String>>,
85    replace: Vec<(PackageIdSpec, Dependency)>,
86    patch: HashMap<Url, Vec<Patch>>,
87    workspace: WorkspaceConfig,
88    unstable_features: Features,
89    edition: Edition,
90    rust_version: Option<RustVersion>,
91    im_a_teapot: Option<bool>,
92    default_run: Option<String>,
93    metabuild: Option<Vec<String>>,
94    resolve_behavior: Option<ResolveBehavior>,
95    lint_rustflags: Vec<String>,
96    hints: Option<Hints>,
97    embedded: bool,
98}
99
100/// When parsing `Cargo.toml`, some warnings should silenced
101/// if the manifest comes from a dependency. `ManifestWarning`
102/// allows this delayed emission of warnings.
103#[derive(Clone, Debug)]
104pub struct DelayedWarning {
105    pub message: String,
106    pub is_critical: bool,
107}
108
109#[derive(Clone, Debug)]
110pub struct Warnings(Vec<DelayedWarning>);
111
112#[derive(Clone, Debug)]
113pub struct VirtualManifest {
114    // alternate forms of manifests:
115    contents: Option<Rc<String>>,
116    document: Option<Rc<toml::Spanned<toml::de::DeTable<'static>>>>,
117    original_toml: Option<Rc<TomlManifest>>,
118    normalized_toml: Rc<TomlManifest>,
119
120    // this form of manifest:
121    replace: Vec<(PackageIdSpec, Dependency)>,
122    patch: HashMap<Url, Vec<Patch>>,
123    workspace: WorkspaceConfig,
124    warnings: Warnings,
125    features: Features,
126    resolve_behavior: Option<ResolveBehavior>,
127}
128
129/// General metadata about a package which is just blindly uploaded to the
130/// registry.
131///
132/// Note that many of these fields can contain invalid values such as the
133/// homepage, repository, documentation, or license. These fields are not
134/// validated by cargo itself, but rather it is up to the registry when uploaded
135/// to validate these fields. Cargo will itself accept any valid TOML
136/// specification for these values.
137#[derive(PartialEq, Clone, Debug)]
138pub struct ManifestMetadata {
139    pub authors: Vec<String>,
140    pub keywords: Vec<String>,
141    pub categories: Vec<String>,
142    pub license: Option<String>,
143    pub license_file: Option<String>,
144    pub description: Option<String>,   // Not in Markdown
145    pub readme: Option<String>,        // File, not contents
146    pub homepage: Option<String>,      // URL
147    pub repository: Option<String>,    // URL
148    pub documentation: Option<String>, // URL
149    pub badges: BTreeMap<String, BTreeMap<String, String>>,
150    pub links: Option<String>,
151    pub rust_version: Option<RustVersion>,
152}
153
154impl ManifestMetadata {
155    /// Whether the given env var should be tracked by Cargo's dep-info.
156    pub fn should_track(env_key: &str) -> bool {
157        let keys = MetadataEnvs::keys();
158        keys.contains(&env_key)
159    }
160
161    pub fn env_var<'a>(&'a self, env_key: &str) -> Option<Cow<'a, str>> {
162        MetadataEnvs::var(self, env_key)
163    }
164
165    pub fn env_vars(&self) -> impl Iterator<Item = (&'static str, Cow<'_, str>)> {
166        MetadataEnvs::keys()
167            .iter()
168            .map(|k| (*k, MetadataEnvs::var(self, k).unwrap()))
169    }
170}
171
172macro_rules! get_metadata_env {
173    ($meta:ident, $field:ident) => {
174        $meta.$field.as_deref().unwrap_or_default().into()
175    };
176    ($meta:ident, $field:ident, $to_var:expr) => {
177        $to_var($meta).into()
178    };
179}
180
181struct MetadataEnvs;
182
183macro_rules! metadata_envs {
184    (
185        $(
186            ($field:ident, $key:literal$(, $to_var:expr)?),
187        )*
188    ) => {
189        impl MetadataEnvs {
190            fn keys() -> &'static [&'static str] {
191                &[$($key),*]
192            }
193
194            fn var<'a>(meta: &'a ManifestMetadata, key: &str) -> Option<Cow<'a, str>> {
195                match key {
196                    $($key => Some(get_metadata_env!(meta, $field$(, $to_var)?)),)*
197                    _ => None,
198                }
199            }
200        }
201    }
202}
203
204// Metadata environmental variables that are emitted to rustc. Usable by `env!()`
205// If these change we need to trigger a rebuild.
206// NOTE: The env var name will be prefixed with `CARGO_PKG_`
207metadata_envs! {
208    (description, "CARGO_PKG_DESCRIPTION"),
209    (homepage, "CARGO_PKG_HOMEPAGE"),
210    (repository, "CARGO_PKG_REPOSITORY"),
211    (license, "CARGO_PKG_LICENSE"),
212    (license_file, "CARGO_PKG_LICENSE_FILE"),
213    (authors, "CARGO_PKG_AUTHORS", |m: &ManifestMetadata| m.authors.join(":")),
214    (rust_version, "CARGO_PKG_RUST_VERSION", |m: &ManifestMetadata| m.rust_version.as_ref().map(ToString::to_string).unwrap_or_default()),
215    (readme, "CARGO_PKG_README"),
216}
217
218#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
219pub enum TargetKind {
220    Lib(Vec<CrateType>),
221    Bin,
222    Test,
223    Bench,
224    ExampleLib(Vec<CrateType>),
225    ExampleBin,
226    CustomBuild,
227}
228
229impl ser::Serialize for TargetKind {
230    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
231    where
232        S: ser::Serializer,
233    {
234        use self::TargetKind::*;
235        match self {
236            Lib(kinds) => s.collect_seq(kinds.iter().map(|t| t.to_string())),
237            Bin => ["bin"].serialize(s),
238            ExampleBin | ExampleLib(_) => ["example"].serialize(s),
239            Test => ["test"].serialize(s),
240            CustomBuild => ["custom-build"].serialize(s),
241            Bench => ["bench"].serialize(s),
242        }
243    }
244}
245
246impl fmt::Debug for TargetKind {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        use self::TargetKind::*;
249        match *self {
250            Lib(ref kinds) => kinds.fmt(f),
251            Bin => "bin".fmt(f),
252            ExampleBin | ExampleLib(_) => "example".fmt(f),
253            Test => "test".fmt(f),
254            CustomBuild => "custom-build".fmt(f),
255            Bench => "bench".fmt(f),
256        }
257    }
258}
259
260impl TargetKind {
261    pub fn description(&self) -> &'static str {
262        match self {
263            TargetKind::Lib(..) => "lib",
264            TargetKind::Bin => "bin",
265            TargetKind::Test => "integration-test",
266            TargetKind::ExampleBin | TargetKind::ExampleLib(..) => "example",
267            TargetKind::Bench => "bench",
268            TargetKind::CustomBuild => "build-script",
269        }
270    }
271
272    /// Returns whether production of this artifact requires the object files
273    /// from dependencies to be available.
274    ///
275    /// This only returns `false` when all we're producing is an rlib, otherwise
276    /// it will return `true`.
277    pub fn requires_upstream_objects(&self) -> bool {
278        match self {
279            TargetKind::Lib(kinds) | TargetKind::ExampleLib(kinds) => {
280                kinds.iter().any(|k| k.requires_upstream_objects())
281            }
282            _ => true,
283        }
284    }
285
286    /// Returns whether production of this artifact could benefit from splitting metadata
287    /// into a .rmeta file.
288    pub fn benefits_from_no_embed_metadata(&self) -> bool {
289        match self {
290            TargetKind::Lib(kinds) | TargetKind::ExampleLib(kinds) => {
291                kinds.iter().any(|k| k.benefits_from_no_embed_metadata())
292            }
293            _ => false,
294        }
295    }
296
297    /// Returns the arguments suitable for `--crate-type` to pass to rustc.
298    pub fn rustc_crate_types(&self) -> Vec<CrateType> {
299        match self {
300            TargetKind::Lib(kinds) | TargetKind::ExampleLib(kinds) => kinds.clone(),
301            TargetKind::CustomBuild
302            | TargetKind::Bench
303            | TargetKind::Test
304            | TargetKind::ExampleBin
305            | TargetKind::Bin => vec![CrateType::Bin],
306        }
307    }
308}
309
310/// Information about a binary, a library, an example, etc. that is part of the
311/// package.
312#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
313pub struct Target {
314    inner: Arc<TargetInner>,
315}
316
317#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
318struct TargetInner {
319    kind: TargetKind,
320    name: String,
321    // Whether the name was inferred by Cargo, or explicitly given.
322    name_inferred: bool,
323    // Note that `bin_name` is used for the cargo-feature `different_binary_name`
324    bin_name: Option<String>,
325    // Note that the `src_path` here is excluded from the `Hash` implementation
326    // as it's absolute currently and is otherwise a little too brittle for
327    // causing rebuilds. Instead the hash for the path that we send to the
328    // compiler is handled elsewhere.
329    src_path: TargetSourcePath,
330    required_features: Option<Vec<String>>,
331    tested: bool,
332    benched: bool,
333    doc: bool,
334    doctest: bool,
335    harness: bool, // whether to use the test harness (--test)
336    for_host: bool,
337    proc_macro: bool,
338    edition: Edition,
339    doc_scrape_examples: RustdocScrapeExamples,
340}
341
342#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
343pub enum TargetSourcePath {
344    Path(PathBuf),
345    Metabuild,
346}
347
348impl TargetSourcePath {
349    pub fn path(&self) -> Option<&Path> {
350        match self {
351            TargetSourcePath::Path(path) => Some(path.as_ref()),
352            TargetSourcePath::Metabuild => None,
353        }
354    }
355
356    pub fn is_path(&self) -> bool {
357        matches!(self, TargetSourcePath::Path(_))
358    }
359}
360
361impl Hash for TargetSourcePath {
362    fn hash<H: Hasher>(&self, _: &mut H) {
363        // ...
364    }
365}
366
367impl fmt::Debug for TargetSourcePath {
368    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369        match self {
370            TargetSourcePath::Path(path) => path.fmt(f),
371            TargetSourcePath::Metabuild => "metabuild".fmt(f),
372        }
373    }
374}
375
376impl From<PathBuf> for TargetSourcePath {
377    fn from(path: PathBuf) -> Self {
378        assert!(path.is_absolute(), "`{}` is not absolute", path.display());
379        TargetSourcePath::Path(path)
380    }
381}
382
383#[derive(Serialize)]
384struct SerializedTarget<'a> {
385    /// Is this a `--bin bin`, `--lib`, `--example ex`?
386    /// Serialized as a list of strings for historical reasons.
387    kind: &'a TargetKind,
388    /// Corresponds to `--crate-type` compiler attribute.
389    /// See <https://doc.rust-lang.org/reference/linkage.html>
390    crate_types: Vec<CrateType>,
391    name: &'a str,
392    src_path: Option<&'a PathBuf>,
393    edition: &'a str,
394    #[serde(rename = "required-features", skip_serializing_if = "Option::is_none")]
395    required_features: Option<Vec<&'a str>>,
396    /// Whether docs should be built for the target via `cargo doc`
397    /// See <https://doc.rust-lang.org/cargo/commands/cargo-doc.html#target-selection>
398    doc: bool,
399    doctest: bool,
400    /// Whether tests should be run for the target (`test` field in `Cargo.toml`)
401    test: bool,
402}
403
404impl ser::Serialize for Target {
405    fn serialize<S: ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
406        let src_path = match self.src_path() {
407            TargetSourcePath::Path(p) => Some(p),
408            // Unfortunately getting the correct path would require access to
409            // target_dir, which is not available here.
410            TargetSourcePath::Metabuild => None,
411        };
412        SerializedTarget {
413            kind: self.kind(),
414            crate_types: self.rustc_crate_types(),
415            name: self.name(),
416            src_path,
417            edition: &self.edition().to_string(),
418            required_features: self
419                .required_features()
420                .map(|rf| rf.iter().map(|s| s.as_str()).collect()),
421            doc: self.documented(),
422            doctest: self.doctested() && self.doctestable(),
423            test: self.tested(),
424        }
425        .serialize(s)
426    }
427}
428
429impl fmt::Debug for Target {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        self.inner.fmt(f)
432    }
433}
434
435compact_debug! {
436    impl fmt::Debug for TargetInner {
437        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438            let (default, default_name) = {
439                match &self.kind {
440                    TargetKind::Lib(kinds) => {
441                        (
442                            Target::lib_target(
443                                &self.name,
444                                kinds.clone(),
445                                self.src_path.path().unwrap().to_path_buf(),
446                                self.edition,
447                            ).inner,
448                            format!("lib_target({:?}, {:?}, {:?}, {:?})",
449                                    self.name, kinds, self.src_path, self.edition),
450                        )
451                    }
452                    TargetKind::CustomBuild => {
453                        match self.src_path {
454                            TargetSourcePath::Path(ref path) => {
455                                (
456                                    Target::custom_build_target(
457                                        &self.name,
458                                        path.to_path_buf(),
459                                        self.edition,
460                                    ).inner,
461                                    format!("custom_build_target({:?}, {:?}, {:?})",
462                                            self.name, path, self.edition),
463                                )
464                            }
465                            TargetSourcePath::Metabuild => {
466                                (
467                                    Target::metabuild_target(&self.name).inner,
468                                    format!("metabuild_target({:?})", self.name),
469                                )
470                            }
471                        }
472                    }
473                    _ => (
474                        Target::new(self.src_path.clone(), self.edition).inner,
475                        format!("with_path({:?}, {:?})", self.src_path, self.edition),
476                    ),
477                }
478            };
479            [debug_the_fields(
480                kind
481                name
482                name_inferred
483                bin_name
484                src_path
485                required_features
486                tested
487                benched
488                doc
489                doctest
490                harness
491                for_host
492                proc_macro
493                edition
494                doc_scrape_examples
495            )]
496        }
497    }
498}
499
500impl Manifest {
501    pub fn new(
502        contents: Option<Rc<String>>,
503        document: Option<Arc<toml::Spanned<toml::de::DeTable<'static>>>>,
504        original_toml: Option<Rc<TomlManifest>>,
505        normalized_toml: Rc<TomlManifest>,
506        summary: Summary,
507
508        default_kind: Option<CompileKind>,
509        forced_kind: Option<CompileKind>,
510        targets: Vec<Target>,
511        exclude: Vec<String>,
512        include: Vec<String>,
513        links: Option<String>,
514        metadata: ManifestMetadata,
515        custom_metadata: Option<toml::Value>,
516        publish: Option<Vec<String>>,
517        replace: Vec<(PackageIdSpec, Dependency)>,
518        patch: HashMap<Url, Vec<Patch>>,
519        workspace: WorkspaceConfig,
520        unstable_features: Features,
521        edition: Edition,
522        rust_version: Option<RustVersion>,
523        im_a_teapot: Option<bool>,
524        default_run: Option<String>,
525        metabuild: Option<Vec<String>>,
526        resolve_behavior: Option<ResolveBehavior>,
527        lint_rustflags: Vec<String>,
528        hints: Option<Hints>,
529        embedded: bool,
530    ) -> Manifest {
531        Manifest {
532            contents,
533            document,
534            original_toml,
535            normalized_toml,
536            summary,
537
538            default_kind,
539            forced_kind,
540            targets,
541            warnings: Warnings::new(),
542            exclude,
543            include,
544            links,
545            metadata,
546            custom_metadata,
547            publish,
548            replace,
549            patch,
550            workspace,
551            unstable_features,
552            edition,
553            rust_version,
554            im_a_teapot,
555            default_run,
556            metabuild,
557            resolve_behavior,
558            lint_rustflags,
559            hints,
560            embedded,
561        }
562    }
563
564    /// The raw contents of the original TOML
565    pub fn contents(&self) -> Option<&str> {
566        self.contents.as_deref().map(|c| c.as_str())
567    }
568    /// See [`Manifest::normalized_toml`] for what "normalized" means
569    pub fn to_normalized_contents(&self) -> CargoResult<String> {
570        let toml = toml::to_string_pretty(self.normalized_toml())?;
571        Ok(format!("{}\n{}", MANIFEST_PREAMBLE, toml))
572    }
573    /// Collection of spans for the original TOML
574    pub fn document(&self) -> Option<&toml::Spanned<toml::de::DeTable<'static>>> {
575        self.document.as_deref()
576    }
577
578    /// Collection of spans for the original TOML, returned as a cloned Arc.
579    pub fn document_rc(&self) -> Option<Arc<toml::Spanned<toml::de::DeTable<'static>>>> {
580        self.document.clone()
581    }
582
583    /// The [`TomlManifest`] as parsed from [`Manifest::document`]
584    pub fn original_toml(&self) -> Option<&TomlManifest> {
585        self.original_toml.as_deref()
586    }
587    /// The [`TomlManifest`] with all fields expanded
588    ///
589    /// This is the intersection of what fields need resolving for cargo-publish that also are
590    /// useful for the operation of cargo, including
591    /// - workspace inheritance
592    /// - target discovery
593    pub fn normalized_toml(&self) -> &TomlManifest {
594        &self.normalized_toml
595    }
596    pub fn summary(&self) -> &Summary {
597        &self.summary
598    }
599    pub fn summary_mut(&mut self) -> &mut Summary {
600        &mut self.summary
601    }
602
603    pub fn dependencies(&self) -> &[Dependency] {
604        self.summary.dependencies()
605    }
606    pub fn default_kind(&self) -> Option<CompileKind> {
607        self.default_kind
608    }
609    pub fn forced_kind(&self) -> Option<CompileKind> {
610        self.forced_kind
611    }
612    pub fn exclude(&self) -> &[String] {
613        &self.exclude
614    }
615    pub fn include(&self) -> &[String] {
616        &self.include
617    }
618    pub fn metadata(&self) -> &ManifestMetadata {
619        &self.metadata
620    }
621    pub fn name(&self) -> InternedString {
622        self.package_id().name()
623    }
624    pub fn package_id(&self) -> PackageId {
625        self.summary.package_id()
626    }
627    pub fn targets(&self) -> &[Target] {
628        &self.targets
629    }
630    // It is used by cargo-c, please do not remove it
631    pub fn targets_mut(&mut self) -> &mut [Target] {
632        &mut self.targets
633    }
634    pub fn version(&self) -> &Version {
635        self.package_id().version()
636    }
637    pub fn warnings_mut(&mut self) -> &mut Warnings {
638        &mut self.warnings
639    }
640    pub fn warnings(&self) -> &Warnings {
641        &self.warnings
642    }
643    pub fn profiles(&self) -> Option<&TomlProfiles> {
644        self.normalized_toml.profile.as_ref()
645    }
646    pub fn publish(&self) -> &Option<Vec<String>> {
647        &self.publish
648    }
649    pub fn replace(&self) -> &[(PackageIdSpec, Dependency)] {
650        &self.replace
651    }
652    pub fn patch(&self) -> &HashMap<Url, Vec<Patch>> {
653        &self.patch
654    }
655    pub fn links(&self) -> Option<&str> {
656        self.links.as_deref()
657    }
658    pub fn is_embedded(&self) -> bool {
659        self.embedded
660    }
661
662    pub fn workspace_config(&self) -> &WorkspaceConfig {
663        &self.workspace
664    }
665
666    /// Unstable, nightly features that are enabled in this manifest.
667    pub fn unstable_features(&self) -> &Features {
668        &self.unstable_features
669    }
670
671    /// The style of resolver behavior to use, declared with the `resolver` field.
672    ///
673    /// Returns `None` if it is not specified.
674    pub fn resolve_behavior(&self) -> Option<ResolveBehavior> {
675        self.resolve_behavior
676    }
677
678    /// `RUSTFLAGS` from the `[lints]` table
679    pub fn lint_rustflags(&self) -> &[String] {
680        self.lint_rustflags.as_slice()
681    }
682
683    pub fn hints(&self) -> Option<&Hints> {
684        self.hints.as_ref()
685    }
686
687    pub fn map_source(self, to_replace: SourceId, replace_with: SourceId) -> Manifest {
688        Manifest {
689            summary: self.summary.map_source(to_replace, replace_with),
690            ..self
691        }
692    }
693
694    pub fn feature_gate(&self) -> CargoResult<()> {
695        if self.im_a_teapot.is_some() {
696            self.unstable_features
697                .require(Feature::test_dummy_unstable())
698                .with_context(|| {
699                    "the `im-a-teapot` manifest key is unstable and may \
700                     not work properly in England"
701                })?;
702        }
703
704        if self.default_kind.is_some() || self.forced_kind.is_some() {
705            self.unstable_features
706                .require(Feature::per_package_target())
707                .with_context(|| {
708                    "the `package.default-target` and `package.forced-target` \
709                     manifest keys are unstable and may not work properly"
710                })?;
711        }
712
713        Ok(())
714    }
715
716    // Just a helper function to test out `-Z` flags on Cargo
717    pub fn print_teapot(&self, gctx: &GlobalContext) {
718        if let Some(teapot) = self.im_a_teapot {
719            if gctx.cli_unstable().print_im_a_teapot {
720                crate::drop_println!(gctx, "im-a-teapot = {}", teapot);
721            }
722        }
723    }
724
725    pub fn edition(&self) -> Edition {
726        self.edition
727    }
728
729    pub fn rust_version(&self) -> Option<&RustVersion> {
730        self.rust_version.as_ref()
731    }
732
733    pub fn custom_metadata(&self) -> Option<&toml::Value> {
734        self.custom_metadata.as_ref()
735    }
736
737    pub fn default_run(&self) -> Option<&str> {
738        self.default_run.as_deref()
739    }
740
741    pub fn metabuild(&self) -> Option<&Vec<String>> {
742        self.metabuild.as_ref()
743    }
744
745    pub fn metabuild_path(&self, target_dir: Filesystem) -> PathBuf {
746        let hash = short_hash(&self.package_id());
747        target_dir
748            .into_path_unlocked()
749            .join(".metabuild")
750            .join(format!("metabuild-{}-{}.rs", self.name(), hash))
751    }
752}
753
754impl VirtualManifest {
755    pub fn new(
756        contents: Option<Rc<String>>,
757        document: Option<Rc<toml::Spanned<toml::de::DeTable<'static>>>>,
758        original_toml: Option<Rc<TomlManifest>>,
759        normalized_toml: Rc<TomlManifest>,
760        replace: Vec<(PackageIdSpec, Dependency)>,
761        patch: HashMap<Url, Vec<Patch>>,
762        workspace: WorkspaceConfig,
763        features: Features,
764        resolve_behavior: Option<ResolveBehavior>,
765    ) -> VirtualManifest {
766        VirtualManifest {
767            contents,
768            document,
769            original_toml,
770            normalized_toml,
771            replace,
772            patch,
773            workspace,
774            warnings: Warnings::new(),
775            features,
776            resolve_behavior,
777        }
778    }
779
780    /// The raw contents of the original TOML
781    pub fn contents(&self) -> Option<&str> {
782        self.contents.as_deref().map(|c| c.as_str())
783    }
784    /// Collection of spans for the original TOML
785    pub fn document(&self) -> Option<&toml::Spanned<toml::de::DeTable<'static>>> {
786        self.document.as_deref()
787    }
788    /// The [`TomlManifest`] as parsed from [`VirtualManifest::document`]
789    pub fn original_toml(&self) -> Option<&TomlManifest> {
790        self.original_toml.as_deref()
791    }
792    /// The [`TomlManifest`] with all fields expanded
793    pub fn normalized_toml(&self) -> &TomlManifest {
794        &self.normalized_toml
795    }
796
797    pub fn replace(&self) -> &[(PackageIdSpec, Dependency)] {
798        &self.replace
799    }
800
801    pub fn patch(&self) -> &HashMap<Url, Vec<Patch>> {
802        &self.patch
803    }
804
805    pub fn workspace_config(&self) -> &WorkspaceConfig {
806        &self.workspace
807    }
808
809    pub fn profiles(&self) -> Option<&TomlProfiles> {
810        self.normalized_toml.profile.as_ref()
811    }
812
813    pub fn warnings_mut(&mut self) -> &mut Warnings {
814        &mut self.warnings
815    }
816
817    pub fn warnings(&self) -> &Warnings {
818        &self.warnings
819    }
820
821    pub fn unstable_features(&self) -> &Features {
822        &self.features
823    }
824
825    /// The style of resolver behavior to use, declared with the `resolver` field.
826    ///
827    /// Returns `None` if it is not specified.
828    pub fn resolve_behavior(&self) -> Option<ResolveBehavior> {
829        self.resolve_behavior
830    }
831}
832
833impl Target {
834    fn new(src_path: TargetSourcePath, edition: Edition) -> Target {
835        Target {
836            inner: Arc::new(TargetInner {
837                kind: TargetKind::Bin,
838                name: String::new(),
839                name_inferred: false,
840                bin_name: None,
841                src_path,
842                required_features: None,
843                doc: false,
844                doctest: false,
845                harness: true,
846                for_host: false,
847                proc_macro: false,
848                doc_scrape_examples: RustdocScrapeExamples::Unset,
849                edition,
850                tested: true,
851                benched: true,
852            }),
853        }
854    }
855
856    fn with_path(src_path: PathBuf, edition: Edition) -> Target {
857        Target::new(TargetSourcePath::from(src_path), edition)
858    }
859
860    pub fn lib_target(
861        name: &str,
862        crate_targets: Vec<CrateType>,
863        src_path: PathBuf,
864        edition: Edition,
865    ) -> Target {
866        let mut target = Target::with_path(src_path, edition);
867        target
868            .set_kind(TargetKind::Lib(crate_targets))
869            .set_name(name)
870            .set_doctest(true)
871            .set_doc(true);
872        target
873    }
874
875    pub fn bin_target(
876        name: &str,
877        bin_name: Option<String>,
878        src_path: PathBuf,
879        required_features: Option<Vec<String>>,
880        edition: Edition,
881    ) -> Target {
882        let mut target = Target::with_path(src_path, edition);
883        target
884            .set_kind(TargetKind::Bin)
885            .set_name(name)
886            .set_binary_name(bin_name)
887            .set_required_features(required_features)
888            .set_doc(true);
889        target
890    }
891
892    /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
893    pub fn custom_build_target(name: &str, src_path: PathBuf, edition: Edition) -> Target {
894        let mut target = Target::with_path(src_path, edition);
895        target
896            .set_kind(TargetKind::CustomBuild)
897            .set_name(name)
898            .set_for_host(true)
899            .set_benched(false)
900            .set_tested(false)
901            .set_doc_scrape_examples(RustdocScrapeExamples::Disabled);
902        target
903    }
904
905    pub fn metabuild_target(name: &str) -> Target {
906        let mut target = Target::new(TargetSourcePath::Metabuild, Edition::Edition2018);
907        target
908            .set_kind(TargetKind::CustomBuild)
909            .set_name(name)
910            .set_for_host(true)
911            .set_benched(false)
912            .set_tested(false)
913            .set_doc_scrape_examples(RustdocScrapeExamples::Disabled);
914        target
915    }
916
917    pub fn example_target(
918        name: &str,
919        crate_targets: Vec<CrateType>,
920        src_path: PathBuf,
921        required_features: Option<Vec<String>>,
922        edition: Edition,
923    ) -> Target {
924        let kind = if crate_targets.is_empty() || crate_targets.iter().all(|t| *t == CrateType::Bin)
925        {
926            TargetKind::ExampleBin
927        } else {
928            TargetKind::ExampleLib(crate_targets)
929        };
930        let mut target = Target::with_path(src_path, edition);
931        target
932            .set_kind(kind)
933            .set_name(name)
934            .set_required_features(required_features)
935            .set_tested(false)
936            .set_benched(false);
937        target
938    }
939
940    pub fn test_target(
941        name: &str,
942        src_path: PathBuf,
943        required_features: Option<Vec<String>>,
944        edition: Edition,
945    ) -> Target {
946        let mut target = Target::with_path(src_path, edition);
947        target
948            .set_kind(TargetKind::Test)
949            .set_name(name)
950            .set_required_features(required_features)
951            .set_benched(false);
952        target
953    }
954
955    pub fn bench_target(
956        name: &str,
957        src_path: PathBuf,
958        required_features: Option<Vec<String>>,
959        edition: Edition,
960    ) -> Target {
961        let mut target = Target::with_path(src_path, edition);
962        target
963            .set_kind(TargetKind::Bench)
964            .set_name(name)
965            .set_required_features(required_features)
966            .set_tested(false);
967        target
968    }
969
970    pub fn name(&self) -> &str {
971        &self.inner.name
972    }
973    pub fn name_inferred(&self) -> bool {
974        self.inner.name_inferred
975    }
976    pub fn crate_name(&self) -> String {
977        self.name().replace("-", "_")
978    }
979    pub fn src_path(&self) -> &TargetSourcePath {
980        &self.inner.src_path
981    }
982    pub fn set_src_path(&mut self, src_path: TargetSourcePath) {
983        Arc::make_mut(&mut self.inner).src_path = src_path;
984    }
985    pub fn required_features(&self) -> Option<&Vec<String>> {
986        self.inner.required_features.as_ref()
987    }
988    pub fn kind(&self) -> &TargetKind {
989        &self.inner.kind
990    }
991    pub fn tested(&self) -> bool {
992        self.inner.tested
993    }
994    pub fn harness(&self) -> bool {
995        self.inner.harness
996    }
997    pub fn documented(&self) -> bool {
998        self.inner.doc
999    }
1000    // A proc-macro or build-script.
1001    pub fn for_host(&self) -> bool {
1002        self.inner.for_host
1003    }
1004    pub fn proc_macro(&self) -> bool {
1005        self.inner.proc_macro
1006    }
1007    pub fn edition(&self) -> Edition {
1008        self.inner.edition
1009    }
1010    pub fn doc_scrape_examples(&self) -> RustdocScrapeExamples {
1011        self.inner.doc_scrape_examples
1012    }
1013    pub fn benched(&self) -> bool {
1014        self.inner.benched
1015    }
1016    pub fn doctested(&self) -> bool {
1017        self.inner.doctest
1018    }
1019
1020    pub fn doctestable(&self) -> bool {
1021        match self.kind() {
1022            TargetKind::Lib(kinds) => kinds.iter().any(|k| {
1023                *k == CrateType::Rlib || *k == CrateType::Lib || *k == CrateType::ProcMacro
1024            }),
1025            _ => false,
1026        }
1027    }
1028
1029    pub fn is_lib(&self) -> bool {
1030        matches!(self.kind(), TargetKind::Lib(_))
1031    }
1032
1033    pub fn is_dylib(&self) -> bool {
1034        match self.kind() {
1035            TargetKind::Lib(libs) => libs.contains(&CrateType::Dylib),
1036            _ => false,
1037        }
1038    }
1039
1040    pub fn is_cdylib(&self) -> bool {
1041        match self.kind() {
1042            TargetKind::Lib(libs) => libs.contains(&CrateType::Cdylib),
1043            _ => false,
1044        }
1045    }
1046
1047    pub fn is_staticlib(&self) -> bool {
1048        match self.kind() {
1049            TargetKind::Lib(libs) => libs.contains(&CrateType::Staticlib),
1050            _ => false,
1051        }
1052    }
1053
1054    /// Returns whether this target produces an artifact which can be linked
1055    /// into a Rust crate.
1056    ///
1057    /// This only returns true for certain kinds of libraries.
1058    pub fn is_linkable(&self) -> bool {
1059        match self.kind() {
1060            TargetKind::Lib(kinds) => kinds.iter().any(|k| k.is_linkable()),
1061            _ => false,
1062        }
1063    }
1064
1065    pub fn is_bin(&self) -> bool {
1066        *self.kind() == TargetKind::Bin
1067    }
1068
1069    pub fn is_example(&self) -> bool {
1070        matches!(
1071            self.kind(),
1072            TargetKind::ExampleBin | TargetKind::ExampleLib(..)
1073        )
1074    }
1075
1076    /// Returns `true` if it is a binary or executable example.
1077    /// NOTE: Tests are `false`!
1078    pub fn is_executable(&self) -> bool {
1079        self.is_bin() || self.is_exe_example()
1080    }
1081
1082    /// Returns `true` if it is an executable example.
1083    pub fn is_exe_example(&self) -> bool {
1084        // Needed for --all-examples in contexts where only runnable examples make sense
1085        matches!(self.kind(), TargetKind::ExampleBin)
1086    }
1087
1088    pub fn is_test(&self) -> bool {
1089        *self.kind() == TargetKind::Test
1090    }
1091    pub fn is_bench(&self) -> bool {
1092        *self.kind() == TargetKind::Bench
1093    }
1094    pub fn is_custom_build(&self) -> bool {
1095        *self.kind() == TargetKind::CustomBuild
1096    }
1097
1098    /// Returns `true` if it is a compile time dependencies, e.g., build script or proc macro
1099    pub fn is_compile_time_dependency(&self) -> bool {
1100        self.is_custom_build() || self.proc_macro()
1101    }
1102
1103    /// Returns the arguments suitable for `--crate-type` to pass to rustc.
1104    pub fn rustc_crate_types(&self) -> Vec<CrateType> {
1105        self.kind().rustc_crate_types()
1106    }
1107
1108    pub fn set_tested(&mut self, tested: bool) -> &mut Target {
1109        Arc::make_mut(&mut self.inner).tested = tested;
1110        self
1111    }
1112    pub fn set_benched(&mut self, benched: bool) -> &mut Target {
1113        Arc::make_mut(&mut self.inner).benched = benched;
1114        self
1115    }
1116    pub fn set_doctest(&mut self, doctest: bool) -> &mut Target {
1117        Arc::make_mut(&mut self.inner).doctest = doctest;
1118        self
1119    }
1120    pub fn set_for_host(&mut self, for_host: bool) -> &mut Target {
1121        Arc::make_mut(&mut self.inner).for_host = for_host;
1122        self
1123    }
1124    pub fn set_proc_macro(&mut self, proc_macro: bool) -> &mut Target {
1125        Arc::make_mut(&mut self.inner).proc_macro = proc_macro;
1126        self
1127    }
1128    pub fn set_edition(&mut self, edition: Edition) -> &mut Target {
1129        Arc::make_mut(&mut self.inner).edition = edition;
1130        self
1131    }
1132    pub fn set_doc_scrape_examples(
1133        &mut self,
1134        doc_scrape_examples: RustdocScrapeExamples,
1135    ) -> &mut Target {
1136        Arc::make_mut(&mut self.inner).doc_scrape_examples = doc_scrape_examples;
1137        self
1138    }
1139    pub fn set_harness(&mut self, harness: bool) -> &mut Target {
1140        Arc::make_mut(&mut self.inner).harness = harness;
1141        self
1142    }
1143    pub fn set_doc(&mut self, doc: bool) -> &mut Target {
1144        Arc::make_mut(&mut self.inner).doc = doc;
1145        self
1146    }
1147    pub fn set_kind(&mut self, kind: TargetKind) -> &mut Target {
1148        Arc::make_mut(&mut self.inner).kind = kind;
1149        self
1150    }
1151    pub fn set_name(&mut self, name: &str) -> &mut Target {
1152        Arc::make_mut(&mut self.inner).name = name.to_string();
1153        self
1154    }
1155    pub fn set_name_inferred(&mut self, inferred: bool) -> &mut Target {
1156        Arc::make_mut(&mut self.inner).name_inferred = inferred;
1157        self
1158    }
1159    pub fn set_binary_name(&mut self, bin_name: Option<String>) -> &mut Target {
1160        Arc::make_mut(&mut self.inner).bin_name = bin_name;
1161        self
1162    }
1163    pub fn set_required_features(&mut self, required_features: Option<Vec<String>>) -> &mut Target {
1164        Arc::make_mut(&mut self.inner).required_features = required_features;
1165        self
1166    }
1167    pub fn binary_filename(&self) -> Option<String> {
1168        self.inner.bin_name.clone()
1169    }
1170    pub fn description_named(&self) -> String {
1171        match self.kind() {
1172            TargetKind::Lib(..) => "lib".to_string(),
1173            TargetKind::Bin => format!("bin \"{}\"", self.name()),
1174            TargetKind::Test => format!("test \"{}\"", self.name()),
1175            TargetKind::Bench => format!("bench \"{}\"", self.name()),
1176            TargetKind::ExampleLib(..) | TargetKind::ExampleBin => {
1177                format!("example \"{}\"", self.name())
1178            }
1179            TargetKind::CustomBuild => "build script".to_string(),
1180        }
1181    }
1182}
1183
1184impl fmt::Display for Target {
1185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1186        match self.kind() {
1187            TargetKind::Lib(..) => write!(f, "Target(lib)"),
1188            TargetKind::Bin => write!(f, "Target(bin: {})", self.name()),
1189            TargetKind::Test => write!(f, "Target(test: {})", self.name()),
1190            TargetKind::Bench => write!(f, "Target(bench: {})", self.name()),
1191            TargetKind::ExampleBin | TargetKind::ExampleLib(..) => {
1192                write!(f, "Target(example: {})", self.name())
1193            }
1194            TargetKind::CustomBuild => write!(f, "Target(script)"),
1195        }
1196    }
1197}
1198
1199impl Warnings {
1200    fn new() -> Warnings {
1201        Warnings(Vec::new())
1202    }
1203
1204    pub fn add_warning(&mut self, s: String) {
1205        self.0.push(DelayedWarning {
1206            message: s,
1207            is_critical: false,
1208        })
1209    }
1210
1211    pub fn add_critical_warning(&mut self, s: String) {
1212        self.0.push(DelayedWarning {
1213            message: s,
1214            is_critical: true,
1215        })
1216    }
1217
1218    pub fn warnings(&self) -> &[DelayedWarning] {
1219        &self.0
1220    }
1221}