Skip to main content

cargo_util_schemas/manifest/
mod.rs

1//! `Cargo.toml` / Manifest schema definition
2//!
3//! ## Style
4//!
5//! - Fields duplicated for an alias will have an accessor with the primary field's name
6//! - Keys that exist for bookkeeping but don't correspond to the schema have a `_` prefix
7
8use std::collections::BTreeMap;
9use std::collections::BTreeSet;
10use std::fmt::{self, Display, Write};
11use std::path::PathBuf;
12use std::str;
13
14use serde::de::{self, IntoDeserializer as _, Unexpected};
15use serde::ser;
16use serde::{Deserialize, Serialize};
17use serde_untagged::UntaggedEnumVisitor;
18
19use crate::core::PackageIdSpec;
20use crate::restricted_names;
21
22mod rust_version;
23
24pub use crate::restricted_names::NameValidationError;
25pub use rust_version::RustVersion;
26pub use rust_version::RustVersionError;
27
28#[cfg(feature = "unstable-schema")]
29use crate::schema::TomlValueWrapper;
30
31/// This type is used to deserialize `Cargo.toml` files.
32#[derive(Default, Clone, Debug, Deserialize, Serialize)]
33#[serde(rename_all = "kebab-case")]
34#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
35pub struct TomlManifest {
36    pub cargo_features: Option<Vec<String>>,
37
38    // Update `requires_package` when adding new package-specific fields
39    pub package: Option<Box<TomlPackage>>,
40    pub project: Option<Box<TomlPackage>>,
41    pub badges: Option<BTreeMap<String, BTreeMap<String, String>>>,
42    pub features: Option<BTreeMap<FeatureName, FeatureDefinition>>,
43    pub lib: Option<TomlLibTarget>,
44    pub bin: Option<Vec<TomlBinTarget>>,
45    pub example: Option<Vec<TomlExampleTarget>>,
46    pub test: Option<Vec<TomlTestTarget>>,
47    pub bench: Option<Vec<TomlTestTarget>>,
48    pub dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
49    pub dev_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
50    #[serde(rename = "dev_dependencies")]
51    pub dev_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
52    pub build_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
53    #[serde(rename = "build_dependencies")]
54    pub build_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
55    pub target: Option<BTreeMap<String, TomlPlatform>>,
56    pub lints: Option<InheritableLints>,
57    pub hints: Option<Hints>,
58
59    pub workspace: Option<TomlWorkspace>,
60    pub profile: Option<TomlProfiles>,
61    pub patch: Option<BTreeMap<String, BTreeMap<PackageName, TomlDependency>>>,
62    pub replace: Option<BTreeMap<String, TomlDependency>>,
63
64    /// Report unused keys (see also nested `_unused_keys`)
65    /// Note: this is populated by the caller, rather than automatically
66    #[serde(skip)]
67    pub _unused_keys: BTreeSet<String>,
68}
69
70impl TomlManifest {
71    pub fn requires_package(&self) -> impl Iterator<Item = &'static str> {
72        [
73            self.badges.as_ref().map(|_| "badges"),
74            self.features.as_ref().map(|_| "features"),
75            self.lib.as_ref().map(|_| "lib"),
76            self.bin.as_ref().map(|_| "bin"),
77            self.example.as_ref().map(|_| "example"),
78            self.test.as_ref().map(|_| "test"),
79            self.bench.as_ref().map(|_| "bench"),
80            self.dependencies.as_ref().map(|_| "dependencies"),
81            self.dev_dependencies().as_ref().map(|_| "dev-dependencies"),
82            self.build_dependencies()
83                .as_ref()
84                .map(|_| "build-dependencies"),
85            self.target.as_ref().map(|_| "target"),
86            self.lints.as_ref().map(|_| "lints"),
87            self.hints.as_ref().map(|_| "hints"),
88        ]
89        .into_iter()
90        .flatten()
91    }
92
93    pub fn has_profiles(&self) -> bool {
94        self.profile.is_some()
95    }
96
97    pub fn package(&self) -> Option<&Box<TomlPackage>> {
98        self.package.as_ref().or(self.project.as_ref())
99    }
100
101    pub fn dev_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
102        self.dev_dependencies
103            .as_ref()
104            .or(self.dev_dependencies2.as_ref())
105    }
106
107    pub fn build_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
108        self.build_dependencies
109            .as_ref()
110            .or(self.build_dependencies2.as_ref())
111    }
112
113    pub fn features(&self) -> Option<&BTreeMap<FeatureName, FeatureDefinition>> {
114        self.features.as_ref()
115    }
116
117    pub fn normalized_lints(&self) -> Result<Option<&TomlLints>, UnresolvedError> {
118        self.lints.as_ref().map(|l| l.normalized()).transpose()
119    }
120}
121
122#[derive(Debug, Default, Deserialize, Serialize, Clone)]
123#[serde(rename_all = "kebab-case")]
124#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
125pub struct TomlWorkspace {
126    pub members: Option<Vec<String>>,
127    pub exclude: Option<Vec<String>>,
128    pub default_members: Option<Vec<String>>,
129    pub resolver: Option<String>,
130
131    #[cfg_attr(
132        feature = "unstable-schema",
133        schemars(with = "Option<TomlValueWrapper>")
134    )]
135    pub metadata: Option<toml::Value>,
136
137    // Properties that can be inherited by members.
138    pub package: Option<InheritablePackage>,
139    pub dependencies: Option<BTreeMap<PackageName, TomlDependency>>,
140    pub lints: Option<TomlLints>,
141}
142
143/// A group of fields that are inheritable by members of the workspace
144#[derive(Clone, Debug, Default, Deserialize, Serialize)]
145#[serde(rename_all = "kebab-case")]
146#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
147pub struct InheritablePackage {
148    pub version: Option<semver::Version>,
149    pub authors: Option<Vec<String>>,
150    pub description: Option<String>,
151    pub homepage: Option<String>,
152    pub documentation: Option<String>,
153    pub readme: Option<StringOrBool>,
154    pub keywords: Option<Vec<String>>,
155    pub categories: Option<Vec<String>>,
156    pub license: Option<String>,
157    pub license_file: Option<String>,
158    pub repository: Option<String>,
159    pub publish: Option<VecStringOrBool>,
160    pub edition: Option<String>,
161    pub badges: Option<BTreeMap<String, BTreeMap<String, String>>>,
162    pub exclude: Option<Vec<String>>,
163    pub include: Option<Vec<String>>,
164    pub rust_version: Option<RustVersion>,
165}
166
167/// Represents the `package`/`project` sections of a `Cargo.toml`.
168///
169/// Note that the order of the fields matters, since this is the order they
170/// are serialized to a TOML file. For example, you cannot have values after
171/// the field `metadata`, since it is a table and values cannot appear after
172/// tables.
173#[derive(Deserialize, Serialize, Clone, Debug, Default)]
174#[serde(rename_all = "kebab-case")]
175#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
176pub struct TomlPackage {
177    pub edition: Option<InheritableString>,
178    pub rust_version: Option<InheritableRustVersion>,
179    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
180    pub name: Option<PackageName>,
181    pub version: Option<InheritableSemverVersion>,
182    pub authors: Option<InheritableVecString>,
183    pub build: Option<TomlPackageBuild>,
184    pub metabuild: Option<StringOrVec>,
185    pub default_target: Option<String>,
186    pub forced_target: Option<String>,
187    pub links: Option<String>,
188    pub exclude: Option<InheritableVecString>,
189    pub include: Option<InheritableVecString>,
190    pub publish: Option<InheritableVecStringOrBool>,
191    pub workspace: Option<String>,
192    pub im_a_teapot: Option<bool>,
193    pub autolib: Option<bool>,
194    pub autobins: Option<bool>,
195    pub autoexamples: Option<bool>,
196    pub autotests: Option<bool>,
197    pub autobenches: Option<bool>,
198    pub default_run: Option<String>,
199
200    // Package metadata.
201    pub description: Option<InheritableString>,
202    pub homepage: Option<InheritableString>,
203    pub documentation: Option<InheritableString>,
204    pub readme: Option<InheritableStringOrBool>,
205    pub keywords: Option<InheritableVecString>,
206    pub categories: Option<InheritableVecString>,
207    pub license: Option<InheritableString>,
208    pub license_file: Option<InheritableString>,
209    pub repository: Option<InheritableString>,
210    pub resolver: Option<String>,
211
212    #[cfg_attr(
213        feature = "unstable-schema",
214        schemars(with = "Option<TomlValueWrapper>")
215    )]
216    pub metadata: Option<toml::Value>,
217
218    /// Provide a helpful error message for a common user error.
219    #[serde(rename = "cargo-features", skip_serializing)]
220    #[cfg_attr(feature = "unstable-schema", schemars(skip))]
221    pub _invalid_cargo_features: Option<InvalidCargoFeatures>,
222}
223
224impl TomlPackage {
225    pub fn new(name: PackageName) -> Self {
226        Self {
227            name: Some(name),
228            ..Default::default()
229        }
230    }
231
232    pub fn normalized_name(&self) -> Result<&PackageName, UnresolvedError> {
233        self.name.as_ref().ok_or(UnresolvedError)
234    }
235
236    pub fn normalized_edition(&self) -> Result<Option<&String>, UnresolvedError> {
237        self.edition.as_ref().map(|v| v.normalized()).transpose()
238    }
239
240    pub fn normalized_rust_version(&self) -> Result<Option<&RustVersion>, UnresolvedError> {
241        self.rust_version
242            .as_ref()
243            .map(|v| v.normalized())
244            .transpose()
245    }
246
247    pub fn normalized_version(&self) -> Result<Option<&semver::Version>, UnresolvedError> {
248        self.version.as_ref().map(|v| v.normalized()).transpose()
249    }
250
251    pub fn normalized_authors(&self) -> Result<Option<&Vec<String>>, UnresolvedError> {
252        self.authors.as_ref().map(|v| v.normalized()).transpose()
253    }
254
255    pub fn normalized_build(&self) -> Result<Option<&[String]>, UnresolvedError> {
256        let build = self.build.as_ref().ok_or(UnresolvedError)?;
257        match build {
258            TomlPackageBuild::Auto(false) => Ok(None),
259            TomlPackageBuild::Auto(true) => Err(UnresolvedError),
260            TomlPackageBuild::SingleScript(value) => Ok(Some(std::slice::from_ref(value))),
261            TomlPackageBuild::MultipleScript(scripts) => Ok(Some(scripts)),
262        }
263    }
264
265    pub fn normalized_exclude(&self) -> Result<Option<&Vec<String>>, UnresolvedError> {
266        self.exclude.as_ref().map(|v| v.normalized()).transpose()
267    }
268
269    pub fn normalized_include(&self) -> Result<Option<&Vec<String>>, UnresolvedError> {
270        self.include.as_ref().map(|v| v.normalized()).transpose()
271    }
272
273    pub fn normalized_publish(&self) -> Result<Option<&VecStringOrBool>, UnresolvedError> {
274        self.publish.as_ref().map(|v| v.normalized()).transpose()
275    }
276
277    pub fn normalized_description(&self) -> Result<Option<&String>, UnresolvedError> {
278        self.description
279            .as_ref()
280            .map(|v| v.normalized())
281            .transpose()
282    }
283
284    pub fn normalized_homepage(&self) -> Result<Option<&String>, UnresolvedError> {
285        self.homepage.as_ref().map(|v| v.normalized()).transpose()
286    }
287
288    pub fn normalized_documentation(&self) -> Result<Option<&String>, UnresolvedError> {
289        self.documentation
290            .as_ref()
291            .map(|v| v.normalized())
292            .transpose()
293    }
294
295    pub fn normalized_readme(&self) -> Result<Option<&String>, UnresolvedError> {
296        let readme = self.readme.as_ref().ok_or(UnresolvedError)?;
297        readme.normalized().and_then(|sb| match sb {
298            StringOrBool::Bool(false) => Ok(None),
299            StringOrBool::Bool(true) => Err(UnresolvedError),
300            StringOrBool::String(value) => Ok(Some(value)),
301        })
302    }
303
304    pub fn normalized_keywords(&self) -> Result<Option<&Vec<String>>, UnresolvedError> {
305        self.keywords.as_ref().map(|v| v.normalized()).transpose()
306    }
307
308    pub fn normalized_categories(&self) -> Result<Option<&Vec<String>>, UnresolvedError> {
309        self.categories.as_ref().map(|v| v.normalized()).transpose()
310    }
311
312    pub fn normalized_license(&self) -> Result<Option<&String>, UnresolvedError> {
313        self.license.as_ref().map(|v| v.normalized()).transpose()
314    }
315
316    pub fn normalized_license_file(&self) -> Result<Option<&String>, UnresolvedError> {
317        self.license_file
318            .as_ref()
319            .map(|v| v.normalized())
320            .transpose()
321    }
322
323    pub fn normalized_repository(&self) -> Result<Option<&String>, UnresolvedError> {
324        self.repository.as_ref().map(|v| v.normalized()).transpose()
325    }
326}
327
328/// An enum that allows for inheriting keys from a workspace in a Cargo.toml.
329#[derive(Serialize, Copy, Clone, Debug)]
330#[serde(untagged)]
331#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
332pub enum InheritableField<T> {
333    /// The type that is used when not inheriting from a workspace.
334    Value(T),
335    /// The type when inheriting from a workspace.
336    Inherit(TomlInheritedField),
337}
338
339impl<T> InheritableField<T> {
340    pub fn normalized(&self) -> Result<&T, UnresolvedError> {
341        self.as_value().ok_or(UnresolvedError)
342    }
343
344    pub fn as_value(&self) -> Option<&T> {
345        match self {
346            InheritableField::Inherit(_) => None,
347            InheritableField::Value(defined) => Some(defined),
348        }
349    }
350
351    pub fn into_value(self) -> Option<T> {
352        match self {
353            Self::Inherit(_) => None,
354            Self::Value(defined) => Some(defined),
355        }
356    }
357
358    pub fn is_inherited(&self) -> bool {
359        matches!(self, Self::Inherit(_))
360    }
361}
362
363//. This already has a `Deserialize` impl from version_trim_whitespace
364pub type InheritableSemverVersion = InheritableField<semver::Version>;
365impl<'de> de::Deserialize<'de> for InheritableSemverVersion {
366    fn deserialize<D>(d: D) -> Result<Self, D::Error>
367    where
368        D: de::Deserializer<'de>,
369    {
370        struct Visitor;
371
372        impl<'de> de::Visitor<'de> for Visitor {
373            type Value = InheritableSemverVersion;
374
375            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376                f.write_str("SemVer version")
377            }
378
379            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
380                value
381                    .trim()
382                    .parse()
383                    .map(InheritableField::Value)
384                    .map_err(E::custom)
385            }
386
387            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
388                TomlInheritedField::deserialize(de::value::MapAccessDeserializer::new(map))
389                    .map(InheritableField::Inherit)
390            }
391        }
392
393        d.deserialize_any(Visitor)
394    }
395}
396
397pub type InheritableString = InheritableField<String>;
398impl<'de> de::Deserialize<'de> for InheritableString {
399    fn deserialize<D>(d: D) -> Result<Self, D::Error>
400    where
401        D: de::Deserializer<'de>,
402    {
403        struct Visitor;
404
405        impl<'de> de::Visitor<'de> for Visitor {
406            type Value = InheritableString;
407
408            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
409                f.write_str("a string or workspace")
410            }
411
412            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
413            where
414                E: de::Error,
415            {
416                Ok(InheritableString::Value(value))
417            }
418
419            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
420            where
421                E: de::Error,
422            {
423                self.visit_string(value.to_owned())
424            }
425
426            fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
427            where
428                V: de::MapAccess<'de>,
429            {
430                let mvd = de::value::MapAccessDeserializer::new(map);
431                TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
432            }
433        }
434
435        d.deserialize_any(Visitor)
436    }
437}
438
439pub type InheritableRustVersion = InheritableField<RustVersion>;
440impl<'de> de::Deserialize<'de> for InheritableRustVersion {
441    fn deserialize<D>(d: D) -> Result<Self, D::Error>
442    where
443        D: de::Deserializer<'de>,
444    {
445        struct Visitor;
446
447        impl<'de> de::Visitor<'de> for Visitor {
448            type Value = InheritableRustVersion;
449
450            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
451                f.write_str("a semver or workspace")
452            }
453
454            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
455            where
456                E: de::Error,
457            {
458                let value = value.parse::<RustVersion>().map_err(|e| E::custom(e))?;
459                Ok(InheritableRustVersion::Value(value))
460            }
461
462            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
463            where
464                E: de::Error,
465            {
466                self.visit_string(value.to_owned())
467            }
468
469            fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
470            where
471                V: de::MapAccess<'de>,
472            {
473                let mvd = de::value::MapAccessDeserializer::new(map);
474                TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
475            }
476        }
477
478        d.deserialize_any(Visitor)
479    }
480}
481
482pub type InheritableVecString = InheritableField<Vec<String>>;
483impl<'de> de::Deserialize<'de> for InheritableVecString {
484    fn deserialize<D>(d: D) -> Result<Self, D::Error>
485    where
486        D: de::Deserializer<'de>,
487    {
488        struct Visitor;
489
490        impl<'de> de::Visitor<'de> for Visitor {
491            type Value = InheritableVecString;
492
493            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
494                f.write_str("a vector of strings or workspace")
495            }
496            fn visit_seq<A>(self, v: A) -> Result<Self::Value, A::Error>
497            where
498                A: de::SeqAccess<'de>,
499            {
500                let seq = de::value::SeqAccessDeserializer::new(v);
501                Vec::deserialize(seq).map(InheritableField::Value)
502            }
503
504            fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
505            where
506                V: de::MapAccess<'de>,
507            {
508                let mvd = de::value::MapAccessDeserializer::new(map);
509                TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
510            }
511        }
512
513        d.deserialize_any(Visitor)
514    }
515}
516
517pub type InheritableStringOrBool = InheritableField<StringOrBool>;
518impl<'de> de::Deserialize<'de> for InheritableStringOrBool {
519    fn deserialize<D>(d: D) -> Result<Self, D::Error>
520    where
521        D: de::Deserializer<'de>,
522    {
523        struct Visitor;
524
525        impl<'de> de::Visitor<'de> for Visitor {
526            type Value = InheritableStringOrBool;
527
528            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
529                f.write_str("a string, a bool, or workspace")
530            }
531
532            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
533            where
534                E: de::Error,
535            {
536                let b = de::value::BoolDeserializer::new(v);
537                StringOrBool::deserialize(b).map(InheritableField::Value)
538            }
539
540            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
541            where
542                E: de::Error,
543            {
544                let string = de::value::StringDeserializer::new(v);
545                StringOrBool::deserialize(string).map(InheritableField::Value)
546            }
547
548            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
549            where
550                E: de::Error,
551            {
552                self.visit_string(value.to_owned())
553            }
554
555            fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
556            where
557                V: de::MapAccess<'de>,
558            {
559                let mvd = de::value::MapAccessDeserializer::new(map);
560                TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
561            }
562        }
563
564        d.deserialize_any(Visitor)
565    }
566}
567
568pub type InheritableVecStringOrBool = InheritableField<VecStringOrBool>;
569impl<'de> de::Deserialize<'de> for InheritableVecStringOrBool {
570    fn deserialize<D>(d: D) -> Result<Self, D::Error>
571    where
572        D: de::Deserializer<'de>,
573    {
574        struct Visitor;
575
576        impl<'de> de::Visitor<'de> for Visitor {
577            type Value = InheritableVecStringOrBool;
578
579            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
580                f.write_str("a boolean, a vector of strings, or workspace")
581            }
582
583            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
584            where
585                E: de::Error,
586            {
587                let b = de::value::BoolDeserializer::new(v);
588                VecStringOrBool::deserialize(b).map(InheritableField::Value)
589            }
590
591            fn visit_seq<A>(self, v: A) -> Result<Self::Value, A::Error>
592            where
593                A: de::SeqAccess<'de>,
594            {
595                let seq = de::value::SeqAccessDeserializer::new(v);
596                VecStringOrBool::deserialize(seq).map(InheritableField::Value)
597            }
598
599            fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
600            where
601                V: de::MapAccess<'de>,
602            {
603                let mvd = de::value::MapAccessDeserializer::new(map);
604                TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
605            }
606        }
607
608        d.deserialize_any(Visitor)
609    }
610}
611
612#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
613#[serde(rename_all = "kebab-case")]
614#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
615pub struct TomlInheritedField {
616    workspace: WorkspaceValue,
617}
618
619impl TomlInheritedField {
620    pub fn new() -> Self {
621        TomlInheritedField {
622            workspace: WorkspaceValue,
623        }
624    }
625}
626
627impl Default for TomlInheritedField {
628    fn default() -> Self {
629        Self::new()
630    }
631}
632
633#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
634#[serde(try_from = "bool")]
635#[serde(into = "bool")]
636#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
637#[cfg_attr(feature = "unstable-schema", schemars(extend("type" = "boolean", "enum" = [true])))]
638struct WorkspaceValue;
639
640impl TryFrom<bool> for WorkspaceValue {
641    type Error = String;
642    fn try_from(other: bool) -> Result<WorkspaceValue, Self::Error> {
643        if other {
644            Ok(WorkspaceValue)
645        } else {
646            Err("`workspace` cannot be false".to_owned())
647        }
648    }
649}
650
651impl From<WorkspaceValue> for bool {
652    fn from(_: WorkspaceValue) -> bool {
653        true
654    }
655}
656
657#[derive(Serialize, Clone, Debug)]
658#[serde(untagged)]
659#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
660pub enum InheritableDependency {
661    /// The type that is used when not inheriting from a workspace.
662    Value(TomlDependency),
663    /// The type when inheriting from a workspace.
664    Inherit(TomlInheritedDependency),
665}
666
667impl InheritableDependency {
668    pub fn unused_keys(&self) -> Vec<String> {
669        match self {
670            InheritableDependency::Value(d) => d.unused_keys(),
671            InheritableDependency::Inherit(w) => w._unused_keys.keys().cloned().collect(),
672        }
673    }
674
675    pub fn normalized(&self) -> Result<&TomlDependency, UnresolvedError> {
676        match self {
677            InheritableDependency::Value(d) => Ok(d),
678            InheritableDependency::Inherit(_) => Err(UnresolvedError),
679        }
680    }
681
682    pub fn is_inherited(&self) -> bool {
683        matches!(self, InheritableDependency::Inherit(_))
684    }
685}
686
687impl<'de> de::Deserialize<'de> for InheritableDependency {
688    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
689    where
690        D: de::Deserializer<'de>,
691    {
692        struct Visitor;
693
694        impl<'de> de::Visitor<'de> for Visitor {
695            type Value = InheritableDependency;
696
697            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698                f.write_str(EXPECTED_DEPENDENCY)
699            }
700
701            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
702                TomlDependency::deserialize(value.into_deserializer())
703                    .map(InheritableDependency::Value)
704            }
705
706            fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
707                TomlDependency::deserialize(value.into_deserializer())
708                    .map(InheritableDependency::Value)
709            }
710
711            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
712                let table = AnyDependencyTable::<String>::deserialize(
713                    de::value::MapAccessDeserializer::new(map),
714                )?;
715                if table.workspace.is_some() {
716                    table.into_inherited().map(InheritableDependency::Inherit)
717                } else {
718                    Ok(InheritableDependency::Value(TomlDependency::Detailed(
719                        table.into_detailed(),
720                    )))
721                }
722            }
723        }
724
725        deserializer.deserialize_any(Visitor)
726    }
727}
728
729#[derive(Serialize, Clone, Debug)]
730#[serde(rename_all = "kebab-case")]
731#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
732pub struct TomlInheritedDependency {
733    pub workspace: bool,
734    pub features: Option<Vec<String>>,
735    pub default_features: Option<bool>,
736    #[serde(rename = "default_features")]
737    pub default_features2: Option<bool>,
738    pub optional: Option<bool>,
739    pub public: Option<bool>,
740
741    /// This is here to provide a way to see the "unused manifest keys" when deserializing
742    #[serde(skip_serializing)]
743    #[serde(flatten)]
744    #[cfg_attr(feature = "unstable-schema", schemars(skip))]
745    pub _unused_keys: BTreeMap<String, toml::Value>,
746}
747
748impl<'de> Deserialize<'de> for TomlInheritedDependency {
749    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
750        AnyDependencyTable::<String>::deserialize(deserializer)?.into_inherited()
751    }
752}
753
754impl TomlInheritedDependency {
755    pub fn default_features(&self) -> Option<bool> {
756        self.default_features.or(self.default_features2)
757    }
758}
759
760#[derive(Clone, Debug, Serialize)]
761#[serde(untagged)]
762#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
763pub enum TomlDependency<P: Clone = String> {
764    /// In the simple format, only a version is specified, eg.
765    /// `package = "<version>"`
766    Simple(String),
767    /// The simple format is equivalent to a detailed dependency
768    /// specifying only a version, eg.
769    /// `package = { version = "<version>" }`
770    Detailed(TomlDetailedDependency<P>),
771}
772
773impl TomlDependency {
774    pub fn is_version_specified(&self) -> bool {
775        match self {
776            TomlDependency::Detailed(d) => d.version.is_some(),
777            TomlDependency::Simple(..) => true,
778        }
779    }
780
781    pub fn is_optional(&self) -> bool {
782        match self {
783            TomlDependency::Detailed(d) => d.optional.unwrap_or(false),
784            TomlDependency::Simple(..) => false,
785        }
786    }
787
788    pub fn is_public(&self) -> bool {
789        match self {
790            TomlDependency::Detailed(d) => d.public.unwrap_or(false),
791            TomlDependency::Simple(..) => false,
792        }
793    }
794
795    pub fn default_features(&self) -> Option<bool> {
796        match self {
797            TomlDependency::Detailed(d) => d.default_features(),
798            TomlDependency::Simple(..) => None,
799        }
800    }
801
802    pub fn unused_keys(&self) -> Vec<String> {
803        match self {
804            TomlDependency::Simple(_) => vec![],
805            TomlDependency::Detailed(detailed) => detailed._unused_keys.keys().cloned().collect(),
806        }
807    }
808}
809
810const EXPECTED_DEPENDENCY: &str = "a version string like \"0.9.8\" or a \
811                     detailed dependency like { version = \"0.9.8\" }";
812
813impl<'de, P: Deserialize<'de> + Clone> de::Deserialize<'de> for TomlDependency<P> {
814    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
815    where
816        D: de::Deserializer<'de>,
817    {
818        struct Visitor<P>(std::marker::PhantomData<P>);
819
820        impl<'de, P: Deserialize<'de> + Clone> de::Visitor<'de> for Visitor<P> {
821            type Value = TomlDependency<P>;
822
823            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824                f.write_str(EXPECTED_DEPENDENCY)
825            }
826
827            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
828                Ok(TomlDependency::Simple(value.to_owned()))
829            }
830
831            fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
832                Ok(TomlDependency::Simple(value))
833            }
834
835            fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
836                let unexpected = Unexpected::Bool(value);
837                if value {
838                    Err(E::custom(format_args!(
839                        "invalid type: {unexpected}, expected {}\nnote: if you meant to use a workspace member, you can write\n dep.workspace = true",
840                        &self as &dyn de::Expected
841                    )))
842                } else {
843                    Err(E::invalid_type(unexpected, &self))
844                }
845            }
846
847            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
848                TomlDetailedDependency::deserialize(de::value::MapAccessDeserializer::new(map))
849                    .map(TomlDependency::Detailed)
850            }
851        }
852
853        deserializer.deserialize_any(Visitor(std::marker::PhantomData))
854    }
855}
856
857#[derive(Serialize, Clone, Debug)]
858#[serde(rename_all = "kebab-case")]
859#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
860pub struct TomlDetailedDependency<P: Clone = String> {
861    pub version: Option<String>,
862
863    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
864    pub registry: Option<RegistryName>,
865    /// The URL of the `registry` field.
866    /// This is an internal implementation detail. When Cargo creates a
867    /// package, it replaces `registry` with `registry-index` so that the
868    /// manifest contains the correct URL. All users won't have the same
869    /// registry names configured, so Cargo can't rely on just the name for
870    /// crates published by other users.
871    pub registry_index: Option<String>,
872    // `path` is relative to the file it appears in. If that's a `Cargo.toml`, it'll be relative to
873    // that TOML file, and if it's a `.cargo/config` file, it'll be relative to that file.
874    pub path: Option<P>,
875    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
876    pub base: Option<PathBaseName>,
877    pub git: Option<String>,
878    pub branch: Option<String>,
879    pub tag: Option<String>,
880    pub rev: Option<String>,
881    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
882    #[cfg_attr(feature = "unstable-schema", schemars(extend("const" = true)))]
883    pub builtin: bool,
884
885    pub features: Option<Vec<String>>,
886    pub optional: Option<bool>,
887    pub default_features: Option<bool>,
888    #[serde(rename = "default_features")]
889    pub default_features2: Option<bool>,
890    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
891    pub package: Option<PackageName>,
892    pub public: Option<bool>,
893
894    /// One or more of `bin`, `cdylib`, `staticlib`, `bin:<name>`.
895    pub artifact: Option<StringOrVec>,
896    /// If set, the artifact should also be a dependency
897    pub lib: Option<bool>,
898    /// A platform name, like `x86_64-apple-darwin`
899    pub target: Option<String>,
900
901    /// This is here to provide a way to see the "unused manifest keys" when deserializing
902    #[serde(skip_serializing)]
903    #[serde(flatten)]
904    #[cfg_attr(feature = "unstable-schema", schemars(skip))]
905    pub _unused_keys: BTreeMap<String, toml::Value>,
906}
907
908impl<'de, P: Deserialize<'de> + Clone> Deserialize<'de> for TomlDetailedDependency<P> {
909    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
910        Ok(AnyDependencyTable::<P>::deserialize(deserializer)?.into_detailed())
911    }
912}
913
914// Deserialize known fields in place so errors retain their source locations.
915#[derive(Deserialize)]
916#[serde(rename_all = "kebab-case")]
917struct AnyDependencyTable<P> {
918    version: Option<String>,
919    registry: Option<RegistryName>,
920    registry_index: Option<String>,
921    path: Option<P>,
922    base: Option<PathBaseName>,
923    git: Option<String>,
924    branch: Option<String>,
925    tag: Option<String>,
926    rev: Option<String>,
927    #[serde(default, deserialize_with = "deserialize_builtin")]
928    builtin: bool,
929    features: Option<Vec<String>>,
930    optional: Option<bool>,
931    default_features: Option<bool>,
932    #[serde(rename = "default_features")]
933    default_features2: Option<bool>,
934    package: Option<PackageName>,
935    public: Option<bool>,
936    artifact: Option<StringOrVec>,
937    lib: Option<bool>,
938    target: Option<String>,
939    workspace: Option<WorkspaceValue>,
940    #[serde(flatten)]
941    _unused_keys: BTreeMap<String, toml::Value>,
942}
943
944impl<P: Clone> AnyDependencyTable<P> {
945    fn into_detailed(self) -> TomlDetailedDependency<P> {
946        let Self {
947            version,
948            registry,
949            registry_index,
950            path,
951            base,
952            git,
953            branch,
954            tag,
955            rev,
956            builtin,
957            features,
958            optional,
959            default_features,
960            default_features2,
961            package,
962            public,
963            artifact,
964            lib,
965            target,
966            workspace,
967            mut _unused_keys,
968        } = self;
969        if let Some(workspace) = workspace {
970            _unused_keys.insert("workspace".into(), toml::Value::Boolean(workspace.into()));
971        }
972        TomlDetailedDependency {
973            version,
974            registry,
975            registry_index,
976            path,
977            base,
978            git,
979            branch,
980            tag,
981            rev,
982            builtin,
983            features,
984            optional,
985            default_features,
986            default_features2,
987            package,
988            public,
989            artifact,
990            lib,
991            target,
992            _unused_keys,
993        }
994    }
995}
996
997impl AnyDependencyTable<String> {
998    fn into_inherited<E: de::Error>(self) -> Result<TomlInheritedDependency, E> {
999        let Self {
1000            version,
1001            registry,
1002            registry_index,
1003            path,
1004            base,
1005            git,
1006            branch,
1007            tag,
1008            rev,
1009            builtin,
1010            features,
1011            optional,
1012            default_features,
1013            default_features2,
1014            package,
1015            public,
1016            artifact,
1017            lib,
1018            target,
1019            workspace,
1020            mut _unused_keys,
1021        } = self;
1022        let workspace = workspace.ok_or_else(|| E::missing_field("workspace"))?;
1023        if builtin {
1024            return Err(E::custom(
1025                "`builtin` cannot be combined with `workspace = true`",
1026            ));
1027        }
1028        for (key, value) in [
1029            ("version", version.map(Into::into)),
1030            ("registry", registry.map(|name| name.into_inner().into())),
1031            ("registry-index", registry_index.map(Into::into)),
1032            ("path", path.map(Into::into)),
1033            ("base", base.map(|name| name.into_inner().into())),
1034            ("git", git.map(Into::into)),
1035            ("branch", branch.map(Into::into)),
1036            ("tag", tag.map(Into::into)),
1037            ("rev", rev.map(Into::into)),
1038            ("package", package.map(|name| name.into_inner().into())),
1039            ("artifact", artifact.map(|value| value.into_vec().into())),
1040            ("lib", lib.map(Into::into)),
1041            ("target", target.map(Into::into)),
1042        ] {
1043            if let Some(value) = value {
1044                _unused_keys.insert(key.into(), value);
1045            }
1046        }
1047        Ok(TomlInheritedDependency {
1048            workspace: workspace.into(),
1049            features,
1050            optional,
1051            default_features,
1052            default_features2,
1053            public,
1054            _unused_keys,
1055        })
1056    }
1057}
1058
1059fn deserialize_builtin<'de, D: de::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
1060    if bool::deserialize(deserializer)? {
1061        Ok(true)
1062    } else {
1063        Err(de::Error::custom("`builtin` cannot be false"))
1064    }
1065}
1066
1067impl<P: Clone> TomlDetailedDependency<P> {
1068    pub fn default_features(&self) -> Option<bool> {
1069        self.default_features.or(self.default_features2)
1070    }
1071}
1072
1073// Explicit implementation so we avoid pulling in P: Default
1074impl<P: Clone> Default for TomlDetailedDependency<P> {
1075    fn default() -> Self {
1076        Self {
1077            version: Default::default(),
1078            builtin: Default::default(),
1079            registry: Default::default(),
1080            registry_index: Default::default(),
1081            path: Default::default(),
1082            base: Default::default(),
1083            git: Default::default(),
1084            branch: Default::default(),
1085            tag: Default::default(),
1086            rev: Default::default(),
1087            features: Default::default(),
1088            optional: Default::default(),
1089            default_features: Default::default(),
1090            default_features2: Default::default(),
1091            package: Default::default(),
1092            public: Default::default(),
1093            artifact: Default::default(),
1094            lib: Default::default(),
1095            target: Default::default(),
1096            _unused_keys: Default::default(),
1097        }
1098    }
1099}
1100
1101#[derive(Deserialize, Serialize, Clone, Debug, Default)]
1102#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1103pub struct TomlProfiles(pub BTreeMap<ProfileName, TomlProfile>);
1104
1105impl TomlProfiles {
1106    pub fn get_all(&self) -> &BTreeMap<ProfileName, TomlProfile> {
1107        &self.0
1108    }
1109
1110    pub fn get(&self, name: &str) -> Option<&TomlProfile> {
1111        self.0.get(name)
1112    }
1113}
1114
1115#[derive(Deserialize, Serialize, Clone, Debug, Default, Eq, PartialEq)]
1116#[serde(default, rename_all = "kebab-case")]
1117#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1118pub struct TomlProfile {
1119    pub opt_level: Option<TomlOptLevel>,
1120    pub lto: Option<StringOrBool>,
1121    pub codegen_backend: Option<String>,
1122    pub codegen_units: Option<u32>,
1123    pub debug: Option<TomlDebugInfo>,
1124    pub split_debuginfo: Option<String>,
1125    pub debug_assertions: Option<bool>,
1126    pub rpath: Option<bool>,
1127    pub panic: Option<String>,
1128    pub overflow_checks: Option<bool>,
1129    pub incremental: Option<bool>,
1130    pub dir_name: Option<String>,
1131    pub inherits: Option<String>,
1132    pub strip: Option<StringOrBool>,
1133    // Note that `rustflags` is used for the cargo-feature `profile_rustflags`
1134    pub rustflags: Option<Vec<String>>,
1135    // These two fields must be last because they are sub-tables, and TOML
1136    // requires all non-tables to be listed first.
1137    pub package: Option<BTreeMap<ProfilePackageSpec, TomlProfile>>,
1138    pub build_override: Option<Box<TomlProfile>>,
1139    /// Controls the scope of path sanitization in build outputs.
1140    pub trim_paths: Option<TomlTrimPaths>,
1141    /// Unstable feature `hint-mostly-unused`
1142    pub hint_mostly_unused: Option<bool>,
1143}
1144
1145impl TomlProfile {
1146    /// Overwrite self's values with the given profile.
1147    pub fn merge(&mut self, profile: &Self) {
1148        if let Some(v) = &profile.opt_level {
1149            self.opt_level = Some(v.clone());
1150        }
1151
1152        if let Some(v) = &profile.lto {
1153            self.lto = Some(v.clone());
1154        }
1155
1156        if let Some(v) = &profile.codegen_backend {
1157            self.codegen_backend = Some(v.clone());
1158        }
1159
1160        if let Some(v) = profile.codegen_units {
1161            self.codegen_units = Some(v);
1162        }
1163
1164        if let Some(v) = profile.debug {
1165            self.debug = Some(v);
1166        }
1167
1168        if let Some(v) = profile.debug_assertions {
1169            self.debug_assertions = Some(v);
1170        }
1171
1172        if let Some(v) = &profile.split_debuginfo {
1173            self.split_debuginfo = Some(v.clone());
1174        }
1175
1176        if let Some(v) = profile.rpath {
1177            self.rpath = Some(v);
1178        }
1179
1180        if let Some(v) = &profile.panic {
1181            self.panic = Some(v.clone());
1182        }
1183
1184        if let Some(v) = profile.overflow_checks {
1185            self.overflow_checks = Some(v);
1186        }
1187
1188        if let Some(v) = profile.incremental {
1189            self.incremental = Some(v);
1190        }
1191
1192        if let Some(v) = &profile.rustflags {
1193            self.rustflags = Some(v.clone());
1194        }
1195
1196        if let Some(other_package) = &profile.package {
1197            match &mut self.package {
1198                Some(self_package) => {
1199                    for (spec, other_pkg_profile) in other_package {
1200                        match self_package.get_mut(spec) {
1201                            Some(p) => p.merge(other_pkg_profile),
1202                            None => {
1203                                self_package.insert(spec.clone(), other_pkg_profile.clone());
1204                            }
1205                        }
1206                    }
1207                }
1208                None => self.package = Some(other_package.clone()),
1209            }
1210        }
1211
1212        if let Some(other_bo) = &profile.build_override {
1213            match &mut self.build_override {
1214                Some(self_bo) => self_bo.merge(other_bo),
1215                None => self.build_override = Some(other_bo.clone()),
1216            }
1217        }
1218
1219        if let Some(v) = &profile.inherits {
1220            self.inherits = Some(v.clone());
1221        }
1222
1223        if let Some(v) = &profile.dir_name {
1224            self.dir_name = Some(v.clone());
1225        }
1226
1227        if let Some(v) = &profile.strip {
1228            self.strip = Some(v.clone());
1229        }
1230
1231        if let Some(v) = &profile.trim_paths {
1232            self.trim_paths = Some(v.clone())
1233        }
1234
1235        if let Some(v) = profile.hint_mostly_unused {
1236            self.hint_mostly_unused = Some(v);
1237        }
1238    }
1239}
1240
1241#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
1242#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1243pub enum ProfilePackageSpec {
1244    Spec(PackageIdSpec),
1245    All,
1246}
1247
1248impl fmt::Display for ProfilePackageSpec {
1249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250        match self {
1251            ProfilePackageSpec::Spec(spec) => spec.fmt(f),
1252            ProfilePackageSpec::All => f.write_str("*"),
1253        }
1254    }
1255}
1256
1257impl ser::Serialize for ProfilePackageSpec {
1258    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
1259    where
1260        S: ser::Serializer,
1261    {
1262        self.to_string().serialize(s)
1263    }
1264}
1265
1266impl<'de> de::Deserialize<'de> for ProfilePackageSpec {
1267    fn deserialize<D>(d: D) -> Result<ProfilePackageSpec, D::Error>
1268    where
1269        D: de::Deserializer<'de>,
1270    {
1271        let string = String::deserialize(d)?;
1272        if string == "*" {
1273            Ok(ProfilePackageSpec::All)
1274        } else {
1275            PackageIdSpec::parse(&string)
1276                .map_err(de::Error::custom)
1277                .map(ProfilePackageSpec::Spec)
1278        }
1279    }
1280}
1281
1282#[derive(Clone, Debug, Eq, PartialEq)]
1283#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1284#[cfg_attr(feature = "unstable-schema", schemars(extend("type" = ["string", "integer"], "enum" = [0, 1, 2, 3, "s", "z"])))]
1285pub struct TomlOptLevel(pub String);
1286
1287impl ser::Serialize for TomlOptLevel {
1288    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1289    where
1290        S: ser::Serializer,
1291    {
1292        match self.0.parse::<u32>() {
1293            Ok(n) => n.serialize(serializer),
1294            Err(_) => self.0.serialize(serializer),
1295        }
1296    }
1297}
1298
1299impl<'de> de::Deserialize<'de> for TomlOptLevel {
1300    fn deserialize<D>(d: D) -> Result<TomlOptLevel, D::Error>
1301    where
1302        D: de::Deserializer<'de>,
1303    {
1304        use serde::de::Error as _;
1305        UntaggedEnumVisitor::new()
1306            .expecting("an optimization level")
1307            .i64(|value| Ok(TomlOptLevel(value.to_string())))
1308            .string(|value| {
1309                if value == "s" || value == "z" {
1310                    Ok(TomlOptLevel(value.to_string()))
1311                } else {
1312                    Err(serde_untagged::de::Error::custom(format!(
1313                        "must be `0`, `1`, `2`, `3`, `s` or `z`, \
1314                         but found the string: \"{}\"",
1315                        value
1316                    )))
1317                }
1318            })
1319            .deserialize(d)
1320    }
1321}
1322
1323#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
1324#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1325#[cfg_attr(feature = "unstable-schema", schemars(rename_all = "kebab-case"))]
1326#[cfg_attr(feature = "unstable-schema", schemars(extend("type" = ["string", "integer", "boolean"])))]
1327#[cfg_attr(feature = "unstable-schema", schemars(transform = Self::transform))]
1328pub enum TomlDebugInfo {
1329    None,
1330    LineDirectivesOnly,
1331    LineTablesOnly,
1332    Limited,
1333    Full,
1334}
1335
1336// Add extra enum variants, preserving existing such "line-tables-only"
1337#[cfg(feature = "unstable-schema")]
1338impl TomlDebugInfo {
1339    fn transform(schema: &mut schemars::Schema) {
1340        if let Some(serde_json::Value::Array(variants)) = schema.get_mut("enum") {
1341            variants.reserve(5);
1342            variants.extend((0..=2).map(Into::into));
1343            variants.extend_from_slice(&[false.into(), true.into()]);
1344        }
1345    }
1346}
1347
1348impl Display for TomlDebugInfo {
1349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1350        match self {
1351            TomlDebugInfo::None => f.write_char('0'),
1352            TomlDebugInfo::Limited => f.write_char('1'),
1353            TomlDebugInfo::Full => f.write_char('2'),
1354            TomlDebugInfo::LineDirectivesOnly => f.write_str("line-directives-only"),
1355            TomlDebugInfo::LineTablesOnly => f.write_str("line-tables-only"),
1356        }
1357    }
1358}
1359
1360impl ser::Serialize for TomlDebugInfo {
1361    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1362    where
1363        S: ser::Serializer,
1364    {
1365        match self {
1366            Self::None => 0.serialize(serializer),
1367            Self::LineDirectivesOnly => "line-directives-only".serialize(serializer),
1368            Self::LineTablesOnly => "line-tables-only".serialize(serializer),
1369            Self::Limited => 1.serialize(serializer),
1370            Self::Full => 2.serialize(serializer),
1371        }
1372    }
1373}
1374
1375impl<'de> de::Deserialize<'de> for TomlDebugInfo {
1376    fn deserialize<D>(d: D) -> Result<TomlDebugInfo, D::Error>
1377    where
1378        D: de::Deserializer<'de>,
1379    {
1380        use serde::de::Error as _;
1381        let expecting = "a boolean, 0, 1, 2, \"none\", \"limited\", \"full\", \"line-tables-only\", or \"line-directives-only\"";
1382        UntaggedEnumVisitor::new()
1383            .expecting(expecting)
1384            .bool(|value| {
1385                Ok(if value {
1386                    TomlDebugInfo::Full
1387                } else {
1388                    TomlDebugInfo::None
1389                })
1390            })
1391            .i64(|value| {
1392                let debuginfo = match value {
1393                    0 => TomlDebugInfo::None,
1394                    1 => TomlDebugInfo::Limited,
1395                    2 => TomlDebugInfo::Full,
1396                    _ => {
1397                        return Err(serde_untagged::de::Error::invalid_value(
1398                            Unexpected::Signed(value),
1399                            &expecting,
1400                        ));
1401                    }
1402                };
1403                Ok(debuginfo)
1404            })
1405            .string(|value| {
1406                let debuginfo = match value {
1407                    "none" => TomlDebugInfo::None,
1408                    "limited" => TomlDebugInfo::Limited,
1409                    "full" => TomlDebugInfo::Full,
1410                    "line-directives-only" => TomlDebugInfo::LineDirectivesOnly,
1411                    "line-tables-only" => TomlDebugInfo::LineTablesOnly,
1412                    _ => {
1413                        return Err(serde_untagged::de::Error::invalid_value(
1414                            Unexpected::Str(value),
1415                            &expecting,
1416                        ));
1417                    }
1418                };
1419                Ok(debuginfo)
1420            })
1421            .deserialize(d)
1422    }
1423}
1424
1425#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
1426#[serde(rename_all = "kebab-case")]
1427#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1428pub enum TomlTrimPaths {
1429    None,
1430    Object,
1431    All,
1432}
1433
1434impl TomlTrimPaths {
1435    pub fn is_none(&self) -> bool {
1436        matches!(self, TomlTrimPaths::None)
1437    }
1438
1439    fn as_str(&self) -> &'static str {
1440        match self {
1441            TomlTrimPaths::None => "none",
1442            TomlTrimPaths::Object => "object",
1443            TomlTrimPaths::All => "all",
1444        }
1445    }
1446}
1447
1448impl fmt::Display for TomlTrimPaths {
1449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1450        write!(f, "{}", self.as_str())
1451    }
1452}
1453
1454pub type TomlLibTarget = TomlTarget;
1455pub type TomlBinTarget = TomlTarget;
1456pub type TomlExampleTarget = TomlTarget;
1457pub type TomlTestTarget = TomlTarget;
1458pub type TomlBenchTarget = TomlTarget;
1459
1460#[derive(Default, Serialize, Deserialize, Debug, Clone)]
1461#[serde(rename_all = "kebab-case")]
1462#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1463pub struct TomlTarget {
1464    pub name: Option<String>,
1465
1466    // The intention was to only accept `crate-type` here but historical
1467    // versions of Cargo also accepted `crate_type`, so look for both.
1468    pub crate_type: Option<Vec<String>>,
1469    #[serde(rename = "crate_type")]
1470    pub crate_type2: Option<Vec<String>>,
1471
1472    #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
1473    pub path: Option<PathValue>,
1474    // Note that `filename` is used for the cargo-feature `different_binary_name`
1475    pub filename: Option<String>,
1476    pub test: Option<bool>,
1477    pub doctest: Option<bool>,
1478    pub bench: Option<bool>,
1479    pub doc: Option<bool>,
1480    pub doc_scrape_examples: Option<bool>,
1481    pub proc_macro: Option<bool>,
1482    #[serde(rename = "proc_macro")]
1483    pub proc_macro2: Option<bool>,
1484    pub harness: Option<bool>,
1485    pub required_features: Option<Vec<String>>,
1486    pub edition: Option<String>,
1487}
1488
1489impl TomlTarget {
1490    pub fn new() -> TomlTarget {
1491        TomlTarget::default()
1492    }
1493
1494    pub fn proc_macro(&self) -> Option<bool> {
1495        self.proc_macro.or(self.proc_macro2).or_else(|| {
1496            if let Some(types) = self.crate_types() {
1497                if types.contains(&"proc-macro".to_string()) {
1498                    return Some(true);
1499                }
1500            }
1501            None
1502        })
1503    }
1504
1505    pub fn crate_types(&self) -> Option<&Vec<String>> {
1506        self.crate_type
1507            .as_ref()
1508            .or_else(|| self.crate_type2.as_ref())
1509    }
1510}
1511
1512macro_rules! str_newtype {
1513    ($name:ident) => {
1514        /// Verified string newtype
1515        #[derive(Serialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1516        #[serde(transparent)]
1517        #[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1518        pub struct $name<T: AsRef<str> = String>(T);
1519
1520        impl<T: AsRef<str>> $name<T> {
1521            pub fn into_inner(self) -> T {
1522                self.0
1523            }
1524        }
1525
1526        impl<T: AsRef<str>> AsRef<str> for $name<T> {
1527            fn as_ref(&self) -> &str {
1528                self.0.as_ref()
1529            }
1530        }
1531
1532        impl<T: AsRef<str>> std::ops::Deref for $name<T> {
1533            type Target = T;
1534
1535            fn deref(&self) -> &Self::Target {
1536                &self.0
1537            }
1538        }
1539
1540        impl<T: AsRef<str>> std::borrow::Borrow<str> for $name<T> {
1541            fn borrow(&self) -> &str {
1542                self.0.as_ref()
1543            }
1544        }
1545
1546        impl<'a> std::str::FromStr for $name<String> {
1547            type Err = restricted_names::NameValidationError;
1548
1549            fn from_str(value: &str) -> Result<Self, Self::Err> {
1550                Self::new(value.to_owned())
1551            }
1552        }
1553
1554        impl<'de, T: AsRef<str> + serde::Deserialize<'de>> serde::Deserialize<'de> for $name<T> {
1555            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1556            where
1557                D: serde::Deserializer<'de>,
1558            {
1559                let inner = T::deserialize(deserializer)?;
1560                Self::new(inner).map_err(serde::de::Error::custom)
1561            }
1562        }
1563
1564        impl<T: AsRef<str>> Display for $name<T> {
1565            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566                self.0.as_ref().fmt(f)
1567            }
1568        }
1569    };
1570}
1571
1572str_newtype!(PackageName);
1573
1574impl<T: AsRef<str>> PackageName<T> {
1575    /// Validated package name
1576    pub fn new(name: T) -> Result<Self, NameValidationError> {
1577        restricted_names::validate_package_name(name.as_ref())?;
1578        Ok(Self(name))
1579    }
1580}
1581
1582impl PackageName {
1583    /// Coerce a value to be a validate package name
1584    ///
1585    /// Replaces invalid values with `placeholder`
1586    pub fn sanitize(name: impl AsRef<str>, placeholder: char) -> Self {
1587        PackageName(restricted_names::sanitize_package_name(
1588            name.as_ref(),
1589            placeholder,
1590        ))
1591    }
1592}
1593
1594str_newtype!(RegistryName);
1595
1596impl<T: AsRef<str>> RegistryName<T> {
1597    /// Validated registry name
1598    pub fn new(name: T) -> Result<Self, NameValidationError> {
1599        restricted_names::validate_registry_name(name.as_ref())?;
1600        Ok(Self(name))
1601    }
1602}
1603
1604str_newtype!(ProfileName);
1605
1606impl<T: AsRef<str>> ProfileName<T> {
1607    /// Validated profile name
1608    pub fn new(name: T) -> Result<Self, NameValidationError> {
1609        restricted_names::validate_profile_name(name.as_ref())?;
1610        Ok(Self(name))
1611    }
1612}
1613
1614str_newtype!(FeatureName);
1615
1616impl<T: AsRef<str>> FeatureName<T> {
1617    /// Validated feature name
1618    pub fn new(name: T) -> Result<Self, NameValidationError> {
1619        restricted_names::validate_feature_name(name.as_ref())?;
1620        Ok(Self(name))
1621    }
1622}
1623
1624str_newtype!(PathBaseName);
1625
1626impl<T: AsRef<str>> PathBaseName<T> {
1627    /// Validated path base name
1628    pub fn new(name: T) -> Result<Self, NameValidationError> {
1629        restricted_names::validate_path_base_name(name.as_ref())?;
1630        Ok(Self(name))
1631    }
1632}
1633
1634/// Corresponds to a `target` entry, but `TomlTarget` is already used.
1635#[derive(Serialize, Deserialize, Debug, Clone)]
1636#[serde(rename_all = "kebab-case")]
1637#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1638pub struct TomlPlatform {
1639    pub dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1640    pub build_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1641    #[serde(rename = "build_dependencies")]
1642    pub build_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
1643    pub dev_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1644    #[serde(rename = "dev_dependencies")]
1645    pub dev_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
1646}
1647
1648impl TomlPlatform {
1649    pub fn dev_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
1650        self.dev_dependencies
1651            .as_ref()
1652            .or(self.dev_dependencies2.as_ref())
1653    }
1654
1655    pub fn build_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
1656        self.build_dependencies
1657            .as_ref()
1658            .or(self.build_dependencies2.as_ref())
1659    }
1660}
1661
1662/// Definition of a feature.
1663#[derive(Clone, Debug, Serialize)]
1664#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1665#[serde(untagged)]
1666pub enum FeatureDefinition {
1667    /// Features that this feature enables.
1668    Array(Vec<String>),
1669    /// Unstable feature `feature-metadata`. Metadata of this feature.
1670    Metadata(FeatureMetadata),
1671}
1672
1673// Implementing `Deserialize` manually allows for a better error message when the `enables` key is
1674// missing.
1675impl<'de> de::Deserialize<'de> for FeatureDefinition {
1676    fn deserialize<D>(d: D) -> Result<FeatureDefinition, D::Error>
1677    where
1678        D: de::Deserializer<'de>,
1679    {
1680        struct Visitor;
1681
1682        impl<'de> de::Visitor<'de> for Visitor {
1683            type Value = FeatureDefinition;
1684
1685            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1686                f.write_str("an array or map")
1687            }
1688
1689            fn visit_seq<S: de::SeqAccess<'de>>(self, seq: S) -> Result<Self::Value, S::Error> {
1690                Vec::deserialize(de::value::SeqAccessDeserializer::new(seq))
1691                    .map(FeatureDefinition::Array)
1692            }
1693
1694            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
1695                FeatureMetadata::deserialize(de::value::MapAccessDeserializer::new(map))
1696                    .map(FeatureDefinition::Metadata)
1697            }
1698        }
1699
1700        d.deserialize_any(Visitor)
1701    }
1702}
1703
1704impl FeatureDefinition {
1705    /// Returns the features that this feature enables.
1706    pub fn enables(&self) -> &[String] {
1707        match self {
1708            Self::Array(features) => features,
1709            Self::Metadata(FeatureMetadata {
1710                enables: features, ..
1711            }) => features,
1712        }
1713    }
1714}
1715
1716/// Unstable feature `feature-metadata`. Metadata of a feature.
1717#[derive(Clone, Debug, Deserialize, Serialize)]
1718#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1719pub struct FeatureMetadata {
1720    /// Features that this feature enables.
1721    pub enables: Vec<String>,
1722
1723    /// Documentation for the feature.
1724    pub doc: Option<String>,
1725
1726    /// This is here to provide a way to see the "unused manifest keys" when deserializing
1727    #[serde(skip_serializing)]
1728    #[serde(flatten)]
1729    #[cfg_attr(feature = "unstable-schema", schemars(skip))]
1730    pub _unused_keys: BTreeMap<String, toml::Value>,
1731}
1732
1733#[derive(Serialize, Debug, Clone)]
1734#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1735pub struct InheritableLints {
1736    #[serde(skip_serializing_if = "std::ops::Not::not")]
1737    #[cfg_attr(feature = "unstable-schema", schemars(default))]
1738    pub workspace: bool,
1739    #[serde(flatten)]
1740    pub lints: TomlLints,
1741}
1742
1743impl InheritableLints {
1744    pub fn normalized(&self) -> Result<&TomlLints, UnresolvedError> {
1745        if self.workspace {
1746            Err(UnresolvedError)
1747        } else {
1748            Ok(&self.lints)
1749        }
1750    }
1751}
1752
1753impl<'de> Deserialize<'de> for InheritableLints {
1754    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1755    where
1756        D: de::Deserializer<'de>,
1757    {
1758        struct InheritableLintsVisitor;
1759
1760        impl<'de> de::Visitor<'de> for InheritableLintsVisitor {
1761            // The type that our Visitor is going to produce.
1762            type Value = InheritableLints;
1763
1764            // Format a message stating what data this Visitor expects to receive.
1765            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1766                formatter.write_str("a lints table")
1767            }
1768
1769            // Deserialize MyMap from an abstract "map" provided by the
1770            // Deserializer. The MapAccess input is a callback provided by
1771            // the Deserializer to let us see each entry in the map.
1772            fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
1773            where
1774                M: de::MapAccess<'de>,
1775            {
1776                let mut lints = TomlLints::new();
1777                let mut workspace = false;
1778
1779                // While there are entries remaining in the input, add them
1780                // into our map.
1781                while let Some(key) = access.next_key()? {
1782                    if key == "workspace" {
1783                        workspace = match access.next_value()? {
1784                            Some(WorkspaceValue) => true,
1785                            None => false,
1786                        };
1787                    } else {
1788                        let value = access.next_value()?;
1789                        lints.insert(key, value);
1790                    }
1791                }
1792
1793                Ok(InheritableLints { workspace, lints })
1794            }
1795        }
1796
1797        deserializer.deserialize_map(InheritableLintsVisitor)
1798    }
1799}
1800
1801pub type TomlLints = BTreeMap<String, TomlToolLints>;
1802
1803pub type TomlToolLints = BTreeMap<String, TomlLint>;
1804
1805#[derive(Serialize, Debug, Clone)]
1806#[serde(untagged)]
1807#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1808pub enum TomlLint {
1809    Level(TomlLintLevel),
1810    Config(TomlLintConfig),
1811}
1812
1813impl<'de> Deserialize<'de> for TomlLint {
1814    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1815    where
1816        D: de::Deserializer<'de>,
1817    {
1818        struct Visitor;
1819
1820        impl<'de> de::Visitor<'de> for Visitor {
1821            type Value = TomlLint;
1822
1823            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1824                f.write_str("a string or map")
1825            }
1826
1827            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
1828                TomlLintLevel::deserialize(value.into_deserializer()).map(TomlLint::Level)
1829            }
1830
1831            fn visit_map<M: de::MapAccess<'de>>(self, map: M) -> Result<Self::Value, M::Error> {
1832                TomlLintConfig::deserialize(de::value::MapAccessDeserializer::new(map))
1833                    .map(TomlLint::Config)
1834            }
1835        }
1836
1837        deserializer.deserialize_any(Visitor)
1838    }
1839}
1840
1841impl TomlLint {
1842    pub fn level(&self) -> TomlLintLevel {
1843        match self {
1844            Self::Level(level) => *level,
1845            Self::Config(config) => config.level,
1846        }
1847    }
1848
1849    pub fn priority(&self) -> i8 {
1850        match self {
1851            Self::Level(_) => 0,
1852            Self::Config(config) => config.priority,
1853        }
1854    }
1855
1856    pub fn config(&self) -> Option<&toml::Table> {
1857        match self {
1858            Self::Level(_) => None,
1859            Self::Config(config) => Some(&config.config),
1860        }
1861    }
1862}
1863
1864#[derive(Serialize, Deserialize, Debug, Clone)]
1865#[serde(rename_all = "kebab-case")]
1866#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1867pub struct TomlLintConfig {
1868    pub level: TomlLintLevel,
1869    #[serde(default)]
1870    pub priority: i8,
1871    #[serde(flatten)]
1872    #[cfg_attr(
1873        feature = "unstable-schema",
1874        schemars(with = "std::collections::HashMap<String, TomlValueWrapper>")
1875    )]
1876    pub config: toml::Table,
1877}
1878
1879#[derive(Serialize, Deserialize, Debug, Copy, Clone, Eq, PartialEq)]
1880#[serde(rename_all = "kebab-case")]
1881#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1882pub enum TomlLintLevel {
1883    Forbid,
1884    Deny,
1885    Warn,
1886    Allow,
1887}
1888
1889#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1890#[serde(rename_all = "kebab-case")]
1891#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1892pub struct Hints {
1893    #[cfg_attr(
1894        feature = "unstable-schema",
1895        schemars(with = "Option<TomlValueWrapper>")
1896    )]
1897    pub min_opt_level: Option<toml::Value>,
1898    #[cfg_attr(
1899        feature = "unstable-schema",
1900        schemars(with = "Option<TomlValueWrapper>")
1901    )]
1902    pub mostly_unused: Option<toml::Value>,
1903}
1904
1905#[derive(Copy, Clone, Debug)]
1906pub struct InvalidCargoFeatures {}
1907
1908impl<'de> de::Deserialize<'de> for InvalidCargoFeatures {
1909    fn deserialize<D>(_d: D) -> Result<Self, D::Error>
1910    where
1911        D: de::Deserializer<'de>,
1912    {
1913        use serde::de::Error as _;
1914
1915        Err(D::Error::custom(
1916            "the field `cargo-features` should be set at the top of Cargo.toml before any tables",
1917        ))
1918    }
1919}
1920
1921/// A TOML string or an array of strings.
1922#[derive(Clone, Debug, Serialize, Eq, PartialEq, PartialOrd, Ord)]
1923#[serde(untagged)]
1924#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1925pub enum StringOrVec {
1926    String(String),
1927    Vec(Vec<String>),
1928}
1929
1930impl StringOrVec {
1931    pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, String> {
1932        self.as_slice().iter()
1933    }
1934
1935    pub fn as_slice(&self) -> &[String] {
1936        match self {
1937            Self::String(value) => std::slice::from_ref(value),
1938            Self::Vec(values) => values,
1939        }
1940    }
1941
1942    pub fn into_vec(self) -> Vec<String> {
1943        match self {
1944            Self::String(value) => vec![value],
1945            Self::Vec(values) => values,
1946        }
1947    }
1948}
1949
1950impl<'de> de::Deserialize<'de> for StringOrVec {
1951    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1952    where
1953        D: de::Deserializer<'de>,
1954    {
1955        UntaggedEnumVisitor::new()
1956            .expecting("string or list of strings")
1957            .string(|value| Ok(Self::String(value.to_owned())))
1958            .seq(|value| value.deserialize().map(Self::Vec))
1959            .deserialize(deserializer)
1960    }
1961}
1962
1963#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
1964#[serde(untagged)]
1965#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1966pub enum StringOrBool {
1967    String(String),
1968    Bool(bool),
1969}
1970
1971impl<'de> Deserialize<'de> for StringOrBool {
1972    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1973    where
1974        D: de::Deserializer<'de>,
1975    {
1976        UntaggedEnumVisitor::new()
1977            .bool(|b| Ok(StringOrBool::Bool(b)))
1978            .string(|s| Ok(StringOrBool::String(s.to_owned())))
1979            .deserialize(deserializer)
1980    }
1981}
1982
1983#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
1984#[serde(untagged)]
1985#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1986pub enum TomlPackageBuild {
1987    /// If build scripts are disabled or enabled.
1988    /// If true, `build.rs` in the root folder will be the build script.
1989    Auto(bool),
1990
1991    /// Path of Build Script if there's just one script.
1992    SingleScript(String),
1993
1994    /// Vector of paths if multiple build script are to be used.
1995    MultipleScript(Vec<String>),
1996}
1997
1998impl<'de> Deserialize<'de> for TomlPackageBuild {
1999    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2000    where
2001        D: de::Deserializer<'de>,
2002    {
2003        UntaggedEnumVisitor::new()
2004            .bool(|b| Ok(TomlPackageBuild::Auto(b)))
2005            .string(|s| Ok(TomlPackageBuild::SingleScript(s.to_owned())))
2006            .seq(|value| value.deserialize().map(TomlPackageBuild::MultipleScript))
2007            .deserialize(deserializer)
2008    }
2009}
2010
2011#[derive(PartialEq, Clone, Debug, Serialize)]
2012#[serde(untagged)]
2013#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
2014pub enum VecStringOrBool {
2015    VecString(Vec<String>),
2016    Bool(bool),
2017}
2018
2019impl<'de> de::Deserialize<'de> for VecStringOrBool {
2020    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2021    where
2022        D: de::Deserializer<'de>,
2023    {
2024        UntaggedEnumVisitor::new()
2025            .expecting("a boolean or vector of strings")
2026            .bool(|value| Ok(VecStringOrBool::Bool(value)))
2027            .seq(|value| value.deserialize().map(VecStringOrBool::VecString))
2028            .deserialize(deserializer)
2029    }
2030}
2031
2032#[derive(Clone, PartialEq, Eq)]
2033pub struct PathValue(pub PathBuf);
2034
2035impl fmt::Debug for PathValue {
2036    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2037        self.0.fmt(f)
2038    }
2039}
2040
2041impl ser::Serialize for PathValue {
2042    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2043    where
2044        S: ser::Serializer,
2045    {
2046        self.0.serialize(serializer)
2047    }
2048}
2049
2050impl<'de> de::Deserialize<'de> for PathValue {
2051    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2052    where
2053        D: de::Deserializer<'de>,
2054    {
2055        Ok(PathValue(String::deserialize(deserializer)?.into()))
2056    }
2057}
2058
2059/// Error validating names in Cargo.
2060#[derive(Debug, thiserror::Error)]
2061#[error("manifest field was not resolved")]
2062#[non_exhaustive]
2063#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
2064pub struct UnresolvedError;
2065
2066#[cfg(feature = "unstable-schema")]
2067#[test]
2068fn dump_manifest_schema() {
2069    let schema = schemars::schema_for!(crate::manifest::TomlManifest);
2070    let dump = serde_json::to_string_pretty(&schema).unwrap();
2071    snapbox::assert_data_eq!(dump, snapbox::file!("../../manifest.schema.json").raw());
2072}