1use 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#[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 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, Vec<String>>>,
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 #[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, Vec<String>>> {
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 pub package: Option<InheritablePackage>,
141 pub dependencies: Option<BTreeMap<PackageName, TomlDependency>>,
142 pub lints: Option<TomlLints>,
143}
144
145#[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#[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 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 #[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#[derive(Serialize, Copy, Clone, Debug)]
334#[serde(untagged)]
335#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
336pub enum InheritableField<T> {
337 Value(T),
339 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 is_inherited(&self) -> bool {
356 matches!(self, Self::Inherit(_))
357 }
358}
359
360pub type InheritableSemverVersion = InheritableField<semver::Version>;
362impl<'de> de::Deserialize<'de> for InheritableSemverVersion {
363 fn deserialize<D>(d: D) -> Result<Self, D::Error>
364 where
365 D: de::Deserializer<'de>,
366 {
367 UntaggedEnumVisitor::new()
368 .expecting("SemVer version")
369 .string(
370 |value| match value.trim().parse().map_err(de::Error::custom) {
371 Ok(parsed) => Ok(InheritableField::Value(parsed)),
372 Err(e) => Err(e),
373 },
374 )
375 .map(|value| value.deserialize().map(InheritableField::Inherit))
376 .deserialize(d)
377 }
378}
379
380pub type InheritableString = InheritableField<String>;
381impl<'de> de::Deserialize<'de> for InheritableString {
382 fn deserialize<D>(d: D) -> Result<Self, D::Error>
383 where
384 D: de::Deserializer<'de>,
385 {
386 struct Visitor;
387
388 impl<'de> de::Visitor<'de> for Visitor {
389 type Value = InheritableString;
390
391 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
392 f.write_str("a string or workspace")
393 }
394
395 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
396 where
397 E: de::Error,
398 {
399 Ok(InheritableString::Value(value))
400 }
401
402 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
403 where
404 E: de::Error,
405 {
406 self.visit_string(value.to_owned())
407 }
408
409 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
410 where
411 V: de::MapAccess<'de>,
412 {
413 let mvd = de::value::MapAccessDeserializer::new(map);
414 TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
415 }
416 }
417
418 d.deserialize_any(Visitor)
419 }
420}
421
422pub type InheritableRustVersion = InheritableField<RustVersion>;
423impl<'de> de::Deserialize<'de> for InheritableRustVersion {
424 fn deserialize<D>(d: D) -> Result<Self, D::Error>
425 where
426 D: de::Deserializer<'de>,
427 {
428 struct Visitor;
429
430 impl<'de> de::Visitor<'de> for Visitor {
431 type Value = InheritableRustVersion;
432
433 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
434 f.write_str("a semver or workspace")
435 }
436
437 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
438 where
439 E: de::Error,
440 {
441 let value = value.parse::<RustVersion>().map_err(|e| E::custom(e))?;
442 Ok(InheritableRustVersion::Value(value))
443 }
444
445 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
446 where
447 E: de::Error,
448 {
449 self.visit_string(value.to_owned())
450 }
451
452 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
453 where
454 V: de::MapAccess<'de>,
455 {
456 let mvd = de::value::MapAccessDeserializer::new(map);
457 TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
458 }
459 }
460
461 d.deserialize_any(Visitor)
462 }
463}
464
465pub type InheritableVecString = InheritableField<Vec<String>>;
466impl<'de> de::Deserialize<'de> for InheritableVecString {
467 fn deserialize<D>(d: D) -> Result<Self, D::Error>
468 where
469 D: de::Deserializer<'de>,
470 {
471 struct Visitor;
472
473 impl<'de> de::Visitor<'de> for Visitor {
474 type Value = InheritableVecString;
475
476 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
477 f.write_str("a vector of strings or workspace")
478 }
479 fn visit_seq<A>(self, v: A) -> Result<Self::Value, A::Error>
480 where
481 A: de::SeqAccess<'de>,
482 {
483 let seq = de::value::SeqAccessDeserializer::new(v);
484 Vec::deserialize(seq).map(InheritableField::Value)
485 }
486
487 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
488 where
489 V: de::MapAccess<'de>,
490 {
491 let mvd = de::value::MapAccessDeserializer::new(map);
492 TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
493 }
494 }
495
496 d.deserialize_any(Visitor)
497 }
498}
499
500pub type InheritableStringOrBool = InheritableField<StringOrBool>;
501impl<'de> de::Deserialize<'de> for InheritableStringOrBool {
502 fn deserialize<D>(d: D) -> Result<Self, D::Error>
503 where
504 D: de::Deserializer<'de>,
505 {
506 struct Visitor;
507
508 impl<'de> de::Visitor<'de> for Visitor {
509 type Value = InheritableStringOrBool;
510
511 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
512 f.write_str("a string, a bool, or workspace")
513 }
514
515 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
516 where
517 E: de::Error,
518 {
519 let b = de::value::BoolDeserializer::new(v);
520 StringOrBool::deserialize(b).map(InheritableField::Value)
521 }
522
523 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
524 where
525 E: de::Error,
526 {
527 let string = de::value::StringDeserializer::new(v);
528 StringOrBool::deserialize(string).map(InheritableField::Value)
529 }
530
531 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
532 where
533 E: de::Error,
534 {
535 self.visit_string(value.to_owned())
536 }
537
538 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
539 where
540 V: de::MapAccess<'de>,
541 {
542 let mvd = de::value::MapAccessDeserializer::new(map);
543 TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
544 }
545 }
546
547 d.deserialize_any(Visitor)
548 }
549}
550
551pub type InheritableVecStringOrBool = InheritableField<VecStringOrBool>;
552impl<'de> de::Deserialize<'de> for InheritableVecStringOrBool {
553 fn deserialize<D>(d: D) -> Result<Self, D::Error>
554 where
555 D: de::Deserializer<'de>,
556 {
557 struct Visitor;
558
559 impl<'de> de::Visitor<'de> for Visitor {
560 type Value = InheritableVecStringOrBool;
561
562 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
563 f.write_str("a boolean, a vector of strings, or workspace")
564 }
565
566 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
567 where
568 E: de::Error,
569 {
570 let b = de::value::BoolDeserializer::new(v);
571 VecStringOrBool::deserialize(b).map(InheritableField::Value)
572 }
573
574 fn visit_seq<A>(self, v: A) -> Result<Self::Value, A::Error>
575 where
576 A: de::SeqAccess<'de>,
577 {
578 let seq = de::value::SeqAccessDeserializer::new(v);
579 VecStringOrBool::deserialize(seq).map(InheritableField::Value)
580 }
581
582 fn visit_map<V>(self, map: V) -> Result<Self::Value, V::Error>
583 where
584 V: de::MapAccess<'de>,
585 {
586 let mvd = de::value::MapAccessDeserializer::new(map);
587 TomlInheritedField::deserialize(mvd).map(InheritableField::Inherit)
588 }
589 }
590
591 d.deserialize_any(Visitor)
592 }
593}
594
595pub type InheritableBtreeMap = InheritableField<BTreeMap<String, BTreeMap<String, String>>>;
596
597impl<'de> de::Deserialize<'de> for InheritableBtreeMap {
598 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
599 where
600 D: de::Deserializer<'de>,
601 {
602 let value = serde_value::Value::deserialize(deserializer)?;
603
604 if let Ok(w) = TomlInheritedField::deserialize(
605 serde_value::ValueDeserializer::<D::Error>::new(value.clone()),
606 ) {
607 return Ok(InheritableField::Inherit(w));
608 }
609 BTreeMap::deserialize(serde_value::ValueDeserializer::<D::Error>::new(value))
610 .map(InheritableField::Value)
611 }
612}
613
614#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
615#[serde(rename_all = "kebab-case")]
616#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
617pub struct TomlInheritedField {
618 workspace: WorkspaceValue,
619}
620
621impl TomlInheritedField {
622 pub fn new() -> Self {
623 TomlInheritedField {
624 workspace: WorkspaceValue,
625 }
626 }
627}
628
629impl Default for TomlInheritedField {
630 fn default() -> Self {
631 Self::new()
632 }
633}
634
635#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
636#[serde(try_from = "bool")]
637#[serde(into = "bool")]
638#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
639struct WorkspaceValue;
640
641impl TryFrom<bool> for WorkspaceValue {
642 type Error = String;
643 fn try_from(other: bool) -> Result<WorkspaceValue, Self::Error> {
644 if other {
645 Ok(WorkspaceValue)
646 } else {
647 Err("`workspace` cannot be false".to_owned())
648 }
649 }
650}
651
652impl From<WorkspaceValue> for bool {
653 fn from(_: WorkspaceValue) -> bool {
654 true
655 }
656}
657
658#[derive(Serialize, Clone, Debug)]
659#[serde(untagged)]
660#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
661pub enum InheritableDependency {
662 Value(TomlDependency),
664 Inherit(TomlInheritedDependency),
666}
667
668impl InheritableDependency {
669 pub fn unused_keys(&self) -> Vec<String> {
670 match self {
671 InheritableDependency::Value(d) => d.unused_keys(),
672 InheritableDependency::Inherit(w) => w._unused_keys.keys().cloned().collect(),
673 }
674 }
675
676 pub fn normalized(&self) -> Result<&TomlDependency, UnresolvedError> {
677 match self {
678 InheritableDependency::Value(d) => Ok(d),
679 InheritableDependency::Inherit(_) => Err(UnresolvedError),
680 }
681 }
682
683 pub fn is_inherited(&self) -> bool {
684 matches!(self, InheritableDependency::Inherit(_))
685 }
686}
687
688impl<'de> de::Deserialize<'de> for InheritableDependency {
689 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
690 where
691 D: de::Deserializer<'de>,
692 {
693 let value = serde_value::Value::deserialize(deserializer)?;
694
695 if let Ok(w) = TomlInheritedDependency::deserialize(serde_value::ValueDeserializer::<
696 D::Error,
697 >::new(value.clone()))
698 {
699 return if w.workspace {
700 Ok(InheritableDependency::Inherit(w))
701 } else {
702 Err(de::Error::custom("`workspace` cannot be false"))
703 };
704 }
705 TomlDependency::deserialize(serde_value::ValueDeserializer::<D::Error>::new(value))
706 .map(InheritableDependency::Value)
707 }
708}
709
710#[derive(Deserialize, Serialize, Clone, Debug)]
711#[serde(rename_all = "kebab-case")]
712#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
713pub struct TomlInheritedDependency {
714 pub workspace: bool,
715 pub features: Option<Vec<String>>,
716 pub default_features: Option<bool>,
717 #[serde(rename = "default_features")]
718 pub default_features2: Option<bool>,
719 pub optional: Option<bool>,
720 pub public: Option<bool>,
721
722 #[serde(skip_serializing)]
724 #[serde(flatten)]
725 #[cfg_attr(feature = "unstable-schema", schemars(skip))]
726 pub _unused_keys: BTreeMap<String, toml::Value>,
727}
728
729impl TomlInheritedDependency {
730 pub fn default_features(&self) -> Option<bool> {
731 self.default_features.or(self.default_features2)
732 }
733}
734
735#[derive(Clone, Debug, Serialize)]
736#[serde(untagged)]
737#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
738pub enum TomlDependency<P: Clone = String> {
739 Simple(String),
742 Detailed(TomlDetailedDependency<P>),
746}
747
748impl TomlDependency {
749 pub fn is_version_specified(&self) -> bool {
750 match self {
751 TomlDependency::Detailed(d) => d.version.is_some(),
752 TomlDependency::Simple(..) => true,
753 }
754 }
755
756 pub fn is_optional(&self) -> bool {
757 match self {
758 TomlDependency::Detailed(d) => d.optional.unwrap_or(false),
759 TomlDependency::Simple(..) => false,
760 }
761 }
762
763 pub fn is_public(&self) -> bool {
764 match self {
765 TomlDependency::Detailed(d) => d.public.unwrap_or(false),
766 TomlDependency::Simple(..) => false,
767 }
768 }
769
770 pub fn default_features(&self) -> Option<bool> {
771 match self {
772 TomlDependency::Detailed(d) => d.default_features(),
773 TomlDependency::Simple(..) => None,
774 }
775 }
776
777 pub fn unused_keys(&self) -> Vec<String> {
778 match self {
779 TomlDependency::Simple(_) => vec![],
780 TomlDependency::Detailed(detailed) => detailed._unused_keys.keys().cloned().collect(),
781 }
782 }
783}
784
785impl<'de, P: Deserialize<'de> + Clone> de::Deserialize<'de> for TomlDependency<P> {
786 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
787 where
788 D: de::Deserializer<'de>,
789 {
790 UntaggedEnumVisitor::new()
791 .expecting(
792 "a version string like \"0.9.8\" or a \
793 detailed dependency like { version = \"0.9.8\" }",
794 )
795 .string(|value| Ok(TomlDependency::Simple(value.to_owned())))
796 .map(|value| value.deserialize().map(TomlDependency::Detailed))
797 .deserialize(deserializer)
798 }
799}
800
801#[derive(Deserialize, Serialize, Clone, Debug)]
802#[serde(rename_all = "kebab-case")]
803#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
804pub struct TomlDetailedDependency<P: Clone = String> {
805 pub version: Option<String>,
806
807 #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
808 pub registry: Option<RegistryName>,
809 pub registry_index: Option<String>,
816 pub path: Option<P>,
819 #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
820 pub base: Option<PathBaseName>,
821 pub git: Option<String>,
822 pub branch: Option<String>,
823 pub tag: Option<String>,
824 pub rev: Option<String>,
825 pub features: Option<Vec<String>>,
826 pub optional: Option<bool>,
827 pub default_features: Option<bool>,
828 #[serde(rename = "default_features")]
829 pub default_features2: Option<bool>,
830 #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
831 pub package: Option<PackageName>,
832 pub public: Option<bool>,
833
834 pub artifact: Option<StringOrVec>,
836 pub lib: Option<bool>,
838 pub target: Option<String>,
840
841 #[serde(skip_serializing)]
843 #[serde(flatten)]
844 #[cfg_attr(feature = "unstable-schema", schemars(skip))]
845 pub _unused_keys: BTreeMap<String, toml::Value>,
846}
847
848impl<P: Clone> TomlDetailedDependency<P> {
849 pub fn default_features(&self) -> Option<bool> {
850 self.default_features.or(self.default_features2)
851 }
852}
853
854impl<P: Clone> Default for TomlDetailedDependency<P> {
856 fn default() -> Self {
857 Self {
858 version: Default::default(),
859 registry: Default::default(),
860 registry_index: Default::default(),
861 path: Default::default(),
862 base: Default::default(),
863 git: Default::default(),
864 branch: Default::default(),
865 tag: Default::default(),
866 rev: Default::default(),
867 features: Default::default(),
868 optional: Default::default(),
869 default_features: Default::default(),
870 default_features2: Default::default(),
871 package: Default::default(),
872 public: Default::default(),
873 artifact: Default::default(),
874 lib: Default::default(),
875 target: Default::default(),
876 _unused_keys: Default::default(),
877 }
878 }
879}
880
881#[derive(Deserialize, Serialize, Clone, Debug, Default)]
882#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
883pub struct TomlProfiles(pub BTreeMap<ProfileName, TomlProfile>);
884
885impl TomlProfiles {
886 pub fn get_all(&self) -> &BTreeMap<ProfileName, TomlProfile> {
887 &self.0
888 }
889
890 pub fn get(&self, name: &str) -> Option<&TomlProfile> {
891 self.0.get(name)
892 }
893}
894
895#[derive(Deserialize, Serialize, Clone, Debug, Default, Eq, PartialEq)]
896#[serde(default, rename_all = "kebab-case")]
897#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
898pub struct TomlProfile {
899 pub opt_level: Option<TomlOptLevel>,
900 pub lto: Option<StringOrBool>,
901 pub codegen_backend: Option<String>,
902 pub codegen_units: Option<u32>,
903 pub debug: Option<TomlDebugInfo>,
904 pub split_debuginfo: Option<String>,
905 pub debug_assertions: Option<bool>,
906 pub rpath: Option<bool>,
907 pub panic: Option<String>,
908 pub overflow_checks: Option<bool>,
909 pub incremental: Option<bool>,
910 pub dir_name: Option<String>,
911 pub inherits: Option<String>,
912 pub strip: Option<StringOrBool>,
913 pub rustflags: Option<Vec<String>>,
915 pub package: Option<BTreeMap<ProfilePackageSpec, TomlProfile>>,
918 pub build_override: Option<Box<TomlProfile>>,
919 pub trim_paths: Option<TomlTrimPaths>,
921 pub hint_mostly_unused: Option<bool>,
923}
924
925impl TomlProfile {
926 pub fn merge(&mut self, profile: &Self) {
928 if let Some(v) = &profile.opt_level {
929 self.opt_level = Some(v.clone());
930 }
931
932 if let Some(v) = &profile.lto {
933 self.lto = Some(v.clone());
934 }
935
936 if let Some(v) = &profile.codegen_backend {
937 self.codegen_backend = Some(v.clone());
938 }
939
940 if let Some(v) = profile.codegen_units {
941 self.codegen_units = Some(v);
942 }
943
944 if let Some(v) = profile.debug {
945 self.debug = Some(v);
946 }
947
948 if let Some(v) = profile.debug_assertions {
949 self.debug_assertions = Some(v);
950 }
951
952 if let Some(v) = &profile.split_debuginfo {
953 self.split_debuginfo = Some(v.clone());
954 }
955
956 if let Some(v) = profile.rpath {
957 self.rpath = Some(v);
958 }
959
960 if let Some(v) = &profile.panic {
961 self.panic = Some(v.clone());
962 }
963
964 if let Some(v) = profile.overflow_checks {
965 self.overflow_checks = Some(v);
966 }
967
968 if let Some(v) = profile.incremental {
969 self.incremental = Some(v);
970 }
971
972 if let Some(v) = &profile.rustflags {
973 self.rustflags = Some(v.clone());
974 }
975
976 if let Some(other_package) = &profile.package {
977 match &mut self.package {
978 Some(self_package) => {
979 for (spec, other_pkg_profile) in other_package {
980 match self_package.get_mut(spec) {
981 Some(p) => p.merge(other_pkg_profile),
982 None => {
983 self_package.insert(spec.clone(), other_pkg_profile.clone());
984 }
985 }
986 }
987 }
988 None => self.package = Some(other_package.clone()),
989 }
990 }
991
992 if let Some(other_bo) = &profile.build_override {
993 match &mut self.build_override {
994 Some(self_bo) => self_bo.merge(other_bo),
995 None => self.build_override = Some(other_bo.clone()),
996 }
997 }
998
999 if let Some(v) = &profile.inherits {
1000 self.inherits = Some(v.clone());
1001 }
1002
1003 if let Some(v) = &profile.dir_name {
1004 self.dir_name = Some(v.clone());
1005 }
1006
1007 if let Some(v) = &profile.strip {
1008 self.strip = Some(v.clone());
1009 }
1010
1011 if let Some(v) = &profile.trim_paths {
1012 self.trim_paths = Some(v.clone())
1013 }
1014
1015 if let Some(v) = profile.hint_mostly_unused {
1016 self.hint_mostly_unused = Some(v);
1017 }
1018 }
1019}
1020
1021#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
1022#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1023pub enum ProfilePackageSpec {
1024 Spec(PackageIdSpec),
1025 All,
1026}
1027
1028impl fmt::Display for ProfilePackageSpec {
1029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1030 match self {
1031 ProfilePackageSpec::Spec(spec) => spec.fmt(f),
1032 ProfilePackageSpec::All => f.write_str("*"),
1033 }
1034 }
1035}
1036
1037impl ser::Serialize for ProfilePackageSpec {
1038 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
1039 where
1040 S: ser::Serializer,
1041 {
1042 self.to_string().serialize(s)
1043 }
1044}
1045
1046impl<'de> de::Deserialize<'de> for ProfilePackageSpec {
1047 fn deserialize<D>(d: D) -> Result<ProfilePackageSpec, D::Error>
1048 where
1049 D: de::Deserializer<'de>,
1050 {
1051 let string = String::deserialize(d)?;
1052 if string == "*" {
1053 Ok(ProfilePackageSpec::All)
1054 } else {
1055 PackageIdSpec::parse(&string)
1056 .map_err(de::Error::custom)
1057 .map(ProfilePackageSpec::Spec)
1058 }
1059 }
1060}
1061
1062#[derive(Clone, Debug, Eq, PartialEq)]
1063#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1064pub struct TomlOptLevel(pub String);
1065
1066impl ser::Serialize for TomlOptLevel {
1067 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1068 where
1069 S: ser::Serializer,
1070 {
1071 match self.0.parse::<u32>() {
1072 Ok(n) => n.serialize(serializer),
1073 Err(_) => self.0.serialize(serializer),
1074 }
1075 }
1076}
1077
1078impl<'de> de::Deserialize<'de> for TomlOptLevel {
1079 fn deserialize<D>(d: D) -> Result<TomlOptLevel, D::Error>
1080 where
1081 D: de::Deserializer<'de>,
1082 {
1083 use serde::de::Error as _;
1084 UntaggedEnumVisitor::new()
1085 .expecting("an optimization level")
1086 .i64(|value| Ok(TomlOptLevel(value.to_string())))
1087 .string(|value| {
1088 if value == "s" || value == "z" {
1089 Ok(TomlOptLevel(value.to_string()))
1090 } else {
1091 Err(serde_untagged::de::Error::custom(format!(
1092 "must be `0`, `1`, `2`, `3`, `s` or `z`, \
1093 but found the string: \"{}\"",
1094 value
1095 )))
1096 }
1097 })
1098 .deserialize(d)
1099 }
1100}
1101
1102#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
1103#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1104pub enum TomlDebugInfo {
1105 None,
1106 LineDirectivesOnly,
1107 LineTablesOnly,
1108 Limited,
1109 Full,
1110}
1111
1112impl Display for TomlDebugInfo {
1113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 match self {
1115 TomlDebugInfo::None => f.write_char('0'),
1116 TomlDebugInfo::Limited => f.write_char('1'),
1117 TomlDebugInfo::Full => f.write_char('2'),
1118 TomlDebugInfo::LineDirectivesOnly => f.write_str("line-directives-only"),
1119 TomlDebugInfo::LineTablesOnly => f.write_str("line-tables-only"),
1120 }
1121 }
1122}
1123
1124impl ser::Serialize for TomlDebugInfo {
1125 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1126 where
1127 S: ser::Serializer,
1128 {
1129 match self {
1130 Self::None => 0.serialize(serializer),
1131 Self::LineDirectivesOnly => "line-directives-only".serialize(serializer),
1132 Self::LineTablesOnly => "line-tables-only".serialize(serializer),
1133 Self::Limited => 1.serialize(serializer),
1134 Self::Full => 2.serialize(serializer),
1135 }
1136 }
1137}
1138
1139impl<'de> de::Deserialize<'de> for TomlDebugInfo {
1140 fn deserialize<D>(d: D) -> Result<TomlDebugInfo, D::Error>
1141 where
1142 D: de::Deserializer<'de>,
1143 {
1144 use serde::de::Error as _;
1145 let expecting = "a boolean, 0, 1, 2, \"none\", \"limited\", \"full\", \"line-tables-only\", or \"line-directives-only\"";
1146 UntaggedEnumVisitor::new()
1147 .expecting(expecting)
1148 .bool(|value| {
1149 Ok(if value {
1150 TomlDebugInfo::Full
1151 } else {
1152 TomlDebugInfo::None
1153 })
1154 })
1155 .i64(|value| {
1156 let debuginfo = match value {
1157 0 => TomlDebugInfo::None,
1158 1 => TomlDebugInfo::Limited,
1159 2 => TomlDebugInfo::Full,
1160 _ => {
1161 return Err(serde_untagged::de::Error::invalid_value(
1162 Unexpected::Signed(value),
1163 &expecting,
1164 ));
1165 }
1166 };
1167 Ok(debuginfo)
1168 })
1169 .string(|value| {
1170 let debuginfo = match value {
1171 "none" => TomlDebugInfo::None,
1172 "limited" => TomlDebugInfo::Limited,
1173 "full" => TomlDebugInfo::Full,
1174 "line-directives-only" => TomlDebugInfo::LineDirectivesOnly,
1175 "line-tables-only" => TomlDebugInfo::LineTablesOnly,
1176 _ => {
1177 return Err(serde_untagged::de::Error::invalid_value(
1178 Unexpected::Str(value),
1179 &expecting,
1180 ));
1181 }
1182 };
1183 Ok(debuginfo)
1184 })
1185 .deserialize(d)
1186 }
1187}
1188
1189#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize)]
1190#[serde(untagged, rename_all = "kebab-case")]
1191#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1192pub enum TomlTrimPaths {
1193 Values(Vec<TomlTrimPathsValue>),
1194 All,
1195}
1196
1197impl TomlTrimPaths {
1198 pub fn none() -> Self {
1199 TomlTrimPaths::Values(Vec::new())
1200 }
1201
1202 pub fn is_none(&self) -> bool {
1203 match self {
1204 TomlTrimPaths::Values(v) => v.is_empty(),
1205 TomlTrimPaths::All => false,
1206 }
1207 }
1208}
1209
1210impl<'de> de::Deserialize<'de> for TomlTrimPaths {
1211 fn deserialize<D>(d: D) -> Result<TomlTrimPaths, D::Error>
1212 where
1213 D: de::Deserializer<'de>,
1214 {
1215 use serde::de::Error as _;
1216 let expecting = r#"a boolean, "none", "diagnostics", "macro", "object", "all", or an array with these options"#;
1217 UntaggedEnumVisitor::new()
1218 .expecting(expecting)
1219 .bool(|value| {
1220 Ok(if value {
1221 TomlTrimPaths::All
1222 } else {
1223 TomlTrimPaths::none()
1224 })
1225 })
1226 .string(|v| match v {
1227 "none" => Ok(TomlTrimPaths::none()),
1228 "all" => Ok(TomlTrimPaths::All),
1229 v => {
1230 let d = v.into_deserializer();
1231 let err = |_: D::Error| {
1232 serde_untagged::de::Error::custom(format!("expected {expecting}"))
1233 };
1234 TomlTrimPathsValue::deserialize(d)
1235 .map_err(err)
1236 .map(|v| v.into())
1237 }
1238 })
1239 .seq(|seq| {
1240 let seq: Vec<String> = seq.deserialize()?;
1241 let seq: Vec<_> = seq
1242 .into_iter()
1243 .map(|s| TomlTrimPathsValue::deserialize(s.into_deserializer()))
1244 .collect::<Result<_, _>>()?;
1245 Ok(seq.into())
1246 })
1247 .deserialize(d)
1248 }
1249}
1250
1251impl fmt::Display for TomlTrimPaths {
1252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253 match self {
1254 TomlTrimPaths::All => write!(f, "all"),
1255 TomlTrimPaths::Values(v) if v.is_empty() => write!(f, "none"),
1256 TomlTrimPaths::Values(v) => {
1257 let mut iter = v.iter();
1258 if let Some(value) = iter.next() {
1259 write!(f, "{value}")?;
1260 }
1261 for value in iter {
1262 write!(f, ",{value}")?;
1263 }
1264 Ok(())
1265 }
1266 }
1267 }
1268}
1269
1270impl From<TomlTrimPathsValue> for TomlTrimPaths {
1271 fn from(value: TomlTrimPathsValue) -> Self {
1272 TomlTrimPaths::Values(vec![value])
1273 }
1274}
1275
1276impl From<Vec<TomlTrimPathsValue>> for TomlTrimPaths {
1277 fn from(value: Vec<TomlTrimPathsValue>) -> Self {
1278 TomlTrimPaths::Values(value)
1279 }
1280}
1281
1282#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
1283#[serde(rename_all = "kebab-case")]
1284#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1285pub enum TomlTrimPathsValue {
1286 Diagnostics,
1287 Macro,
1288 Object,
1289}
1290
1291impl TomlTrimPathsValue {
1292 pub fn as_str(&self) -> &'static str {
1293 match self {
1294 TomlTrimPathsValue::Diagnostics => "diagnostics",
1295 TomlTrimPathsValue::Macro => "macro",
1296 TomlTrimPathsValue::Object => "object",
1297 }
1298 }
1299}
1300
1301impl fmt::Display for TomlTrimPathsValue {
1302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1303 write!(f, "{}", self.as_str())
1304 }
1305}
1306
1307pub type TomlLibTarget = TomlTarget;
1308pub type TomlBinTarget = TomlTarget;
1309pub type TomlExampleTarget = TomlTarget;
1310pub type TomlTestTarget = TomlTarget;
1311pub type TomlBenchTarget = TomlTarget;
1312
1313#[derive(Default, Serialize, Deserialize, Debug, Clone)]
1314#[serde(rename_all = "kebab-case")]
1315#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1316pub struct TomlTarget {
1317 pub name: Option<String>,
1318
1319 pub crate_type: Option<Vec<String>>,
1322 #[serde(rename = "crate_type")]
1323 pub crate_type2: Option<Vec<String>>,
1324
1325 #[cfg_attr(feature = "unstable-schema", schemars(with = "Option<String>"))]
1326 pub path: Option<PathValue>,
1327 pub filename: Option<String>,
1329 pub test: Option<bool>,
1330 pub doctest: Option<bool>,
1331 pub bench: Option<bool>,
1332 pub doc: Option<bool>,
1333 pub doc_scrape_examples: Option<bool>,
1334 pub proc_macro: Option<bool>,
1335 #[serde(rename = "proc_macro")]
1336 pub proc_macro2: Option<bool>,
1337 pub harness: Option<bool>,
1338 pub required_features: Option<Vec<String>>,
1339 pub edition: Option<String>,
1340}
1341
1342impl TomlTarget {
1343 pub fn new() -> TomlTarget {
1344 TomlTarget::default()
1345 }
1346
1347 pub fn proc_macro(&self) -> Option<bool> {
1348 self.proc_macro.or(self.proc_macro2).or_else(|| {
1349 if let Some(types) = self.crate_types() {
1350 if types.contains(&"proc-macro".to_string()) {
1351 return Some(true);
1352 }
1353 }
1354 None
1355 })
1356 }
1357
1358 pub fn crate_types(&self) -> Option<&Vec<String>> {
1359 self.crate_type
1360 .as_ref()
1361 .or_else(|| self.crate_type2.as_ref())
1362 }
1363}
1364
1365macro_rules! str_newtype {
1366 ($name:ident) => {
1367 #[derive(Serialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1369 #[serde(transparent)]
1370 #[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1371 pub struct $name<T: AsRef<str> = String>(T);
1372
1373 impl<T: AsRef<str>> $name<T> {
1374 pub fn into_inner(self) -> T {
1375 self.0
1376 }
1377 }
1378
1379 impl<T: AsRef<str>> AsRef<str> for $name<T> {
1380 fn as_ref(&self) -> &str {
1381 self.0.as_ref()
1382 }
1383 }
1384
1385 impl<T: AsRef<str>> std::ops::Deref for $name<T> {
1386 type Target = T;
1387
1388 fn deref(&self) -> &Self::Target {
1389 &self.0
1390 }
1391 }
1392
1393 impl<T: AsRef<str>> std::borrow::Borrow<str> for $name<T> {
1394 fn borrow(&self) -> &str {
1395 self.0.as_ref()
1396 }
1397 }
1398
1399 impl<'a> std::str::FromStr for $name<String> {
1400 type Err = restricted_names::NameValidationError;
1401
1402 fn from_str(value: &str) -> Result<Self, Self::Err> {
1403 Self::new(value.to_owned())
1404 }
1405 }
1406
1407 impl<'de, T: AsRef<str> + serde::Deserialize<'de>> serde::Deserialize<'de> for $name<T> {
1408 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1409 where
1410 D: serde::Deserializer<'de>,
1411 {
1412 let inner = T::deserialize(deserializer)?;
1413 Self::new(inner).map_err(serde::de::Error::custom)
1414 }
1415 }
1416
1417 impl<T: AsRef<str>> Display for $name<T> {
1418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1419 self.0.as_ref().fmt(f)
1420 }
1421 }
1422 };
1423}
1424
1425str_newtype!(PackageName);
1426
1427impl<T: AsRef<str>> PackageName<T> {
1428 pub fn new(name: T) -> Result<Self, NameValidationError> {
1430 restricted_names::validate_package_name(name.as_ref())?;
1431 Ok(Self(name))
1432 }
1433}
1434
1435impl PackageName {
1436 pub fn sanitize(name: impl AsRef<str>, placeholder: char) -> Self {
1440 PackageName(restricted_names::sanitize_package_name(
1441 name.as_ref(),
1442 placeholder,
1443 ))
1444 }
1445}
1446
1447str_newtype!(RegistryName);
1448
1449impl<T: AsRef<str>> RegistryName<T> {
1450 pub fn new(name: T) -> Result<Self, NameValidationError> {
1452 restricted_names::validate_registry_name(name.as_ref())?;
1453 Ok(Self(name))
1454 }
1455}
1456
1457str_newtype!(ProfileName);
1458
1459impl<T: AsRef<str>> ProfileName<T> {
1460 pub fn new(name: T) -> Result<Self, NameValidationError> {
1462 restricted_names::validate_profile_name(name.as_ref())?;
1463 Ok(Self(name))
1464 }
1465}
1466
1467str_newtype!(FeatureName);
1468
1469impl<T: AsRef<str>> FeatureName<T> {
1470 pub fn new(name: T) -> Result<Self, NameValidationError> {
1472 restricted_names::validate_feature_name(name.as_ref())?;
1473 Ok(Self(name))
1474 }
1475}
1476
1477str_newtype!(PathBaseName);
1478
1479impl<T: AsRef<str>> PathBaseName<T> {
1480 pub fn new(name: T) -> Result<Self, NameValidationError> {
1482 restricted_names::validate_path_base_name(name.as_ref())?;
1483 Ok(Self(name))
1484 }
1485}
1486
1487#[derive(Serialize, Deserialize, Debug, Clone)]
1489#[serde(rename_all = "kebab-case")]
1490#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1491pub struct TomlPlatform {
1492 pub dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1493 pub build_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1494 #[serde(rename = "build_dependencies")]
1495 pub build_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
1496 pub dev_dependencies: Option<BTreeMap<PackageName, InheritableDependency>>,
1497 #[serde(rename = "dev_dependencies")]
1498 pub dev_dependencies2: Option<BTreeMap<PackageName, InheritableDependency>>,
1499}
1500
1501impl TomlPlatform {
1502 pub fn dev_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
1503 self.dev_dependencies
1504 .as_ref()
1505 .or(self.dev_dependencies2.as_ref())
1506 }
1507
1508 pub fn build_dependencies(&self) -> Option<&BTreeMap<PackageName, InheritableDependency>> {
1509 self.build_dependencies
1510 .as_ref()
1511 .or(self.build_dependencies2.as_ref())
1512 }
1513}
1514
1515#[derive(Serialize, Debug, Clone)]
1516#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1517pub struct InheritableLints {
1518 #[serde(skip_serializing_if = "std::ops::Not::not")]
1519 #[cfg_attr(feature = "unstable-schema", schemars(default))]
1520 pub workspace: bool,
1521 #[serde(flatten)]
1522 pub lints: TomlLints,
1523}
1524
1525impl InheritableLints {
1526 pub fn normalized(&self) -> Result<&TomlLints, UnresolvedError> {
1527 if self.workspace {
1528 Err(UnresolvedError)
1529 } else {
1530 Ok(&self.lints)
1531 }
1532 }
1533}
1534
1535impl<'de> Deserialize<'de> for InheritableLints {
1536 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1537 where
1538 D: de::Deserializer<'de>,
1539 {
1540 struct InheritableLintsVisitor;
1541
1542 impl<'de> de::Visitor<'de> for InheritableLintsVisitor {
1543 type Value = InheritableLints;
1545
1546 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1548 formatter.write_str("a lints table")
1549 }
1550
1551 fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
1555 where
1556 M: de::MapAccess<'de>,
1557 {
1558 let mut lints = TomlLints::new();
1559 let mut workspace = false;
1560
1561 while let Some(key) = access.next_key()? {
1564 if key == "workspace" {
1565 workspace = match access.next_value()? {
1566 Some(WorkspaceValue) => true,
1567 None => false,
1568 };
1569 } else {
1570 let value = access.next_value()?;
1571 lints.insert(key, value);
1572 }
1573 }
1574
1575 Ok(InheritableLints { workspace, lints })
1576 }
1577 }
1578
1579 deserializer.deserialize_map(InheritableLintsVisitor)
1580 }
1581}
1582
1583pub type TomlLints = BTreeMap<String, TomlToolLints>;
1584
1585pub type TomlToolLints = BTreeMap<String, TomlLint>;
1586
1587#[derive(Serialize, Debug, Clone)]
1588#[serde(untagged)]
1589#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1590pub enum TomlLint {
1591 Level(TomlLintLevel),
1592 Config(TomlLintConfig),
1593}
1594
1595impl<'de> Deserialize<'de> for TomlLint {
1596 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1597 where
1598 D: de::Deserializer<'de>,
1599 {
1600 UntaggedEnumVisitor::new()
1601 .string(|string| {
1602 TomlLintLevel::deserialize(string.into_deserializer()).map(TomlLint::Level)
1603 })
1604 .map(|map| map.deserialize().map(TomlLint::Config))
1605 .deserialize(deserializer)
1606 }
1607}
1608
1609impl TomlLint {
1610 pub fn level(&self) -> TomlLintLevel {
1611 match self {
1612 Self::Level(level) => *level,
1613 Self::Config(config) => config.level,
1614 }
1615 }
1616
1617 pub fn priority(&self) -> i8 {
1618 match self {
1619 Self::Level(_) => 0,
1620 Self::Config(config) => config.priority,
1621 }
1622 }
1623
1624 pub fn config(&self) -> Option<&toml::Table> {
1625 match self {
1626 Self::Level(_) => None,
1627 Self::Config(config) => Some(&config.config),
1628 }
1629 }
1630}
1631
1632#[derive(Serialize, Deserialize, Debug, Clone)]
1633#[serde(rename_all = "kebab-case")]
1634#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1635pub struct TomlLintConfig {
1636 pub level: TomlLintLevel,
1637 #[serde(default)]
1638 pub priority: i8,
1639 #[serde(flatten)]
1640 #[cfg_attr(
1641 feature = "unstable-schema",
1642 schemars(with = "HashMap<String, TomlValueWrapper>")
1643 )]
1644 pub config: toml::Table,
1645}
1646
1647#[derive(Serialize, Deserialize, Debug, Copy, Clone, Eq, PartialEq)]
1648#[serde(rename_all = "kebab-case")]
1649#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1650pub enum TomlLintLevel {
1651 Forbid,
1652 Deny,
1653 Warn,
1654 Allow,
1655}
1656
1657#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1658#[serde(rename_all = "kebab-case")]
1659#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1660pub struct Hints {
1661 #[cfg_attr(
1662 feature = "unstable-schema",
1663 schemars(with = "Option<TomlValueWrapper>")
1664 )]
1665 pub mostly_unused: Option<toml::Value>,
1666}
1667
1668#[derive(Copy, Clone, Debug)]
1669pub struct InvalidCargoFeatures {}
1670
1671impl<'de> de::Deserialize<'de> for InvalidCargoFeatures {
1672 fn deserialize<D>(_d: D) -> Result<Self, D::Error>
1673 where
1674 D: de::Deserializer<'de>,
1675 {
1676 use serde::de::Error as _;
1677
1678 Err(D::Error::custom(
1679 "the field `cargo-features` should be set at the top of Cargo.toml before any tables",
1680 ))
1681 }
1682}
1683
1684#[derive(Clone, Debug, Serialize, Eq, PartialEq, PartialOrd, Ord)]
1687#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1688pub struct StringOrVec(pub Vec<String>);
1689
1690impl StringOrVec {
1691 pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, String> {
1692 self.0.iter()
1693 }
1694}
1695
1696impl<'de> de::Deserialize<'de> for StringOrVec {
1697 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1698 where
1699 D: de::Deserializer<'de>,
1700 {
1701 UntaggedEnumVisitor::new()
1702 .expecting("string or list of strings")
1703 .string(|value| Ok(StringOrVec(vec![value.to_owned()])))
1704 .seq(|value| value.deserialize().map(StringOrVec))
1705 .deserialize(deserializer)
1706 }
1707}
1708
1709#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
1710#[serde(untagged)]
1711#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1712pub enum StringOrBool {
1713 String(String),
1714 Bool(bool),
1715}
1716
1717impl<'de> Deserialize<'de> for StringOrBool {
1718 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1719 where
1720 D: de::Deserializer<'de>,
1721 {
1722 UntaggedEnumVisitor::new()
1723 .bool(|b| Ok(StringOrBool::Bool(b)))
1724 .string(|s| Ok(StringOrBool::String(s.to_owned())))
1725 .deserialize(deserializer)
1726 }
1727}
1728
1729#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
1730#[serde(untagged)]
1731#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1732pub enum TomlPackageBuild {
1733 Auto(bool),
1736
1737 SingleScript(String),
1739
1740 MultipleScript(Vec<String>),
1742}
1743
1744impl<'de> Deserialize<'de> for TomlPackageBuild {
1745 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1746 where
1747 D: de::Deserializer<'de>,
1748 {
1749 UntaggedEnumVisitor::new()
1750 .bool(|b| Ok(TomlPackageBuild::Auto(b)))
1751 .string(|s| Ok(TomlPackageBuild::SingleScript(s.to_owned())))
1752 .seq(|value| value.deserialize().map(TomlPackageBuild::MultipleScript))
1753 .deserialize(deserializer)
1754 }
1755}
1756
1757#[derive(PartialEq, Clone, Debug, Serialize)]
1758#[serde(untagged)]
1759#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1760pub enum VecStringOrBool {
1761 VecString(Vec<String>),
1762 Bool(bool),
1763}
1764
1765impl<'de> de::Deserialize<'de> for VecStringOrBool {
1766 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1767 where
1768 D: de::Deserializer<'de>,
1769 {
1770 UntaggedEnumVisitor::new()
1771 .expecting("a boolean or vector of strings")
1772 .bool(|value| Ok(VecStringOrBool::Bool(value)))
1773 .seq(|value| value.deserialize().map(VecStringOrBool::VecString))
1774 .deserialize(deserializer)
1775 }
1776}
1777
1778#[derive(Clone)]
1779pub struct PathValue(pub PathBuf);
1780
1781impl fmt::Debug for PathValue {
1782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1783 self.0.fmt(f)
1784 }
1785}
1786
1787impl ser::Serialize for PathValue {
1788 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1789 where
1790 S: ser::Serializer,
1791 {
1792 self.0.serialize(serializer)
1793 }
1794}
1795
1796impl<'de> de::Deserialize<'de> for PathValue {
1797 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1798 where
1799 D: de::Deserializer<'de>,
1800 {
1801 Ok(PathValue(String::deserialize(deserializer)?.into()))
1802 }
1803}
1804
1805#[derive(Debug, thiserror::Error)]
1807#[error("manifest field was not resolved")]
1808#[non_exhaustive]
1809#[cfg_attr(feature = "unstable-schema", derive(schemars::JsonSchema))]
1810pub struct UnresolvedError;
1811
1812#[cfg(feature = "unstable-schema")]
1813#[test]
1814fn dump_manifest_schema() {
1815 let schema = schemars::schema_for!(crate::manifest::TomlManifest);
1816 let dump = serde_json::to_string_pretty(&schema).unwrap();
1817 snapbox::assert_data_eq!(dump, snapbox::file!("../../manifest.schema.json").raw());
1818}