1use std::collections::{HashSet, VecDeque};
2use std::{borrow::Cow, fmt};
3
4use granit_parser::ScalarStyle;
5use serde_core::de::{self, Deserializer as _, IntoDeserializer, Visitor};
6
7use super::base64::decode_base64_yaml;
8use super::cfg::Cfg;
9#[cfg(feature = "comments")]
10use super::commented_deser;
11use super::error::{Error, MissingFieldLocationGuard, TransformReason};
12use super::events::{
13 Ev, Events, RecordedEvents, ReplayEvents, attach_alias_locations_if_missing, eof_with_loc,
14 with_deferred_recursive_aliases,
15};
16use super::key_nodes::{
17 KeyFingerprint, KeyNode, PendingEntry, apply_duplicate_key_policy_to_entries,
18 capture_node_with_legacy_octal, capture_simple_tagged_node_as_map_events,
19 is_empty_mapping_key_fingerprint, is_merge_key, pending_entries_from_live_events,
20 simple_tagged_enum_name, validate_no_merge_keys_in_node_events,
21};
22#[cfg(feature = "properties")]
23use super::options::PropertySyntax;
24use super::options::{DuplicateKeyPolicy, MergeKeyPolicy, NonFiniteFloatPolicy};
25#[cfg(any(feature = "garde", feature = "validator"))]
26use super::path_map::PathRecorder;
27#[cfg(feature = "properties")]
28use super::properties::{interpolate_compose_style_with_limits, is_sole_unset_reference};
29use super::properties_redaction::{
30 ScalarRedactionCtx, ScalarRedactionGuard, with_interp_redaction_scope,
31};
32use super::spanned_deser;
33use super::tagged_deser;
34use super::tags::SfTag;
35use crate::anchor_store::{self, AnchorKind};
36#[cfg(feature = "properties")]
37use crate::budget::BudgetBreach;
38#[cfg(feature = "properties")]
39use crate::de_error::budget_error;
40use crate::location::Location;
41#[cfg(any(feature = "garde", feature = "validator"))]
42use crate::location::Locations;
43use crate::parse_scalars::{
44 is_signed_nan, leading_zero_decimal, maybe_not_string, parse_int_signed, parse_int_unsigned,
45 parse_yaml11_bool, parse_yaml12_bool, parse_yaml12_float, scalar_is_null, scalar_is_nullish,
46 try_parse_float_incl_overflow, yaml_trim,
47};
48
49struct TupleLenExpected {
50 len: usize,
51}
52
53impl fmt::Display for TupleLenExpected {
54 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55 write!(formatter, "a tuple of size {}", self.len)
56 }
57}
58
59impl de::Expected for TupleLenExpected {
60 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61 fmt::Display::fmt(self, formatter)
62 }
63}
64
65struct TupleLenVisitor<V> {
66 inner: V,
67 len: usize,
68}
69
70impl<'de, V> Visitor<'de> for TupleLenVisitor<V>
71where
72 V: Visitor<'de>,
73{
74 type Value = V::Value;
75
76 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77 self.inner.expecting(formatter)
78 }
79
80 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
81 where
82 A: de::SeqAccess<'de>,
83 {
84 let mut consumed = 0usize;
85 let value = self.inner.visit_seq(CountingSeqAccess {
86 inner: &mut seq,
87 consumed: &mut consumed,
88 })?;
89
90 if seq.next_element::<de::IgnoredAny>()?.is_some() {
91 return Err(<A::Error as de::Error>::invalid_length(
92 consumed + 1,
93 &TupleLenExpected { len: self.len },
94 ));
95 }
96
97 Ok(value)
98 }
99}
100
101struct CountingSeqAccess<'a, A> {
102 inner: &'a mut A,
103 consumed: &'a mut usize,
104}
105
106impl<'de, A> de::SeqAccess<'de> for CountingSeqAccess<'_, A>
107where
108 A: de::SeqAccess<'de>,
109{
110 type Error = A::Error;
111
112 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
113 where
114 T: de::DeserializeSeed<'de>,
115 {
116 let value = self.inner.next_element_seed(seed)?;
117 if value.is_some() {
118 *self.consumed += 1;
119 }
120 Ok(value)
121 }
122
123 fn size_hint(&self) -> Option<usize> {
124 self.inner.size_hint()
125 }
126}
127
128fn skip_one_node_from_events(ev: &mut dyn Events<'_>) -> Result<(), Error> {
129 let mut depth;
130 match ev.next()? {
131 Some(Ev::RecursiveAlias { location, .. }) => {
132 return Err(Error::RecursiveReferencesRequireWeakTypes { location });
133 }
134 Some(Ev::Scalar { .. }) => return Ok(()),
135 Some(Ev::SeqStart { .. } | Ev::MapStart { .. }) => depth = 1usize,
136 Some(Ev::SeqEnd { location } | Ev::MapEnd { location }) => {
137 return Err(Error::UnexpectedContainerEndWhileSkippingNode { location });
138 }
139 Some(Ev::Taken { location }) => {
140 return Err(Error::unexpected("consumed event").with_location(location));
141 }
142 None => return Err(eof_with_loc(ev)),
143 }
144
145 while depth != 0 {
146 match ev.next()? {
147 Some(Ev::RecursiveAlias { location, .. }) => {
148 return Err(Error::RecursiveReferencesRequireWeakTypes { location });
149 }
150 Some(Ev::SeqStart { .. } | Ev::MapStart { .. }) => depth += 1,
151 Some(Ev::SeqEnd { .. } | Ev::MapEnd { .. }) => depth -= 1,
152 Some(Ev::Scalar { .. }) => {}
153 Some(Ev::Taken { location }) => {
154 return Err(Error::unexpected("consumed event").with_location(location));
155 }
156 None => return Err(eof_with_loc(ev)),
157 }
158 }
159
160 Ok(())
161}
162
163fn drain_remaining_sequence(ev: &mut dyn Events<'_>) -> Result<(), Error> {
164 loop {
165 match ev.peek()? {
166 Some(Ev::SeqEnd { .. }) => {
167 let _ = ev.next()?;
168 return Ok(());
169 }
170 Some(_) => skip_one_node_from_events(ev)?,
171 None => return Err(eof_with_loc(ev)),
172 }
173 }
174}
175
176fn remembers_seen_keys(cfg: &Cfg) -> bool {
179 !matches!(cfg.dup_policy, DuplicateKeyPolicy::PassThrough)
180 || cfg.merge_keys == MergeKeyPolicy::Merge
181}
182
183fn is_serde_content_buffer<V>() -> bool {
190 let name = std::any::type_name::<V>();
191 let bare_name = name
194 .split_once('<')
195 .map_or(name, |(bare_name, _)| bare_name);
196 name.contains("::private::de::") && bare_name.ends_with("::ContentVisitor")
197}
198
199pub struct YamlDeserializer<'de, 'e> {
241 pub(super) ev: &'e mut dyn Events<'de>,
242 pub(super) cfg: Cfg,
243 in_key: bool,
245 struct_mode: bool,
250 key_empty_map_node: bool,
252 pub(super) pending_comments: Vec<Cow<'de, str>>,
254 pub(super) pending_value_separator_comments: Vec<Cow<'de, str>>,
256 pub(super) pending_value_comments: Vec<Cow<'de, str>>,
258
259 #[cfg(any(feature = "garde", feature = "validator"))]
260 pub(super) garde: Option<&'e mut PathRecorder>,
261}
262
263#[derive(Clone)]
264struct ScalarView<'de> {
265 raw: Cow<'de, str>,
266 effective: Cow<'de, str>,
267 tag: SfTag,
268 style: ScalarStyle,
269 location: Location,
270 interpolated: bool,
271}
272
273type EffectiveScalar<'de> = (Cow<'de, str>, SfTag, ScalarStyle, Location);
274
275impl<'de> ScalarView<'de> {
276 fn redaction_ctx(&self) -> Option<ScalarRedactionCtx> {
277 self.interpolated.then(|| ScalarRedactionCtx {
278 raw: self.raw.as_ref().to_owned(),
279 effective: self.effective.as_ref().to_owned(),
280 })
281 }
282
283 fn into_string_value(self, null_as_string: bool) -> Cow<'de, str> {
286 if null_as_string
289 && !self.interpolated
290 && self.style == ScalarStyle::Plain
291 && self.raw == "~"
292 && self.location.span().is_empty()
293 {
294 Cow::Borrowed("")
295 } else {
296 self.effective
297 }
298 }
299}
300
301fn with_scalar_redaction<T>(
302 ctx: Option<ScalarRedactionCtx>,
303 f: impl FnOnce() -> Result<T, Error>,
304) -> Result<T, Error> {
305 let _guard = ctx.map(ScalarRedactionGuard::new);
306 f()
307}
308
309fn with_subtree_redaction<T>(
316 ctx: Option<ScalarRedactionCtx>,
317 f: impl FnOnce() -> Result<T, Error>,
318) -> Result<T, Error> {
319 with_interp_redaction_scope(|| with_scalar_redaction(ctx, f))
320}
321
322#[cfg(feature = "properties")]
323pub(crate) fn with_root_redaction<'de, 'e, T>(
324 mut de: YamlDeserializer<'de, 'e>,
325 f: impl FnOnce(YamlDeserializer<'de, 'e>) -> Result<T, Error>,
326) -> Result<T, Error> {
327 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
328 with_subtree_redaction(redaction_ctx, || f(de))
329}
330
331#[cfg(not(feature = "properties"))]
332pub(crate) fn with_root_redaction<'de, 'e, T>(
333 de: YamlDeserializer<'de, 'e>,
334 f: impl FnOnce(YamlDeserializer<'de, 'e>) -> Result<T, Error>,
335) -> Result<T, Error> {
336 f(de)
337}
338
339#[cfg_attr(not(feature = "properties"), allow(unused_mut))]
344pub(crate) fn with_root_redaction_unless_null<'de, 'e, T>(
345 mut de: YamlDeserializer<'de, 'e>,
346 f: impl FnOnce(YamlDeserializer<'de, 'e>) -> Result<T, Error>,
347) -> Result<Option<T>, Error> {
348 if let Some(Ev::Scalar {
349 value, tag, style, ..
350 }) = de.ev.peek()?
351 {
352 let keep_tagged = *tag == SfTag::Other;
353 if !keep_tagged && scalar_is_null(tag, value, style) {
354 let _ = de.ev.next()?;
355 return Ok(None);
356 }
357
358 #[cfg(feature = "properties")]
359 {
360 let (tag, style) = (*tag, *style);
361 if de.interpolation_possible(tag, style) {
362 let Some(view) = de.peek_scalar_view()? else {
363 return Err(eof_with_loc(de.ev));
364 };
365 if !keep_tagged
366 && de.ev.property_interpolation().syntax()
367 == PropertySyntax::DockerComposeWithNulls
368 && view.tag == SfTag::Null
369 {
370 let _ = de.ev.next()?;
371 return Ok(None);
372 }
373 return with_subtree_redaction(view.redaction_ctx(), || f(de)).map(Some);
374 }
375 }
376 }
377
378 with_root_redaction(de, f).map(Some)
379}
380
381struct EnumScalarId<'de> {
382 raw: Cow<'de, str>,
383 effective: Cow<'de, str>,
384 interpolated: bool,
385 location: Location,
386}
387
388impl<'de> EnumScalarId<'de> {
389 fn from_view(view: ScalarView<'de>) -> Self {
390 Self {
391 raw: view.raw,
392 effective: view.effective,
393 interpolated: view.interpolated,
394 location: view.location,
395 }
396 }
397
398 fn redaction_ctx(&self) -> Option<ScalarRedactionCtx> {
399 self.interpolated.then(|| ScalarRedactionCtx {
400 raw: self.raw.as_ref().to_owned(),
401 effective: self.effective.as_ref().to_owned(),
402 })
403 }
404}
405
406impl<'de> IntoDeserializer<'de, Error> for EnumScalarId<'de> {
407 type Deserializer = Self;
408
409 fn into_deserializer(self) -> Self::Deserializer {
410 self
411 }
412}
413
414impl<'de> de::Deserializer<'de> for EnumScalarId<'de> {
415 type Error = Error;
416
417 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
418 where
419 V: Visitor<'de>,
420 {
421 self.deserialize_identifier(visitor)
422 }
423
424 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
425 where
426 V: Visitor<'de>,
427 {
428 let ctx = self.redaction_ctx();
429 let location = self.location;
430 let effective = self.effective;
431 with_scalar_redaction(ctx, move || match effective {
432 Cow::Borrowed(value) => visitor.visit_borrowed_str(value),
433 Cow::Owned(value) => visitor.visit_string(value),
434 })
435 .map_err(|err| err.with_location(location))
436 }
437
438 serde_core::forward_to_deserialize_any! {
439 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
440 option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum
441 ignored_any
442 }
443}
444
445impl<'de, 'e> YamlDeserializer<'de, 'e> {
446 fn validate_scalar_tag(
452 &self,
453 tag: SfTag,
454 expected: SfTag,
455 ty: &'static str,
456 location: Location,
457 ) -> Result<(), Error> {
458 let compatible = tag == expected
459 || match tag {
460 SfTag::None
461 | SfTag::Other
462 | SfTag::Include
463 | SfTag::Merge
464 | SfTag::Value
465 | SfTag::NonSpecific => true,
466 tag if tag.is_robotics() => {
467 expected == SfTag::Float
468 && cfg!(feature = "robotics")
469 && self.cfg.angle_conversions
470 }
471 _ => false,
472 };
473 if compatible {
474 Ok(())
475 } else {
476 Err(Error::InvalidScalar { ty, location })
477 }
478 }
479
480 pub(crate) fn new(ev: &'e mut dyn Events<'de>, cfg: Cfg) -> Self {
492 Self {
493 ev,
494 cfg,
495 in_key: false,
496 struct_mode: false,
497 key_empty_map_node: false,
498 pending_comments: Vec::new(),
499 pending_value_separator_comments: Vec::new(),
500 pending_value_comments: Vec::new(),
501
502 #[cfg(any(feature = "garde", feature = "validator"))]
503 garde: None,
504 }
505 }
506
507 fn quoting_required_for_scalar(view: &ScalarView<'de>) -> Error {
508 Error::quoting_required(view.raw.as_ref(), view.interpolated).with_location(view.location)
509 }
510
511 #[cfg(feature = "properties")]
512 fn interpolation_possible(&self, tag: SfTag, style: ScalarStyle) -> bool {
513 if self.in_key || tag == SfTag::Binary {
514 return false;
515 }
516
517 let properties = self.ev.property_interpolation();
518 if properties.property_map().is_none() {
519 return false;
520 }
521
522 match properties.syntax() {
523 syntax if syntax.is_docker_compose() => tag.can_parse_into_string(),
524 _ => style == ScalarStyle::Plain,
525 }
526 }
527
528 #[cfg(not(feature = "properties"))]
529 fn interpolation_possible(&self, _tag: SfTag, _style: ScalarStyle) -> bool {
530 false
531 }
532
533 #[cfg(feature = "properties")]
534 fn peek_scalar_redaction_ctx(&mut self) -> Result<Option<ScalarRedactionCtx>, Error> {
535 let Some((tag, style)) = (match self.ev.peek()? {
536 Some(Ev::Scalar { tag, style, .. }) => Some((*tag, *style)),
537 _ => None,
538 }) else {
539 return Ok(None);
540 };
541
542 if !self.interpolation_possible(tag, style) {
543 return Ok(None);
544 }
545
546 Ok(self
547 .peek_scalar_view()?
548 .and_then(|view| view.redaction_ctx()))
549 }
550
551 #[cfg(not(feature = "properties"))]
552 fn peek_scalar_redaction_ctx(&mut self) -> Result<Option<ScalarRedactionCtx>, Error> {
553 Ok(None)
554 }
555
556 #[cfg(any(feature = "garde", feature = "validator"))]
557 pub(crate) fn new_with_path_recorder(
558 ev: &'e mut dyn Events<'de>,
559 cfg: Cfg,
560 garde: &'e mut PathRecorder,
561 ) -> Self {
562 Self {
563 ev,
564 cfg,
565 in_key: false,
566 struct_mode: false,
567 key_empty_map_node: false,
568 pending_comments: Vec::new(),
569 pending_value_separator_comments: Vec::new(),
570 pending_value_comments: Vec::new(),
571 garde: Some(garde),
572 }
573 }
574
575 fn take_scalar_event(&mut self) -> Result<(String, SfTag, Location), Error> {
584 let view = self.take_scalar_view()?;
585 Ok((view.effective.into_owned(), view.tag, view.location))
586 }
587
588 fn take_scalar_cow_event(&mut self) -> Result<(Cow<'de, str>, SfTag, Location), Error> {
593 let view = self.take_scalar_view()?;
594 Ok((view.effective, view.tag, view.location))
595 }
596
597 fn take_scalar_view(&mut self) -> Result<ScalarView<'de>, Error> {
598 match self.ev.next()? {
599 Some(Ev::Scalar {
600 value,
601 tag,
602 style,
603 location,
604 ..
605 }) => self.scalar_view_from_parts(value, tag, style, location),
606 Some(other) => Err(Error::unexpected("string scalar").with_location(other.location())),
607 None => Err(eof_with_loc(self.ev)),
608 }
609 }
610
611 fn take_peeked_scalar_view(&mut self, view: ScalarView<'de>) -> Result<ScalarView<'de>, Error> {
612 match self.ev.next()? {
613 Some(Ev::Scalar { .. }) => Ok(view),
614 Some(other) => Err(Error::unexpected("string scalar").with_location(other.location())),
615 None => Err(eof_with_loc(self.ev)),
616 }
617 }
618
619 fn take_string_scalar(&mut self) -> Result<String, Error> {
624 let (value, tag, location) = self.take_scalar_event()?;
625
626 if tag == SfTag::Binary && !self.cfg.ignore_binary_tag_for_string {
628 let data = decode_base64_yaml(&value).map_err(|err| err.with_location(location))?;
629 let text = String::from_utf8(data).map_err(|_| Error::BinaryNotUtf8 { location })?;
630 return Ok(text);
631 }
632
633 if !(tag.can_parse_into_string()
635 || self.cfg.ignore_binary_tag_for_string && tag == SfTag::Binary)
636 {
637 return Err(Error::TaggedScalarCannotDeserializeIntoString { location });
638 }
639
640 Ok(value)
641 }
642
643 fn visit_typeless_float<V: Visitor<'de>>(
645 &self,
646 value: f64,
647 raw: String,
648 location: Location,
649 visitor: V,
650 ) -> Result<V::Value, Error> {
651 if value.is_finite() {
652 return visitor.visit_f64(value);
653 }
654 match self.cfg.non_finite_float_policy {
655 NonFiniteFloatPolicy::PassThrough => visitor.visit_f64(value),
656 NonFiniteFloatPolicy::Default | NonFiniteFloatPolicy::Reject => {
659 Err(Error::NonFiniteFloat {
660 value: raw,
661 location,
662 })
663 }
664 NonFiniteFloatPolicy::AsString => {
665 let canonical = if value.is_nan() {
666 ".nan"
667 } else if value.is_sign_negative() {
668 "-.inf"
669 } else {
670 ".inf"
671 };
672 visitor.visit_string(canonical.to_owned())
673 }
674 }
675 }
676
677 fn expect_seq_start(&mut self) -> Result<(), Error> {
679 match self.ev.next()? {
680 Some(Ev::SeqStart { .. }) => Ok(()),
681 Some(other) => Err(Error::unexpected("sequence start").with_location(other.location())),
682 None => Err(eof_with_loc(self.ev)),
683 }
684 }
685
686 fn expect_map_start(&mut self) -> Result<(), Error> {
688 match self.ev.next()? {
689 Some(Ev::MapStart { .. }) => Ok(()),
690 Some(other) => Err(Error::unexpected("mapping start").with_location(other.location())),
691 None => Err(eof_with_loc(self.ev)),
692 }
693 }
694
695 fn peek_effective_scalar(&mut self) -> Result<Option<EffectiveScalar<'de>>, Error> {
696 let Some(view) = self.peek_scalar_view()? else {
697 return Ok(None);
698 };
699 Ok(Some((view.effective, view.tag, view.style, view.location)))
700 }
701
702 pub(super) fn peek_null_value(&mut self) -> Result<bool, Error> {
707 match self.ev.peek()? {
708 Some(Ev::Scalar {
709 value, tag, style, ..
710 }) => {
711 if scalar_is_null(tag, value, style) {
712 return Ok(true);
713 }
714
715 #[cfg(feature = "properties")]
716 {
717 let (tag, style) = (*tag, *style);
718 if self.ev.property_interpolation().syntax()
719 == PropertySyntax::DockerComposeWithNulls
720 && !tag.forces_string()
721 && self.interpolation_possible(tag, style)
722 {
723 return Ok(self
724 .peek_scalar_view()?
725 .is_some_and(|view| view.tag == SfTag::Null));
726 }
727 }
728
729 Ok(false)
730 }
731 _ => Ok(false),
732 }
733 }
734
735 fn peek_scalar_view(&mut self) -> Result<Option<ScalarView<'de>>, Error> {
736 let (value, tag, style, location) = match self.ev.peek()? {
737 Some(Ev::Scalar {
738 value,
739 tag,
740 style,
741 location,
742 ..
743 }) => (value.clone(), *tag, *style, *location),
744 _ => return Ok(None),
745 };
746
747 Ok(Some(
748 self.scalar_view_from_parts(value, tag, style, location)?,
749 ))
750 }
751
752 fn scalar_view_from_parts(
753 &self,
754 raw: Cow<'de, str>,
755 tag: SfTag,
756 style: ScalarStyle,
757 location: Location,
758 ) -> Result<ScalarView<'de>, Error> {
759 let can_interpolate = self.interpolation_possible(tag, style);
760 let effective = if can_interpolate {
761 self.effective_scalar_value(raw.clone(), location)?
762 } else {
763 raw.clone()
764 };
765 let interpolated = can_interpolate && raw.as_ref() != effective.as_ref();
766 #[cfg(feature = "properties")]
767 let tag = if interpolated {
768 self.compose_expansion_tag(&raw, &effective, tag)
769 } else {
770 tag
771 };
772 Ok(ScalarView {
773 raw,
774 effective,
775 tag,
776 style,
777 location,
778 interpolated,
779 })
780 }
781
782 #[cfg(feature = "properties")]
793 fn compose_expansion_tag(&self, raw: &str, effective: &str, tag: SfTag) -> SfTag {
794 let properties = self.ev.property_interpolation();
795 let syntax = properties.syntax();
796 if !syntax.is_docker_compose() || !tag.can_parse_into_string() || tag.forces_string() {
797 return tag;
798 }
799 let becomes_null = syntax == PropertySyntax::DockerComposeWithNulls
800 && (matches!(effective, "~" | "null" | "Null" | "NULL")
801 || properties
802 .property_map()
803 .is_some_and(|vars| is_sole_unset_reference(raw, vars, syntax)));
804 if becomes_null {
805 SfTag::Null
806 } else {
807 SfTag::NonSpecific
808 }
809 }
810
811 #[cfg(feature = "properties")]
813 fn effective_scalar_value(
814 &self,
815 value: Cow<'de, str>,
816 location: Location,
817 ) -> Result<Cow<'de, str>, Error> {
818 let properties = self.ev.property_interpolation();
819 let Some(vars) = properties.property_map() else {
820 return Ok(value);
821 };
822 let vars = vars.as_ref();
823 let syntax = properties.syntax();
824
825 match interpolate_compose_style_with_limits(
826 value,
827 vars,
828 syntax,
829 properties.max_expansion_depth(),
830 properties.max_total_work(),
831 properties.total_work(),
832 ) {
833 Ok(value) => Ok(value),
834 Err(crate::properties::PropertyError::Unresolved(name)) => {
835 Err(Error::UnresolvedProperty { name, location })
836 }
837 Err(crate::properties::PropertyError::InvalidName(name)) => {
838 Err(Error::InvalidPropertyName { name, location })
839 }
840 Err(crate::properties::PropertyError::RequiredButUnset { name, message }) => {
841 Err(Error::PropertyRequiredButUnset {
842 name,
843 message,
844 location,
845 })
846 }
847 Err(crate::properties::PropertyError::RequiredButEmpty { name, message }) => {
848 Err(Error::PropertyRequiredButEmpty {
849 name,
850 message,
851 location,
852 })
853 }
854 Err(crate::properties::PropertyError::ExpansionDepthLimitExceeded {
855 depth,
856 max_depth,
857 }) => {
858 let breach = BudgetBreach::PropertyExpansionDepth { depth, max_depth };
859 properties.record_breach(breach.clone());
860 Err(budget_error(breach).with_location(location))
861 }
862 Err(crate::properties::PropertyError::ExpansionWorkLimitExceeded {
863 work,
864 max_work,
865 }) => {
866 let breach = BudgetBreach::PropertyInterpolationWork { work, max_work };
867 properties.record_breach(breach.clone());
868 Err(budget_error(breach).with_location(location))
869 }
870 }
871 }
872
873 #[cfg(not(feature = "properties"))]
874 fn effective_scalar_value(
875 &self,
876 value: Cow<'de, str>,
877 _location: Location,
878 ) -> Result<Cow<'de, str>, Error> {
879 Ok(value)
880 }
881
882 fn peek_anchor_id(&mut self) -> Result<Option<usize>, Error> {
884 match self.ev.peek()? {
885 Some(
886 Ev::Scalar { anchor, .. }
887 | Ev::SeqStart { anchor, .. }
888 | Ev::MapStart { anchor, .. },
889 ) => {
890 if *anchor == 0 {
891 Ok(None)
892 } else {
893 Ok(Some(*anchor))
894 }
895 }
896 _ => Ok(None),
897 }
898 }
899}
900
901impl<'de> de::Deserializer<'de> for YamlDeserializer<'de, '_> {
902 type Error = Error;
903
904 fn deserialize_any<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
935 if is_serde_content_buffer::<V>()
939 && let Some(events) = capture_simple_tagged_node_as_map_events(self.ev)?
940 {
941 let mut replay = ReplayEvents::new(
942 events,
943 #[cfg(feature = "properties")]
944 self.ev.property_interpolation().clone(),
945 );
946 return YamlDeserializer::new(&mut replay, self.cfg).deserialize_map(visitor);
947 }
948
949 if let Some((value, tag, style, location)) = self.peek_effective_scalar()? {
950 match tag {
953 SfTag::Null => {
954 let _ = self.take_scalar_event()?;
955 return visitor.visit_unit();
956 }
957 SfTag::Bool => return self.deserialize_bool(visitor),
958 SfTag::Int if yaml_trim(&value).starts_with('-') => {
959 return self.deserialize_i64(visitor);
960 }
961 SfTag::Int => return self.deserialize_u64(visitor),
962 SfTag::Float | SfTag::Time | SfTag::Degrees | SfTag::Radians => {
963 self.validate_scalar_tag(tag, SfTag::Float, "floating point", location)?;
964 let view = self.take_scalar_view()?;
965 let value = try_parse_float_incl_overflow(
966 &view.effective,
967 view.location,
968 view.tag,
969 self.cfg.angle_conversions,
970 )
971 .ok_or(Error::InvalidScalar {
972 ty: "floating point",
973 location: view.location,
974 })?;
975 return self.visit_typeless_float(
976 value,
977 view.raw.into_owned(),
978 view.location,
979 visitor,
980 );
981 }
982 _ => {}
983 }
984 let is_plain = matches!(style, ScalarStyle::Plain);
985 if scalar_is_null(&tag, &value, &style) {
987 let _ = self.ev.next()?; return visitor.visit_unit();
989 }
990 if !is_plain
991 || !tag.can_parse_into_string()
992 || tag == SfTag::Binary
993 || tag.forces_string()
994 {
995 if tag == SfTag::Binary && !self.cfg.ignore_binary_tag_for_string {
999 return visitor.visit_string(self.take_string_scalar()?);
1000 }
1001 if !(tag.can_parse_into_string()
1002 || self.cfg.ignore_binary_tag_for_string && tag == SfTag::Binary)
1003 {
1004 return Err(Error::TaggedScalarCannotDeserializeIntoString { location });
1005 }
1006
1007 let (cow, _tag2, _location) = self.take_scalar_cow_event()?;
1008 return match cow {
1009 Cow::Borrowed(b) => visitor.visit_borrowed_str(b),
1010 Cow::Owned(s) => visitor.visit_string(s),
1011 };
1012 }
1013
1014 let view = self.take_scalar_view()?;
1017 let effective = view.effective;
1018 let location = view.location;
1019
1020 if self.cfg.strict_booleans {
1022 if let Some(b) = parse_yaml12_bool(&effective) {
1023 return visitor.visit_bool(b);
1024 }
1025 } else if let Some(b) = parse_yaml11_bool(&effective) {
1026 return visitor.visit_bool(b);
1027 }
1028
1029 let t = yaml_trim(&effective);
1030 let unsigned = t.strip_prefix(['+', '-']).unwrap_or(t);
1033 let uppercase_radix = matches!(unsigned.as_bytes(), [b'0', b'X' | b'O' | b'B', ..]);
1034 if uppercase_radix
1035 || is_signed_nan(t)
1036 || (self.cfg.leading_zero_numbers_as_strings && leading_zero_decimal(t))
1037 || (self.cfg.underscored_numbers_as_strings && t.contains('_'))
1038 {
1039 return match effective {
1040 Cow::Borrowed(b) => visitor.visit_borrowed_str(b),
1041 Cow::Owned(s) => visitor.visit_string(s),
1042 };
1043 }
1044
1045 if t.starts_with('-') {
1047 if (!leading_zero_decimal(t) || self.cfg.legacy_octal_numbers)
1048 && let Ok(v) =
1049 parse_int_signed::<i64>(t, "i64", location, self.cfg.legacy_octal_numbers)
1050 {
1051 return visitor.visit_i64(v);
1052 }
1053 } else {
1054 if let Ok(v) =
1055 parse_int_unsigned::<u64>(t, "u64", location, self.cfg.legacy_octal_numbers)
1056 {
1057 return visitor.visit_u64(v);
1058 }
1059 }
1060
1061 if let Some(v) = try_parse_float_incl_overflow(
1064 &effective,
1065 location,
1066 view.tag,
1067 self.cfg.angle_conversions,
1068 ) {
1069 return self.visit_typeless_float(v, view.raw.into_owned(), location, visitor);
1070 }
1071
1072 return match effective {
1075 Cow::Borrowed(b) => visitor.visit_borrowed_str(b),
1076 Cow::Owned(s) => visitor.visit_string(s),
1077 };
1078 }
1079
1080 match self.ev.peek()? {
1081 Some(Ev::SeqStart { .. }) => self.deserialize_seq(visitor),
1082 Some(Ev::MapStart { .. }) => self.deserialize_map(visitor),
1083 Some(Ev::RecursiveAlias { location, .. }) => {
1084 Err(Error::RecursiveReferencesRequireWeakTypes {
1085 location: *location,
1086 })
1087 }
1088 Some(Ev::SeqEnd { location }) => Err(Error::UnexpectedSequenceEnd {
1089 location: *location,
1090 }),
1091 Some(Ev::MapEnd { location }) => Err(Error::UnexpectedMappingEnd {
1092 location: *location,
1093 }),
1094 None => {
1095 visitor.visit_unit()
1098 }
1099 Some(Ev::Taken { location }) => {
1100 Err(Error::unexpected("consumed event").with_location(*location))
1101 }
1102 Some(Ev::Scalar { location, .. }) => {
1103 Err(Error::unexpected("scalar").with_location(*location))
1104 }
1105 }
1106 }
1107
1108 fn deserialize_bool<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1113 let (s, tag, location) = self.take_scalar_cow_event()?;
1114 self.validate_scalar_tag(tag, SfTag::Bool, "boolean", location)?;
1115 let s = s.as_ref();
1116 let b: bool = if self.cfg.strict_booleans {
1117 parse_yaml12_bool(s).ok_or(Error::InvalidBooleanStrict { location })?
1118 } else {
1119 parse_yaml11_bool(s).ok_or(Error::InvalidScalar {
1120 ty: "boolean",
1121 location,
1122 })?
1123 };
1124 visitor.visit_bool(b)
1125 }
1126
1127 fn deserialize_i8<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1129 let (s, tag, location) = self.take_scalar_cow_event()?;
1130 self.validate_scalar_tag(tag, SfTag::Int, "i8", location)?;
1131 let v: i8 = parse_int_signed(s.as_ref(), "i8", location, self.cfg.legacy_octal_numbers)?;
1132 visitor.visit_i8(v)
1133 }
1134 fn deserialize_i16<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1136 let (s, tag, location) = self.take_scalar_cow_event()?;
1137 self.validate_scalar_tag(tag, SfTag::Int, "i16", location)?;
1138 let v: i16 = parse_int_signed(s.as_ref(), "i16", location, self.cfg.legacy_octal_numbers)?;
1139 visitor.visit_i16(v)
1140 }
1141 fn deserialize_i32<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1143 let (s, tag, location) = self.take_scalar_cow_event()?;
1144 self.validate_scalar_tag(tag, SfTag::Int, "i32", location)?;
1145 let v: i32 = parse_int_signed(s.as_ref(), "i32", location, self.cfg.legacy_octal_numbers)?;
1146 visitor.visit_i32(v)
1147 }
1148 fn deserialize_i64<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1150 let (s, tag, location) = self.take_scalar_cow_event()?;
1151 self.validate_scalar_tag(tag, SfTag::Int, "i64", location)?;
1152 let v: i64 = parse_int_signed(s.as_ref(), "i64", location, self.cfg.legacy_octal_numbers)?;
1153 visitor.visit_i64(v)
1154 }
1155 fn deserialize_i128<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1157 let (s, tag, location) = self.take_scalar_cow_event()?;
1158 self.validate_scalar_tag(tag, SfTag::Int, "i128", location)?;
1159 let v: i128 =
1160 parse_int_signed(s.as_ref(), "i128", location, self.cfg.legacy_octal_numbers)?;
1161 visitor.visit_i128(v)
1162 }
1163
1164 fn deserialize_u8<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1166 let (s, tag, location) = self.take_scalar_cow_event()?;
1167 self.validate_scalar_tag(tag, SfTag::Int, "u8", location)?;
1168 let v: u8 = parse_int_unsigned(s.as_ref(), "u8", location, self.cfg.legacy_octal_numbers)?;
1169 visitor.visit_u8(v)
1170 }
1171 fn deserialize_u16<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1173 let (s, tag, location) = self.take_scalar_cow_event()?;
1174 self.validate_scalar_tag(tag, SfTag::Int, "u16", location)?;
1175 let v: u16 =
1176 parse_int_unsigned(s.as_ref(), "u16", location, self.cfg.legacy_octal_numbers)?;
1177 visitor.visit_u16(v)
1178 }
1179 fn deserialize_u32<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1181 let (s, tag, location) = self.take_scalar_cow_event()?;
1182 self.validate_scalar_tag(tag, SfTag::Int, "u32", location)?;
1183 let v: u32 =
1184 parse_int_unsigned(s.as_ref(), "u32", location, self.cfg.legacy_octal_numbers)?;
1185 visitor.visit_u32(v)
1186 }
1187 fn deserialize_u64<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1189 let (s, tag, location) = self.take_scalar_cow_event()?;
1190 self.validate_scalar_tag(tag, SfTag::Int, "u64", location)?;
1191 let v: u64 =
1192 parse_int_unsigned(s.as_ref(), "u64", location, self.cfg.legacy_octal_numbers)?;
1193 visitor.visit_u64(v)
1194 }
1195 fn deserialize_u128<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1197 let (s, tag, location) = self.take_scalar_cow_event()?;
1198 self.validate_scalar_tag(tag, SfTag::Int, "u128", location)?;
1199 let v: u128 =
1200 parse_int_unsigned(s.as_ref(), "u128", location, self.cfg.legacy_octal_numbers)?;
1201 visitor.visit_u128(v)
1202 }
1203
1204 fn deserialize_f32<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1206 let (s, tag, location) = self.take_scalar_cow_event()?;
1207 self.validate_scalar_tag(tag, SfTag::Float, "floating point", location)?;
1208 let v: f32 = parse_yaml12_float(s.as_ref(), location, tag, self.cfg.angle_conversions)?;
1209 visitor.visit_f32(v)
1210 }
1211 fn deserialize_f64<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1213 let (s, tag, location) = self.take_scalar_cow_event()?;
1214 self.validate_scalar_tag(tag, SfTag::Float, "floating point", location)?;
1215 let v: f64 = parse_yaml12_float(s.as_ref(), location, tag, self.cfg.angle_conversions)?;
1216 visitor.visit_f64(v)
1217 }
1218
1219 fn deserialize_char<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1227 if let Some(view) = self.peek_scalar_view()?
1229 && !view.tag.forces_string()
1230 {
1231 if view.tag == SfTag::Null || scalar_is_nullish(&view.effective, &view.style) {
1233 let (_value, _tag, location) = self.take_scalar_event()?;
1234 return Err(Error::InvalidCharNull { location });
1235 } else if self.cfg.no_schema
1236 && maybe_not_string(&view.effective, &view.style, self.cfg.strict_booleans)
1237 {
1238 let view = self.take_scalar_view()?;
1240 return Err(Self::quoting_required_for_scalar(&view));
1241 }
1242 }
1243
1244 let (s, tag, location) = self.take_scalar_cow_event()?;
1246 self.validate_scalar_tag(tag, SfTag::String, "char", location)?;
1247 let mut it = s.as_ref().chars();
1248 match (it.next(), it.next()) {
1249 (Some(c), None) => visitor.visit_char(c),
1250 _ => Err(Error::InvalidCharNotSingleScalar { location }),
1251 }
1252 }
1253
1254 fn deserialize_str<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1267 let view = match self.peek_scalar_view()? {
1268 Some(view) => {
1269 if (view.tag == SfTag::Null
1272 || (!self.cfg.null_as_string
1273 && !view.interpolated
1274 && scalar_is_nullish(&view.effective, &view.style)))
1275 && !view.tag.forces_string()
1276 {
1277 let loc = view.location;
1278 let _ = self.ev.next()?;
1279 return Err(Error::NullIntoString { location: loc });
1280 } else if self.cfg.no_schema
1281 && maybe_not_string(&view.effective, &view.style, self.cfg.strict_booleans)
1282 && !view.tag.forces_string()
1283 {
1284 let view = self.take_scalar_view()?;
1285 return Err(Self::quoting_required_for_scalar(&view));
1286 }
1287
1288 if view.tag == SfTag::Binary && !self.cfg.ignore_binary_tag_for_string {
1289 let res: Result<V::Value, Self::Error> =
1290 visitor.visit_string(self.take_string_scalar()?);
1291 return match res {
1292 Ok(v) => Ok(v),
1293 Err(err) if err.to_string().contains("expected a borrowed string") => Err(
1294 Error::cannot_borrow_transformed(TransformReason::ParserReturnedOwned)
1295 .with_location(view.location),
1296 ),
1297 Err(err) => Err(err),
1298 };
1299 }
1300 if !(view.tag.can_parse_into_string()
1301 || self.cfg.ignore_binary_tag_for_string && view.tag == SfTag::Binary)
1302 {
1303 return Err(Error::TaggedScalarCannotDeserializeIntoString {
1304 location: view.location,
1305 });
1306 }
1307
1308 view
1309 }
1310 None => {
1312 return Err(self
1313 .take_scalar_view()
1314 .err()
1315 .unwrap_or_else(|| eof_with_loc(self.ev)));
1316 }
1317 };
1318
1319 let location = view.location;
1320 let redaction_ctx = view.redaction_ctx();
1321 let cannot_borrow_reason = if view.interpolated {
1322 TransformReason::VariableInterpolation
1323 } else if self.ev.input_for_borrowing().is_none() {
1324 TransformReason::InputNotBorrowable
1325 } else {
1326 TransformReason::ParserReturnedOwned
1327 };
1328
1329 let view = self.take_peeked_scalar_view(view)?;
1330 let value = view.into_string_value(self.cfg.null_as_string);
1331 if let Cow::Borrowed(b) = value {
1332 return visitor.visit_borrowed_str(b);
1333 }
1334
1335 let res: Result<V::Value, Self::Error> =
1336 with_scalar_redaction(redaction_ctx, || visitor.visit_string(value.into_owned()));
1337 match res {
1338 Ok(v) => Ok(v),
1339 Err(err) => {
1340 let msg = err.to_string();
1341 if msg.contains("expected a borrowed string") {
1342 return Err(Error::cannot_borrow_transformed(cannot_borrow_reason)
1343 .with_location(location));
1344 }
1345 Err(err)
1346 }
1347 }
1348 }
1349
1350 fn deserialize_string<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1360 let view = if let Some(view) = self.peek_scalar_view()? {
1362 if (view.tag == SfTag::Null
1365 || (!self.cfg.null_as_string
1366 && !view.interpolated
1367 && scalar_is_nullish(&view.effective, &view.style)))
1368 && !view.tag.forces_string()
1369 {
1370 let (_value, _tag, location) = self.take_scalar_event()?;
1372 return Err(Error::NullIntoString { location });
1373 } else if self.cfg.no_schema
1374 && maybe_not_string(&view.effective, &view.style, self.cfg.strict_booleans)
1375 && !view.tag.forces_string()
1376 {
1377 let view = self.take_scalar_view()?;
1379 return Err(Self::quoting_required_for_scalar(&view));
1380 }
1381 if view.tag == SfTag::Binary && !self.cfg.ignore_binary_tag_for_string {
1382 return visitor.visit_string(self.take_string_scalar()?);
1383 }
1384 if !(view.tag.can_parse_into_string()
1385 || self.cfg.ignore_binary_tag_for_string && view.tag == SfTag::Binary)
1386 {
1387 return Err(Error::TaggedScalarCannotDeserializeIntoString {
1388 location: view.location,
1389 });
1390 }
1391
1392 view
1393 } else {
1394 return visitor.visit_string(self.take_string_scalar()?);
1396 };
1397
1398 let redaction_ctx = view.redaction_ctx();
1399 let view = self.take_peeked_scalar_view(view)?;
1400 match view.into_string_value(self.cfg.null_as_string) {
1401 Cow::Borrowed(b) => {
1402 with_scalar_redaction(redaction_ctx, || visitor.visit_borrowed_str(b))
1403 }
1404 Cow::Owned(s) => with_scalar_redaction(redaction_ctx, || visitor.visit_string(s)),
1405 }
1406 }
1407
1408 fn deserialize_bytes<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1414 if let Some((_value, tag, _style, location)) = self.peek_effective_scalar()? {
1415 if tag == SfTag::Binary {
1416 let (value, data_location) = match self.ev.next()? {
1417 Some(Ev::Scalar {
1418 value, location, ..
1419 }) => (value, location),
1420 Some(other) => {
1421 return Err(
1422 Error::unexpected("binary scalar").with_location(other.location())
1423 );
1424 }
1425 None => return Err(eof_with_loc(self.ev)),
1426 };
1427 let data =
1428 decode_base64_yaml(&value).map_err(|err| err.with_location(data_location))?;
1429 return visitor.visit_byte_buf(data);
1430 }
1431 return Err(Error::BytesNotSupportedMissingBinaryTag { location });
1432 }
1433
1434 match self.ev.peek()? {
1435 Some(Ev::SeqStart { .. }) => {
1437 self.expect_seq_start()?;
1438 let mut out = Vec::new();
1439 loop {
1440 match self.ev.peek()? {
1441 Some(Ev::SeqEnd { .. }) => {
1442 let _ = self.ev.next()?; break;
1444 }
1445 Some(_) => {
1446 let b: u8 = <u8 as serde_core::Deserialize>::deserialize(
1448 YamlDeserializer::new(&mut *self.ev, self.cfg),
1449 )?;
1450 out.push(b);
1451 }
1452 None => return Err(eof_with_loc(self.ev)),
1453 }
1454 }
1455 visitor.visit_byte_buf(out)
1456 }
1457
1458 Some(other) => Err(
1460 Error::unexpected("scalar (!!binary) or sequence of 0..=255")
1461 .with_location(other.location()),
1462 ),
1463 None => Err(eof_with_loc(self.ev)),
1464 }
1465 }
1466
1467 fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
1469 self.deserialize_bytes(visitor)
1470 }
1471
1472 fn deserialize_option<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1479 if self.in_key && self.key_empty_map_node {
1484 match self.ev.next()? {
1486 Some(Ev::MapStart { .. }) => {}
1487 Some(other) => {
1488 return Err(
1489 Error::unexpected("empty mapping start").with_location(other.location())
1490 );
1491 }
1492 None => return Err(eof_with_loc(self.ev)),
1493 }
1494 match self.ev.next()? {
1495 Some(Ev::MapEnd { .. }) => {}
1496 Some(other) => {
1497 return Err(
1498 Error::unexpected("empty mapping end").with_location(other.location())
1499 );
1500 }
1501 None => return Err(eof_with_loc(self.ev)),
1502 }
1503 return visitor.visit_none();
1504 }
1505
1506 if let Some((value, tag, style, _location)) = self.peek_effective_scalar()?
1507 && scalar_is_null(&tag, &value, &style)
1508 {
1509 let _ = self.ev.next()?; return visitor.visit_none();
1511 }
1512
1513 match self.ev.peek()? {
1514 None | Some(Ev::MapEnd { .. } | Ev::SeqEnd { .. }) => visitor.visit_none(),
1516
1517 Some(_) => visitor.visit_some(self),
1519 }
1520 }
1521
1522 fn deserialize_unit<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1530 if let Some((value, tag, style, _location)) = self.peek_effective_scalar()?
1531 && scalar_is_null(&tag, &value, &style)
1532 {
1533 let _ = self.ev.next()?; return visitor.visit_unit();
1535 }
1536
1537 match self.ev.peek()? {
1538 None | Some(Ev::MapEnd { .. } | Ev::SeqEnd { .. }) => visitor.visit_unit(),
1540 Some(other) => Err(Error::UnexpectedValueForUnit {
1542 location: other.location(),
1543 }),
1544 }
1545 }
1546
1547 fn deserialize_unit_struct<V: Visitor<'de>>(
1556 self,
1557 _name: &'static str,
1558 visitor: V,
1559 ) -> Result<V::Value, Self::Error> {
1560 match self.ev.peek()? {
1561 Some(Ev::MapStart { .. }) => {
1563 let _ = self.ev.next()?; match self.ev.peek()? {
1565 Some(Ev::MapEnd { .. }) => {
1566 let _ = self.ev.next()?; visitor.visit_unit()
1568 }
1569 Some(other) => Err(Error::ExpectedEmptyMappingForUnitStruct {
1570 location: other.location(),
1571 }),
1572 None => Err(eof_with_loc(self.ev)),
1573 }
1574 }
1575 _ => self.deserialize_unit(visitor),
1577 }
1578 }
1579
1580 fn deserialize_newtype_struct<V: Visitor<'de>>(
1590 mut self,
1591 n: &'static str,
1592 visitor: V,
1593 ) -> Result<V::Value, Self::Error> {
1594 match n {
1595 "__yaml_spanned" => spanned_deser::deserialize_yaml_spanned(self, visitor),
1597 #[cfg(feature = "comments")]
1598 "__yaml_commented" => commented_deser::deserialize_yaml_commented(self, visitor),
1599 "__yaml_tagged" => tagged_deser::deserialize_yaml_tagged(self, visitor),
1600 "__yaml_rc_anchor" => {
1601 let anchor = self.peek_anchor_id()?;
1602 anchor_store::with_anchor_context(AnchorKind::Rc, anchor, || {
1603 visitor.visit_newtype_struct(self)
1604 })
1605 }
1606 "__yaml_arc_anchor" => {
1607 let anchor = self.peek_anchor_id()?;
1608 anchor_store::with_anchor_context(AnchorKind::Arc, anchor, || {
1609 visitor.visit_newtype_struct(self)
1610 })
1611 }
1612 "__yaml_rc_recursive" => {
1613 let anchor = self.peek_anchor_id()?;
1614 anchor_store::with_anchor_context(AnchorKind::RcRecursive, anchor, || {
1615 visitor.visit_newtype_struct(self)
1616 })
1617 }
1618 "__yaml_arc_recursive" => {
1619 let anchor = self.peek_anchor_id()?;
1620 anchor_store::with_anchor_context(AnchorKind::ArcRecursive, anchor, || {
1621 visitor.visit_newtype_struct(self)
1622 })
1623 }
1624 "__yaml_rc_weak_anchor" => {
1625 let anchor = self.peek_anchor_id()?;
1626 anchor_store::with_anchor_context(AnchorKind::Rc, anchor, || {
1627 visitor.visit_newtype_struct(self)
1628 })
1629 }
1630 "__yaml_arc_weak_anchor" => {
1631 let anchor = self.peek_anchor_id()?;
1632 anchor_store::with_anchor_context(AnchorKind::Arc, anchor, || {
1633 visitor.visit_newtype_struct(self)
1634 })
1635 }
1636 "__yaml_rc_recursion" => {
1637 let anchor = self.peek_anchor_id()?;
1638 anchor_store::with_anchor_context(AnchorKind::RcRecursive, anchor, || {
1639 visitor.visit_newtype_struct(self)
1640 })
1641 }
1642 "__yaml_arc_recursion" => {
1643 let anchor = self.peek_anchor_id()?;
1644 anchor_store::with_anchor_context(AnchorKind::ArcRecursive, anchor, || {
1645 visitor.visit_newtype_struct(self)
1646 })
1647 }
1648 _ => visitor.visit_newtype_struct(self),
1649 }
1650 }
1651
1652 fn deserialize_seq<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1659 if self.ev.take_empty_stream()? {
1660 return visitor.visit_seq(de::value::SeqDeserializer::<_, Error>::new(
1661 std::iter::empty::<()>(),
1662 ));
1663 }
1664 if let Some((_, SfTag::Binary, _, _)) = self.peek_effective_scalar()? {
1665 let (scalar, data_location) = match self.ev.next()? {
1666 Some(Ev::Scalar {
1667 value, location, ..
1668 }) => (value, location),
1669 Some(other) => {
1670 return Err(Error::unexpected("binary scalar").with_location(other.location()));
1671 }
1672 None => return Err(eof_with_loc(self.ev)),
1673 };
1674 let data =
1675 decode_base64_yaml(&scalar).map_err(|err| err.with_location(data_location))?;
1676 struct ByteSeq {
1678 data: Vec<u8>,
1679 idx: usize,
1680 }
1681 impl<'de> de::SeqAccess<'de> for ByteSeq {
1682 type Error = Error;
1683 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1684 where
1685 T: de::DeserializeSeed<'de>,
1686 {
1687 if self.idx >= self.data.len() {
1688 return Ok(None);
1689 }
1690 let b = self.data[self.idx];
1691 self.idx += 1;
1692 let deser = serde_core::de::value::U8Deserializer::<Error>::new(b);
1693 seed.deserialize(deser).map(Some)
1694 }
1695 }
1696 return visitor.visit_seq(ByteSeq { data, idx: 0 });
1697 }
1698 let mut seq_start_comments = std::mem::take(&mut self.pending_value_comments);
1703 seq_start_comments.extend(self.ev.take_leading_comments_for_next_node()?);
1704 let seq_location = match self.ev.peek()? {
1705 Some(ev) => ev.location(),
1706 None => self.ev.last_location(),
1707 };
1708 let child_cfg = self.cfg.enter_container(seq_location)?;
1709 self.expect_seq_start()?;
1710 struct SA<'de, 'e> {
1712 ev: &'e mut dyn Events<'de>,
1713 cfg: Cfg,
1714 pending_first_element_comments: Vec<Cow<'de, str>>,
1715
1716 #[cfg(any(feature = "garde", feature = "validator"))]
1717 garde: Option<&'e mut PathRecorder>,
1718 #[cfg(any(feature = "garde", feature = "validator"))]
1719 idx: usize,
1720 }
1721 impl<'de> de::SeqAccess<'de> for SA<'de, '_> {
1722 type Error = Error;
1723 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error>
1725 where
1726 T: de::DeserializeSeed<'de>,
1727 {
1728 let (is_end, defined_location) = {
1729 let peeked = self.ev.peek()?;
1730 match peeked {
1731 Some(Ev::SeqEnd { .. }) => (true, Location::UNKNOWN),
1732 Some(ev) => (false, ev.location()),
1733 None => return Err(eof_with_loc(self.ev)),
1734 }
1735 };
1736
1737 if is_end {
1738 return Ok(None);
1739 }
1740
1741 let reference_location = self.ev.reference_location();
1743 let alias_reference_location = self.ev.alias_reference_location();
1744 let _missing_field_guard = MissingFieldLocationGuard::new(reference_location);
1745 let mut item_comments = std::mem::take(&mut self.pending_first_element_comments);
1746 item_comments.extend(self.ev.take_leading_comments_for_next_node()?);
1747 let value_separator_comments = self
1748 .ev
1749 .take_separator_comments_before_sequence_item_value()?;
1750
1751 #[cfg(any(feature = "garde", feature = "validator"))]
1752 {
1753 if let Some(garde_ref) = self.garde.as_mut() {
1754 let recorder: &mut PathRecorder = garde_ref;
1755
1756 let prev = recorder.current.take();
1757 let now = prev.clone().join(self.idx);
1758 recorder.current = now.clone();
1759 recorder.map.insert(
1760 now,
1761 Locations {
1762 reference_location,
1763 defined_location,
1764 },
1765 );
1766
1767 let mut de =
1768 YamlDeserializer::new_with_path_recorder(self.ev, self.cfg, recorder);
1769 de.pending_comments = item_comments;
1770 de.pending_value_separator_comments = value_separator_comments;
1771 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
1772 let res = with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
1773 .map(Some)
1774 .map_err(|e| {
1775 attach_alias_locations_if_missing(
1776 e,
1777 alias_reference_location,
1778 defined_location,
1779 )
1780 });
1781
1782 recorder.current = prev;
1783 self.idx += 1;
1784 return res;
1785 }
1786 }
1787
1788 let mut de = YamlDeserializer::new(self.ev, self.cfg);
1789 de.pending_comments = item_comments;
1790 de.pending_value_separator_comments = value_separator_comments;
1791 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
1792 with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
1793 .map(Some)
1794 .map_err(|e| {
1795 attach_alias_locations_if_missing(
1796 e,
1797 alias_reference_location,
1798 defined_location,
1799 )
1800 })
1801 }
1802 }
1803
1804 #[cfg(any(feature = "garde", feature = "validator"))]
1805 let garde = self.garde;
1806
1807 let result = visitor.visit_seq(SA {
1808 ev: self.ev,
1809 cfg: child_cfg,
1810 pending_first_element_comments: seq_start_comments,
1811
1812 #[cfg(any(feature = "garde", feature = "validator"))]
1813 garde,
1814 #[cfg(any(feature = "garde", feature = "validator"))]
1815 idx: 0,
1816 })?;
1817 drain_remaining_sequence(self.ev)?;
1818 Ok(result)
1819 }
1820
1821 fn deserialize_tuple<V: Visitor<'de>>(
1823 self,
1824 len: usize,
1825 visitor: V,
1826 ) -> Result<V::Value, Self::Error> {
1827 self.deserialize_seq(TupleLenVisitor {
1828 inner: visitor,
1829 len,
1830 })
1831 }
1832
1833 fn deserialize_tuple_struct<V: Visitor<'de>>(
1835 self,
1836 _name: &'static str,
1837 len: usize,
1838 visitor: V,
1839 ) -> Result<V::Value, Self::Error> {
1840 self.deserialize_seq(TupleLenVisitor {
1841 inner: visitor,
1842 len,
1843 })
1844 }
1845
1846 fn deserialize_map<V: Visitor<'de>>(mut self, visitor: V) -> Result<V::Value, Self::Error> {
1856 if self.ev.take_empty_stream()? {
1857 struct EmptyMap {
1858 location: Location,
1859 }
1860 impl<'de> de::MapAccess<'de> for EmptyMap {
1861 type Error = Error;
1862
1863 fn next_key_seed<K>(&mut self, _seed: K) -> Result<Option<K::Value>, Error>
1864 where
1865 K: de::DeserializeSeed<'de>,
1866 {
1867 Ok(None)
1868 }
1869
1870 fn next_value_seed<V>(&mut self, _seed: V) -> Result<V::Value, Error>
1871 where
1872 V: de::DeserializeSeed<'de>,
1873 {
1874 Err(Error::ValueRequestedBeforeKey {
1875 location: self.location,
1876 })
1877 }
1878 }
1879 return visitor.visit_map(EmptyMap {
1880 location: self.ev.last_location(),
1881 });
1882 }
1883 let _map_node_comments = std::mem::take(&mut self.pending_value_separator_comments);
1887 let mut map_start_comments = std::mem::take(&mut self.pending_value_comments);
1892 map_start_comments.extend(self.ev.take_leading_comments_for_next_node()?);
1893 let map_location = match self.ev.peek()? {
1894 Some(ev) => ev.location(),
1895 None => self.ev.last_location(),
1896 };
1897 let map_reference_location = self.ev.reference_location();
1898 let child_cfg = self.cfg.enter_container(map_location)?;
1899 self.expect_map_start()?;
1900
1901 let _missing_field_guard = MissingFieldLocationGuard::new(map_reference_location);
1904
1905 #[cfg(any(feature = "garde", feature = "validator"))]
1906 if let Some(recorder) = self.garde.as_mut() {
1907 let path = recorder.current.clone();
1910 recorder.map.insert(
1911 path,
1912 Locations {
1913 reference_location: map_reference_location,
1914 defined_location: map_location,
1915 },
1916 );
1917 }
1918
1919 fn collect_last_wins_entries<'de>(
1920 ev: &mut dyn Events<'de>,
1921 mut first_key_comments: Vec<Cow<'de, str>>,
1922 cfg: Cfg,
1923 mut first_key: Option<KeyNode<'de>>,
1924 prior_seen: &HashSet<KeyFingerprint<'de>>,
1925 mut merge_batches: VecDeque<Vec<PendingEntry<'de>>>,
1926 ) -> Result<VecDeque<PendingEntry<'de>>, Error> {
1927 with_deferred_recursive_aliases(ev, |ev| {
1928 let mut explicit_entries = Vec::new();
1929
1930 loop {
1931 let (key, field_comments) = if let Some(key) = first_key.take() {
1932 (key, std::mem::take(&mut first_key_comments))
1933 } else {
1934 match ev.peek()? {
1935 Some(Ev::MapEnd { .. }) => {
1936 let _ = ev.next()?;
1937 break;
1938 }
1939 Some(_) => {
1940 let mut key_comments = std::mem::take(&mut first_key_comments);
1941 key_comments.extend(ev.take_leading_comments_for_next_node()?);
1942 let key =
1943 capture_node_with_legacy_octal(ev, cfg.legacy_octal_numbers)?;
1944 (key, key_comments)
1945 }
1946 None => return Err(eof_with_loc(ev)),
1947 }
1948 };
1949
1950 if is_merge_key(&key) {
1951 match cfg.merge_keys {
1952 MergeKeyPolicy::Merge => {
1953 let _ = ev.peek()?;
1954 let merge_ref_loc = ev.reference_location();
1955 let entries =
1956 pending_entries_from_live_events(ev, merge_ref_loc, cfg)?;
1957 if !entries.is_empty() {
1958 merge_batches.push_back(entries);
1959 }
1960 continue;
1961 }
1962 MergeKeyPolicy::AsOrdinary => {}
1963 MergeKeyPolicy::Error => {
1964 return Err(Error::MergeKeyNotAllowed {
1965 location: key.location(),
1966 });
1967 }
1968 }
1969 }
1970
1971 if cfg.reject_tagged_field_names {
1972 key.validate_field_name_tag()?;
1973 }
1974 let value_separator_comments =
1975 ev.take_separator_comments_before_mapping_value()?;
1976 let value_comments = ev.take_leading_comments_for_next_node()?;
1977 let _ = ev.peek()?;
1980 let reference_location = ev.reference_location();
1981 let value = capture_node_with_legacy_octal(ev, cfg.legacy_octal_numbers)?;
1982 explicit_entries.push(PendingEntry {
1983 key,
1984 value,
1985 reference_location,
1986 field_comments,
1987 value_separator_comments,
1988 value_comments,
1989 });
1990 }
1991
1992 let mut explicit_entries = apply_duplicate_key_policy_to_entries(
1993 explicit_entries,
1994 cfg.dup_policy,
1995 cfg.merge_keys,
1996 )?;
1997 let mut seen = prior_seen.clone();
1998 seen.reserve(explicit_entries.len());
1999 for entry in &explicit_entries {
2000 seen.insert(entry.key.fingerprint().into_owned());
2001 }
2002
2003 let mut merge_entries = Vec::new();
2004 for batch in merge_batches {
2005 for entry in batch {
2006 let fingerprint = entry.key.fingerprint().into_owned();
2007 if seen.insert(fingerprint) {
2008 merge_entries.push(entry);
2009 }
2010 }
2011 }
2012
2013 explicit_entries.extend(merge_entries);
2014 Ok(explicit_entries.into_iter().collect())
2015 })
2016 }
2017
2018 struct MA<'de, 'e> {
2020 ev: &'e mut dyn Events<'de>,
2021 cfg: Cfg,
2022 struct_mode: bool,
2023 have_key: bool,
2024
2025 fallback_guard: Option<MissingFieldLocationGuard>,
2029
2030 #[cfg(any(feature = "garde", feature = "validator"))]
2031 garde: Option<&'e mut PathRecorder>,
2032 #[cfg(any(feature = "garde", feature = "validator"))]
2033 pending_path_segment: Option<String>,
2034
2035 seen: HashSet<KeyFingerprint<'de>>,
2037 pending: VecDeque<PendingEntry<'de>>,
2038 merge_stack: VecDeque<Vec<PendingEntry<'de>>>,
2039 flushing_merges: bool,
2040 live_done: bool,
2041 pending_value: Option<Box<(RecordedEvents<'de>, Location)>>,
2042 pending_field_comments: Vec<Cow<'de, str>>,
2043 pending_value_separator_comments: Vec<Cow<'de, str>>,
2044 pending_value_comments: Vec<Cow<'de, str>>,
2045 pending_first_key_comments: Vec<Cow<'de, str>>,
2046 }
2047
2048 impl<'de> MA<'de, '_> {
2049 fn skip_one_node(&mut self) -> Result<(), Error> {
2054 if self.cfg.merge_keys == MergeKeyPolicy::Error {
2055 let node =
2056 capture_node_with_legacy_octal(self.ev, self.cfg.legacy_octal_numbers)?;
2057 return validate_no_merge_keys_in_node_events(node.events());
2058 }
2059
2060 let mut depth; match self.ev.next()? {
2062 Some(Ev::RecursiveAlias { location, .. }) => {
2063 return Err(Error::RecursiveReferencesRequireWeakTypes { location });
2064 }
2065 Some(Ev::Scalar { .. }) => return Ok(()),
2066 Some(Ev::SeqStart { .. } | Ev::MapStart { .. }) => depth = 1,
2067 Some(Ev::SeqEnd { location } | Ev::MapEnd { location }) => {
2068 return Err(Error::UnexpectedContainerEndWhileSkippingNode { location });
2069 }
2070 Some(Ev::Taken { location }) => {
2071 return Err(Error::unexpected("consumed event").with_location(location));
2072 }
2073 None => return Err(eof_with_loc(self.ev)),
2074 }
2075 while depth != 0 {
2076 match self.ev.next()? {
2077 Some(Ev::RecursiveAlias { location, .. }) => {
2078 return Err(Error::RecursiveReferencesRequireWeakTypes { location });
2079 }
2080 Some(Ev::SeqStart { .. } | Ev::MapStart { .. }) => depth += 1,
2081 Some(Ev::SeqEnd { .. } | Ev::MapEnd { .. }) => depth -= 1,
2082 Some(Ev::Scalar { .. }) => {}
2083 Some(Ev::Taken { location }) => {
2084 return Err(Error::unexpected("consumed event").with_location(location));
2085 }
2086 None => return Err(eof_with_loc(self.ev)),
2087 }
2088 }
2089 Ok(())
2090 }
2091
2092 fn validate_skipped_node(&self, node: &KeyNode<'_>) -> Result<(), Error> {
2093 if self.cfg.merge_keys == MergeKeyPolicy::Error {
2094 validate_no_merge_keys_in_node_events(node.events())?;
2095 }
2096 Ok(())
2097 }
2098
2099 fn deserialize_recorded_key<'de2, K>(
2105 &mut self,
2106 seed: K,
2107 events: RecordedEvents<'de2>,
2108 kemn: bool,
2109 ) -> Result<K::Value, Error>
2110 where
2111 K: de::DeserializeSeed<'de2>,
2112 {
2113 let mut replay = ReplayEvents::new(
2114 events,
2115 #[cfg(feature = "properties")]
2116 self.ev.property_interpolation().for_key(),
2117 );
2118
2119 let location = replay.reference_location();
2121
2122 let de = YamlDeserializer::<'de2, '_> {
2123 ev: &mut replay,
2124 cfg: self.cfg,
2125 in_key: true,
2126 struct_mode: false,
2127 key_empty_map_node: kemn,
2128 pending_comments: Vec::new(),
2129 pending_value_separator_comments: Vec::new(),
2130 pending_value_comments: Vec::new(),
2131
2132 #[cfg(any(feature = "garde", feature = "validator"))]
2133 garde: None,
2134 };
2135 seed.deserialize(de).map_err(|e| {
2136 if e.location().is_none() {
2137 e.with_location(location)
2138 } else {
2139 e
2140 }
2141 })
2142 }
2143
2144 fn enqueue_entries(&mut self, entries: Vec<PendingEntry<'de>>) {
2146 self.pending.reserve(entries.len());
2147 for entry in entries.into_iter().rev() {
2148 self.pending.push_front(entry);
2149 }
2150 }
2151
2152 fn enqueue_next_merge_batch(&mut self) -> bool {
2154 while let Some(entries) = self.merge_stack.pop_front() {
2155 if entries.is_empty() {
2156 continue;
2157 }
2158 self.enqueue_entries(entries);
2159 return true;
2160 }
2161 false
2162 }
2163
2164 fn finish(&mut self) -> Result<(), Error> {
2170 if self.have_key {
2171 return Err(
2172 Error::unexpected("mapping end").with_location(self.ev.last_location())
2173 );
2174 }
2175
2176 if de::MapAccess::next_key::<de::IgnoredAny>(self)?.is_some() {
2177 return Err(
2178 Error::unexpected("mapping end").with_location(self.ev.last_location())
2179 );
2180 }
2181
2182 Ok(())
2183 }
2184 }
2185
2186 impl<'de> de::MapAccess<'de> for MA<'de, '_> {
2187 type Error = Error;
2188
2189 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error>
2191 where
2192 K: de::DeserializeSeed<'de>,
2193 {
2194 let mut seed = Some(seed);
2195
2196 loop {
2197 if let Some(entry) = self.pending.pop_front() {
2198 let PendingEntry {
2199 mut key,
2200 mut value,
2201 reference_location,
2202 field_comments,
2203 value_separator_comments,
2204 value_comments,
2205 } = entry;
2206 let fingerprint = key.take_fingerprint();
2207 let location = key.location();
2208
2209 let is_duplicate = self.seen.contains(&fingerprint);
2210 if self.flushing_merges {
2211 if is_duplicate {
2212 self.validate_skipped_node(&value)?;
2213 continue;
2214 }
2215 } else {
2216 match self.cfg.dup_policy {
2217 DuplicateKeyPolicy::Error => {
2218 if is_duplicate {
2219 let key = key.stringy_scalar_value().map(|s| s.to_owned());
2220 return Err(Error::DuplicateMappingKey { key, location });
2221 }
2222 }
2223 DuplicateKeyPolicy::FirstWins => {
2224 if is_duplicate {
2225 self.validate_skipped_node(&value)?;
2226 continue;
2227 }
2228 }
2229 DuplicateKeyPolicy::LastWins | DuplicateKeyPolicy::PassThrough => {}
2230 }
2231 }
2232
2233 #[cfg(any(feature = "garde", feature = "validator"))]
2234 let key_path_segment = key.stringy_scalar_value().map(ToOwned::to_owned);
2235 let events = key.take_events();
2236 let value_events = value.take_events();
2237 let kemn = is_empty_mapping_key_fingerprint(&fingerprint);
2238 let Some(key_seed) = seed.take() else {
2239 return Err(Error::InternalSeedReusedForMapKey { location });
2240 };
2241
2242 match &mut self.fallback_guard {
2247 Some(guard) => guard.replace_location(location),
2248 None => {
2249 self.fallback_guard =
2250 Some(MissingFieldLocationGuard::new(location));
2251 }
2252 }
2253
2254 let key_value = self.deserialize_recorded_key(key_seed, events, kemn)?;
2255 self.have_key = true;
2256 self.pending_field_comments = field_comments;
2257 self.pending_value_separator_comments = value_separator_comments;
2258 self.pending_value_comments = value_comments;
2259 self.pending_value = Some(Box::new((value_events, reference_location)));
2260
2261 #[cfg(any(feature = "garde", feature = "validator"))]
2262 {
2263 self.pending_path_segment = key_path_segment;
2264 }
2265
2266 if remembers_seen_keys(&self.cfg) {
2267 self.seen.insert(fingerprint);
2268 }
2269 return Ok(Some(key_value));
2270 }
2271
2272 if self.live_done {
2273 return Ok(None);
2274 }
2275
2276 if self.flushing_merges {
2277 if self.enqueue_next_merge_batch() {
2278 continue;
2279 }
2280 self.flushing_merges = false;
2281 self.live_done = true;
2282 return Ok(None);
2283 }
2284
2285 match self.ev.peek()? {
2286 Some(Ev::MapEnd { .. }) => {
2287 let _ = self.ev.next()?; if self.merge_stack.is_empty() {
2289 self.live_done = true;
2290 return Ok(None);
2291 }
2292 self.flushing_merges = true;
2293 if self.enqueue_next_merge_batch() {
2294 continue;
2295 }
2296 self.flushing_merges = false;
2297 self.live_done = true;
2298 return Ok(None);
2299 }
2300 Some(_) => {
2301 let mut key_comments =
2302 std::mem::take(&mut self.pending_first_key_comments);
2303 key_comments.extend(self.ev.take_leading_comments_for_next_node()?);
2304 let mut key_node = capture_node_with_legacy_octal(
2305 self.ev,
2306 self.cfg.legacy_octal_numbers,
2307 )?;
2308 if is_merge_key(&key_node) {
2309 match self.cfg.merge_keys {
2310 MergeKeyPolicy::Merge => {
2311 let _ = self.ev.peek()?;
2316 let merge_ref_loc = self.ev.reference_location();
2317 let entries = pending_entries_from_live_events(
2318 self.ev,
2319 merge_ref_loc,
2320 Cfg {
2321 reject_tagged_field_names: self.struct_mode
2322 && self.cfg.reject_tagged_field_names,
2323 ..self.cfg
2324 },
2325 )?;
2326 if !entries.is_empty() {
2327 self.merge_stack.push_back(entries);
2328 }
2329 continue;
2330 }
2331 MergeKeyPolicy::AsOrdinary => {}
2332 MergeKeyPolicy::Error => {
2333 return Err(Error::MergeKeyNotAllowed {
2334 location: key_node.location(),
2335 });
2336 }
2337 }
2338 }
2339
2340 if self.struct_mode && self.cfg.reject_tagged_field_names {
2341 key_node.validate_field_name_tag()?;
2342 }
2343
2344 if matches!(self.cfg.dup_policy, DuplicateKeyPolicy::LastWins)
2345 && key_node.fingerprint().contains_integer()
2346 {
2347 self.pending = collect_last_wins_entries(
2350 self.ev,
2351 key_comments,
2352 Cfg {
2353 reject_tagged_field_names: self.struct_mode
2354 && self.cfg.reject_tagged_field_names,
2355 ..self.cfg
2356 },
2357 Some(key_node),
2358 &self.seen,
2359 std::mem::take(&mut self.merge_stack),
2360 )?;
2361 self.live_done = true;
2362 continue;
2363 }
2364
2365 let fingerprint = key_node.fingerprint();
2366 let is_duplicate = self.seen.contains(&fingerprint);
2367 match self.cfg.dup_policy {
2368 DuplicateKeyPolicy::Error => {
2369 if is_duplicate {
2370 let location = key_node.location();
2371 let key =
2372 key_node.stringy_scalar_value().map(|s| s.to_owned());
2373 return Err(Error::DuplicateMappingKey { key, location });
2374 }
2375 }
2376 DuplicateKeyPolicy::FirstWins => {
2377 if is_duplicate {
2378 self.skip_one_node()?;
2379 continue;
2380 }
2381 }
2382 DuplicateKeyPolicy::LastWins | DuplicateKeyPolicy::PassThrough => {}
2383 }
2384
2385 let kemn_direct =
2386 is_empty_mapping_key_fingerprint(fingerprint.as_ref());
2387 let fingerprint =
2389 remembers_seen_keys(&self.cfg).then(|| fingerprint.into_owned());
2390 let location = key_node.location();
2391 #[cfg(any(feature = "garde", feature = "validator"))]
2392 let key_path_segment =
2393 key_node.stringy_scalar_value().map(ToOwned::to_owned);
2394 let events = key_node.take_events();
2395 let Some(key_seed) = seed.take() else {
2396 return Err(Error::InternalSeedReusedForMapKey { location });
2397 };
2398
2399 match &mut self.fallback_guard {
2403 Some(guard) => guard.replace_location(location),
2404 None => {
2405 self.fallback_guard =
2406 Some(MissingFieldLocationGuard::new(location));
2407 }
2408 }
2409
2410 let key_value =
2411 self.deserialize_recorded_key(key_seed, events, kemn_direct)?;
2412 self.have_key = true;
2413 self.pending_field_comments = key_comments;
2414 self.pending_value = None; #[cfg(any(feature = "garde", feature = "validator"))]
2417 {
2418 self.pending_path_segment = key_path_segment;
2419 }
2420
2421 if let Some(fingerprint) = fingerprint {
2422 self.seen.insert(fingerprint);
2423 }
2424 return Ok(Some(key_value));
2425 }
2426 None => return Err(eof_with_loc(self.ev)),
2427 }
2428 }
2429 }
2430
2431 fn next_value_seed<Vv>(&mut self, seed: Vv) -> Result<Vv::Value, Error>
2433 where
2434 Vv: de::DeserializeSeed<'de>,
2435 {
2436 if !self.have_key {
2437 return Err(Error::ValueRequestedBeforeKey {
2438 location: self.ev.last_location(),
2439 });
2440 }
2441 self.have_key = false;
2442
2443 #[cfg(any(feature = "garde", feature = "validator"))]
2444 let pending_segment = self.pending_path_segment.take();
2445
2446 let field_comments = std::mem::take(&mut self.pending_field_comments);
2447 let mut value_separator_comments =
2448 std::mem::take(&mut self.pending_value_separator_comments);
2449 let mut value_comments = std::mem::take(&mut self.pending_value_comments);
2450
2451 if let Some(events) = self.pending_value.take() {
2452 let (events, fallback_reference_location) = *events;
2453 let mut replay = ReplayEvents::new(
2456 events,
2457 #[cfg(feature = "properties")]
2458 self.ev.property_interpolation().clone(),
2459 );
2460
2461 let defined_location = match replay.peek()? {
2464 Some(ev) => ev.location(),
2465 None => replay.last_location(),
2466 };
2467 let alias_reference_location = replay.alias_reference_location();
2468 #[cfg(any(feature = "garde", feature = "validator"))]
2469 let reference_location = if defined_location == Location::UNKNOWN {
2470 fallback_reference_location
2471 } else {
2472 replay.reference_location()
2473 };
2474 #[cfg(not(any(feature = "garde", feature = "validator")))]
2475 let _ = fallback_reference_location;
2476
2477 #[cfg(any(feature = "garde", feature = "validator"))]
2478 {
2479 if let (Some(seg), Some(garde_ref)) = (pending_segment, self.garde.as_mut())
2480 {
2481 let recorder: &mut PathRecorder = garde_ref;
2482
2483 let prev = recorder.current.take();
2484 let now = prev.clone().join(seg.as_str());
2485 recorder.current = now.clone();
2486 recorder.map.insert(
2487 now,
2488 Locations {
2489 reference_location,
2490 defined_location,
2491 },
2492 );
2493
2494 let mut de = YamlDeserializer::new_with_path_recorder(
2495 &mut replay,
2496 self.cfg,
2497 recorder,
2498 );
2499 de.pending_comments = field_comments;
2500 de.pending_value_separator_comments = value_separator_comments;
2501 de.pending_value_comments = value_comments;
2502 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
2503 let res =
2504 with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
2505 .map_err(|e| {
2506 attach_alias_locations_if_missing(
2507 e,
2508 alias_reference_location,
2509 defined_location,
2510 )
2511 });
2512 recorder.current = prev;
2513 return res;
2514 }
2515 }
2516
2517 let mut de = YamlDeserializer::new(&mut replay, self.cfg);
2518 de.pending_comments = field_comments;
2519 de.pending_value_separator_comments = value_separator_comments;
2520 de.pending_value_comments = value_comments;
2521 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
2522 with_subtree_redaction(redaction_ctx, || seed.deserialize(de)).map_err(|e| {
2523 attach_alias_locations_if_missing(
2524 e,
2525 alias_reference_location,
2526 defined_location,
2527 )
2528 })
2529 } else {
2530 value_separator_comments
2531 .extend(self.ev.take_separator_comments_before_mapping_value()?);
2532 value_comments.extend(self.ev.take_leading_comments_for_next_node()?);
2533
2534 let defined_location = match self.ev.peek()? {
2536 Some(ev) => ev.location(),
2537 None => self.ev.last_location(),
2538 };
2539
2540 #[cfg(any(feature = "garde", feature = "validator"))]
2541 let reference_location = self.ev.reference_location();
2542 let alias_reference_location = self.ev.alias_reference_location();
2543
2544 #[cfg(any(feature = "garde", feature = "validator"))]
2545 {
2546 if let (Some(seg), Some(garde_ref)) = (pending_segment, self.garde.as_mut())
2547 {
2548 let recorder: &mut PathRecorder = garde_ref;
2549 let prev = recorder.current.take();
2550 let now = prev.clone().join(seg.as_str());
2551 recorder.current = now.clone();
2552 recorder.map.insert(
2553 now,
2554 Locations {
2555 reference_location,
2556 defined_location,
2557 },
2558 );
2559
2560 let mut de = YamlDeserializer::new_with_path_recorder(
2561 self.ev, self.cfg, recorder,
2562 );
2563 de.pending_comments = field_comments;
2564 de.pending_value_separator_comments = value_separator_comments;
2565 de.pending_value_comments = value_comments;
2566 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
2567 let res =
2568 with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
2569 .map_err(|e| {
2570 attach_alias_locations_if_missing(
2571 e,
2572 alias_reference_location,
2573 defined_location,
2574 )
2575 });
2576 recorder.current = prev;
2577 return res;
2578 }
2579 }
2580
2581 let mut de = YamlDeserializer::new(self.ev, self.cfg);
2582 de.pending_comments = field_comments;
2583 de.pending_value_separator_comments = value_separator_comments;
2584 de.pending_value_comments = value_comments;
2585 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
2586 with_scalar_redaction(redaction_ctx, || seed.deserialize(de)).map_err(|e| {
2587 attach_alias_locations_if_missing(
2588 e,
2589 alias_reference_location,
2590 defined_location,
2591 )
2592 })
2593 }
2594 }
2595 }
2596
2597 let (pending, pending_first_key_comments, live_done) =
2598 if self.struct_mode && matches!(self.cfg.dup_policy, DuplicateKeyPolicy::LastWins) {
2599 (
2600 collect_last_wins_entries(
2601 self.ev,
2602 map_start_comments,
2603 self.cfg,
2604 None,
2605 &HashSet::new(),
2606 VecDeque::new(),
2607 )?,
2608 Vec::new(),
2609 true,
2610 )
2611 } else {
2612 (VecDeque::new(), map_start_comments, false)
2613 };
2614
2615 #[cfg(any(feature = "garde", feature = "validator"))]
2616 let garde = self.garde;
2617
2618 let mut access = MA {
2619 ev: self.ev,
2620 cfg: child_cfg,
2621 struct_mode: self.struct_mode,
2622 have_key: false,
2623
2624 fallback_guard: None,
2625
2626 #[cfg(any(feature = "garde", feature = "validator"))]
2627 garde,
2628 #[cfg(any(feature = "garde", feature = "validator"))]
2629 pending_path_segment: None,
2630
2631 seen: if remembers_seen_keys(&child_cfg) {
2632 HashSet::with_capacity(8)
2633 } else {
2634 HashSet::new()
2635 },
2636 pending,
2637 merge_stack: VecDeque::new(),
2638 flushing_merges: false,
2639 live_done,
2640 pending_value: None,
2641 pending_field_comments: Vec::new(),
2642 pending_value_separator_comments: Vec::new(),
2643 pending_value_comments: Vec::new(),
2644 pending_first_key_comments,
2645 };
2646 let result = visitor.visit_map(&mut access)?;
2647 access.finish()?;
2648 Ok(result)
2649 }
2650
2651 fn deserialize_struct<V: Visitor<'de>>(
2659 self,
2660 _name: &'static str,
2661 _fields: &'static [&'static str],
2662 visitor: V,
2663 ) -> Result<V::Value, Self::Error> {
2664 let mut de = self;
2665 de.struct_mode = true;
2666 de.deserialize_map(visitor)
2667 }
2668
2669 fn deserialize_enum<V: Visitor<'de>>(
2675 mut self,
2676 name: &'static str,
2677 variants: &'static [&'static str],
2678 visitor: V,
2679 ) -> Result<V::Value, Self::Error> {
2680 enum Mode<'de, 'a> {
2681 Unit(EnumScalarId<'de>),
2682 Map(String, Location),
2683 TaggedNewtype(EnumScalarId<'de>, RecordedEvents<'a>),
2685 }
2686
2687 let mut tagged_enum = None;
2688
2689 let peeked_ev = self.ev.peek()?.cloned();
2690 let mode = match peeked_ev {
2691 Some(Ev::RecursiveAlias { location, .. }) => {
2692 return Err(Error::RecursiveReferencesRequireWeakTypes { location });
2693 }
2694 Some(Ev::Scalar {
2695 tag,
2696 style,
2697 value: _,
2698 raw_tag,
2699 location,
2700 ..
2701 }) => {
2702 if let Some(tag_name) = simple_tagged_enum_name(&raw_tag, &tag) {
2703 tagged_enum = Some((tag_name, location));
2704 }
2705 if let Some((ref tag_name, tag_loc)) = tagged_enum
2708 && variants.contains(&tag_name.as_str())
2709 {
2710 let variant_name = EnumScalarId {
2711 raw: Cow::Owned(tag_name.clone()),
2712 effective: Cow::Owned(tag_name.clone()),
2713 interpolated: false,
2714 location: tag_loc,
2715 };
2716 let origin = self.ev.node_origin();
2718 let Some(mut ev) = self.ev.next()? else {
2719 return Err(eof_with_loc(self.ev));
2720 };
2721 ev.strip_node_tag();
2722 let replay = RecordedEvents::from_event(ev, origin);
2723 tagged_enum = None; Mode::TaggedNewtype(variant_name, replay)
2725 } else {
2726 let Some(view) = self.peek_scalar_view()? else {
2727 return Err(eof_with_loc(self.ev));
2728 };
2729 self.validate_scalar_tag(
2730 view.tag,
2731 SfTag::String,
2732 "enum variant",
2733 view.location,
2734 )?;
2735 if self.cfg.no_schema
2736 && !view.tag.forces_string()
2737 && maybe_not_string(&view.effective, &style, self.cfg.strict_booleans)
2738 {
2739 let view = self.take_scalar_view()?;
2740 return Err(Self::quoting_required_for_scalar(&view));
2741 }
2742 let view = self.take_scalar_view()?;
2743 Mode::Unit(EnumScalarId::from_view(view))
2744 }
2745 }
2746 Some(Ev::MapStart {
2747 tag,
2748 raw_tag,
2749 location,
2750 ..
2751 }) => {
2752 let tag_name = simple_tagged_enum_name(&raw_tag, &tag).or_else(|| {
2758 (tag == SfTag::Map && raw_tag.as_deref() == Some("!map"))
2759 .then(|| "map".to_owned())
2760 });
2761 if let Some(tag_name) = tag_name
2762 && variants.contains(&tag_name.as_str())
2763 {
2764 self.ev.strip_peeked_node_tag()?;
2765 return visitor.visit_enum(EA {
2766 ev: self.ev,
2767 cfg: self.cfg,
2768 variant: EnumScalarId {
2769 raw: Cow::Owned(tag_name.clone()),
2770 effective: Cow::Owned(tag_name),
2771 interpolated: false,
2772 location,
2773 },
2774 map_mode: false,
2775 tagged_payload: true,
2776 });
2777 }
2778
2779 self.expect_map_start()?;
2780 let mut key_de = YamlDeserializer::new(&mut *self.ev, self.cfg);
2781 key_de.in_key = true;
2782 if let Some(view) = key_de.peek_scalar_view()? {
2783 key_de.validate_scalar_tag(
2784 view.tag,
2785 SfTag::String,
2786 "enum variant",
2787 view.location,
2788 )?;
2789 if self.cfg.no_schema
2790 && !view.tag.forces_string()
2791 && maybe_not_string(&view.raw, &view.style, self.cfg.strict_booleans)
2792 {
2793 let view = key_de.take_scalar_view()?;
2794 return Err(Self::quoting_required_for_scalar(&view));
2795 }
2796 let view = key_de.take_scalar_view()?;
2797 Mode::Map(view.raw.into_owned(), view.location)
2798 } else {
2799 match self.ev.next()? {
2800 Some(other) => {
2801 return Err(Error::ExpectedStringKeyForExternallyTaggedEnum {
2802 location: other.location(),
2803 });
2804 }
2805 None => return Err(eof_with_loc(self.ev)),
2806 }
2807 }
2808 }
2809 Some(Ev::SeqStart {
2810 tag,
2811 raw_tag,
2812 location,
2813 ..
2814 }) => {
2815 if let Some(tag_name) = simple_tagged_enum_name(&raw_tag, &tag)
2816 && variants.contains(&tag_name.as_str())
2817 {
2818 let origin = self.ev.node_origin();
2820 let Some(seq_start) = self.ev.next()? else {
2821 return Err(eof_with_loc(self.ev));
2822 };
2823 let start_loc = seq_start.location();
2824 let mut replay_events = RecordedEvents::new();
2825 if let Ev::SeqStart {
2827 anchor, location, ..
2828 } = seq_start
2829 {
2830 replay_events.push(
2831 Ev::SeqStart {
2832 anchor,
2833 tag: SfTag::None,
2834 raw_tag: None,
2835 location,
2836 },
2837 origin,
2838 );
2839 }
2840 let mut depth = 1usize;
2841 while depth > 0 {
2842 let _ = self.ev.peek()?;
2843 let origin = self.ev.node_origin();
2844 match self.ev.next()? {
2845 Some(ev @ (Ev::SeqStart { .. } | Ev::MapStart { .. })) => {
2846 depth += 1;
2847 replay_events.push(ev, origin);
2848 }
2849 Some(ev @ (Ev::SeqEnd { .. } | Ev::MapEnd { .. })) => {
2850 depth -= 1;
2851 replay_events.push(ev, origin);
2852 }
2853 Some(ev) => {
2854 replay_events.push(ev, origin);
2855 }
2856 None => return Err(eof_with_loc(self.ev)),
2857 }
2858 }
2859 let replay = Box::new(ReplayEvents::new(
2860 replay_events,
2861 #[cfg(feature = "properties")]
2862 self.ev.property_interpolation().clone(),
2863 ));
2864 return visitor.visit_enum(TaggedEA {
2865 replay,
2866 cfg: self.cfg,
2867 variant: EnumScalarId {
2868 raw: Cow::Owned(tag_name.clone()),
2869 effective: Cow::Owned(tag_name),
2870 interpolated: false,
2871 location: start_loc,
2872 },
2873 });
2874 }
2875 return Err(Error::ExternallyTaggedEnumExpectedScalarOrMapping { location });
2876 }
2877 Some(Ev::SeqEnd { location }) => {
2878 return Err(Error::UnexpectedSequenceEnd { location });
2879 }
2880 Some(Ev::MapEnd { location }) => {
2881 return Err(Error::UnexpectedMappingEnd { location });
2882 }
2883 Some(Ev::Taken { location }) => {
2884 return Err(Error::unexpected("consumed event").with_location(location));
2885 }
2886 None => return Err(eof_with_loc(self.ev)),
2887 };
2888
2889 if let Some((tag_name, location)) = tagged_enum
2890 && tag_name != name
2891 {
2892 return Err(Error::TaggedEnumMismatch {
2893 tagged: tag_name,
2894 target: name,
2895 location,
2896 });
2897 }
2898
2899 struct EA<'de, 'e> {
2900 ev: &'e mut dyn Events<'de>,
2901 cfg: Cfg,
2902 variant: EnumScalarId<'de>,
2903 map_mode: bool,
2904 tagged_payload: bool,
2905 }
2906
2907 impl<'de, 'e> de::EnumAccess<'de> for EA<'de, 'e> {
2908 type Error = Error;
2909 type Variant = VA<'de, 'e>;
2910
2911 fn variant_seed<Vv>(self, seed: Vv) -> Result<(Vv::Value, Self::Variant), Error>
2913 where
2914 Vv: de::DeserializeSeed<'de>,
2915 {
2916 let EA {
2917 ev,
2918 cfg,
2919 variant,
2920 map_mode,
2921 tagged_payload,
2922 } = self;
2923 let v = seed.deserialize(variant.into_deserializer())?;
2924 Ok((
2925 v,
2926 VA {
2927 ev,
2928 cfg,
2929 map_mode,
2930 tagged_payload,
2931 },
2932 ))
2933 }
2934 }
2935
2936 struct VA<'de, 'e> {
2937 ev: &'e mut dyn Events<'de>,
2938 cfg: Cfg,
2939 map_mode: bool,
2940 tagged_payload: bool,
2941 }
2942
2943 impl VA<'_, '_> {
2944 fn expect_map_end(&mut self) -> Result<(), Error> {
2946 match self.ev.next()? {
2947 Some(Ev::MapEnd { .. }) => Ok(()),
2948 Some(other) => Err(Error::ExpectedMappingEndAfterEnumVariantValue {
2949 location: other.location(),
2950 }),
2951 None => Err(eof_with_loc(self.ev)),
2952 }
2953 }
2954 }
2955
2956 impl<'de> de::VariantAccess<'de> for VA<'de, '_> {
2957 type Error = Error;
2958
2959 fn unit_variant(mut self) -> Result<(), Error> {
2961 if self.map_mode {
2962 if YamlDeserializer::new(self.ev, self.cfg).peek_null_value()? {
2963 let _ = self.ev.next()?; return self.expect_map_end();
2965 }
2966 match self.ev.peek()? {
2967 Some(Ev::MapEnd { .. }) => {
2968 let _ = self.ev.next()?;
2969 Ok(())
2970 }
2971 Some(other) => Err(Error::UnexpectedValueForUnitEnumVariant {
2972 location: other.location(),
2973 }),
2974 None => Err(eof_with_loc(self.ev)),
2975 }
2976 } else if self.tagged_payload {
2977 de::Deserialize::deserialize(YamlDeserializer::new(self.ev, self.cfg))
2978 } else {
2979 Ok(())
2980 }
2981 }
2982
2983 fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value, Error>
2985 where
2986 T: de::DeserializeSeed<'de>,
2987 {
2988 let defined_location = match self.ev.peek()? {
2990 Some(ev) => ev.location(),
2991 None => self.ev.last_location(),
2992 };
2993 let alias_reference_location = self.ev.alias_reference_location();
2994
2995 let mut de = YamlDeserializer::new(self.ev, self.cfg);
2996 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
2997 let value = with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
2998 .map_err(|e| {
2999 attach_alias_locations_if_missing(
3000 e,
3001 alias_reference_location,
3002 defined_location,
3003 )
3004 })?;
3005 if self.map_mode {
3006 self.expect_map_end()?;
3007 }
3008 Ok(value)
3009 }
3010
3011 fn tuple_variant<Vv>(mut self, len: usize, visitor: Vv) -> Result<Vv::Value, Error>
3013 where
3014 Vv: Visitor<'de>,
3015 {
3016 let result =
3017 YamlDeserializer::new(self.ev, self.cfg).deserialize_tuple(len, visitor)?;
3018 if self.map_mode {
3019 self.expect_map_end()?;
3020 }
3021 Ok(result)
3022 }
3023
3024 fn struct_variant<Vv>(
3026 mut self,
3027 fields: &'static [&'static str],
3028 visitor: Vv,
3029 ) -> Result<Vv::Value, Error>
3030 where
3031 Vv: Visitor<'de>,
3032 {
3033 let result = YamlDeserializer::new(self.ev, self.cfg)
3034 .deserialize_struct("", fields, visitor)?;
3035 if self.map_mode {
3036 self.expect_map_end()?;
3037 }
3038 Ok(result)
3039 }
3040 }
3041
3042 struct TaggedEA<'de> {
3043 replay: Box<ReplayEvents<'de>>,
3044 cfg: Cfg,
3045 variant: EnumScalarId<'de>,
3046 }
3047
3048 impl<'de> de::EnumAccess<'de> for TaggedEA<'de> {
3049 type Error = Error;
3050 type Variant = TaggedVA<'de>;
3051
3052 fn variant_seed<Vv>(self, seed: Vv) -> Result<(Vv::Value, Self::Variant), Error>
3053 where
3054 Vv: de::DeserializeSeed<'de>,
3055 {
3056 let v = seed.deserialize(self.variant.into_deserializer())?;
3057 Ok((
3058 v,
3059 TaggedVA {
3060 replay: self.replay,
3061 cfg: self.cfg,
3062 },
3063 ))
3064 }
3065 }
3066
3067 struct TaggedVA<'de> {
3068 replay: Box<ReplayEvents<'de>>,
3069 cfg: Cfg,
3070 }
3071
3072 impl<'de> de::VariantAccess<'de> for TaggedVA<'de> {
3073 type Error = Error;
3074
3075 fn unit_variant(mut self) -> Result<(), Error> {
3076 de::Deserialize::deserialize(YamlDeserializer::new(&mut *self.replay, self.cfg))
3077 }
3078
3079 fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value, Error>
3080 where
3081 T: de::DeserializeSeed<'de>,
3082 {
3083 let mut de = YamlDeserializer::new(&mut *self.replay, self.cfg);
3084 let redaction_ctx = de.peek_scalar_redaction_ctx()?;
3085 with_subtree_redaction(redaction_ctx, || seed.deserialize(de))
3086 }
3087
3088 fn tuple_variant<Vv>(mut self, len: usize, visitor: Vv) -> Result<Vv::Value, Error>
3089 where
3090 Vv: Visitor<'de>,
3091 {
3092 YamlDeserializer::new(&mut *self.replay, self.cfg).deserialize_tuple(len, visitor)
3093 }
3094
3095 fn struct_variant<Vv>(
3096 mut self,
3097 fields: &'static [&'static str],
3098 visitor: Vv,
3099 ) -> Result<Vv::Value, Error>
3100 where
3101 Vv: Visitor<'de>,
3102 {
3103 YamlDeserializer::new(&mut *self.replay, self.cfg)
3104 .deserialize_struct("", fields, visitor)
3105 }
3106 }
3107
3108 let access = match mode {
3109 Mode::Unit(variant) => EA {
3110 ev: self.ev,
3111 cfg: self.cfg,
3112 variant,
3113 map_mode: false,
3114 tagged_payload: false,
3115 },
3116 Mode::Map(variant, variant_location) => EA {
3117 ev: self.ev,
3118 cfg: self.cfg,
3119 variant: EnumScalarId {
3120 raw: Cow::Owned(variant.clone()),
3121 effective: Cow::Owned(variant),
3122 interpolated: false,
3123 location: variant_location,
3124 },
3125 map_mode: true,
3126 tagged_payload: false,
3127 },
3128 Mode::TaggedNewtype(variant, replay_buf) => {
3129 let replay = Box::new(ReplayEvents::new(
3130 replay_buf,
3131 #[cfg(feature = "properties")]
3132 self.ev.property_interpolation().clone(),
3133 ));
3134 return visitor.visit_enum(TaggedEA {
3136 replay,
3137 cfg: self.cfg,
3138 variant,
3139 });
3140 }
3141 };
3142
3143 visitor.visit_enum(access)
3144 }
3145
3146 fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
3148 self.deserialize_str(visitor)
3149 }
3150
3151 fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
3155 self.deserialize_any(visitor)
3156 }
3157}
3158
3159#[cfg(all(test, feature = "properties"))]
3160mod tests {
3161 use super::super::events::PropertyInterpolation;
3162 use super::super::options::{Options, PropertySyntax};
3163 use super::*;
3164
3165 #[test]
3166 fn effective_scalar_value_without_property_map_returns_original_scalar() {
3167 let budget = crate::Budget::default();
3168 let mut events = ReplayEvents::new(
3169 Vec::new(),
3170 PropertyInterpolation::new(None, PropertySyntax::Braced, Some(&budget)),
3171 );
3172 let de = YamlDeserializer::new(&mut events, Cfg::from_options(&Options::default()));
3173
3174 let value = de
3175 .effective_scalar_value(Cow::Borrowed("${MISSING}"), Location::new(1, 1))
3176 .expect("missing property map should not be treated as interpolation");
3177
3178 assert_eq!(value, Cow::Borrowed("${MISSING}"));
3179 }
3180}