facet_format/
deserializer.rs

1extern crate alloc;
2
3use alloc::borrow::Cow;
4use alloc::format;
5use alloc::string::String;
6use core::fmt;
7
8use facet_core::{
9    Def, Facet, KnownPointer, NumericType, PrimitiveType, StructKind, Type, UserType,
10};
11use facet_reflect::{HeapValue, Partial, ReflectError, is_spanned_shape};
12
13use crate::{FieldLocationHint, FormatParser, ParseEvent, ScalarTypeHint, ScalarValue};
14
15/// Generic deserializer that drives a format-specific parser directly into `Partial`.
16///
17/// The const generic `BORROW` controls whether string data can be borrowed:
18/// - `BORROW=true`: strings without escapes are borrowed from input
19/// - `BORROW=false`: all strings are owned
20pub struct FormatDeserializer<'input, const BORROW: bool, P> {
21    parser: P,
22    /// The span of the most recently consumed event (for error reporting).
23    last_span: Option<facet_reflect::Span>,
24    _marker: core::marker::PhantomData<&'input ()>,
25}
26
27impl<'input, P> FormatDeserializer<'input, true, P> {
28    /// Create a new deserializer that can borrow strings from input.
29    pub const fn new(parser: P) -> Self {
30        Self {
31            parser,
32            last_span: None,
33            _marker: core::marker::PhantomData,
34        }
35    }
36}
37
38impl<'input, P> FormatDeserializer<'input, false, P> {
39    /// Create a new deserializer that produces owned strings.
40    pub const fn new_owned(parser: P) -> Self {
41        Self {
42            parser,
43            last_span: None,
44            _marker: core::marker::PhantomData,
45        }
46    }
47}
48
49impl<'input, const BORROW: bool, P> FormatDeserializer<'input, BORROW, P> {
50    /// Consume the facade and return the underlying parser.
51    pub fn into_inner(self) -> P {
52        self.parser
53    }
54
55    /// Borrow the inner parser mutably.
56    pub fn parser_mut(&mut self) -> &mut P {
57        &mut self.parser
58    }
59}
60
61impl<'input, P> FormatDeserializer<'input, true, P>
62where
63    P: FormatParser<'input>,
64{
65    /// Deserialize the next value in the stream into `T`, allowing borrowed strings.
66    pub fn deserialize<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
67    where
68        T: Facet<'input>,
69    {
70        let wip: Partial<'input, true> =
71            Partial::alloc::<T>().map_err(DeserializeError::reflect)?;
72        let partial = self.deserialize_into(wip)?;
73        let heap_value: HeapValue<'input, true> =
74            partial.build().map_err(DeserializeError::reflect)?;
75        heap_value
76            .materialize::<T>()
77            .map_err(DeserializeError::reflect)
78    }
79
80    /// Deserialize the next value in the stream into `T` (for backward compatibility).
81    pub fn deserialize_root<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
82    where
83        T: Facet<'input>,
84    {
85        self.deserialize()
86    }
87}
88
89impl<'input, P> FormatDeserializer<'input, false, P>
90where
91    P: FormatParser<'input>,
92{
93    /// Deserialize the next value in the stream into `T`, using owned strings.
94    pub fn deserialize<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
95    where
96        T: Facet<'static>,
97    {
98        // SAFETY: alloc_owned produces Partial<'static, false>, but our deserializer
99        // expects 'input. Since BORROW=false means we never borrow from input anyway,
100        // this is safe. We also transmute the HeapValue back to 'static before materializing.
101        #[allow(unsafe_code)]
102        let wip: Partial<'input, false> = unsafe {
103            core::mem::transmute::<Partial<'static, false>, Partial<'input, false>>(
104                Partial::alloc_owned::<T>().map_err(DeserializeError::reflect)?,
105            )
106        };
107        let partial = self.deserialize_into(wip)?;
108        let heap_value: HeapValue<'input, false> =
109            partial.build().map_err(DeserializeError::reflect)?;
110
111        // SAFETY: HeapValue<'input, false> contains no borrowed data because BORROW=false.
112        // The transmute only changes the phantom lifetime marker.
113        #[allow(unsafe_code)]
114        let heap_value: HeapValue<'static, false> = unsafe {
115            core::mem::transmute::<HeapValue<'input, false>, HeapValue<'static, false>>(heap_value)
116        };
117
118        heap_value
119            .materialize::<T>()
120            .map_err(DeserializeError::reflect)
121    }
122
123    /// Deserialize the next value in the stream into `T` (for backward compatibility).
124    pub fn deserialize_root<T>(&mut self) -> Result<T, DeserializeError<P::Error>>
125    where
126        T: Facet<'static>,
127    {
128        self.deserialize()
129    }
130}
131
132impl<'input, const BORROW: bool, P> FormatDeserializer<'input, BORROW, P>
133where
134    P: FormatParser<'input>,
135{
136    /// Read the next event, returning an error if EOF is reached.
137    #[inline]
138    fn expect_event(
139        &mut self,
140        expected: &'static str,
141    ) -> Result<ParseEvent<'input>, DeserializeError<P::Error>> {
142        let event = self
143            .parser
144            .next_event()
145            .map_err(DeserializeError::Parser)?
146            .ok_or(DeserializeError::UnexpectedEof { expected })?;
147        // Capture the span of the consumed event for error reporting
148        self.last_span = self.parser.current_span();
149        Ok(event)
150    }
151
152    /// Peek at the next event, returning an error if EOF is reached.
153    #[inline]
154    fn expect_peek(
155        &mut self,
156        expected: &'static str,
157    ) -> Result<ParseEvent<'input>, DeserializeError<P::Error>> {
158        self.parser
159            .peek_event()
160            .map_err(DeserializeError::Parser)?
161            .ok_or(DeserializeError::UnexpectedEof { expected })
162    }
163
164    /// Main deserialization entry point - deserialize into a Partial.
165    pub fn deserialize_into(
166        &mut self,
167        mut wip: Partial<'input, BORROW>,
168    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
169        let shape = wip.shape();
170
171        // Check for raw capture type (e.g., RawJson)
172        // Raw capture types are tuple structs with a single Cow<str> field
173        // If capture_raw returns None (e.g., streaming mode), fall through
174        // and try normal deserialization (which will likely fail with a helpful error)
175        if self.parser.raw_capture_shape() == Some(shape)
176            && let Some(raw) = self
177                .parser
178                .capture_raw()
179                .map_err(DeserializeError::Parser)?
180        {
181            // The raw type is a tuple struct like RawJson(Cow<str>)
182            // Access field 0 (the Cow<str>) and set it
183            wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
184            wip = self.set_string_value(wip, Cow::Borrowed(raw))?;
185            wip = wip.end().map_err(DeserializeError::reflect)?;
186            return Ok(wip);
187        }
188
189        // Check for container-level proxy
190        let (wip_returned, has_proxy) = wip
191            .begin_custom_deserialization_from_shape()
192            .map_err(DeserializeError::reflect)?;
193        wip = wip_returned;
194        if has_proxy {
195            wip = self.deserialize_into(wip)?;
196            return wip.end().map_err(DeserializeError::reflect);
197        }
198
199        // Check for field-level proxy (opaque types with proxy attribute)
200        if wip
201            .parent_field()
202            .and_then(|field| field.proxy_convert_in_fn())
203            .is_some()
204        {
205            wip = wip
206                .begin_custom_deserialization()
207                .map_err(DeserializeError::reflect)?;
208            wip = self.deserialize_into(wip)?;
209            wip = wip.end().map_err(DeserializeError::reflect)?;
210            return Ok(wip);
211        }
212
213        // Check Def first for Option
214        if matches!(&shape.def, Def::Option(_)) {
215            return self.deserialize_option(wip);
216        }
217
218        // Check Def for Result - treat it as a 2-variant enum
219        if matches!(&shape.def, Def::Result(_)) {
220            return self.deserialize_result_as_enum(wip);
221        }
222
223        // Priority 1: Check for builder_shape (immutable collections like Bytes -> BytesMut)
224        if shape.builder_shape.is_some() {
225            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
226            wip = self.deserialize_into(wip)?;
227            wip = wip.end().map_err(DeserializeError::reflect)?;
228            return Ok(wip);
229        }
230
231        // Priority 2: Check for smart pointers (Box, Arc, Rc)
232        if matches!(&shape.def, Def::Pointer(_)) {
233            return self.deserialize_pointer(wip);
234        }
235
236        // Priority 3: Check for .inner (transparent wrappers like NonZero)
237        // Collections (List/Map/Set/Array) have .inner for variance but shouldn't use this path
238        // Opaque scalars (like ULID) may have .inner for documentation but should NOT be
239        // deserialized as transparent wrappers - they use hint_opaque_scalar instead
240        let is_opaque_scalar =
241            matches!(shape.def, Def::Scalar) && matches!(shape.ty, Type::User(UserType::Opaque));
242        if shape.inner.is_some()
243            && !is_opaque_scalar
244            && !matches!(
245                &shape.def,
246                Def::List(_) | Def::Map(_) | Def::Set(_) | Def::Array(_)
247            )
248        {
249            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
250            wip = self.deserialize_into(wip)?;
251            wip = wip.end().map_err(DeserializeError::reflect)?;
252            return Ok(wip);
253        }
254
255        // Priority 4: Check for metadata-annotated types (like Spanned<T>)
256        if is_spanned_shape(shape) {
257            return self.deserialize_spanned(wip);
258        }
259
260        // Priority 5: Check the Type for structs and enums
261        match &shape.ty {
262            Type::User(UserType::Struct(struct_def)) => {
263                if matches!(struct_def.kind, StructKind::Tuple | StructKind::TupleStruct) {
264                    return self.deserialize_tuple(wip);
265                }
266                return self.deserialize_struct(wip);
267            }
268            Type::User(UserType::Enum(_)) => return self.deserialize_enum(wip),
269            _ => {}
270        }
271
272        // Priority 6: Check Def for containers and scalars
273        match &shape.def {
274            Def::Scalar => self.deserialize_scalar(wip),
275            Def::List(_) => self.deserialize_list(wip),
276            Def::Map(_) => self.deserialize_map(wip),
277            Def::Array(_) => self.deserialize_array(wip),
278            Def::Set(_) => self.deserialize_set(wip),
279            Def::DynamicValue(_) => self.deserialize_dynamic_value(wip),
280            _ => Err(DeserializeError::Unsupported(format!(
281                "unsupported shape def: {:?}",
282                shape.def
283            ))),
284        }
285    }
286
287    fn deserialize_option(
288        &mut self,
289        mut wip: Partial<'input, BORROW>,
290    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
291        // Hint to non-self-describing parsers that an Option is expected
292        self.parser.hint_option();
293
294        let event = self.expect_peek("value for option")?;
295
296        if matches!(event, ParseEvent::Scalar(ScalarValue::Null)) {
297            // Consume the null
298            let _ = self.expect_event("null")?;
299            // Set to None (default)
300            wip = wip.set_default().map_err(DeserializeError::reflect)?;
301        } else {
302            // Some(value)
303            wip = wip.begin_some().map_err(DeserializeError::reflect)?;
304            wip = self.deserialize_into(wip)?;
305            wip = wip.end().map_err(DeserializeError::reflect)?;
306        }
307        Ok(wip)
308    }
309
310    fn deserialize_result_as_enum(
311        &mut self,
312        mut wip: Partial<'input, BORROW>,
313    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
314        use facet_core::StructKind;
315
316        // Hint to non-self-describing parsers that a Result enum is expected
317        // Result is encoded as a 2-variant enum: Ok (index 0) and Err (index 1)
318        let variant_hints: Vec<crate::EnumVariantHint> = vec![
319            crate::EnumVariantHint {
320                name: "Ok",
321                kind: StructKind::TupleStruct,
322                field_count: 1,
323            },
324            crate::EnumVariantHint {
325                name: "Err",
326                kind: StructKind::TupleStruct,
327                field_count: 1,
328            },
329        ];
330        self.parser.hint_enum(&variant_hints);
331
332        // Read the StructStart emitted by the parser after hint_enum
333        let event = self.expect_event("struct start for Result")?;
334        if !matches!(event, ParseEvent::StructStart(_)) {
335            return Err(DeserializeError::TypeMismatch {
336                expected: "struct start for Result variant",
337                got: format!("{event:?}"),
338            });
339        }
340
341        // Read the FieldKey with the variant name ("Ok" or "Err")
342        let key_event = self.expect_event("variant key for Result")?;
343        let variant_name = match key_event {
344            ParseEvent::FieldKey(key) => key.name,
345            other => {
346                return Err(DeserializeError::TypeMismatch {
347                    expected: "field key with variant name",
348                    got: format!("{other:?}"),
349                });
350            }
351        };
352
353        // Select the appropriate variant and deserialize its content
354        if variant_name == "Ok" {
355            wip = wip.begin_ok().map_err(DeserializeError::reflect)?;
356        } else if variant_name == "Err" {
357            wip = wip.begin_err().map_err(DeserializeError::reflect)?;
358        } else {
359            return Err(DeserializeError::TypeMismatch {
360                expected: "Ok or Err variant",
361                got: alloc::format!("variant '{}'", variant_name),
362            });
363        }
364
365        // Deserialize the variant's value (newtype pattern - single field)
366        wip = self.deserialize_into(wip)?;
367        wip = wip.end().map_err(DeserializeError::reflect)?;
368
369        // Consume StructEnd
370        let end_event = self.expect_event("struct end for Result")?;
371        if !matches!(end_event, ParseEvent::StructEnd) {
372            return Err(DeserializeError::TypeMismatch {
373                expected: "struct end for Result variant",
374                got: format!("{end_event:?}"),
375            });
376        }
377
378        Ok(wip)
379    }
380
381    fn deserialize_pointer(
382        &mut self,
383        mut wip: Partial<'input, BORROW>,
384    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
385        use facet_core::KnownPointer;
386
387        let shape = wip.shape();
388        let is_cow = if let Def::Pointer(ptr_def) = shape.def {
389            matches!(ptr_def.known, Some(KnownPointer::Cow))
390        } else {
391            false
392        };
393
394        if is_cow {
395            // Cow<str> - handle specially to preserve borrowing
396            if let Def::Pointer(ptr_def) = shape.def
397                && let Some(pointee) = ptr_def.pointee()
398                && pointee.type_identifier == "str"
399            {
400                // Hint to non-self-describing parsers that a string is expected
401                self.parser.hint_scalar_type(ScalarTypeHint::String);
402                let event = self.expect_event("string for Cow<str>")?;
403                if let ParseEvent::Scalar(ScalarValue::Str(s)) = event {
404                    // Pass through the Cow as-is to preserve borrowing
405                    wip = wip.set(s).map_err(DeserializeError::reflect)?;
406                    return Ok(wip);
407                } else {
408                    return Err(DeserializeError::TypeMismatch {
409                        expected: "string for Cow<str>",
410                        got: format!("{event:?}"),
411                    });
412                }
413            }
414            // Cow<[u8]> - handle specially to preserve borrowing
415            if let Def::Pointer(ptr_def) = shape.def
416                && let Some(pointee) = ptr_def.pointee()
417                && let Def::Slice(slice_def) = pointee.def
418                && slice_def.t.type_identifier == "u8"
419            {
420                // Hint to non-self-describing parsers that bytes are expected
421                self.parser.hint_scalar_type(ScalarTypeHint::Bytes);
422                let event = self.expect_event("bytes for Cow<[u8]>")?;
423                if let ParseEvent::Scalar(ScalarValue::Bytes(b)) = event {
424                    // Pass through the Cow as-is to preserve borrowing
425                    wip = wip.set(b).map_err(DeserializeError::reflect)?;
426                    return Ok(wip);
427                } else {
428                    return Err(DeserializeError::TypeMismatch {
429                        expected: "bytes for Cow<[u8]>",
430                        got: format!("{event:?}"),
431                    });
432                }
433            }
434            // Other Cow types - use begin_inner
435            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
436            wip = self.deserialize_into(wip)?;
437            wip = wip.end().map_err(DeserializeError::reflect)?;
438            return Ok(wip);
439        }
440
441        // &str - handle specially for zero-copy borrowing
442        if let Def::Pointer(ptr_def) = shape.def
443            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
444            && ptr_def
445                .pointee()
446                .is_some_and(|p| p.type_identifier == "str")
447        {
448            // Hint to non-self-describing parsers that a string is expected
449            self.parser.hint_scalar_type(ScalarTypeHint::String);
450            let event = self.expect_event("string for &str")?;
451            if let ParseEvent::Scalar(ScalarValue::Str(s)) = event {
452                return self.set_string_value(wip, s);
453            } else {
454                return Err(DeserializeError::TypeMismatch {
455                    expected: "string for &str",
456                    got: format!("{event:?}"),
457                });
458            }
459        }
460
461        // &[u8] - handle specially for zero-copy borrowing
462        if let Def::Pointer(ptr_def) = shape.def
463            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
464            && let Some(pointee) = ptr_def.pointee()
465            && let Def::Slice(slice_def) = pointee.def
466            && slice_def.t.type_identifier == "u8"
467        {
468            // Hint to non-self-describing parsers that bytes are expected
469            self.parser.hint_scalar_type(ScalarTypeHint::Bytes);
470            let event = self.expect_event("bytes for &[u8]")?;
471            if let ParseEvent::Scalar(ScalarValue::Bytes(b)) = event {
472                return self.set_bytes_value(wip, b);
473            } else {
474                return Err(DeserializeError::TypeMismatch {
475                    expected: "bytes for &[u8]",
476                    got: format!("{event:?}"),
477                });
478            }
479        }
480
481        // Regular smart pointer (Box, Arc, Rc)
482        wip = wip.begin_smart_ptr().map_err(DeserializeError::reflect)?;
483
484        // Check if begin_smart_ptr set up a slice builder (for Arc<[T]>, Rc<[T]>, Box<[T]>)
485        // In this case, we need to deserialize as a list manually
486        let is_slice_builder = wip.is_building_smart_ptr_slice();
487
488        if is_slice_builder {
489            // Deserialize the list elements into the slice builder
490            // We can't use deserialize_list() because it calls begin_list() which interferes
491            // Hint to non-self-describing parsers that a sequence is expected
492            self.parser.hint_sequence();
493            let event = self.expect_event("value")?;
494
495            // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
496            // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
497            let struct_mode = match event {
498                ParseEvent::SequenceStart(_) => false,
499                ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
500                ParseEvent::StructStart(kind) => {
501                    return Err(DeserializeError::TypeMismatch {
502                        expected: "array",
503                        got: kind.name().into(),
504                    });
505                }
506                _ => {
507                    return Err(DeserializeError::TypeMismatch {
508                        expected: "sequence start for Arc<[T]>/Rc<[T]>/Box<[T]>",
509                        got: format!("{event:?}"),
510                    });
511                }
512            };
513
514            loop {
515                let event = self.expect_peek("value")?;
516
517                // Check for end of container
518                if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
519                    self.expect_event("value")?;
520                    break;
521                }
522
523                // In struct mode, skip FieldKey events
524                if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
525                    self.expect_event("value")?;
526                    continue;
527                }
528
529                wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
530                wip = self.deserialize_into(wip)?;
531                wip = wip.end().map_err(DeserializeError::reflect)?;
532            }
533
534            // Convert the slice builder to Arc/Rc/Box and mark as initialized
535            wip = wip.end().map_err(DeserializeError::reflect)?;
536            // DON'T call end() again - the caller (deserialize_struct) will do that
537        } else {
538            // Regular smart pointer with sized pointee
539            wip = self.deserialize_into(wip)?;
540            wip = wip.end().map_err(DeserializeError::reflect)?;
541        }
542
543        Ok(wip)
544    }
545
546    /// Check if a field matches the given name and namespace constraints.
547    ///
548    /// This implements namespace-aware field matching for XML:
549    /// - Text: Match fields with xml::text attribute (name is ignored - text content goes to the field)
550    /// - Attributes: Only match if explicit xml::ns matches (no ns_all inheritance per XML spec)
551    /// - Elements: Match if explicit xml::ns OR ns_all matches
552    /// - No constraint: Backwards compatible - match any namespace by name only
553    fn field_matches_with_namespace(
554        field: &facet_core::Field,
555        name: &str,
556        namespace: Option<&str>,
557        location: FieldLocationHint,
558        ns_all: Option<&str>,
559    ) -> bool {
560        // Special case: Text location matches fields with xml::text attribute
561        // The name "_text" from the parser is ignored - we match by attribute presence
562        if matches!(location, FieldLocationHint::Text) {
563            return field.get_attr(Some("xml"), "text").is_some();
564        }
565
566        // Check name/alias
567        let name_matches = field.name == name || field.alias.iter().any(|alias| *alias == name);
568
569        if !name_matches {
570            return false;
571        }
572
573        // Get the expected namespace for this field
574        let field_xml_ns = field
575            .get_attr(Some("xml"), "ns")
576            .and_then(|attr| attr.get_as::<&str>().copied());
577
578        // CRITICAL: Attributes don't inherit ns_all (per XML spec)
579        let expected_ns = if matches!(location, FieldLocationHint::Attribute) {
580            field_xml_ns // Attributes: only explicit xml::ns
581        } else {
582            field_xml_ns.or(ns_all) // Elements: xml::ns OR ns_all
583        };
584
585        // Check if namespaces match
586        match (namespace, expected_ns) {
587            (Some(input_ns), Some(expected)) => input_ns == expected,
588            (Some(_input_ns), None) => true, // Input has namespace, field doesn't require one - match
589            (None, Some(_expected)) => false, // Input has no namespace, field requires one - NO match
590            (None, None) => true,             // Neither has namespace - match
591        }
592    }
593
594    fn deserialize_struct(
595        &mut self,
596        wip: Partial<'input, BORROW>,
597    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
598        // Get struct fields for lookup
599        let struct_def = match &wip.shape().ty {
600            Type::User(UserType::Struct(def)) => def,
601            _ => {
602                return Err(DeserializeError::Unsupported(format!(
603                    "expected struct type but got {:?}",
604                    wip.shape().ty
605                )));
606            }
607        };
608
609        // Check if we have any flattened fields
610        let has_flatten = struct_def.fields.iter().any(|f| f.is_flattened());
611
612        if has_flatten {
613            // Check if any flatten field is an enum (requires solver)
614            // or if there's nested flatten (flatten inside flatten)
615            let needs_solver = struct_def.fields.iter().any(|f| {
616                if !f.is_flattened() {
617                    return false;
618                }
619                // Get inner type, unwrapping Option if present
620                let inner_shape = match f.shape().def {
621                    Def::Option(opt) => opt.t,
622                    _ => f.shape(),
623                };
624                match inner_shape.ty {
625                    // Enum flatten needs solver
626                    Type::User(UserType::Enum(_)) => true,
627                    // Check for nested flatten (flatten field has its own flatten fields)
628                    Type::User(UserType::Struct(inner_struct)) => inner_struct
629                        .fields
630                        .iter()
631                        .any(|inner_f| inner_f.is_flattened()),
632                    _ => false,
633                }
634            });
635
636            if needs_solver {
637                self.deserialize_struct_with_flatten(wip)
638            } else {
639                // Simple single-level flatten - use the original approach
640                self.deserialize_struct_single_flatten(wip)
641            }
642        } else {
643            self.deserialize_struct_simple(wip)
644        }
645    }
646
647    /// Deserialize a struct without flattened fields (simple case).
648    fn deserialize_struct_simple(
649        &mut self,
650        mut wip: Partial<'input, BORROW>,
651    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
652        use facet_core::Characteristic;
653
654        // Get struct fields for lookup (needed before hint)
655        let struct_def = match &wip.shape().ty {
656            Type::User(UserType::Struct(def)) => def,
657            _ => {
658                return Err(DeserializeError::Unsupported(format!(
659                    "expected struct type but got {:?}",
660                    wip.shape().ty
661                )));
662            }
663        };
664
665        // Hint to non-self-describing parsers how many fields to expect
666        self.parser.hint_struct_fields(struct_def.fields.len());
667
668        // Expect StructStart
669        let event = self.expect_event("value")?;
670        if !matches!(event, ParseEvent::StructStart(_)) {
671            return Err(DeserializeError::TypeMismatch {
672                expected: "struct start",
673                got: format!("{event:?}"),
674            });
675        }
676
677        let struct_has_default = wip.shape().has_default_attr();
678        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();
679
680        // Extract container-level default namespace (xml::ns_all) for namespace-aware matching
681        let ns_all = wip
682            .shape()
683            .attributes
684            .iter()
685            .find(|attr| attr.ns == Some("xml") && attr.key == "ns_all")
686            .and_then(|attr| attr.get_as::<&str>().copied());
687
688        // Track which fields have been set
689        let num_fields = struct_def.fields.len();
690        let mut fields_set = alloc::vec![false; num_fields];
691        let mut ordered_field_index = 0usize;
692
693        loop {
694            let event = self.expect_event("value")?;
695            match event {
696                ParseEvent::StructEnd => break,
697                ParseEvent::OrderedField => {
698                    // Non-self-describing formats emit OrderedField events in order
699                    let idx = ordered_field_index;
700                    ordered_field_index += 1;
701                    if idx < num_fields {
702                        wip = wip
703                            .begin_nth_field(idx)
704                            .map_err(DeserializeError::reflect)?;
705                        wip = self.deserialize_into(wip)?;
706                        wip = wip.end().map_err(DeserializeError::reflect)?;
707                        fields_set[idx] = true;
708                    }
709                }
710                ParseEvent::FieldKey(key) => {
711                    // Look up field in struct fields
712                    let field_info = struct_def.fields.iter().enumerate().find(|(_, f)| {
713                        Self::field_matches_with_namespace(
714                            f,
715                            key.name.as_ref(),
716                            key.namespace.as_deref(),
717                            key.location,
718                            ns_all,
719                        )
720                    });
721
722                    if let Some((idx, _field)) = field_info {
723                        wip = wip
724                            .begin_nth_field(idx)
725                            .map_err(DeserializeError::reflect)?;
726                        wip = self.deserialize_into(wip)?;
727                        wip = wip.end().map_err(DeserializeError::reflect)?;
728                        fields_set[idx] = true;
729                        continue;
730                    }
731
732                    if deny_unknown_fields {
733                        return Err(DeserializeError::UnknownField(key.name.into_owned()));
734                    } else {
735                        // Unknown field - skip it
736                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
737                    }
738                }
739                other => {
740                    return Err(DeserializeError::TypeMismatch {
741                        expected: "field key or struct end",
742                        got: format!("{other:?}"),
743                    });
744                }
745            }
746        }
747
748        // Apply defaults for missing fields
749        for (idx, field) in struct_def.fields.iter().enumerate() {
750            if fields_set[idx] {
751                continue;
752            }
753
754            let field_has_default = field.has_default();
755            let field_type_has_default = field.shape().is(Characteristic::Default);
756            let field_is_option = matches!(field.shape().def, Def::Option(_));
757
758            if field_has_default || (struct_has_default && field_type_has_default) {
759                wip = wip
760                    .set_nth_field_to_default(idx)
761                    .map_err(DeserializeError::reflect)?;
762            } else if field_is_option {
763                wip = wip
764                    .begin_field(field.name)
765                    .map_err(DeserializeError::reflect)?;
766                wip = wip.set_default().map_err(DeserializeError::reflect)?;
767                wip = wip.end().map_err(DeserializeError::reflect)?;
768            } else if field.should_skip_deserializing() {
769                wip = wip
770                    .set_nth_field_to_default(idx)
771                    .map_err(DeserializeError::reflect)?;
772            } else {
773                return Err(DeserializeError::TypeMismatch {
774                    expected: "field to be present or have default",
775                    got: format!("missing field '{}'", field.name),
776                });
777            }
778        }
779
780        Ok(wip)
781    }
782
783    /// Deserialize a struct with single-level flattened fields (original approach).
784    /// This handles simple flatten cases where there's no nested flatten or enum flatten.
785    fn deserialize_struct_single_flatten(
786        &mut self,
787        mut wip: Partial<'input, BORROW>,
788    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
789        use alloc::collections::BTreeMap;
790        use facet_core::Characteristic;
791        use facet_reflect::Resolution;
792
793        // Expect StructStart
794        let event = self.expect_event("value")?;
795        if !matches!(event, ParseEvent::StructStart(_)) {
796            return Err(DeserializeError::TypeMismatch {
797                expected: "struct start",
798                got: format!("{event:?}"),
799            });
800        }
801
802        // Get struct fields for lookup
803        let struct_def = match &wip.shape().ty {
804            Type::User(UserType::Struct(def)) => def,
805            _ => {
806                return Err(DeserializeError::Unsupported(format!(
807                    "expected struct type but got {:?}",
808                    wip.shape().ty
809                )));
810            }
811        };
812
813        let struct_has_default = wip.shape().has_default_attr();
814        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();
815
816        // Extract container-level default namespace (xml::ns_all) for namespace-aware matching
817        let ns_all = wip
818            .shape()
819            .attributes
820            .iter()
821            .find(|attr| attr.ns == Some("xml") && attr.key == "ns_all")
822            .and_then(|attr| attr.get_as::<&str>().copied());
823
824        // Track which fields have been set
825        let num_fields = struct_def.fields.len();
826        let mut fields_set = alloc::vec![false; num_fields];
827
828        // Build flatten info: for each flattened field, get its inner struct fields
829        // and track which inner fields have been set
830        let mut flatten_info: alloc::vec::Vec<
831            Option<(&'static [facet_core::Field], alloc::vec::Vec<bool>)>,
832        > = alloc::vec![None; num_fields];
833
834        // Track which fields are DynamicValue flattens (like facet_value::Value)
835        let mut dynamic_value_flattens: alloc::vec::Vec<bool> = alloc::vec![false; num_fields];
836
837        // Track field names across flattened structs to detect duplicates
838        let mut flatten_field_names: BTreeMap<&str, usize> = BTreeMap::new();
839
840        for (idx, field) in struct_def.fields.iter().enumerate() {
841            if field.is_flattened() {
842                // Handle Option<T> flatten by unwrapping to inner type
843                let inner_shape = match field.shape().def {
844                    Def::Option(opt) => opt.t,
845                    _ => field.shape(),
846                };
847
848                // Check if this is a DynamicValue flatten (like facet_value::Value)
849                if matches!(inner_shape.def, Def::DynamicValue(_)) {
850                    dynamic_value_flattens[idx] = true;
851                } else if let Type::User(UserType::Struct(inner_def)) = &inner_shape.ty {
852                    let inner_fields = inner_def.fields;
853                    let inner_set = alloc::vec![false; inner_fields.len()];
854                    flatten_info[idx] = Some((inner_fields, inner_set));
855
856                    // Check for duplicate field names across flattened structs
857                    for inner_field in inner_fields.iter() {
858                        let field_name = inner_field.rename.unwrap_or(inner_field.name);
859                        if let Some(_prev_idx) = flatten_field_names.insert(field_name, idx) {
860                            return Err(DeserializeError::Unsupported(format!(
861                                "duplicate field `{}` in flattened structs",
862                                field_name
863                            )));
864                        }
865                    }
866                }
867            }
868        }
869
870        // Enter deferred mode for flatten handling
871        let resolution = Resolution::new();
872        wip = wip
873            .begin_deferred(resolution)
874            .map_err(DeserializeError::reflect)?;
875
876        loop {
877            let event = self.expect_event("value")?;
878            match event {
879                ParseEvent::StructEnd => break,
880                ParseEvent::FieldKey(key) => {
881                    // First, look up field in direct struct fields (non-flattened)
882                    let direct_field_info = struct_def.fields.iter().enumerate().find(|(_, f)| {
883                        !f.is_flattened()
884                            && Self::field_matches_with_namespace(
885                                f,
886                                key.name.as_ref(),
887                                key.namespace.as_deref(),
888                                key.location,
889                                ns_all,
890                            )
891                    });
892
893                    if let Some((idx, _field)) = direct_field_info {
894                        wip = wip
895                            .begin_nth_field(idx)
896                            .map_err(DeserializeError::reflect)?;
897                        wip = self.deserialize_into(wip)?;
898                        wip = wip.end().map_err(DeserializeError::reflect)?;
899                        fields_set[idx] = true;
900                        continue;
901                    }
902
903                    // Check flattened fields for a match
904                    let mut found_flatten = false;
905                    for (flatten_idx, field) in struct_def.fields.iter().enumerate() {
906                        if !field.is_flattened() {
907                            continue;
908                        }
909                        if let Some((inner_fields, inner_set)) = flatten_info[flatten_idx].as_mut()
910                        {
911                            let inner_match = inner_fields.iter().enumerate().find(|(_, f)| {
912                                Self::field_matches_with_namespace(
913                                    f,
914                                    key.name.as_ref(),
915                                    key.namespace.as_deref(),
916                                    key.location,
917                                    ns_all,
918                                )
919                            });
920
921                            if let Some((inner_idx, _inner_field)) = inner_match {
922                                // Check if flatten field is Option - if so, wrap in Some
923                                let is_option = matches!(field.shape().def, Def::Option(_));
924                                wip = wip
925                                    .begin_nth_field(flatten_idx)
926                                    .map_err(DeserializeError::reflect)?;
927                                if is_option {
928                                    wip = wip.begin_some().map_err(DeserializeError::reflect)?;
929                                }
930                                wip = wip
931                                    .begin_nth_field(inner_idx)
932                                    .map_err(DeserializeError::reflect)?;
933                                wip = self.deserialize_into(wip)?;
934                                wip = wip.end().map_err(DeserializeError::reflect)?;
935                                if is_option {
936                                    wip = wip.end().map_err(DeserializeError::reflect)?;
937                                }
938                                wip = wip.end().map_err(DeserializeError::reflect)?;
939                                inner_set[inner_idx] = true;
940                                fields_set[flatten_idx] = true;
941                                found_flatten = true;
942                                break;
943                            }
944                        }
945                    }
946
947                    if found_flatten {
948                        continue;
949                    }
950
951                    // Check if this unknown field should go to a DynamicValue flatten
952                    let mut found_dynamic = false;
953                    for (flatten_idx, _field) in struct_def.fields.iter().enumerate() {
954                        if !dynamic_value_flattens[flatten_idx] {
955                            continue;
956                        }
957
958                        // This is a DynamicValue flatten - insert the field into it
959                        // First, ensure the DynamicValue is initialized as an object
960                        let is_option =
961                            matches!(struct_def.fields[flatten_idx].shape().def, Def::Option(_));
962
963                        // Navigate to the DynamicValue field
964                        if !fields_set[flatten_idx] {
965                            // First time - need to initialize
966                            wip = wip
967                                .begin_nth_field(flatten_idx)
968                                .map_err(DeserializeError::reflect)?;
969                            if is_option {
970                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
971                            }
972                            // Initialize the DynamicValue as an object
973                            wip = wip.begin_map().map_err(DeserializeError::reflect)?;
974                            fields_set[flatten_idx] = true;
975                        } else {
976                            // Already initialized - just navigate to it
977                            wip = wip
978                                .begin_nth_field(flatten_idx)
979                                .map_err(DeserializeError::reflect)?;
980                            if is_option {
981                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
982                            }
983                        }
984
985                        // Insert the key-value pair into the object
986                        wip = wip
987                            .begin_object_entry(key.name.as_ref())
988                            .map_err(DeserializeError::reflect)?;
989                        wip = self.deserialize_into(wip)?;
990                        wip = wip.end().map_err(DeserializeError::reflect)?;
991
992                        // Navigate back out (Note: we close the map when we're done with ALL fields, not per-field)
993                        if is_option {
994                            wip = wip.end().map_err(DeserializeError::reflect)?;
995                        }
996                        wip = wip.end().map_err(DeserializeError::reflect)?;
997
998                        found_dynamic = true;
999                        break;
1000                    }
1001
1002                    if found_dynamic {
1003                        continue;
1004                    }
1005
1006                    if deny_unknown_fields {
1007                        return Err(DeserializeError::UnknownField(key.name.into_owned()));
1008                    } else {
1009                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1010                    }
1011                }
1012                other => {
1013                    return Err(DeserializeError::TypeMismatch {
1014                        expected: "field key or struct end",
1015                        got: format!("{other:?}"),
1016                    });
1017                }
1018            }
1019        }
1020
1021        // Apply defaults for missing fields
1022        for (idx, field) in struct_def.fields.iter().enumerate() {
1023            if field.is_flattened() {
1024                // Handle DynamicValue flattens that received no fields
1025                if dynamic_value_flattens[idx] && !fields_set[idx] {
1026                    let is_option = matches!(field.shape().def, Def::Option(_));
1027
1028                    if is_option {
1029                        // Option<DynamicValue> with no fields -> set to None
1030                        wip = wip
1031                            .begin_nth_field(idx)
1032                            .map_err(DeserializeError::reflect)?;
1033                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
1034                        wip = wip.end().map_err(DeserializeError::reflect)?;
1035                    } else {
1036                        // DynamicValue with no fields -> initialize as empty object
1037                        wip = wip
1038                            .begin_nth_field(idx)
1039                            .map_err(DeserializeError::reflect)?;
1040                        // Initialize as object (for DynamicValue, begin_map creates an object)
1041                        wip = wip.begin_map().map_err(DeserializeError::reflect)?;
1042                        // The map is now initialized and empty, just end the field
1043                        wip = wip.end().map_err(DeserializeError::reflect)?;
1044                    }
1045                    continue;
1046                }
1047
1048                if let Some((inner_fields, inner_set)) = flatten_info[idx].as_ref() {
1049                    let any_inner_set = inner_set.iter().any(|&s| s);
1050                    let is_option = matches!(field.shape().def, Def::Option(_));
1051
1052                    if any_inner_set {
1053                        // Some inner fields were set - apply defaults to missing ones
1054                        wip = wip
1055                            .begin_nth_field(idx)
1056                            .map_err(DeserializeError::reflect)?;
1057                        if is_option {
1058                            wip = wip.begin_some().map_err(DeserializeError::reflect)?;
1059                        }
1060                        for (inner_idx, inner_field) in inner_fields.iter().enumerate() {
1061                            if inner_set[inner_idx] {
1062                                continue;
1063                            }
1064                            let inner_has_default = inner_field.has_default();
1065                            let inner_type_has_default =
1066                                inner_field.shape().is(Characteristic::Default);
1067                            let inner_is_option = matches!(inner_field.shape().def, Def::Option(_));
1068
1069                            if inner_has_default || inner_type_has_default {
1070                                wip = wip
1071                                    .set_nth_field_to_default(inner_idx)
1072                                    .map_err(DeserializeError::reflect)?;
1073                            } else if inner_is_option {
1074                                wip = wip
1075                                    .begin_nth_field(inner_idx)
1076                                    .map_err(DeserializeError::reflect)?;
1077                                wip = wip.set_default().map_err(DeserializeError::reflect)?;
1078                                wip = wip.end().map_err(DeserializeError::reflect)?;
1079                            } else if inner_field.should_skip_deserializing() {
1080                                wip = wip
1081                                    .set_nth_field_to_default(inner_idx)
1082                                    .map_err(DeserializeError::reflect)?;
1083                            } else {
1084                                return Err(DeserializeError::TypeMismatch {
1085                                    expected: "field to be present or have default",
1086                                    got: format!("missing field '{}'", inner_field.name),
1087                                });
1088                            }
1089                        }
1090                        if is_option {
1091                            wip = wip.end().map_err(DeserializeError::reflect)?;
1092                        }
1093                        wip = wip.end().map_err(DeserializeError::reflect)?;
1094                    } else if is_option {
1095                        // No inner fields set and field is Option - set to None
1096                        wip = wip
1097                            .begin_nth_field(idx)
1098                            .map_err(DeserializeError::reflect)?;
1099                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
1100                        wip = wip.end().map_err(DeserializeError::reflect)?;
1101                    } else {
1102                        // No inner fields set - try to default the whole flattened field
1103                        let field_has_default = field.has_default();
1104                        let field_type_has_default = field.shape().is(Characteristic::Default);
1105                        if field_has_default || (struct_has_default && field_type_has_default) {
1106                            wip = wip
1107                                .set_nth_field_to_default(idx)
1108                                .map_err(DeserializeError::reflect)?;
1109                        } else {
1110                            let all_inner_can_default = inner_fields.iter().all(|f| {
1111                                f.has_default()
1112                                    || f.shape().is(Characteristic::Default)
1113                                    || matches!(f.shape().def, Def::Option(_))
1114                                    || f.should_skip_deserializing()
1115                            });
1116                            if all_inner_can_default {
1117                                wip = wip
1118                                    .begin_nth_field(idx)
1119                                    .map_err(DeserializeError::reflect)?;
1120                                for (inner_idx, inner_field) in inner_fields.iter().enumerate() {
1121                                    let inner_has_default = inner_field.has_default();
1122                                    let inner_type_has_default =
1123                                        inner_field.shape().is(Characteristic::Default);
1124                                    let inner_is_option =
1125                                        matches!(inner_field.shape().def, Def::Option(_));
1126
1127                                    if inner_has_default || inner_type_has_default {
1128                                        wip = wip
1129                                            .set_nth_field_to_default(inner_idx)
1130                                            .map_err(DeserializeError::reflect)?;
1131                                    } else if inner_is_option {
1132                                        wip = wip
1133                                            .begin_nth_field(inner_idx)
1134                                            .map_err(DeserializeError::reflect)?;
1135                                        wip =
1136                                            wip.set_default().map_err(DeserializeError::reflect)?;
1137                                        wip = wip.end().map_err(DeserializeError::reflect)?;
1138                                    } else if inner_field.should_skip_deserializing() {
1139                                        wip = wip
1140                                            .set_nth_field_to_default(inner_idx)
1141                                            .map_err(DeserializeError::reflect)?;
1142                                    }
1143                                }
1144                                wip = wip.end().map_err(DeserializeError::reflect)?;
1145                            } else {
1146                                return Err(DeserializeError::TypeMismatch {
1147                                    expected: "field to be present or have default",
1148                                    got: format!("missing flattened field '{}'", field.name),
1149                                });
1150                            }
1151                        }
1152                    }
1153                }
1154                continue;
1155            }
1156
1157            if fields_set[idx] {
1158                continue;
1159            }
1160
1161            let field_has_default = field.has_default();
1162            let field_type_has_default = field.shape().is(Characteristic::Default);
1163            let field_is_option = matches!(field.shape().def, Def::Option(_));
1164
1165            if field_has_default || (struct_has_default && field_type_has_default) {
1166                wip = wip
1167                    .set_nth_field_to_default(idx)
1168                    .map_err(DeserializeError::reflect)?;
1169            } else if field_is_option {
1170                wip = wip
1171                    .begin_field(field.name)
1172                    .map_err(DeserializeError::reflect)?;
1173                wip = wip.set_default().map_err(DeserializeError::reflect)?;
1174                wip = wip.end().map_err(DeserializeError::reflect)?;
1175            } else if field.should_skip_deserializing() {
1176                wip = wip
1177                    .set_nth_field_to_default(idx)
1178                    .map_err(DeserializeError::reflect)?;
1179            } else {
1180                return Err(DeserializeError::TypeMismatch {
1181                    expected: "field to be present or have default",
1182                    got: format!("missing field '{}'", field.name),
1183                });
1184            }
1185        }
1186
1187        // Finish deferred mode
1188        wip = wip.finish_deferred().map_err(DeserializeError::reflect)?;
1189
1190        Ok(wip)
1191    }
1192
1193    /// Deserialize a struct with flattened fields using facet-solver.
1194    ///
1195    /// This uses the solver's Schema/Resolution to handle arbitrarily nested
1196    /// flatten structures by looking up the full path for each field.
1197    /// It also handles flattened enums by using probing to collect keys first,
1198    /// then using the Solver to disambiguate between resolutions.
1199    fn deserialize_struct_with_flatten(
1200        &mut self,
1201        mut wip: Partial<'input, BORROW>,
1202    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1203        use alloc::collections::BTreeSet;
1204        use facet_core::Characteristic;
1205        use facet_reflect::Resolution;
1206        use facet_solver::{PathSegment, Schema, Solver};
1207
1208        let deny_unknown_fields = wip.shape().has_deny_unknown_fields_attr();
1209
1210        // Build the schema for this type - this recursively expands all flatten fields
1211        let schema = Schema::build_auto(wip.shape())
1212            .map_err(|e| DeserializeError::Unsupported(format!("failed to build schema: {e}")))?;
1213
1214        // Check if we have multiple resolutions (i.e., flattened enums)
1215        let resolutions = schema.resolutions();
1216        if resolutions.is_empty() {
1217            return Err(DeserializeError::Unsupported(
1218                "schema has no resolutions".into(),
1219            ));
1220        }
1221
1222        // ========== PASS 1: Probe to collect all field keys ==========
1223        let probe = self
1224            .parser
1225            .begin_probe()
1226            .map_err(DeserializeError::Parser)?;
1227        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;
1228
1229        // Feed keys to solver to narrow down resolutions
1230        let mut solver = Solver::new(&schema);
1231        for ev in &evidence {
1232            solver.see_key(ev.name.clone());
1233        }
1234
1235        // Get the resolved configuration
1236        let config_handle = solver
1237            .finish()
1238            .map_err(|e| DeserializeError::Unsupported(format!("solver failed: {e}")))?;
1239        let resolution = config_handle.resolution();
1240
1241        // ========== PASS 2: Parse the struct with resolved paths ==========
1242        // Expect StructStart
1243        let event = self.expect_event("value")?;
1244        if !matches!(event, ParseEvent::StructStart(_)) {
1245            return Err(DeserializeError::TypeMismatch {
1246                expected: "struct start",
1247                got: format!("{event:?}"),
1248            });
1249        }
1250
1251        // Enter deferred mode for flatten handling
1252        let reflect_resolution = Resolution::new();
1253        wip = wip
1254            .begin_deferred(reflect_resolution)
1255            .map_err(DeserializeError::reflect)?;
1256
1257        // Track which fields have been set (by serialized name - uses 'static str from resolution)
1258        let mut fields_set: BTreeSet<&'static str> = BTreeSet::new();
1259
1260        // Track currently open path segments: (field_name, is_option, is_variant)
1261        // The is_variant flag indicates if we've selected a variant at this level
1262        let mut open_segments: alloc::vec::Vec<(&str, bool, bool)> = alloc::vec::Vec::new();
1263
1264        loop {
1265            let event = self.expect_event("value")?;
1266            match event {
1267                ParseEvent::StructEnd => break,
1268                ParseEvent::FieldKey(key) => {
1269                    // Look up field in the resolution
1270                    if let Some(field_info) = resolution.field(key.name.as_ref()) {
1271                        let segments = field_info.path.segments();
1272
1273                        // Check if this path ends with a Variant segment (externally-tagged enum)
1274                        let ends_with_variant = segments
1275                            .last()
1276                            .is_some_and(|s| matches!(s, PathSegment::Variant(_, _)));
1277
1278                        // Extract field names from the path (excluding trailing Variant)
1279                        let field_segments: alloc::vec::Vec<&str> = segments
1280                            .iter()
1281                            .filter_map(|s| match s {
1282                                PathSegment::Field(name) => Some(*name),
1283                                PathSegment::Variant(_, _) => None,
1284                            })
1285                            .collect();
1286
1287                        // Find common prefix with currently open segments
1288                        let common_len = open_segments
1289                            .iter()
1290                            .zip(field_segments.iter())
1291                            .take_while(|((name, _, _), b)| *name == **b)
1292                            .count();
1293
1294                        // Close segments that are no longer needed (in reverse order)
1295                        while open_segments.len() > common_len {
1296                            let (_, is_option, _) = open_segments.pop().unwrap();
1297                            if is_option {
1298                                wip = wip.end().map_err(DeserializeError::reflect)?;
1299                            }
1300                            wip = wip.end().map_err(DeserializeError::reflect)?;
1301                        }
1302
1303                        // Open new segments
1304                        for &segment in &field_segments[common_len..] {
1305                            wip = wip
1306                                .begin_field(segment)
1307                                .map_err(DeserializeError::reflect)?;
1308                            let is_option = matches!(wip.shape().def, Def::Option(_));
1309                            if is_option {
1310                                wip = wip.begin_some().map_err(DeserializeError::reflect)?;
1311                            }
1312                            open_segments.push((segment, is_option, false));
1313                        }
1314
1315                        if ends_with_variant {
1316                            // For externally-tagged enums: select variant and deserialize content
1317                            if let Some(PathSegment::Variant(_, variant_name)) = segments.last() {
1318                                wip = wip
1319                                    .select_variant_named(variant_name)
1320                                    .map_err(DeserializeError::reflect)?;
1321                                // Deserialize the variant's struct content (the nested object)
1322                                wip = self.deserialize_variant_struct_fields(wip)?;
1323                            }
1324                        } else {
1325                            // Regular field: deserialize into it
1326                            wip = self.deserialize_into(wip)?;
1327                        }
1328
1329                        // Close segments we just opened (we're done with this field)
1330                        while open_segments.len() > common_len {
1331                            let (_, is_option, _) = open_segments.pop().unwrap();
1332                            if is_option {
1333                                wip = wip.end().map_err(DeserializeError::reflect)?;
1334                            }
1335                            wip = wip.end().map_err(DeserializeError::reflect)?;
1336                        }
1337
1338                        // Store the static serialized_name from the resolution
1339                        fields_set.insert(field_info.serialized_name);
1340                        continue;
1341                    }
1342
1343                    if deny_unknown_fields {
1344                        return Err(DeserializeError::UnknownField(key.name.into_owned()));
1345                    } else {
1346                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1347                    }
1348                }
1349                other => {
1350                    return Err(DeserializeError::TypeMismatch {
1351                        expected: "field key or struct end",
1352                        got: format!("{other:?}"),
1353                    });
1354                }
1355            }
1356        }
1357
1358        // Close any remaining open segments
1359        while let Some((_, is_option, _)) = open_segments.pop() {
1360            if is_option {
1361                wip = wip.end().map_err(DeserializeError::reflect)?;
1362            }
1363            wip = wip.end().map_err(DeserializeError::reflect)?;
1364        }
1365
1366        // Handle missing fields - apply defaults
1367        // Get all fields sorted by path depth (deepest first for proper default handling)
1368        let all_fields = resolution.deserialization_order();
1369
1370        // Track which top-level flatten fields have had any sub-fields set
1371        let mut touched_top_fields: BTreeSet<&str> = BTreeSet::new();
1372        for field_name in &fields_set {
1373            if let Some(info) = resolution.field(field_name)
1374                && let Some(PathSegment::Field(top)) = info.path.segments().first()
1375            {
1376                touched_top_fields.insert(*top);
1377            }
1378        }
1379
1380        for field_info in all_fields {
1381            if fields_set.contains(field_info.serialized_name) {
1382                continue;
1383            }
1384
1385            // Skip fields that end with Variant - these are handled by enum deserialization
1386            let ends_with_variant = field_info
1387                .path
1388                .segments()
1389                .last()
1390                .is_some_and(|s| matches!(s, PathSegment::Variant(_, _)));
1391            if ends_with_variant {
1392                continue;
1393            }
1394
1395            let path_segments: alloc::vec::Vec<&str> = field_info
1396                .path
1397                .segments()
1398                .iter()
1399                .filter_map(|s| match s {
1400                    PathSegment::Field(name) => Some(*name),
1401                    PathSegment::Variant(_, _) => None,
1402                })
1403                .collect();
1404
1405            // Check if this field's parent was touched
1406            let first_segment = path_segments.first().copied();
1407            let parent_touched = first_segment
1408                .map(|s| touched_top_fields.contains(s))
1409                .unwrap_or(false);
1410
1411            // If parent wasn't touched at all, we might default the whole parent
1412            // For now, handle individual field defaults
1413            let field_has_default = field_info.field.has_default();
1414            let field_type_has_default = field_info.value_shape.is(Characteristic::Default);
1415            let field_is_option = matches!(field_info.value_shape.def, Def::Option(_));
1416
1417            if field_has_default
1418                || field_type_has_default
1419                || field_is_option
1420                || field_info.field.should_skip_deserializing()
1421            {
1422                // Navigate to the field and set default
1423                for &segment in &path_segments[..path_segments.len().saturating_sub(1)] {
1424                    wip = wip
1425                        .begin_field(segment)
1426                        .map_err(DeserializeError::reflect)?;
1427                    if matches!(wip.shape().def, Def::Option(_)) {
1428                        wip = wip.begin_some().map_err(DeserializeError::reflect)?;
1429                    }
1430                }
1431
1432                if let Some(&last) = path_segments.last() {
1433                    wip = wip.begin_field(last).map_err(DeserializeError::reflect)?;
1434                    wip = wip.set_default().map_err(DeserializeError::reflect)?;
1435                    wip = wip.end().map_err(DeserializeError::reflect)?;
1436                }
1437
1438                // Close the path we opened
1439                for _ in 0..path_segments.len().saturating_sub(1) {
1440                    // Need to check if we're in an option
1441                    wip = wip.end().map_err(DeserializeError::reflect)?;
1442                }
1443            } else if !parent_touched && path_segments.len() > 1 {
1444                // Parent wasn't touched and field has no default - this is OK if the whole
1445                // parent can be defaulted (handled by deferred mode)
1446                continue;
1447            } else if field_info.required {
1448                return Err(DeserializeError::TypeMismatch {
1449                    expected: "field to be present or have default",
1450                    got: format!("missing field '{}'", field_info.serialized_name),
1451                });
1452            }
1453        }
1454
1455        // Finish deferred mode
1456        wip = wip.finish_deferred().map_err(DeserializeError::reflect)?;
1457
1458        Ok(wip)
1459    }
1460
1461    /// Deserialize the struct fields of a variant.
1462    /// Expects the variant to already be selected.
1463    fn deserialize_variant_struct_fields(
1464        &mut self,
1465        mut wip: Partial<'input, BORROW>,
1466    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1467        use facet_core::StructKind;
1468
1469        let variant = wip
1470            .selected_variant()
1471            .ok_or_else(|| DeserializeError::TypeMismatch {
1472                expected: "selected variant",
1473                got: "no variant selected".into(),
1474            })?;
1475
1476        let variant_fields = variant.data.fields;
1477        let kind = variant.data.kind;
1478
1479        // Handle based on variant kind
1480        match kind {
1481            StructKind::TupleStruct if variant_fields.len() == 1 => {
1482                // Single-element tuple variant (newtype): deserialize the inner value directly
1483                wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
1484                wip = self.deserialize_into(wip)?;
1485                wip = wip.end().map_err(DeserializeError::reflect)?;
1486                return Ok(wip);
1487            }
1488            StructKind::TupleStruct | StructKind::Tuple => {
1489                // Multi-element tuple variant - not yet supported in this context
1490                return Err(DeserializeError::Unsupported(
1491                    "multi-element tuple variants in flatten not yet supported".into(),
1492                ));
1493            }
1494            StructKind::Unit => {
1495                // Unit variant - nothing to deserialize
1496                return Ok(wip);
1497            }
1498            StructKind::Struct => {
1499                // Struct variant - fall through to struct deserialization below
1500            }
1501        }
1502
1503        // Struct variant: deserialize as a struct with named fields
1504        // Expect StructStart for the variant content
1505        let event = self.expect_event("value")?;
1506        if !matches!(event, ParseEvent::StructStart(_)) {
1507            return Err(DeserializeError::TypeMismatch {
1508                expected: "struct start for variant content",
1509                got: format!("{event:?}"),
1510            });
1511        }
1512
1513        // Track which fields have been set
1514        let num_fields = variant_fields.len();
1515        let mut fields_set = alloc::vec![false; num_fields];
1516
1517        // Process all fields
1518        loop {
1519            let event = self.expect_event("value")?;
1520            match event {
1521                ParseEvent::StructEnd => break,
1522                ParseEvent::FieldKey(key) => {
1523                    // Look up field in variant's fields
1524                    let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
1525                        Self::field_matches_with_namespace(
1526                            f,
1527                            key.name.as_ref(),
1528                            key.namespace.as_deref(),
1529                            key.location,
1530                            None,
1531                        )
1532                    });
1533
1534                    if let Some((idx, _field)) = field_info {
1535                        wip = wip
1536                            .begin_nth_field(idx)
1537                            .map_err(DeserializeError::reflect)?;
1538                        wip = self.deserialize_into(wip)?;
1539                        wip = wip.end().map_err(DeserializeError::reflect)?;
1540                        fields_set[idx] = true;
1541                    } else {
1542                        // Unknown field - skip
1543                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1544                    }
1545                }
1546                other => {
1547                    return Err(DeserializeError::TypeMismatch {
1548                        expected: "field key or struct end",
1549                        got: format!("{other:?}"),
1550                    });
1551                }
1552            }
1553        }
1554
1555        // Apply defaults for missing fields
1556        for (idx, field) in variant_fields.iter().enumerate() {
1557            if fields_set[idx] {
1558                continue;
1559            }
1560
1561            let field_has_default = field.has_default();
1562            let field_type_has_default = field.shape().is(facet_core::Characteristic::Default);
1563            let field_is_option = matches!(field.shape().def, Def::Option(_));
1564
1565            if field_has_default || field_type_has_default {
1566                wip = wip
1567                    .set_nth_field_to_default(idx)
1568                    .map_err(DeserializeError::reflect)?;
1569            } else if field_is_option {
1570                wip = wip
1571                    .begin_nth_field(idx)
1572                    .map_err(DeserializeError::reflect)?;
1573                wip = wip.set_default().map_err(DeserializeError::reflect)?;
1574                wip = wip.end().map_err(DeserializeError::reflect)?;
1575            } else if field.should_skip_deserializing() {
1576                wip = wip
1577                    .set_nth_field_to_default(idx)
1578                    .map_err(DeserializeError::reflect)?;
1579            } else {
1580                return Err(DeserializeError::TypeMismatch {
1581                    expected: "field to be present or have default",
1582                    got: format!("missing field '{}'", field.name),
1583                });
1584            }
1585        }
1586
1587        Ok(wip)
1588    }
1589
1590    /// Deserialize into a type with span metadata (like `Spanned<T>`).
1591    ///
1592    /// This handles structs that have:
1593    /// - One or more non-metadata fields (the actual values to deserialize)
1594    /// - A field with `#[facet(metadata = span)]` to store source location
1595    ///
1596    /// The metadata field is populated with a default span since most format parsers
1597    /// don't track source locations.
1598    fn deserialize_spanned(
1599        &mut self,
1600        mut wip: Partial<'input, BORROW>,
1601    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1602        let shape = wip.shape();
1603
1604        // Find the span metadata field and non-metadata fields
1605        let Type::User(UserType::Struct(struct_def)) = &shape.ty else {
1606            return Err(DeserializeError::Unsupported(format!(
1607                "expected struct with span metadata, found {}",
1608                shape.type_identifier
1609            )));
1610        };
1611
1612        let span_field = struct_def
1613            .fields
1614            .iter()
1615            .find(|f| f.metadata_kind() == Some("span"))
1616            .ok_or_else(|| {
1617                DeserializeError::Unsupported(format!(
1618                    "expected struct with span metadata field, found {}",
1619                    shape.type_identifier
1620                ))
1621            })?;
1622
1623        let value_fields: alloc::vec::Vec<_> = struct_def
1624            .fields
1625            .iter()
1626            .filter(|f| !f.is_metadata())
1627            .collect();
1628
1629        // Deserialize all non-metadata fields transparently
1630        // For the common case (Spanned<T> with a single "value" field), this is just one field
1631        for field in value_fields {
1632            wip = wip
1633                .begin_field(field.name)
1634                .map_err(DeserializeError::reflect)?;
1635            wip = self.deserialize_into(wip)?;
1636            wip = wip.end().map_err(DeserializeError::reflect)?;
1637        }
1638
1639        // Set the span metadata field to default
1640        // Most format parsers don't track source spans, so we use a default (unknown) span
1641        wip = wip
1642            .begin_field(span_field.name)
1643            .map_err(DeserializeError::reflect)?;
1644        wip = wip.set_default().map_err(DeserializeError::reflect)?;
1645        wip = wip.end().map_err(DeserializeError::reflect)?;
1646
1647        Ok(wip)
1648    }
1649
1650    fn deserialize_tuple(
1651        &mut self,
1652        mut wip: Partial<'input, BORROW>,
1653    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1654        // Get field count for tuple hints (needed for non-self-describing formats like postcard)
1655        let field_count = match &wip.shape().ty {
1656            Type::User(UserType::Struct(def)) => def.fields.len(),
1657            _ => 0, // Unit type or unknown - will be handled below
1658        };
1659
1660        // Hint to non-self-describing parsers how many fields to expect
1661        // Tuples are like positional structs, so we use hint_struct_fields
1662        self.parser.hint_struct_fields(field_count);
1663
1664        let event = self.expect_event("value")?;
1665
1666        // Accept either SequenceStart (JSON arrays) or StructStart (for XML elements or
1667        // non-self-describing formats like postcard where tuples are positional structs)
1668        let struct_mode = match event {
1669            ParseEvent::SequenceStart(_) => false,
1670            // Ambiguous containers (XML elements) always use struct mode
1671            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
1672            // For non-self-describing formats, StructStart(Object) is valid for tuples
1673            // because hint_struct_fields was called and tuples are positional structs
1674            ParseEvent::StructStart(_) if !self.parser.is_self_describing() => true,
1675            ParseEvent::StructStart(kind) => {
1676                return Err(DeserializeError::TypeMismatch {
1677                    expected: "array",
1678                    got: kind.name().into(),
1679                });
1680            }
1681            _ => {
1682                return Err(DeserializeError::TypeMismatch {
1683                    expected: "sequence start for tuple",
1684                    got: format!("{event:?}"),
1685                });
1686            }
1687        };
1688
1689        let mut index = 0usize;
1690        loop {
1691            let event = self.expect_peek("value")?;
1692
1693            // Check for end of container
1694            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
1695                self.expect_event("value")?;
1696                break;
1697            }
1698
1699            // In struct mode, skip FieldKey events
1700            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
1701                self.expect_event("value")?;
1702                continue;
1703            }
1704
1705            // Select field by index
1706            let field_name = alloc::string::ToString::to_string(&index);
1707            wip = wip
1708                .begin_field(&field_name)
1709                .map_err(DeserializeError::reflect)?;
1710            wip = self.deserialize_into(wip)?;
1711            wip = wip.end().map_err(DeserializeError::reflect)?;
1712            index += 1;
1713        }
1714
1715        Ok(wip)
1716    }
1717
1718    fn deserialize_enum(
1719        &mut self,
1720        wip: Partial<'input, BORROW>,
1721    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1722        let shape = wip.shape();
1723
1724        // Hint to non-self-describing parsers what variant metadata to expect
1725        if let Type::User(UserType::Enum(enum_def)) = &shape.ty {
1726            let variant_hints: Vec<crate::EnumVariantHint> = enum_def
1727                .variants
1728                .iter()
1729                .map(|v| crate::EnumVariantHint {
1730                    name: v.name,
1731                    kind: v.data.kind,
1732                    field_count: v.data.fields.len(),
1733                })
1734                .collect();
1735            self.parser.hint_enum(&variant_hints);
1736        }
1737
1738        // Check for different tagging modes
1739        let tag_attr = shape.get_tag_attr();
1740        let content_attr = shape.get_content_attr();
1741        let is_numeric = shape.is_numeric();
1742        let is_untagged = shape.is_untagged();
1743
1744        if is_numeric {
1745            return self.deserialize_numeric_enum(wip);
1746        }
1747
1748        // Determine tagging mode
1749        if is_untagged {
1750            return self.deserialize_enum_untagged(wip);
1751        }
1752
1753        if let (Some(tag_key), Some(content_key)) = (tag_attr, content_attr) {
1754            // Adjacently tagged: {"t": "VariantName", "c": {...}}
1755            return self.deserialize_enum_adjacently_tagged(wip, tag_key, content_key);
1756        }
1757
1758        if let Some(tag_key) = tag_attr {
1759            // Internally tagged: {"type": "VariantName", ...fields...}
1760            return self.deserialize_enum_internally_tagged(wip, tag_key);
1761        }
1762
1763        // Externally tagged (default): {"VariantName": {...}} or just "VariantName"
1764        self.deserialize_enum_externally_tagged(wip)
1765    }
1766
1767    fn deserialize_enum_externally_tagged(
1768        &mut self,
1769        mut wip: Partial<'input, BORROW>,
1770    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1771        let event = self.expect_peek("value")?;
1772
1773        // Check for unit variant (just a string)
1774        if let ParseEvent::Scalar(ScalarValue::Str(variant_name)) = &event {
1775            self.expect_event("value")?;
1776            wip = wip
1777                .select_variant_named(variant_name)
1778                .map_err(DeserializeError::reflect)?;
1779            return Ok(wip);
1780        }
1781
1782        // Otherwise expect a struct { VariantName: ... }
1783        if !matches!(event, ParseEvent::StructStart(_)) {
1784            return Err(DeserializeError::TypeMismatch {
1785                expected: "string or struct for enum",
1786                got: format!("{event:?}"),
1787            });
1788        }
1789
1790        self.expect_event("value")?; // consume StructStart
1791
1792        // Get the variant name
1793        let event = self.expect_event("value")?;
1794        let variant_name = match event {
1795            ParseEvent::FieldKey(key) => key.name,
1796            other => {
1797                return Err(DeserializeError::TypeMismatch {
1798                    expected: "variant name",
1799                    got: format!("{other:?}"),
1800                });
1801            }
1802        };
1803
1804        wip = wip
1805            .select_variant_named(&variant_name)
1806            .map_err(DeserializeError::reflect)?;
1807
1808        // Deserialize the variant content
1809        wip = self.deserialize_enum_variant_content(wip)?;
1810
1811        // Consume StructEnd
1812        let event = self.expect_event("value")?;
1813        if !matches!(event, ParseEvent::StructEnd) {
1814            return Err(DeserializeError::TypeMismatch {
1815                expected: "struct end after enum variant",
1816                got: format!("{event:?}"),
1817            });
1818        }
1819
1820        Ok(wip)
1821    }
1822
1823    fn deserialize_enum_internally_tagged(
1824        &mut self,
1825        mut wip: Partial<'input, BORROW>,
1826        tag_key: &str,
1827    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
1828        use facet_core::Characteristic;
1829
1830        // Step 1: Probe to find the tag value (handles out-of-order fields)
1831        let probe = self
1832            .parser
1833            .begin_probe()
1834            .map_err(DeserializeError::Parser)?;
1835        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;
1836
1837        let variant_name = Self::find_tag_value(&evidence, tag_key)
1838            .ok_or_else(|| DeserializeError::TypeMismatch {
1839                expected: "tag field in internally tagged enum",
1840                got: format!("missing '{tag_key}' field"),
1841            })?
1842            .to_string();
1843
1844        // Step 2: Consume StructStart
1845        let event = self.expect_event("value")?;
1846        if !matches!(event, ParseEvent::StructStart(_)) {
1847            return Err(DeserializeError::TypeMismatch {
1848                expected: "struct for internally tagged enum",
1849                got: format!("{event:?}"),
1850            });
1851        }
1852
1853        // Step 3: Select the variant
1854        wip = wip
1855            .select_variant_named(&variant_name)
1856            .map_err(DeserializeError::reflect)?;
1857
1858        // Get the selected variant info
1859        let variant = wip
1860            .selected_variant()
1861            .ok_or_else(|| DeserializeError::TypeMismatch {
1862                expected: "selected variant",
1863                got: "no variant selected".into(),
1864            })?;
1865
1866        let variant_fields = variant.data.fields;
1867
1868        // Check if this is a unit variant (no fields)
1869        if variant_fields.is_empty() || variant.data.kind == StructKind::Unit {
1870            // Consume remaining fields in the object
1871            loop {
1872                let event = self.expect_event("value")?;
1873                match event {
1874                    ParseEvent::StructEnd => break,
1875                    ParseEvent::FieldKey(_) => {
1876                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1877                    }
1878                    other => {
1879                        return Err(DeserializeError::TypeMismatch {
1880                            expected: "field key or struct end",
1881                            got: format!("{other:?}"),
1882                        });
1883                    }
1884                }
1885            }
1886            return Ok(wip);
1887        }
1888
1889        // Track which fields have been set
1890        let num_fields = variant_fields.len();
1891        let mut fields_set = alloc::vec![false; num_fields];
1892
1893        // Step 4: Process all fields (they can come in any order now)
1894        loop {
1895            let event = self.expect_event("value")?;
1896            match event {
1897                ParseEvent::StructEnd => break,
1898                ParseEvent::FieldKey(key) => {
1899                    // Skip the tag field - already used
1900                    if key.name.as_ref() == tag_key {
1901                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1902                        continue;
1903                    }
1904
1905                    // Look up field in variant's fields
1906                    // Uses namespace-aware matching when namespace is present
1907                    let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
1908                        Self::field_matches_with_namespace(
1909                            f,
1910                            key.name.as_ref(),
1911                            key.namespace.as_deref(),
1912                            key.location,
1913                            None, // Enums don't have ns_all
1914                        )
1915                    });
1916
1917                    if let Some((idx, _field)) = field_info {
1918                        wip = wip
1919                            .begin_nth_field(idx)
1920                            .map_err(DeserializeError::reflect)?;
1921                        wip = self.deserialize_into(wip)?;
1922                        wip = wip.end().map_err(DeserializeError::reflect)?;
1923                        fields_set[idx] = true;
1924                    } else {
1925                        // Unknown field - skip
1926                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
1927                    }
1928                }
1929                other => {
1930                    return Err(DeserializeError::TypeMismatch {
1931                        expected: "field key or struct end",
1932                        got: format!("{other:?}"),
1933                    });
1934                }
1935            }
1936        }
1937
1938        // Apply defaults for missing fields
1939        for (idx, field) in variant_fields.iter().enumerate() {
1940            if fields_set[idx] {
1941                continue;
1942            }
1943
1944            let field_has_default = field.has_default();
1945            let field_type_has_default = field.shape().is(Characteristic::Default);
1946            let field_is_option = matches!(field.shape().def, Def::Option(_));
1947
1948            if field_has_default || field_type_has_default {
1949                wip = wip
1950                    .set_nth_field_to_default(idx)
1951                    .map_err(DeserializeError::reflect)?;
1952            } else if field_is_option {
1953                wip = wip
1954                    .begin_nth_field(idx)
1955                    .map_err(DeserializeError::reflect)?;
1956                wip = wip.set_default().map_err(DeserializeError::reflect)?;
1957                wip = wip.end().map_err(DeserializeError::reflect)?;
1958            } else if field.should_skip_deserializing() {
1959                wip = wip
1960                    .set_nth_field_to_default(idx)
1961                    .map_err(DeserializeError::reflect)?;
1962            } else {
1963                return Err(DeserializeError::TypeMismatch {
1964                    expected: "field to be present or have default",
1965                    got: format!("missing field '{}'", field.name),
1966                });
1967            }
1968        }
1969
1970        Ok(wip)
1971    }
1972
1973    /// Helper to find a tag value from field evidence.
1974    fn find_tag_value<'a>(
1975        evidence: &'a [crate::FieldEvidence<'input>],
1976        tag_key: &str,
1977    ) -> Option<&'a str> {
1978        evidence
1979            .iter()
1980            .find(|e| e.name == tag_key)
1981            .and_then(|e| match &e.scalar_value {
1982                Some(ScalarValue::Str(s)) => Some(s.as_ref()),
1983                _ => None,
1984            })
1985    }
1986
1987    /// Helper to collect all evidence from a probe stream.
1988    fn collect_evidence<S: crate::ProbeStream<'input, Error = P::Error>>(
1989        mut probe: S,
1990    ) -> Result<alloc::vec::Vec<crate::FieldEvidence<'input>>, P::Error> {
1991        let mut evidence = alloc::vec::Vec::new();
1992        while let Some(ev) = probe.next()? {
1993            evidence.push(ev);
1994        }
1995        Ok(evidence)
1996    }
1997
1998    fn deserialize_enum_adjacently_tagged(
1999        &mut self,
2000        mut wip: Partial<'input, BORROW>,
2001        tag_key: &str,
2002        content_key: &str,
2003    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2004        // Step 1: Probe to find the tag value (handles out-of-order fields)
2005        let probe = self
2006            .parser
2007            .begin_probe()
2008            .map_err(DeserializeError::Parser)?;
2009        let evidence = Self::collect_evidence(probe).map_err(DeserializeError::Parser)?;
2010
2011        let variant_name = Self::find_tag_value(&evidence, tag_key)
2012            .ok_or_else(|| DeserializeError::TypeMismatch {
2013                expected: "tag field in adjacently tagged enum",
2014                got: format!("missing '{tag_key}' field"),
2015            })?
2016            .to_string();
2017
2018        // Step 2: Consume StructStart
2019        let event = self.expect_event("value")?;
2020        if !matches!(event, ParseEvent::StructStart(_)) {
2021            return Err(DeserializeError::TypeMismatch {
2022                expected: "struct for adjacently tagged enum",
2023                got: format!("{event:?}"),
2024            });
2025        }
2026
2027        // Step 3: Select the variant
2028        wip = wip
2029            .select_variant_named(&variant_name)
2030            .map_err(DeserializeError::reflect)?;
2031
2032        // Step 4: Process fields in any order
2033        let mut content_seen = false;
2034        loop {
2035            let event = self.expect_event("value")?;
2036            match event {
2037                ParseEvent::StructEnd => break,
2038                ParseEvent::FieldKey(key) => {
2039                    if key.name.as_ref() == tag_key {
2040                        // Skip the tag field - already used
2041                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
2042                    } else if key.name.as_ref() == content_key {
2043                        // Deserialize the content
2044                        wip = self.deserialize_enum_variant_content(wip)?;
2045                        content_seen = true;
2046                    } else {
2047                        // Unknown field - skip
2048                        self.parser.skip_value().map_err(DeserializeError::Parser)?;
2049                    }
2050                }
2051                other => {
2052                    return Err(DeserializeError::TypeMismatch {
2053                        expected: "field key or struct end",
2054                        got: format!("{other:?}"),
2055                    });
2056                }
2057            }
2058        }
2059
2060        // If no content field was present, it's a unit variant (already selected above)
2061        if !content_seen {
2062            // Check if the variant expects content
2063            let variant = wip.selected_variant();
2064            if let Some(v) = variant
2065                && v.data.kind != StructKind::Unit
2066                && !v.data.fields.is_empty()
2067            {
2068                return Err(DeserializeError::TypeMismatch {
2069                    expected: "content field for non-unit variant",
2070                    got: format!("missing '{content_key}' field"),
2071                });
2072            }
2073        }
2074
2075        Ok(wip)
2076    }
2077
2078    fn deserialize_enum_variant_content(
2079        &mut self,
2080        mut wip: Partial<'input, BORROW>,
2081    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2082        use facet_core::Characteristic;
2083
2084        // Get the selected variant's info
2085        let variant = wip
2086            .selected_variant()
2087            .ok_or_else(|| DeserializeError::TypeMismatch {
2088                expected: "selected variant",
2089                got: "no variant selected".into(),
2090            })?;
2091
2092        let variant_kind = variant.data.kind;
2093        let variant_fields = variant.data.fields;
2094
2095        match variant_kind {
2096            StructKind::Unit => {
2097                // Unit variant - nothing to deserialize
2098                // But we might have gotten here with content that should be consumed
2099                Ok(wip)
2100            }
2101            StructKind::Tuple | StructKind::TupleStruct => {
2102                if variant_fields.len() == 1 {
2103                    // Newtype variant - content is the single field's value
2104                    wip = wip.begin_nth_field(0).map_err(DeserializeError::reflect)?;
2105                    wip = self.deserialize_into(wip)?;
2106                    wip = wip.end().map_err(DeserializeError::reflect)?;
2107                } else {
2108                    // Multi-field tuple variant - expect array or struct (for XML)
2109                    let event = self.expect_event("value")?;
2110
2111                    // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
2112                    let struct_mode = match event {
2113                        ParseEvent::SequenceStart(_) => false,
2114                        ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
2115                        ParseEvent::StructStart(kind) => {
2116                            return Err(DeserializeError::TypeMismatch {
2117                                expected: "array",
2118                                got: kind.name().into(),
2119                            });
2120                        }
2121                        _ => {
2122                            return Err(DeserializeError::TypeMismatch {
2123                                expected: "sequence for tuple variant",
2124                                got: format!("{event:?}"),
2125                            });
2126                        }
2127                    };
2128
2129                    let mut idx = 0;
2130                    while idx < variant_fields.len() {
2131                        // In struct mode, skip FieldKey events
2132                        if struct_mode {
2133                            let event = self.expect_peek("value")?;
2134                            if matches!(event, ParseEvent::FieldKey(_)) {
2135                                self.expect_event("value")?;
2136                                continue;
2137                            }
2138                        }
2139
2140                        wip = wip
2141                            .begin_nth_field(idx)
2142                            .map_err(DeserializeError::reflect)?;
2143                        wip = self.deserialize_into(wip)?;
2144                        wip = wip.end().map_err(DeserializeError::reflect)?;
2145                        idx += 1;
2146                    }
2147
2148                    let event = self.expect_event("value")?;
2149                    if !matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
2150                        return Err(DeserializeError::TypeMismatch {
2151                            expected: "sequence end for tuple variant",
2152                            got: format!("{event:?}"),
2153                        });
2154                    }
2155                }
2156                Ok(wip)
2157            }
2158            StructKind::Struct => {
2159                // Struct variant - expect object with fields
2160                let event = self.expect_event("value")?;
2161                if !matches!(event, ParseEvent::StructStart(_)) {
2162                    return Err(DeserializeError::TypeMismatch {
2163                        expected: "struct for struct variant",
2164                        got: format!("{event:?}"),
2165                    });
2166                }
2167
2168                let num_fields = variant_fields.len();
2169                let mut fields_set = alloc::vec![false; num_fields];
2170                let mut ordered_field_index = 0usize;
2171
2172                loop {
2173                    let event = self.expect_event("value")?;
2174                    match event {
2175                        ParseEvent::StructEnd => break,
2176                        ParseEvent::OrderedField => {
2177                            // Non-self-describing formats emit OrderedField events in order
2178                            let idx = ordered_field_index;
2179                            ordered_field_index += 1;
2180                            if idx < num_fields {
2181                                wip = wip
2182                                    .begin_nth_field(idx)
2183                                    .map_err(DeserializeError::reflect)?;
2184                                wip = self.deserialize_into(wip)?;
2185                                wip = wip.end().map_err(DeserializeError::reflect)?;
2186                                fields_set[idx] = true;
2187                            }
2188                        }
2189                        ParseEvent::FieldKey(key) => {
2190                            // Uses namespace-aware matching when namespace is present
2191                            let field_info = variant_fields.iter().enumerate().find(|(_, f)| {
2192                                Self::field_matches_with_namespace(
2193                                    f,
2194                                    key.name.as_ref(),
2195                                    key.namespace.as_deref(),
2196                                    key.location,
2197                                    None, // Enums don't have ns_all
2198                                )
2199                            });
2200
2201                            if let Some((idx, _field)) = field_info {
2202                                wip = wip
2203                                    .begin_nth_field(idx)
2204                                    .map_err(DeserializeError::reflect)?;
2205                                wip = self.deserialize_into(wip)?;
2206                                wip = wip.end().map_err(DeserializeError::reflect)?;
2207                                fields_set[idx] = true;
2208                            } else {
2209                                // Unknown field - skip
2210                                self.parser.skip_value().map_err(DeserializeError::Parser)?;
2211                            }
2212                        }
2213                        other => {
2214                            return Err(DeserializeError::TypeMismatch {
2215                                expected: "field key, ordered field, or struct end",
2216                                got: format!("{other:?}"),
2217                            });
2218                        }
2219                    }
2220                }
2221
2222                // Apply defaults for missing fields
2223                for (idx, field) in variant_fields.iter().enumerate() {
2224                    if fields_set[idx] {
2225                        continue;
2226                    }
2227
2228                    let field_has_default = field.has_default();
2229                    let field_type_has_default = field.shape().is(Characteristic::Default);
2230                    let field_is_option = matches!(field.shape().def, Def::Option(_));
2231
2232                    if field_has_default || field_type_has_default {
2233                        wip = wip
2234                            .set_nth_field_to_default(idx)
2235                            .map_err(DeserializeError::reflect)?;
2236                    } else if field_is_option {
2237                        wip = wip
2238                            .begin_nth_field(idx)
2239                            .map_err(DeserializeError::reflect)?;
2240                        wip = wip.set_default().map_err(DeserializeError::reflect)?;
2241                        wip = wip.end().map_err(DeserializeError::reflect)?;
2242                    } else if field.should_skip_deserializing() {
2243                        wip = wip
2244                            .set_nth_field_to_default(idx)
2245                            .map_err(DeserializeError::reflect)?;
2246                    } else {
2247                        return Err(DeserializeError::TypeMismatch {
2248                            expected: "field to be present or have default",
2249                            got: format!("missing field '{}'", field.name),
2250                        });
2251                    }
2252                }
2253
2254                Ok(wip)
2255            }
2256        }
2257    }
2258
2259    fn deserialize_numeric_enum(
2260        &mut self,
2261        mut wip: Partial<'input, BORROW>,
2262    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2263        let event = self.parser.peek_event().map_err(DeserializeError::Parser)?;
2264
2265        if let Some(ParseEvent::Scalar(scalar)) = event {
2266            let span = self.last_span;
2267            wip = match scalar {
2268                ScalarValue::I64(discriminant) => wip
2269                    .select_variant(discriminant)
2270                    .map_err(|error| DeserializeError::Reflect { error, span })?,
2271                ScalarValue::U64(discriminant) => wip
2272                    .select_variant(discriminant as i64)
2273                    .map_err(|error| DeserializeError::Reflect { error, span })?,
2274                ScalarValue::Str(str_discriminant) => {
2275                    let discriminant =
2276                        str_discriminant
2277                            .parse()
2278                            .map_err(|_| DeserializeError::TypeMismatch {
2279                                expected: "String representing an integer (i64)",
2280                                got: str_discriminant.to_string(),
2281                            })?;
2282                    wip.select_variant(discriminant)
2283                        .map_err(|error| DeserializeError::Reflect { error, span })?
2284                }
2285                _ => {
2286                    return Err(DeserializeError::Unsupported(
2287                        "Unexpected ScalarValue".to_string(),
2288                    ));
2289                }
2290            };
2291            self.parser.next_event().map_err(DeserializeError::Parser)?;
2292            Ok(wip)
2293        } else {
2294            Err(DeserializeError::Unsupported(
2295                "Expected integer value".to_string(),
2296            ))
2297        }
2298    }
2299
2300    fn deserialize_enum_untagged(
2301        &mut self,
2302        mut wip: Partial<'input, BORROW>,
2303    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2304        use facet_solver::VariantsByFormat;
2305
2306        let shape = wip.shape();
2307        let variants_by_format = VariantsByFormat::from_shape(shape).ok_or_else(|| {
2308            DeserializeError::Unsupported("expected enum type for untagged".into())
2309        })?;
2310
2311        let event = self.expect_peek("value")?;
2312
2313        match &event {
2314            ParseEvent::Scalar(scalar) => {
2315                // Try unit variants for null
2316                if matches!(scalar, ScalarValue::Null)
2317                    && let Some(variant) = variants_by_format.unit_variants.first()
2318                {
2319                    wip = wip
2320                        .select_variant_named(variant.name)
2321                        .map_err(DeserializeError::reflect)?;
2322                    // Consume the null
2323                    self.expect_event("value")?;
2324                    return Ok(wip);
2325                }
2326
2327                // Try unit variants for string values (match variant name)
2328                // This handles untagged enums with only unit variants like:
2329                // #[facet(untagged)] enum Color { Red, Green, Blue }
2330                // which deserialize from "Red", "Green", "Blue"
2331                if let ScalarValue::Str(s) = scalar {
2332                    for variant in &variants_by_format.unit_variants {
2333                        // Match against variant name or rename attribute
2334                        let variant_display_name = variant
2335                            .get_builtin_attr("rename")
2336                            .and_then(|attr| attr.get_as::<&str>().copied())
2337                            .unwrap_or(variant.name);
2338                        if s.as_ref() == variant_display_name {
2339                            wip = wip
2340                                .select_variant_named(variant.name)
2341                                .map_err(DeserializeError::reflect)?;
2342                            // Consume the string
2343                            self.expect_event("value")?;
2344                            return Ok(wip);
2345                        }
2346                    }
2347                }
2348
2349                // Try scalar variants
2350                // For untagged enums, we should try to deserialize each scalar variant in order.
2351                // This handles both primitive scalars (String, i32, etc.) and complex types that
2352                // can be deserialized from scalars (e.g., enums with #[facet(rename)]).
2353                //
2354                // Note: We can't easily back track parser state, so we only try the first variant
2355                // that matches. For proper untagged behavior with multiple possibilities, we'd need
2356                // to either:
2357                // 1. Implement parser checkpointing/backtracking
2358                // 2. Use a probe to determine which variant will succeed before attempting deserialization
2359                //
2360                // For now, we prioritize variants that match primitive scalars (fast path),
2361                // then try other scalar variants.
2362
2363                // First try variants that match primitive scalar types (fast path for String, i32, etc.)
2364                for (variant, inner_shape) in &variants_by_format.scalar_variants {
2365                    if self.scalar_matches_shape(scalar, inner_shape) {
2366                        wip = wip
2367                            .select_variant_named(variant.name)
2368                            .map_err(DeserializeError::reflect)?;
2369                        wip = self.deserialize_enum_variant_content(wip)?;
2370                        return Ok(wip);
2371                    }
2372                }
2373
2374                // Then try other scalar variants that don't match primitive types.
2375                // This handles cases like newtype variants wrapping enums with #[facet(rename)]:
2376                //   #[facet(untagged)]
2377                //   enum EditionOrWorkspace {
2378                //       Edition(Edition),  // Edition is an enum with #[facet(rename = "2024")]
2379                //       Workspace(WorkspaceRef),
2380                //   }
2381                // When deserializing "2024", Edition doesn't match as a primitive scalar,
2382                // but it CAN be deserialized from the string via its renamed unit variants.
2383                for (variant, inner_shape) in &variants_by_format.scalar_variants {
2384                    if !self.scalar_matches_shape(scalar, inner_shape) {
2385                        wip = wip
2386                            .select_variant_named(variant.name)
2387                            .map_err(DeserializeError::reflect)?;
2388                        // Try to deserialize - if this fails, it will bubble up as an error.
2389                        // TODO: Implement proper variant trying with backtracking for better error messages
2390                        wip = self.deserialize_enum_variant_content(wip)?;
2391                        return Ok(wip);
2392                    }
2393                }
2394
2395                Err(DeserializeError::TypeMismatch {
2396                    expected: "matching untagged variant for scalar",
2397                    got: format!("{:?}", scalar),
2398                })
2399            }
2400            ParseEvent::StructStart(_) => {
2401                // For struct input, use solve_variant for proper field-based matching
2402                match crate::solve_variant(shape, &mut self.parser) {
2403                    Ok(Some(outcome)) => {
2404                        // Successfully identified which variant matches based on fields
2405                        let resolution = outcome.resolution();
2406                        // For top-level untagged enum, there should be exactly one variant selection
2407                        let variant_name = resolution
2408                            .variant_selections()
2409                            .first()
2410                            .map(|vs| vs.variant_name)
2411                            .ok_or_else(|| {
2412                                DeserializeError::Unsupported(
2413                                    "solved resolution has no variant selection".into(),
2414                                )
2415                            })?;
2416                        wip = wip
2417                            .select_variant_named(variant_name)
2418                            .map_err(DeserializeError::reflect)?;
2419                        wip = self.deserialize_enum_variant_content(wip)?;
2420                        Ok(wip)
2421                    }
2422                    Ok(None) => {
2423                        // No variant matched - fall back to trying the first struct variant
2424                        // (we can't backtrack parser state to try multiple variants)
2425                        if let Some(variant) = variants_by_format.struct_variants.first() {
2426                            wip = wip
2427                                .select_variant_named(variant.name)
2428                                .map_err(DeserializeError::reflect)?;
2429                            wip = self.deserialize_enum_variant_content(wip)?;
2430                            Ok(wip)
2431                        } else {
2432                            Err(DeserializeError::Unsupported(
2433                                "no struct variant found for untagged enum with struct input"
2434                                    .into(),
2435                            ))
2436                        }
2437                    }
2438                    Err(_) => Err(DeserializeError::Unsupported(
2439                        "failed to solve variant for untagged enum".into(),
2440                    )),
2441                }
2442            }
2443            ParseEvent::SequenceStart(_) => {
2444                // For sequence input, use first tuple variant
2445                if let Some((variant, _arity)) = variants_by_format.tuple_variants.first() {
2446                    wip = wip
2447                        .select_variant_named(variant.name)
2448                        .map_err(DeserializeError::reflect)?;
2449                    wip = self.deserialize_enum_variant_content(wip)?;
2450                    return Ok(wip);
2451                }
2452
2453                Err(DeserializeError::Unsupported(
2454                    "no tuple variant found for untagged enum with sequence input".into(),
2455                ))
2456            }
2457            _ => Err(DeserializeError::TypeMismatch {
2458                expected: "scalar, struct, or sequence for untagged enum",
2459                got: format!("{:?}", event),
2460            }),
2461        }
2462    }
2463
2464    fn scalar_matches_shape(
2465        &self,
2466        scalar: &ScalarValue<'input>,
2467        shape: &'static facet_core::Shape,
2468    ) -> bool {
2469        use facet_core::ScalarType;
2470
2471        let Some(scalar_type) = shape.scalar_type() else {
2472            // Not a scalar type - check for Option wrapping null
2473            if matches!(scalar, ScalarValue::Null) {
2474                return matches!(shape.def, Def::Option(_));
2475            }
2476            return false;
2477        };
2478
2479        match scalar {
2480            ScalarValue::Bool(_) => matches!(scalar_type, ScalarType::Bool),
2481            ScalarValue::I64(val) => {
2482                // I64 matches signed types directly
2483                if matches!(
2484                    scalar_type,
2485                    ScalarType::I8
2486                        | ScalarType::I16
2487                        | ScalarType::I32
2488                        | ScalarType::I64
2489                        | ScalarType::I128
2490                        | ScalarType::ISize
2491                ) {
2492                    return true;
2493                }
2494
2495                // I64 can also match unsigned types if the value is non-negative and in range
2496                // This handles TOML's requirement to represent all integers as i64
2497                if *val >= 0 {
2498                    let uval = *val as u64;
2499                    match scalar_type {
2500                        ScalarType::U8 => uval <= u8::MAX as u64,
2501                        ScalarType::U16 => uval <= u16::MAX as u64,
2502                        ScalarType::U32 => uval <= u32::MAX as u64,
2503                        ScalarType::U64 | ScalarType::U128 | ScalarType::USize => true,
2504                        _ => false,
2505                    }
2506                } else {
2507                    false
2508                }
2509            }
2510            ScalarValue::U64(_) => matches!(
2511                scalar_type,
2512                ScalarType::U8
2513                    | ScalarType::U16
2514                    | ScalarType::U32
2515                    | ScalarType::U64
2516                    | ScalarType::U128
2517                    | ScalarType::USize
2518            ),
2519            ScalarValue::U128(_) => matches!(scalar_type, ScalarType::U128 | ScalarType::I128),
2520            ScalarValue::I128(_) => matches!(scalar_type, ScalarType::I128 | ScalarType::U128),
2521            ScalarValue::F64(_) => matches!(scalar_type, ScalarType::F32 | ScalarType::F64),
2522            ScalarValue::Str(_) => matches!(
2523                scalar_type,
2524                ScalarType::String | ScalarType::Str | ScalarType::CowStr | ScalarType::Char
2525            ),
2526            ScalarValue::Bytes(_) => {
2527                // Bytes don't have a ScalarType - would need to check for Vec<u8> or [u8]
2528                false
2529            }
2530            ScalarValue::Null => {
2531                // Null matches Unit type
2532                matches!(scalar_type, ScalarType::Unit)
2533            }
2534        }
2535    }
2536
2537    fn deserialize_list(
2538        &mut self,
2539        mut wip: Partial<'input, BORROW>,
2540    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2541        // Hint to non-self-describing parsers that a sequence is expected
2542        self.parser.hint_sequence();
2543
2544        let event = self.expect_event("value")?;
2545
2546        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
2547        // In struct mode, we skip FieldKey events and treat values as sequence items
2548        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
2549        let struct_mode = match event {
2550            ParseEvent::SequenceStart(_) => false,
2551            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
2552            ParseEvent::StructStart(kind) => {
2553                return Err(DeserializeError::TypeMismatch {
2554                    expected: "array",
2555                    got: kind.name().into(),
2556                });
2557            }
2558            _ => {
2559                return Err(DeserializeError::TypeMismatch {
2560                    expected: "sequence start",
2561                    got: format!("{event:?}"),
2562                });
2563            }
2564        };
2565
2566        // Initialize the list
2567        wip = wip.begin_list().map_err(DeserializeError::reflect)?;
2568
2569        loop {
2570            let event = self.expect_peek("value")?;
2571
2572            // Check for end of container
2573            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
2574                self.expect_event("value")?;
2575                break;
2576            }
2577
2578            // In struct mode, skip FieldKey events (they're just labels for items)
2579            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
2580                self.expect_event("value")?;
2581                continue;
2582            }
2583
2584            wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
2585            wip = self.deserialize_into(wip)?;
2586            wip = wip.end().map_err(DeserializeError::reflect)?;
2587        }
2588
2589        Ok(wip)
2590    }
2591
2592    fn deserialize_array(
2593        &mut self,
2594        mut wip: Partial<'input, BORROW>,
2595    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2596        // Get the fixed array length from the type definition
2597        let array_len = match &wip.shape().def {
2598            Def::Array(array_def) => array_def.n,
2599            _ => {
2600                return Err(DeserializeError::Unsupported(
2601                    "deserialize_array called on non-array type".into(),
2602                ));
2603            }
2604        };
2605
2606        // Hint to non-self-describing parsers that a fixed-size array is expected
2607        // (unlike hint_sequence, this doesn't read a length prefix)
2608        self.parser.hint_array(array_len);
2609
2610        let event = self.expect_event("value")?;
2611
2612        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
2613        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
2614        let struct_mode = match event {
2615            ParseEvent::SequenceStart(_) => false,
2616            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
2617            ParseEvent::StructStart(kind) => {
2618                return Err(DeserializeError::TypeMismatch {
2619                    expected: "array",
2620                    got: kind.name().into(),
2621                });
2622            }
2623            _ => {
2624                return Err(DeserializeError::TypeMismatch {
2625                    expected: "sequence start for array",
2626                    got: format!("{event:?}"),
2627                });
2628            }
2629        };
2630
2631        // Transition to Array tracker state. This is important for empty arrays
2632        // like [u8; 0] which have no elements to initialize but still need
2633        // their tracker state set correctly for require_full_initialization to pass.
2634        wip = wip.begin_array().map_err(DeserializeError::reflect)?;
2635
2636        let mut index = 0usize;
2637        loop {
2638            let event = self.expect_peek("value")?;
2639
2640            // Check for end of container
2641            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
2642                self.expect_event("value")?;
2643                break;
2644            }
2645
2646            // In struct mode, skip FieldKey events
2647            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
2648                self.expect_event("value")?;
2649                continue;
2650            }
2651
2652            wip = wip
2653                .begin_nth_field(index)
2654                .map_err(DeserializeError::reflect)?;
2655            wip = self.deserialize_into(wip)?;
2656            wip = wip.end().map_err(DeserializeError::reflect)?;
2657            index += 1;
2658        }
2659
2660        Ok(wip)
2661    }
2662
2663    fn deserialize_set(
2664        &mut self,
2665        mut wip: Partial<'input, BORROW>,
2666    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2667        // Hint to non-self-describing parsers that a sequence is expected
2668        self.parser.hint_sequence();
2669
2670        let event = self.expect_event("value")?;
2671
2672        // Accept either SequenceStart (JSON arrays) or StructStart (XML elements)
2673        // Only accept StructStart if the container kind is ambiguous (e.g., XML Element)
2674        let struct_mode = match event {
2675            ParseEvent::SequenceStart(_) => false,
2676            ParseEvent::StructStart(kind) if kind.is_ambiguous() => true,
2677            ParseEvent::StructStart(kind) => {
2678                return Err(DeserializeError::TypeMismatch {
2679                    expected: "array",
2680                    got: kind.name().into(),
2681                });
2682            }
2683            _ => {
2684                return Err(DeserializeError::TypeMismatch {
2685                    expected: "sequence start for set",
2686                    got: format!("{event:?}"),
2687                });
2688            }
2689        };
2690
2691        // Initialize the set
2692        wip = wip.begin_set().map_err(DeserializeError::reflect)?;
2693
2694        loop {
2695            let event = self.expect_peek("value")?;
2696
2697            // Check for end of container
2698            if matches!(event, ParseEvent::SequenceEnd | ParseEvent::StructEnd) {
2699                self.expect_event("value")?;
2700                break;
2701            }
2702
2703            // In struct mode, skip FieldKey events
2704            if struct_mode && matches!(event, ParseEvent::FieldKey(_)) {
2705                self.expect_event("value")?;
2706                continue;
2707            }
2708
2709            wip = wip.begin_set_item().map_err(DeserializeError::reflect)?;
2710            wip = self.deserialize_into(wip)?;
2711            wip = wip.end().map_err(DeserializeError::reflect)?;
2712        }
2713
2714        Ok(wip)
2715    }
2716
2717    fn deserialize_map(
2718        &mut self,
2719        mut wip: Partial<'input, BORROW>,
2720    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2721        // For non-self-describing formats, hint that a map is expected
2722        self.parser.hint_map();
2723
2724        let event = self.expect_event("value")?;
2725
2726        // Initialize the map
2727        wip = wip.begin_map().map_err(DeserializeError::reflect)?;
2728
2729        // Handle both self-describing (StructStart) and non-self-describing (SequenceStart) formats
2730        match event {
2731            ParseEvent::StructStart(_) => {
2732                // Self-describing format (e.g., JSON): maps are represented as objects
2733                loop {
2734                    let event = self.expect_event("value")?;
2735                    match event {
2736                        ParseEvent::StructEnd => break,
2737                        ParseEvent::FieldKey(key) => {
2738                            // Begin key
2739                            wip = wip.begin_key().map_err(DeserializeError::reflect)?;
2740                            wip = self.deserialize_map_key(wip, key.name)?;
2741                            wip = wip.end().map_err(DeserializeError::reflect)?;
2742
2743                            // Begin value
2744                            wip = wip.begin_value().map_err(DeserializeError::reflect)?;
2745                            wip = self.deserialize_into(wip)?;
2746                            wip = wip.end().map_err(DeserializeError::reflect)?;
2747                        }
2748                        other => {
2749                            return Err(DeserializeError::TypeMismatch {
2750                                expected: "field key or struct end for map",
2751                                got: format!("{other:?}"),
2752                            });
2753                        }
2754                    }
2755                }
2756            }
2757            ParseEvent::SequenceStart(_) => {
2758                // Non-self-describing format (e.g., postcard): maps are sequences of key-value pairs
2759                loop {
2760                    let event = self.expect_peek("value")?;
2761                    match event {
2762                        ParseEvent::SequenceEnd => {
2763                            self.expect_event("value")?;
2764                            break;
2765                        }
2766                        ParseEvent::OrderedField => {
2767                            self.expect_event("value")?;
2768
2769                            // Deserialize key
2770                            wip = wip.begin_key().map_err(DeserializeError::reflect)?;
2771                            wip = self.deserialize_into(wip)?;
2772                            wip = wip.end().map_err(DeserializeError::reflect)?;
2773
2774                            // Deserialize value
2775                            wip = wip.begin_value().map_err(DeserializeError::reflect)?;
2776                            wip = self.deserialize_into(wip)?;
2777                            wip = wip.end().map_err(DeserializeError::reflect)?;
2778                        }
2779                        other => {
2780                            return Err(DeserializeError::TypeMismatch {
2781                                expected: "ordered field or sequence end for map",
2782                                got: format!("{other:?}"),
2783                            });
2784                        }
2785                    }
2786                }
2787            }
2788            other => {
2789                return Err(DeserializeError::TypeMismatch {
2790                    expected: "struct start or sequence start for map",
2791                    got: format!("{other:?}"),
2792                });
2793            }
2794        }
2795
2796        Ok(wip)
2797    }
2798
2799    fn deserialize_scalar(
2800        &mut self,
2801        mut wip: Partial<'input, BORROW>,
2802    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2803        // Hint to non-self-describing parsers what scalar type is expected
2804        let shape = wip.shape();
2805
2806        // First, try hint_opaque_scalar for types that may have format-specific
2807        // binary representations (e.g., UUID as 16 raw bytes in postcard)
2808        let opaque_handled = match shape.type_identifier {
2809            // Standard primitives are never opaque
2810            "bool" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32"
2811            | "i64" | "i128" | "isize" | "f32" | "f64" | "String" | "&str" | "char" => false,
2812            // For all other scalar types, ask the parser if it handles them specially
2813            _ => self.parser.hint_opaque_scalar(shape.type_identifier, shape),
2814        };
2815
2816        // If the parser didn't handle the opaque type, fall back to standard hints
2817        if !opaque_handled {
2818            let hint = match shape.type_identifier {
2819                "bool" => Some(ScalarTypeHint::Bool),
2820                "u8" => Some(ScalarTypeHint::U8),
2821                "u16" => Some(ScalarTypeHint::U16),
2822                "u32" => Some(ScalarTypeHint::U32),
2823                "u64" => Some(ScalarTypeHint::U64),
2824                "u128" => Some(ScalarTypeHint::U128),
2825                "usize" => Some(ScalarTypeHint::Usize),
2826                "i8" => Some(ScalarTypeHint::I8),
2827                "i16" => Some(ScalarTypeHint::I16),
2828                "i32" => Some(ScalarTypeHint::I32),
2829                "i64" => Some(ScalarTypeHint::I64),
2830                "i128" => Some(ScalarTypeHint::I128),
2831                "isize" => Some(ScalarTypeHint::Isize),
2832                "f32" => Some(ScalarTypeHint::F32),
2833                "f64" => Some(ScalarTypeHint::F64),
2834                "String" | "&str" => Some(ScalarTypeHint::String),
2835                "char" => Some(ScalarTypeHint::Char),
2836                // For unknown scalar types, check if they implement FromStr
2837                // (e.g., camino::Utf8PathBuf, types not handled by hint_opaque_scalar)
2838                _ if shape.is_from_str() => Some(ScalarTypeHint::String),
2839                _ => None,
2840            };
2841            if let Some(hint) = hint {
2842                self.parser.hint_scalar_type(hint);
2843            }
2844        }
2845
2846        let event = self.expect_event("value")?;
2847
2848        match event {
2849            ParseEvent::Scalar(scalar) => {
2850                wip = self.set_scalar(wip, scalar)?;
2851                Ok(wip)
2852            }
2853            other => Err(DeserializeError::TypeMismatch {
2854                expected: "scalar value",
2855                got: format!("{other:?}"),
2856            }),
2857        }
2858    }
2859
2860    fn set_scalar(
2861        &mut self,
2862        mut wip: Partial<'input, BORROW>,
2863        scalar: ScalarValue<'input>,
2864    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
2865        let shape = wip.shape();
2866        // Capture the span for error reporting - this is where the scalar value was parsed
2867        let span = self.last_span;
2868        let reflect_err = |e: ReflectError| DeserializeError::Reflect { error: e, span };
2869
2870        match scalar {
2871            ScalarValue::Null => {
2872                wip = wip.set_default().map_err(&reflect_err)?;
2873            }
2874            ScalarValue::Bool(b) => {
2875                wip = wip.set(b).map_err(&reflect_err)?;
2876            }
2877            ScalarValue::I64(n) => {
2878                // Handle signed types
2879                if shape.type_identifier == "i8" {
2880                    wip = wip.set(n as i8).map_err(&reflect_err)?;
2881                } else if shape.type_identifier == "i16" {
2882                    wip = wip.set(n as i16).map_err(&reflect_err)?;
2883                } else if shape.type_identifier == "i32" {
2884                    wip = wip.set(n as i32).map_err(&reflect_err)?;
2885                } else if shape.type_identifier == "i64" {
2886                    wip = wip.set(n).map_err(&reflect_err)?;
2887                } else if shape.type_identifier == "i128" {
2888                    wip = wip.set(n as i128).map_err(&reflect_err)?;
2889                } else if shape.type_identifier == "isize" {
2890                    wip = wip.set(n as isize).map_err(&reflect_err)?;
2891                // Handle unsigned types (I64 can fit in unsigned if non-negative)
2892                } else if shape.type_identifier == "u8" {
2893                    wip = wip.set(n as u8).map_err(&reflect_err)?;
2894                } else if shape.type_identifier == "u16" {
2895                    wip = wip.set(n as u16).map_err(&reflect_err)?;
2896                } else if shape.type_identifier == "u32" {
2897                    wip = wip.set(n as u32).map_err(&reflect_err)?;
2898                } else if shape.type_identifier == "u64" {
2899                    wip = wip.set(n as u64).map_err(&reflect_err)?;
2900                } else if shape.type_identifier == "u128" {
2901                    wip = wip.set(n as u128).map_err(&reflect_err)?;
2902                } else if shape.type_identifier == "usize" {
2903                    wip = wip.set(n as usize).map_err(&reflect_err)?;
2904                // Handle floats
2905                } else if shape.type_identifier == "f32" {
2906                    wip = wip.set(n as f32).map_err(&reflect_err)?;
2907                } else if shape.type_identifier == "f64" {
2908                    wip = wip.set(n as f64).map_err(&reflect_err)?;
2909                // Handle String - stringify the number
2910                } else if shape.type_identifier == "String" {
2911                    wip = wip
2912                        .set(alloc::string::ToString::to_string(&n))
2913                        .map_err(&reflect_err)?;
2914                } else {
2915                    wip = wip.set(n).map_err(&reflect_err)?;
2916                }
2917            }
2918            ScalarValue::U64(n) => {
2919                // Handle unsigned types
2920                if shape.type_identifier == "u8" {
2921                    wip = wip.set(n as u8).map_err(&reflect_err)?;
2922                } else if shape.type_identifier == "u16" {
2923                    wip = wip.set(n as u16).map_err(&reflect_err)?;
2924                } else if shape.type_identifier == "u32" {
2925                    wip = wip.set(n as u32).map_err(&reflect_err)?;
2926                } else if shape.type_identifier == "u64" {
2927                    wip = wip.set(n).map_err(&reflect_err)?;
2928                } else if shape.type_identifier == "u128" {
2929                    wip = wip.set(n as u128).map_err(&reflect_err)?;
2930                } else if shape.type_identifier == "usize" {
2931                    wip = wip.set(n as usize).map_err(&reflect_err)?;
2932                // Handle signed types (U64 can fit in signed if small enough)
2933                } else if shape.type_identifier == "i8" {
2934                    wip = wip.set(n as i8).map_err(&reflect_err)?;
2935                } else if shape.type_identifier == "i16" {
2936                    wip = wip.set(n as i16).map_err(&reflect_err)?;
2937                } else if shape.type_identifier == "i32" {
2938                    wip = wip.set(n as i32).map_err(&reflect_err)?;
2939                } else if shape.type_identifier == "i64" {
2940                    wip = wip.set(n as i64).map_err(&reflect_err)?;
2941                } else if shape.type_identifier == "i128" {
2942                    wip = wip.set(n as i128).map_err(&reflect_err)?;
2943                } else if shape.type_identifier == "isize" {
2944                    wip = wip.set(n as isize).map_err(&reflect_err)?;
2945                // Handle floats
2946                } else if shape.type_identifier == "f32" {
2947                    wip = wip.set(n as f32).map_err(&reflect_err)?;
2948                } else if shape.type_identifier == "f64" {
2949                    wip = wip.set(n as f64).map_err(&reflect_err)?;
2950                // Handle String - stringify the number
2951                } else if shape.type_identifier == "String" {
2952                    wip = wip
2953                        .set(alloc::string::ToString::to_string(&n))
2954                        .map_err(&reflect_err)?;
2955                } else {
2956                    wip = wip.set(n).map_err(&reflect_err)?;
2957                }
2958            }
2959            ScalarValue::U128(n) => {
2960                // Handle u128 scalar
2961                if shape.type_identifier == "u128" {
2962                    wip = wip.set(n).map_err(&reflect_err)?;
2963                } else if shape.type_identifier == "i128" {
2964                    wip = wip.set(n as i128).map_err(&reflect_err)?;
2965                } else {
2966                    // For smaller types, truncate (caller should have used correct hint)
2967                    wip = wip.set(n as u64).map_err(&reflect_err)?;
2968                }
2969            }
2970            ScalarValue::I128(n) => {
2971                // Handle i128 scalar
2972                if shape.type_identifier == "i128" {
2973                    wip = wip.set(n).map_err(&reflect_err)?;
2974                } else if shape.type_identifier == "u128" {
2975                    wip = wip.set(n as u128).map_err(&reflect_err)?;
2976                } else {
2977                    // For smaller types, truncate (caller should have used correct hint)
2978                    wip = wip.set(n as i64).map_err(&reflect_err)?;
2979                }
2980            }
2981            ScalarValue::F64(n) => {
2982                if shape.type_identifier == "f32" {
2983                    wip = wip.set(n as f32).map_err(&reflect_err)?;
2984                } else if shape.type_identifier == "f64" {
2985                    wip = wip.set(n).map_err(&reflect_err)?;
2986                } else if shape.vtable.has_try_from() && shape.inner.is_some() {
2987                    // For opaque types with try_from (like NotNan, OrderedFloat), use
2988                    // begin_inner() + set + end() to trigger conversion
2989                    let inner_shape = shape.inner.unwrap();
2990                    wip = wip.begin_inner().map_err(&reflect_err)?;
2991                    if inner_shape.is_type::<f32>() {
2992                        wip = wip.set(n as f32).map_err(&reflect_err)?;
2993                    } else {
2994                        wip = wip.set(n).map_err(&reflect_err)?;
2995                    }
2996                    wip = wip.end().map_err(&reflect_err)?;
2997                } else {
2998                    wip = wip.set(n).map_err(&reflect_err)?;
2999                }
3000            }
3001            ScalarValue::Str(s) => {
3002                // Try parse_from_str first if the type supports it
3003                if shape.vtable.has_parse() {
3004                    wip = wip.parse_from_str(s.as_ref()).map_err(&reflect_err)?;
3005                } else {
3006                    wip = self.set_string_value(wip, s)?;
3007                }
3008            }
3009            ScalarValue::Bytes(b) => {
3010                // First try parse_from_bytes if the type supports it (e.g., UUID from 16 bytes)
3011                if shape.vtable.has_parse_bytes() {
3012                    wip = wip.parse_from_bytes(b.as_ref()).map_err(&reflect_err)?;
3013                } else {
3014                    // Fall back to setting as Vec<u8>
3015                    wip = wip.set(b.into_owned()).map_err(&reflect_err)?;
3016                }
3017            }
3018        }
3019
3020        Ok(wip)
3021    }
3022
3023    /// Set a string value, handling `&str`, `Cow<str>`, and `String` appropriately.
3024    fn set_string_value(
3025        &mut self,
3026        mut wip: Partial<'input, BORROW>,
3027        s: Cow<'input, str>,
3028    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
3029        let shape = wip.shape();
3030
3031        // Check if target is &str (shared reference to str)
3032        if let Def::Pointer(ptr_def) = shape.def
3033            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
3034            && ptr_def
3035                .pointee()
3036                .is_some_and(|p| p.type_identifier == "str")
3037        {
3038            // In owned mode, we cannot borrow from input at all
3039            if !BORROW {
3040                return Err(DeserializeError::CannotBorrow {
3041                    message: "cannot deserialize into &str when borrowing is disabled - use String or Cow<str> instead".into(),
3042                });
3043            }
3044            match s {
3045                Cow::Borrowed(borrowed) => {
3046                    wip = wip.set(borrowed).map_err(DeserializeError::reflect)?;
3047                    return Ok(wip);
3048                }
3049                Cow::Owned(_) => {
3050                    return Err(DeserializeError::CannotBorrow {
3051                        message: "cannot borrow &str from string containing escape sequences - use String or Cow<str> instead".into(),
3052                    });
3053                }
3054            }
3055        }
3056
3057        // Check if target is Cow<str>
3058        if let Def::Pointer(ptr_def) = shape.def
3059            && matches!(ptr_def.known, Some(KnownPointer::Cow))
3060            && ptr_def
3061                .pointee()
3062                .is_some_and(|p| p.type_identifier == "str")
3063        {
3064            wip = wip.set(s).map_err(DeserializeError::reflect)?;
3065            return Ok(wip);
3066        }
3067
3068        // Default: convert to owned String
3069        wip = wip.set(s.into_owned()).map_err(DeserializeError::reflect)?;
3070        Ok(wip)
3071    }
3072
3073    /// Set a bytes value with proper handling for borrowed vs owned data.
3074    ///
3075    /// This handles `&[u8]`, `Cow<[u8]>`, and `Vec<u8>` appropriately based on
3076    /// whether borrowing is enabled and whether the data is borrowed or owned.
3077    fn set_bytes_value(
3078        &mut self,
3079        mut wip: Partial<'input, BORROW>,
3080        b: Cow<'input, [u8]>,
3081    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
3082        let shape = wip.shape();
3083
3084        // Helper to check if a shape is a byte slice ([u8])
3085        let is_byte_slice = |pointee: &facet_core::Shape| matches!(pointee.def, Def::Slice(slice_def) if slice_def.t.type_identifier == "u8");
3086
3087        // Check if target is &[u8] (shared reference to byte slice)
3088        if let Def::Pointer(ptr_def) = shape.def
3089            && matches!(ptr_def.known, Some(KnownPointer::SharedReference))
3090            && ptr_def.pointee().is_some_and(is_byte_slice)
3091        {
3092            // In owned mode, we cannot borrow from input at all
3093            if !BORROW {
3094                return Err(DeserializeError::CannotBorrow {
3095                    message: "cannot deserialize into &[u8] when borrowing is disabled - use Vec<u8> or Cow<[u8]> instead".into(),
3096                });
3097            }
3098            match b {
3099                Cow::Borrowed(borrowed) => {
3100                    wip = wip.set(borrowed).map_err(DeserializeError::reflect)?;
3101                    return Ok(wip);
3102                }
3103                Cow::Owned(_) => {
3104                    return Err(DeserializeError::CannotBorrow {
3105                        message: "cannot borrow &[u8] from owned bytes - use Vec<u8> or Cow<[u8]> instead".into(),
3106                    });
3107                }
3108            }
3109        }
3110
3111        // Check if target is Cow<[u8]>
3112        if let Def::Pointer(ptr_def) = shape.def
3113            && matches!(ptr_def.known, Some(KnownPointer::Cow))
3114            && ptr_def.pointee().is_some_and(is_byte_slice)
3115        {
3116            wip = wip.set(b).map_err(DeserializeError::reflect)?;
3117            return Ok(wip);
3118        }
3119
3120        // Default: convert to owned Vec<u8>
3121        wip = wip.set(b.into_owned()).map_err(DeserializeError::reflect)?;
3122        Ok(wip)
3123    }
3124
3125    /// Deserialize a map key from a string.
3126    ///
3127    /// Format parsers typically emit string keys, but the target map might have non-string key types
3128    /// (e.g., integers, enums). This function parses the string key into the appropriate type:
3129    /// - String types: set directly
3130    /// - Enum unit variants: use select_variant_named
3131    /// - Integer types: parse the string as a number
3132    /// - Transparent newtypes: descend into the inner type
3133    fn deserialize_map_key(
3134        &mut self,
3135        mut wip: Partial<'input, BORROW>,
3136        key: Cow<'input, str>,
3137    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
3138        let shape = wip.shape();
3139
3140        // For transparent types (like UserId(String)), we need to use begin_inner
3141        // to set the inner value. But NOT for pointer types like &str or Cow<str>
3142        // which are handled directly.
3143        let is_pointer = matches!(shape.def, Def::Pointer(_));
3144        if shape.inner.is_some() && !is_pointer {
3145            wip = wip.begin_inner().map_err(DeserializeError::reflect)?;
3146            wip = self.deserialize_map_key(wip, key)?;
3147            wip = wip.end().map_err(DeserializeError::reflect)?;
3148            return Ok(wip);
3149        }
3150
3151        // Check if target is an enum - use select_variant_named for unit variants
3152        if let Type::User(UserType::Enum(_)) = &shape.ty {
3153            wip = wip
3154                .select_variant_named(&key)
3155                .map_err(DeserializeError::reflect)?;
3156            return Ok(wip);
3157        }
3158
3159        // Check if target is a numeric type - parse the string key as a number
3160        if let Type::Primitive(PrimitiveType::Numeric(num_ty)) = &shape.ty {
3161            match num_ty {
3162                NumericType::Integer { signed } => {
3163                    if *signed {
3164                        let n: i64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
3165                            expected: "valid integer for map key",
3166                            got: format!("string '{}'", key),
3167                        })?;
3168                        // Use set for each size - the Partial handles type conversion
3169                        wip = wip.set(n).map_err(DeserializeError::reflect)?;
3170                    } else {
3171                        let n: u64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
3172                            expected: "valid unsigned integer for map key",
3173                            got: format!("string '{}'", key),
3174                        })?;
3175                        wip = wip.set(n).map_err(DeserializeError::reflect)?;
3176                    }
3177                    return Ok(wip);
3178                }
3179                NumericType::Float => {
3180                    let n: f64 = key.parse().map_err(|_| DeserializeError::TypeMismatch {
3181                        expected: "valid float for map key",
3182                        got: format!("string '{}'", key),
3183                    })?;
3184                    wip = wip.set(n).map_err(DeserializeError::reflect)?;
3185                    return Ok(wip);
3186                }
3187            }
3188        }
3189
3190        // Default: treat as string
3191        wip = self.set_string_value(wip, key)?;
3192        Ok(wip)
3193    }
3194
3195    /// Deserialize any value into a DynamicValue type (e.g., facet_value::Value).
3196    ///
3197    /// This handles all value types by inspecting the parse events and calling
3198    /// the appropriate methods on the Partial, which delegates to the DynamicValue vtable.
3199    fn deserialize_dynamic_value(
3200        &mut self,
3201        mut wip: Partial<'input, BORROW>,
3202    ) -> Result<Partial<'input, BORROW>, DeserializeError<P::Error>> {
3203        let event = self.expect_peek("value for dynamic value")?;
3204
3205        match event {
3206            ParseEvent::Scalar(_) => {
3207                // Consume the scalar
3208                let event = self.expect_event("scalar")?;
3209                if let ParseEvent::Scalar(scalar) = event {
3210                    // Use set_scalar which already handles all scalar types
3211                    wip = self.set_scalar(wip, scalar)?;
3212                }
3213            }
3214            ParseEvent::SequenceStart(_) => {
3215                // Array/list
3216                self.expect_event("sequence start")?; // consume '['
3217                wip = wip.begin_list().map_err(DeserializeError::reflect)?;
3218
3219                loop {
3220                    let event = self.expect_peek("value or end")?;
3221                    if matches!(event, ParseEvent::SequenceEnd) {
3222                        self.expect_event("sequence end")?;
3223                        break;
3224                    }
3225
3226                    wip = wip.begin_list_item().map_err(DeserializeError::reflect)?;
3227                    wip = self.deserialize_dynamic_value(wip)?;
3228                    wip = wip.end().map_err(DeserializeError::reflect)?;
3229                }
3230            }
3231            ParseEvent::StructStart(_) => {
3232                // Object/map/table
3233                self.expect_event("struct start")?; // consume '{'
3234                wip = wip.begin_map().map_err(DeserializeError::reflect)?;
3235
3236                loop {
3237                    let event = self.expect_peek("field key or end")?;
3238                    if matches!(event, ParseEvent::StructEnd) {
3239                        self.expect_event("struct end")?;
3240                        break;
3241                    }
3242
3243                    // Parse the key
3244                    let key_event = self.expect_event("field key")?;
3245                    let key = match key_event {
3246                        ParseEvent::FieldKey(field_key) => field_key.name.into_owned(),
3247                        _ => {
3248                            return Err(DeserializeError::TypeMismatch {
3249                                expected: "field key",
3250                                got: format!("{:?}", key_event),
3251                            });
3252                        }
3253                    };
3254
3255                    // Begin the object entry and deserialize the value
3256                    wip = wip
3257                        .begin_object_entry(&key)
3258                        .map_err(DeserializeError::reflect)?;
3259                    wip = self.deserialize_dynamic_value(wip)?;
3260                    wip = wip.end().map_err(DeserializeError::reflect)?;
3261                }
3262            }
3263            _ => {
3264                return Err(DeserializeError::TypeMismatch {
3265                    expected: "scalar, sequence, or struct",
3266                    got: format!("{:?}", event),
3267                });
3268            }
3269        }
3270
3271        Ok(wip)
3272    }
3273}
3274
3275/// Error produced by [`FormatDeserializer`].
3276#[derive(Debug)]
3277pub enum DeserializeError<E> {
3278    /// Error emitted by the format-specific parser.
3279    Parser(E),
3280    /// Reflection error from Partial operations.
3281    Reflect {
3282        /// The underlying reflection error.
3283        error: ReflectError,
3284        /// Source span where the error occurred (if available).
3285        span: Option<facet_reflect::Span>,
3286    },
3287    /// Type mismatch during deserialization.
3288    TypeMismatch {
3289        /// The expected type or token.
3290        expected: &'static str,
3291        /// The actual type or token that was encountered.
3292        got: String,
3293    },
3294    /// Unsupported type or operation.
3295    Unsupported(String),
3296    /// Unknown field encountered when deny_unknown_fields is set.
3297    UnknownField(String),
3298    /// Cannot borrow string from input (e.g., escaped string into &str).
3299    CannotBorrow {
3300        /// Description of why borrowing failed.
3301        message: String,
3302    },
3303    /// Required field missing from input.
3304    MissingField {
3305        /// The field that is missing.
3306        field: &'static str,
3307        /// The type that contains the field.
3308        type_name: &'static str,
3309    },
3310    /// Unexpected end of input.
3311    UnexpectedEof {
3312        /// What was expected before EOF.
3313        expected: &'static str,
3314    },
3315}
3316
3317impl<E: fmt::Display> fmt::Display for DeserializeError<E> {
3318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3319        match self {
3320            DeserializeError::Parser(err) => write!(f, "{err}"),
3321            DeserializeError::Reflect { error, .. } => write!(f, "reflection error: {error}"),
3322            DeserializeError::TypeMismatch { expected, got } => {
3323                write!(f, "type mismatch: expected {expected}, got {got}")
3324            }
3325            DeserializeError::Unsupported(msg) => write!(f, "unsupported: {msg}"),
3326            DeserializeError::UnknownField(field) => write!(f, "unknown field: {field}"),
3327            DeserializeError::CannotBorrow { message } => write!(f, "{message}"),
3328            DeserializeError::MissingField { field, type_name } => {
3329                write!(f, "missing field `{field}` in type `{type_name}`")
3330            }
3331            DeserializeError::UnexpectedEof { expected } => {
3332                write!(f, "unexpected end of input, expected {expected}")
3333            }
3334        }
3335    }
3336}
3337
3338impl<E: fmt::Debug + fmt::Display> std::error::Error for DeserializeError<E> {}
3339
3340impl<E> DeserializeError<E> {
3341    /// Create a Reflect error without span information.
3342    #[inline]
3343    pub fn reflect(error: ReflectError) -> Self {
3344        DeserializeError::Reflect { error, span: None }
3345    }
3346
3347    /// Create a Reflect error with span information.
3348    #[inline]
3349    pub fn reflect_with_span(error: ReflectError, span: facet_reflect::Span) -> Self {
3350        DeserializeError::Reflect {
3351            error,
3352            span: Some(span),
3353        }
3354    }
3355}