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