1#![cfg_attr(not(feature = "std"), no_std)]
2#![warn(missing_docs)]
3#![warn(clippy::std_instead_of_core)]
4#![warn(clippy::std_instead_of_alloc)]
5#![doc = include_str!("../README.md")]
6
7extern crate alloc;
8
9use alloc::string::ToString;
10use alloc::{vec, vec::Vec};
11use core::fmt::Debug;
12use facet_core::{NumericType, PrimitiveType};
13
14mod error;
15use alloc::borrow::Cow;
16
17pub use error::*;
18
19mod span;
20use facet_core::{Characteristic, Def, Facet, FieldFlags, PointerType, StructKind, Type, UserType};
21use owo_colors::OwoColorize;
22pub use span::*;
23
24use facet_reflect::{HeapValue, Partial, ReflectError};
25use log::trace;
26
27#[derive(PartialEq, Debug, Clone)]
28pub enum Scalar<'input> {
33 String(Cow<'input, str>),
35 U64(u64),
37 I64(i64),
39 F64(f64),
41 U128(u128),
43 I128(i128),
45 Bool(bool),
47 Null,
49}
50
51#[derive(PartialEq, Debug, Clone)]
52pub enum Expectation {
54 Value,
56 ObjectKeyOrObjectClose,
58 ObjectVal,
60 ListItemOrListClose,
62}
63
64#[derive(PartialEq, Debug, Clone)]
65pub enum Outcome<'input> {
67 Scalar(Scalar<'input>),
69 ListStarted,
71 ListEnded,
73 ObjectStarted,
75 ObjectEnded,
77}
78
79impl<'input> From<Scalar<'input>> for Outcome<'input> {
80 fn from(scalar: Scalar<'input>) -> Self {
81 Outcome::Scalar(scalar)
82 }
83}
84
85use core::fmt;
86
87impl fmt::Display for Outcome<'_> {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 match self {
91 Outcome::Scalar(scalar) => write!(f, "scalar {scalar}"),
92 Outcome::ListStarted => write!(f, "list start"),
93 Outcome::ListEnded => write!(f, "list end"),
94 Outcome::ObjectStarted => write!(f, "object start"),
95 Outcome::ObjectEnded => write!(f, "object end"),
96 }
97 }
98}
99
100impl fmt::Display for Scalar<'_> {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self {
104 Scalar::String(s) => write!(f, "string \"{s}\""),
105 Scalar::U64(val) => write!(f, "u64 {val}"),
106 Scalar::I64(val) => write!(f, "i64 {val}"),
107 Scalar::F64(val) => write!(f, "f64 {val}"),
108 Scalar::U128(val) => write!(f, "u128 {val}"),
109 Scalar::I128(val) => write!(f, "i128 {val}"),
110 Scalar::Bool(val) => write!(f, "bool {val}"),
111 Scalar::Null => write!(f, "null"),
112 }
113 }
114}
115
116impl Outcome<'_> {
117 fn into_owned(self) -> Outcome<'static> {
118 match self {
119 Outcome::Scalar(scalar) => {
120 let owned_scalar = match scalar {
121 Scalar::String(cow) => Scalar::String(Cow::Owned(cow.into_owned())),
122 Scalar::U64(val) => Scalar::U64(val),
123 Scalar::I64(val) => Scalar::I64(val),
124 Scalar::F64(val) => Scalar::F64(val),
125 Scalar::U128(val) => Scalar::U128(val),
126 Scalar::I128(val) => Scalar::I128(val),
127 Scalar::Bool(val) => Scalar::Bool(val),
128 Scalar::Null => Scalar::Null,
129 };
130 Outcome::Scalar(owned_scalar)
131 }
132 Outcome::ListStarted => Outcome::ListStarted,
133 Outcome::ListEnded => Outcome::ListEnded,
134 Outcome::ObjectStarted => Outcome::ObjectStarted,
135 Outcome::ObjectEnded => Outcome::ObjectEnded,
136 }
137 }
138}
139
140pub struct NextData<'input, 'facet>
143where
144 'input: 'facet,
145{
146 start: usize,
148
149 runner: StackRunner<'input>,
151
152 pub wip: Partial<'facet>,
154}
155
156impl<'input, 'facet> NextData<'input, 'facet>
157where
158 'input: 'facet,
159{
160 pub fn input(&self) -> &'input [u8] {
162 self.runner.input
163 }
164
165 pub fn start(&self) -> usize {
167 self.start
168 }
169}
170
171pub type NextResult<'input, 'facet, T, E> = (NextData<'input, 'facet>, Result<T, E>);
173
174pub trait Format {
177 fn source(&self) -> &'static str;
179
180 #[allow(clippy::type_complexity)]
182 fn next<'input, 'facet>(
183 &mut self,
184 nd: NextData<'input, 'facet>,
185 expectation: Expectation,
186 ) -> NextResult<'input, 'facet, Spanned<Outcome<'input>>, Spanned<DeserErrorKind>>;
187
188 #[allow(clippy::type_complexity)]
190 fn skip<'input, 'facet>(
191 &mut self,
192 nd: NextData<'input, 'facet>,
193 ) -> NextResult<'input, 'facet, Span, Spanned<DeserErrorKind>>;
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Instruction {
199 Value(ValueReason),
201 SkipValue,
203 Pop(PopReason),
205 ObjectKeyOrObjectClose,
207 ListItemOrListClose,
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum ValueReason {
214 TopLevel,
216 ObjectVal,
218}
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum PopReason {
223 TopLevel,
225 ObjectVal,
227 ListVal,
229 Some,
231 SmartPointer,
233 Wrapper,
235}
236
237mod deser_impl {
238 use super::*;
239
240 pub fn deserialize<'input, 'facet, T, F>(
245 input: &'input [u8],
246 format: &mut F,
247 ) -> Result<T, DeserError<'input>>
248 where
249 T: Facet<'facet>,
250 F: Format,
251 'input: 'facet,
252 {
253 let result: Result<T, DeserError<'input>> = {
255 let wip = match Partial::alloc_shape(T::SHAPE) {
257 Ok(wip) => wip,
258 Err(e) => {
259 let default_span = Span::default();
260 return Err(DeserError::new_reflect(e, input, default_span));
261 }
262 };
263
264 let heap_value = match deserialize_wip(wip, input, format) {
266 Ok(val) => val,
267 Err(e) => {
268 return Err(e);
269 }
270 };
271
272 match heap_value.materialize() {
274 Ok(val) => Ok(val),
275 Err(e) => {
276 let default_span = Span::default();
277 return Err(DeserError::new_reflect(e, input, default_span));
278 }
279 }
280 };
281
282 result
283 }
284}
285
286pub fn deserialize<'input, 'facet, T, F>(
291 input: &'input [u8],
292 format: F,
293) -> Result<T, DeserError<'input>>
294where
295 T: Facet<'facet>,
296 F: Format,
297 'input: 'facet,
298{
299 let mut format_copy = format;
300 deser_impl::deserialize(input, &mut format_copy)
301}
302
303pub fn deserialize_wip<'input, 'facet, F>(
306 mut wip: Partial<'facet>,
307 input: &'input [u8],
308 format: &mut F,
309) -> Result<HeapValue<'facet>, DeserError<'input>>
310where
311 F: Format,
312 'input: 'facet,
313{
314 let mut runner = StackRunner {
316 original_input: input,
317 input,
318 stack: vec![
319 Instruction::Pop(PopReason::TopLevel),
320 Instruction::Value(ValueReason::TopLevel),
321 ],
322 last_span: Span::new(0, 0),
323 format_source: format.source(),
324 array_indices: Vec::new(),
325 enum_tuple_field_count: None,
326 enum_tuple_current_field: None,
327 };
328
329 macro_rules! next {
330 ($runner:ident, $wip:ident, $expectation:expr, $method:ident) => {{
331 let nd = NextData {
332 start: $runner.last_span.end(), runner: $runner,
334 wip: $wip,
335 };
336 let (nd, res) = format.next(nd, $expectation);
337 $runner = nd.runner;
338 $wip = nd.wip;
339 let outcome = res.map_err(|span_kind| {
340 $runner.last_span = span_kind.span;
341 $runner.err(span_kind.node)
342 })?;
343 $runner.last_span = outcome.span;
344 $wip = $runner.$method($wip, outcome)?;
345 }};
346 }
347
348 loop {
349 let insn = match runner.stack.pop() {
353 Some(insn) => insn,
354 None => unreachable!("Instruction stack is empty"),
355 };
356
357 trace!("Instruction {:?}", insn.bright_red());
358
359 match insn {
360 Instruction::Pop(reason) => {
361 wip = runner.pop(wip, reason)?;
362
363 if reason == PopReason::TopLevel {
364 while wip.frame_count() > 1 {
366 wip.end().map_err(|e| runner.reflect_err(e))?;
367 }
368 return wip.build().map_err(|e| runner.reflect_err(e));
369 } else {
370 wip.end().map_err(|e| runner.reflect_err(e))?;
371 }
372 }
373 Instruction::Value(_why) => {
374 let expectation = match _why {
375 ValueReason::TopLevel => Expectation::Value,
376 ValueReason::ObjectVal => Expectation::ObjectVal,
377 };
378 next!(runner, wip, expectation, value);
379 }
380 Instruction::ObjectKeyOrObjectClose => {
381 next!(
382 runner,
383 wip,
384 Expectation::ObjectKeyOrObjectClose,
385 object_key_or_object_close
386 );
387 }
388 Instruction::ListItemOrListClose => {
389 next!(
390 runner,
391 wip,
392 Expectation::ListItemOrListClose,
393 list_item_or_list_close
394 );
395 }
396 Instruction::SkipValue => {
397 let nd = NextData {
399 start: runner.last_span.end(),
400 runner,
401 wip,
402 };
403 let (nd, res) = format.skip(nd);
404 runner = nd.runner;
405 wip = nd.wip;
406 let span = res.map_err(|span_kind| {
408 runner.last_span = span_kind.span;
409 runner.err(span_kind.node)
410 })?;
411 runner.last_span = span;
413 }
414 }
415 }
416}
417
418#[inline]
421fn has_no_fractional_part(value: f64) -> bool {
422 value == (value as i64) as f64
423}
424
425trait NumericConvert {
427 fn to_i8(&self) -> Option<i8>;
428 fn to_i16(&self) -> Option<i16>;
429 fn to_i32(&self) -> Option<i32>;
430 fn to_i64(&self) -> Option<i64>;
431 fn to_i128(&self) -> Option<i128>;
432 fn to_isize(&self) -> Option<isize>;
433
434 fn to_u8(&self) -> Option<u8>;
435 fn to_u16(&self) -> Option<u16>;
436 fn to_u32(&self) -> Option<u32>;
437 fn to_u64(&self) -> Option<u64>;
438 fn to_u128(&self) -> Option<u128>;
439 fn to_usize(&self) -> Option<usize>;
440
441 fn to_f32(&self) -> Option<f32>;
442 fn to_f64(&self) -> Option<f64>;
443}
444
445impl NumericConvert for u64 {
446 fn to_i8(&self) -> Option<i8> {
447 (*self).try_into().ok()
448 }
449 fn to_i16(&self) -> Option<i16> {
450 (*self).try_into().ok()
451 }
452 fn to_i32(&self) -> Option<i32> {
453 (*self).try_into().ok()
454 }
455 fn to_i64(&self) -> Option<i64> {
456 (*self).try_into().ok()
457 }
458 fn to_i128(&self) -> Option<i128> {
459 Some(*self as i128)
460 }
461 fn to_isize(&self) -> Option<isize> {
462 (*self).try_into().ok()
463 }
464
465 fn to_u8(&self) -> Option<u8> {
466 (*self).try_into().ok()
467 }
468 fn to_u16(&self) -> Option<u16> {
469 (*self).try_into().ok()
470 }
471 fn to_u32(&self) -> Option<u32> {
472 (*self).try_into().ok()
473 }
474 fn to_u64(&self) -> Option<u64> {
475 Some(*self)
476 }
477 fn to_u128(&self) -> Option<u128> {
478 Some(*self as u128)
479 }
480 fn to_usize(&self) -> Option<usize> {
481 (*self).try_into().ok()
482 }
483
484 fn to_f32(&self) -> Option<f32> {
485 Some(*self as f32)
486 }
487 fn to_f64(&self) -> Option<f64> {
488 Some(*self as f64)
489 }
490}
491
492impl NumericConvert for i64 {
493 fn to_i8(&self) -> Option<i8> {
494 (*self).try_into().ok()
495 }
496 fn to_i16(&self) -> Option<i16> {
497 (*self).try_into().ok()
498 }
499 fn to_i32(&self) -> Option<i32> {
500 (*self).try_into().ok()
501 }
502 fn to_i64(&self) -> Option<i64> {
503 Some(*self)
504 }
505 fn to_i128(&self) -> Option<i128> {
506 Some(*self as i128)
507 }
508 fn to_isize(&self) -> Option<isize> {
509 (*self).try_into().ok()
510 }
511
512 fn to_u8(&self) -> Option<u8> {
513 (*self).try_into().ok()
514 }
515 fn to_u16(&self) -> Option<u16> {
516 (*self).try_into().ok()
517 }
518 fn to_u32(&self) -> Option<u32> {
519 (*self).try_into().ok()
520 }
521 fn to_u64(&self) -> Option<u64> {
522 (*self).try_into().ok()
523 }
524 fn to_u128(&self) -> Option<u128> {
525 (*self).try_into().ok()
526 }
527 fn to_usize(&self) -> Option<usize> {
528 (*self).try_into().ok()
529 }
530
531 fn to_f32(&self) -> Option<f32> {
532 Some(*self as f32)
533 }
534 fn to_f64(&self) -> Option<f64> {
535 Some(*self as f64)
536 }
537}
538
539impl NumericConvert for f64 {
540 fn to_i8(&self) -> Option<i8> {
541 if has_no_fractional_part(*self) && *self >= i8::MIN as f64 && *self <= i8::MAX as f64 {
542 Some(*self as i8)
543 } else {
544 None
545 }
546 }
547 fn to_i16(&self) -> Option<i16> {
548 if has_no_fractional_part(*self) && *self >= i16::MIN as f64 && *self <= i16::MAX as f64 {
549 Some(*self as i16)
550 } else {
551 None
552 }
553 }
554 fn to_i32(&self) -> Option<i32> {
555 if has_no_fractional_part(*self) && *self >= i32::MIN as f64 && *self <= i32::MAX as f64 {
556 Some(*self as i32)
557 } else {
558 None
559 }
560 }
561 fn to_i64(&self) -> Option<i64> {
562 if has_no_fractional_part(*self) && *self >= i64::MIN as f64 && *self <= i64::MAX as f64 {
563 Some(*self as i64)
564 } else {
565 None
566 }
567 }
568 fn to_i128(&self) -> Option<i128> {
569 if has_no_fractional_part(*self) && *self >= i128::MIN as f64 && *self <= i128::MAX as f64 {
570 Some(*self as i128)
571 } else {
572 None
573 }
574 }
575 fn to_isize(&self) -> Option<isize> {
576 if has_no_fractional_part(*self) && *self >= isize::MIN as f64 && *self <= isize::MAX as f64
577 {
578 Some(*self as isize)
579 } else {
580 None
581 }
582 }
583
584 fn to_u8(&self) -> Option<u8> {
585 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= u8::MAX as f64 {
586 Some(*self as u8)
587 } else {
588 None
589 }
590 }
591 fn to_u16(&self) -> Option<u16> {
592 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= u16::MAX as f64 {
593 Some(*self as u16)
594 } else {
595 None
596 }
597 }
598 fn to_u32(&self) -> Option<u32> {
599 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= u32::MAX as f64 {
600 Some(*self as u32)
601 } else {
602 None
603 }
604 }
605 fn to_u64(&self) -> Option<u64> {
606 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= u64::MAX as f64 {
607 Some(*self as u64)
608 } else {
609 None
610 }
611 }
612 fn to_u128(&self) -> Option<u128> {
613 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= u128::MAX as f64 {
614 Some(*self as u128)
615 } else {
616 None
617 }
618 }
619 fn to_usize(&self) -> Option<usize> {
620 if has_no_fractional_part(*self) && *self >= 0.0 && *self <= usize::MAX as f64 {
621 Some(*self as usize)
622 } else {
623 None
624 }
625 }
626
627 fn to_f32(&self) -> Option<f32> {
628 Some(*self as f32)
629 }
630 fn to_f64(&self) -> Option<f64> {
631 Some(*self)
632 }
633}
634
635impl NumericConvert for u128 {
636 fn to_i8(&self) -> Option<i8> {
637 (*self).try_into().ok()
638 }
639 fn to_i16(&self) -> Option<i16> {
640 (*self).try_into().ok()
641 }
642 fn to_i32(&self) -> Option<i32> {
643 (*self).try_into().ok()
644 }
645 fn to_i64(&self) -> Option<i64> {
646 (*self).try_into().ok()
647 }
648 fn to_i128(&self) -> Option<i128> {
649 Some(*self as i128)
650 }
651 fn to_isize(&self) -> Option<isize> {
652 (*self).try_into().ok()
653 }
654
655 fn to_u8(&self) -> Option<u8> {
656 (*self).try_into().ok()
657 }
658 fn to_u16(&self) -> Option<u16> {
659 (*self).try_into().ok()
660 }
661 fn to_u32(&self) -> Option<u32> {
662 (*self).try_into().ok()
663 }
664 fn to_u64(&self) -> Option<u64> {
665 (*self).try_into().ok()
666 }
667 fn to_u128(&self) -> Option<u128> {
668 Some(*self)
669 }
670 fn to_usize(&self) -> Option<usize> {
671 (*self).try_into().ok()
672 }
673
674 fn to_f32(&self) -> Option<f32> {
675 Some(*self as f32)
676 }
677 fn to_f64(&self) -> Option<f64> {
678 Some(*self as f64)
679 }
680}
681
682impl NumericConvert for i128 {
683 fn to_i8(&self) -> Option<i8> {
684 (*self).try_into().ok()
685 }
686 fn to_i16(&self) -> Option<i16> {
687 (*self).try_into().ok()
688 }
689 fn to_i32(&self) -> Option<i32> {
690 (*self).try_into().ok()
691 }
692 fn to_i64(&self) -> Option<i64> {
693 (*self).try_into().ok()
694 }
695 fn to_i128(&self) -> Option<i128> {
696 Some(*self)
697 }
698 fn to_isize(&self) -> Option<isize> {
699 (*self).try_into().ok()
700 }
701
702 fn to_u8(&self) -> Option<u8> {
703 (*self).try_into().ok()
704 }
705 fn to_u16(&self) -> Option<u16> {
706 (*self).try_into().ok()
707 }
708 fn to_u32(&self) -> Option<u32> {
709 (*self).try_into().ok()
710 }
711 fn to_u64(&self) -> Option<u64> {
712 (*self).try_into().ok()
713 }
714 fn to_u128(&self) -> Option<u128> {
715 (*self).try_into().ok()
716 }
717 fn to_usize(&self) -> Option<usize> {
718 (*self).try_into().ok()
719 }
720
721 fn to_f32(&self) -> Option<f32> {
722 Some(*self as f32)
723 }
724 fn to_f64(&self) -> Option<f64> {
725 Some(*self as f64)
726 }
727}
728
729#[doc(hidden)]
730pub struct StackRunner<'input> {
735 pub original_input: &'input [u8],
737
738 pub input: &'input [u8],
740
741 pub stack: Vec<Instruction>,
743
744 pub last_span: Span,
746
747 pub format_source: &'static str,
749
750 pub array_indices: Vec<usize>,
752
753 pub enum_tuple_field_count: Option<usize>,
755
756 pub enum_tuple_current_field: Option<usize>,
758}
759
760impl<'input> StackRunner<'input> {
761 fn err(&self, kind: DeserErrorKind) -> DeserError<'input> {
763 DeserError::new(kind, self.original_input, self.last_span)
764 }
765
766 fn reflect_err(&self, err: ReflectError) -> DeserError<'input> {
769 DeserError::new_reflect(err, self.original_input, self.last_span)
770 }
771
772 pub fn pop<'facet>(
773 &mut self,
774 mut wip: Partial<'facet>,
775 reason: PopReason,
776 ) -> Result<Partial<'facet>, DeserError<'input>> {
777 trace!(
778 "--- STACK has {:?} {}",
779 self.stack.green(),
780 "(POP)".bright_yellow()
781 );
782 trace!("Popping because {:?}", reason.yellow());
783
784 let container_shape = wip.shape();
785 match container_shape.ty {
786 Type::User(UserType::Struct(sd)) => {
787 let mut has_unset = false;
788
789 trace!("Let's check all fields are initialized");
790 for (index, field) in sd.fields.iter().enumerate() {
791 let is_set = wip.is_field_set(index).map_err(|err| {
792 trace!("Error checking field set status: {err:?}");
793 self.reflect_err(err)
794 })?;
795 if !is_set {
796 if field.flags.contains(FieldFlags::DEFAULT) {
797 wip.set_nth_field_to_default(index)
798 .map_err(|e| self.reflect_err(e))?;
799 } else {
800 trace!(
801 "Field #{} {} @ {} is not initialized",
802 index.yellow(),
803 field.name.green(),
804 field.offset.blue(),
805 );
806 has_unset = true;
807 }
808 }
809 }
810
811 if has_unset {
812 if container_shape.has_default_attr() {
813 let default_val = Partial::alloc_shape(container_shape)
815 .map_err(|e| self.reflect_err(e))?
816 .set_default()
817 .map_err(|e| self.reflect_err(e))?
818 .build()
819 .map_err(|e| self.reflect_err(e))?;
820 let peek = default_val.peek().into_struct().unwrap();
821
822 for (index, field) in sd.fields.iter().enumerate() {
823 let is_set = wip.is_field_set(index).map_err(|err| {
824 trace!("Error checking field set status: {err:?}");
825 self.reflect_err(err)
826 })?;
827 if !is_set {
828 trace!(
829 "Field #{} {} @ {} is being set to default value (from default instance)",
830 index.yellow(),
831 field.name.green(),
832 field.offset.blue(),
833 );
834 wip.begin_nth_field(index)
835 .map_err(|e| self.reflect_err(e))?;
836 let def_field = peek.field(index).unwrap();
838
839 unsafe {
843 wip.set_from_peek(&def_field)
844 .map_err(|e| self.reflect_err(e))?;
845 }
846 wip.end().map_err(|e| self.reflect_err(e))?;
847 }
848 }
849 } else {
850 for (index, field) in sd.fields.iter().enumerate() {
852 let is_set = wip.is_field_set(index).map_err(|err| {
853 trace!("Error checking field set status: {err:?}");
854 self.reflect_err(err)
855 })?;
856 if !is_set {
857 return Err(self.reflect_err(ReflectError::UninitializedField {
858 shape: container_shape,
859 field_name: field.name,
860 }));
861 }
862 }
863 }
864 }
865 }
866 Type::User(UserType::Enum(_ed)) => {
867 trace!("Checking if enum is initialized correctly");
868
869 if let Some(variant) = wip.selected_variant() {
871 trace!("Variant {} is selected", variant.name.blue());
872
873 if !variant.data.fields.is_empty() {
875 let mut has_unset = false;
876
877 for (index, field) in variant.data.fields.iter().enumerate() {
878 let is_set = wip.is_field_set(index).map_err(|err| {
879 trace!("Error checking field set status: {err:?}");
880 self.reflect_err(err)
881 })?;
882
883 if !is_set {
884 if field.flags.contains(FieldFlags::DEFAULT) {
885 wip.begin_nth_field(index)
886 .map_err(|e| self.reflect_err(e))?;
887
888 if field.vtable.default_fn.is_some() {
890 wip.set_default().map_err(|e| self.reflect_err(e))?;
891 trace!(
892 "Field #{} @ {} in variant {} was set to default value (via field default function)",
893 index.yellow(),
894 field.offset.blue(),
895 variant.name
896 );
897 } else if field.shape().is(Characteristic::Default) {
898 wip.set_default().map_err(|e| self.reflect_err(e))?;
899 trace!(
900 "Field #{} @ {} in variant {} was set to default value (via type default impl)",
901 index.yellow(),
902 field.offset.blue(),
903 variant.name
904 );
905 } else {
906 return Err(self.reflect_err(
907 ReflectError::DefaultAttrButNoDefaultImpl {
908 shape: field.shape(),
909 },
910 ));
911 }
912 wip.end().map_err(|e| self.reflect_err(e))?;
913 } else {
914 trace!(
915 "Field #{} @ {} in variant {} is not initialized",
916 index.yellow(),
917 field.offset.blue(),
918 variant.name
919 );
920 has_unset = true;
921 }
922 }
923 }
924
925 if has_unset {
926 if container_shape.has_default_attr() {
927 trace!(
928 "Enum has DEFAULT attr but variant has uninitialized fields"
929 );
930 let default_val = Partial::alloc_shape(container_shape)
932 .map_err(|e| self.reflect_err(e))?
933 .set_default()
934 .map_err(|e| self.reflect_err(e))?
935 .build()
936 .map_err(|e| self.reflect_err(e))?;
937
938 let peek = default_val.peek();
939 let peek_enum =
940 peek.into_enum().map_err(|e| self.reflect_err(e))?;
941 let default_variant = peek_enum
942 .active_variant()
943 .map_err(|e| self.err(DeserErrorKind::VariantError(e)))?;
944
945 if default_variant.name == variant.name {
946 for (index, _field) in variant.data.fields.iter().enumerate() {
948 let is_set = wip.is_field_set(index).map_err(|err| {
949 trace!("Error checking field set status: {err:?}");
950 self.reflect_err(err)
951 })?;
952 if !is_set {
953 if let Ok(Some(def_field)) = peek_enum.field(index) {
954 wip.begin_nth_field(index)
955 .map_err(|e| self.reflect_err(e))?;
956
957 unsafe {
961 wip.set_from_peek(&def_field)
962 .map_err(|e| self.reflect_err(e))?;
963 }
964 wip.end().map_err(|e| self.reflect_err(e))?;
965 }
966 }
967 }
968 }
969 } else {
970 for (index, field) in variant.data.fields.iter().enumerate() {
972 let is_set = wip.is_field_set(index).map_err(|err| {
973 trace!("Error checking field set status: {err:?}");
974 self.reflect_err(err)
975 })?;
976 if !is_set {
977 return Err(self.reflect_err(
978 ReflectError::UninitializedEnumField {
979 shape: container_shape,
980 variant_name: variant.name,
981 field_name: field.name,
982 },
983 ));
984 }
985 }
986 }
987 }
988 }
989 } else if container_shape.has_default_attr() {
990 trace!("No variant selected but enum has DEFAULT attr; setting to default");
992
993 wip.set_default().map_err(|e| self.reflect_err(e))?;
994 }
995 }
996 _ => {
997 trace!(
998 "Thing being popped is not a container I guess (it's a {})",
999 wip.shape(),
1000 );
1001 }
1002 }
1003 Ok(wip)
1004 }
1005
1006 fn set_numeric_value<'facet>(
1009 &self,
1010 wip: &mut Partial<'facet>,
1011 value: &dyn NumericConvert,
1012 ) -> Result<(), DeserError<'input>>
1013 where
1014 'input: 'facet,
1015 {
1016 let shape = wip.shape();
1017
1018 let Type::Primitive(PrimitiveType::Numeric(numeric_type)) = shape.ty else {
1019 return Err(self.err(DeserErrorKind::UnsupportedType {
1020 got: shape,
1021 wanted: "numeric type",
1022 }));
1023 };
1024
1025 let size_bytes = shape
1027 .layout
1028 .sized_layout()
1029 .map_err(|_| {
1030 self.err(DeserErrorKind::UnsupportedType {
1031 got: shape,
1032 wanted: "sized numeric type",
1033 })
1034 })?
1035 .size();
1036
1037 if matches!(shape.def, Def::Scalar) {
1038 macro_rules! convert_and_set {
1040 ($converter:expr, $target_type:expr) => {{
1041 let converted = $converter.ok_or_else(|| {
1042 self.err(DeserErrorKind::NumericConversion {
1043 from: "numeric",
1044 to: $target_type,
1045 })
1046 })?;
1047 wip.set(converted).map_err(|e| self.reflect_err(e))?;
1048 }};
1049 }
1050
1051 match numeric_type {
1052 NumericType::Integer { signed } => {
1053 if !signed && shape.is_type::<usize>() {
1055 convert_and_set!(value.to_usize(), "usize")
1056 } else if signed && shape.is_type::<isize>() {
1057 convert_and_set!(value.to_isize(), "isize")
1058 } else {
1059 match (size_bytes, signed) {
1061 (1, true) => convert_and_set!(value.to_i8(), "i8"),
1062 (2, true) => convert_and_set!(value.to_i16(), "i16"),
1063 (4, true) => convert_and_set!(value.to_i32(), "i32"),
1064 (8, true) => convert_and_set!(value.to_i64(), "i64"),
1065 (16, true) => convert_and_set!(value.to_i128(), "i128"),
1066 (1, false) => convert_and_set!(value.to_u8(), "u8"),
1067 (2, false) => convert_and_set!(value.to_u16(), "u16"),
1068 (4, false) => convert_and_set!(value.to_u32(), "u32"),
1069 (8, false) => convert_and_set!(value.to_u64(), "u64"),
1070 (16, false) => convert_and_set!(value.to_u128(), "u128"),
1071 _ => {
1072 return Err(self.err(DeserErrorKind::NumericConversion {
1073 from: "numeric",
1074 to: if signed {
1075 "unknown signed integer size"
1076 } else {
1077 "unknown unsigned integer size"
1078 },
1079 }));
1080 }
1081 }
1082 }
1083 }
1084 NumericType::Float => match size_bytes {
1085 4 => convert_and_set!(value.to_f32(), "f32"),
1086 8 => convert_and_set!(value.to_f64(), "f64"),
1087 _ => {
1088 return Err(self.err(DeserErrorKind::NumericConversion {
1089 from: "numeric",
1090 to: "unknown float size",
1091 }));
1092 }
1093 },
1094 }
1095 } else {
1096 return Err(self.err(DeserErrorKind::UnsupportedType {
1098 got: shape,
1099 wanted: "scalar type",
1100 }));
1101 }
1102
1103 Ok(())
1104 }
1105
1106 fn handle_scalar<'facet>(
1107 &self,
1108 wip: &mut Partial<'facet>,
1109 scalar: Scalar<'input>,
1110 ) -> Result<(), DeserError<'input>>
1111 where
1112 'input: 'facet, {
1114 match scalar {
1115 Scalar::String(cow) => {
1116 match wip.shape().ty {
1117 Type::User(UserType::Enum(_)) => {
1118 if wip.selected_variant().is_some() {
1119 wip.set(cow).map_err(|e| self.reflect_err(e))?;
1121 } else {
1122 match wip.find_variant(&cow) {
1124 Some((variant_index, _)) => {
1125 wip.select_nth_variant(variant_index)
1126 .map_err(|e| self.reflect_err(e))?;
1127 }
1128 None => {
1129 return Err(self.err(DeserErrorKind::NoSuchVariant {
1130 name: cow.to_string(),
1131 enum_shape: wip.shape(),
1132 }));
1133 }
1134 }
1135 }
1136 }
1137 Type::Pointer(PointerType::Reference(_)) if wip.shape().is_type::<&str>() => {
1138 match cow {
1141 Cow::Borrowed(s) => wip.set(s).map_err(|e| self.reflect_err(e))?,
1142 Cow::Owned(s) => wip.set(s).map_err(|e| self.reflect_err(e))?,
1143 }; }
1145 _ => {
1146 let shape = wip.shape();
1148 if matches!(shape.def, Def::Scalar) {
1149 match wip.parse_from_str(cow.as_ref()) {
1152 Ok(_) => {
1153 }
1155 Err(parse_err) => {
1156 match parse_err {
1159 ReflectError::OperationFailed {
1160 shape: _,
1161 operation,
1162 } if operation.contains("does not support parsing") => {
1163 wip.set(cow.to_string())
1165 .map_err(|e| self.reflect_err(e))?;
1166 }
1167 _ => {
1168 return Err(self.err(DeserErrorKind::ReflectError(
1170 ReflectError::OperationFailed {
1171 shape,
1172 operation: "Failed to parse string value",
1173 },
1174 )));
1175 }
1176 }
1177 }
1178 }
1179 } else {
1180 wip.set(cow.to_string()).map_err(|e| self.reflect_err(e))?;
1182 }
1183 }
1184 }
1185 }
1186 Scalar::U64(value) => {
1187 self.set_numeric_value(wip, &value)?;
1188 }
1189 Scalar::I64(value) => {
1190 self.set_numeric_value(wip, &value)?;
1191 }
1192 Scalar::F64(value) => {
1193 self.set_numeric_value(wip, &value)?;
1194 }
1195 Scalar::U128(value) => {
1196 self.set_numeric_value(wip, &value)?;
1197 }
1198 Scalar::I128(value) => {
1199 self.set_numeric_value(wip, &value)?;
1200 }
1201 Scalar::Bool(value) => {
1202 wip.set(value).map_err(|e| self.reflect_err(e))?;
1203 }
1204 Scalar::Null => {
1205 wip.set_default().map_err(|e| self.reflect_err(e))?;
1206 }
1207 }
1208 Ok(())
1209 }
1210
1211 fn value<'facet>(
1213 &mut self,
1214 mut wip: Partial<'facet>,
1215 outcome: Spanned<Outcome<'input>>,
1216 ) -> Result<Partial<'facet>, DeserError<'input>>
1217 where
1218 'input: 'facet, {
1220 trace!(
1221 "--- STACK has {:?} {}",
1222 self.stack.green(),
1223 "(VALUE)".bright_yellow()
1224 );
1225
1226 let original_shape = wip.shape();
1227 trace!("Handling value of type {}", original_shape.blue());
1228
1229 if matches!(outcome.node, Outcome::Scalar(Scalar::Null)) {
1231 wip.set_default().map_err(|e| self.reflect_err(e))?;
1232 return Ok(wip);
1233 }
1234
1235 let mut smart_pointer_begun = false;
1237 loop {
1238 trace!(" Loop iteration: current shape is {}", wip.shape().blue());
1239 if matches!(wip.shape().def, Def::Option(_)) {
1240 trace!(" Starting Some(_) option for {}", wip.shape().blue());
1241 wip.begin_some().map_err(|e| self.reflect_err(e))?;
1242 self.stack.push(Instruction::Pop(PopReason::Some));
1243 } else if let Def::Pointer(inner) = wip.shape().def {
1244 if smart_pointer_begun {
1247 break;
1248 }
1249 if let Some(pointee) = inner.pointee() {
1250 trace!(
1251 " Starting smart pointer for {} (pointee is {})",
1252 wip.shape().blue(),
1253 pointee.yellow(),
1254 );
1255 } else {
1256 trace!(
1257 " Starting smart pointer for {} (no pointee)",
1258 wip.shape().blue()
1259 );
1260 }
1261 trace!(" About to call begin_smart_ptr()");
1262 wip.begin_smart_ptr().map_err(|e| self.reflect_err(e))?;
1263 trace!(
1264 " After begin_smart_ptr(), shape is now {}",
1265 wip.shape().blue()
1266 );
1267 self.stack.push(Instruction::Pop(PopReason::SmartPointer));
1268 smart_pointer_begun = true;
1269 } else if let Some(inner) = wip.shape().inner {
1270 trace!(
1271 " Starting wrapped value for {} (inner is {})",
1272 wip.shape().blue(),
1273 inner.yellow()
1274 );
1275 wip.begin_inner().map_err(|e| self.reflect_err(e))?;
1276 self.stack.push(Instruction::Pop(PopReason::Wrapper));
1277 } else {
1278 break;
1279 }
1280 }
1281
1282 if wip.shape() != original_shape {
1283 trace!(
1284 "Handling shape {} as innermost {}",
1285 original_shape.blue(),
1286 wip.shape().yellow()
1287 );
1288 }
1289
1290 match outcome.node {
1291 Outcome::Scalar(s) => {
1292 trace!("Parsed scalar value: {}", s.cyan());
1293 self.handle_scalar(&mut wip, s)?;
1294 }
1295 Outcome::ListStarted => {
1296 let shape = wip.shape();
1297
1298 if let Type::User(UserType::Struct(st)) = shape.ty {
1300 if st.kind == StructKind::Tuple {
1301 trace!(
1302 "Array starting for tuple struct ({}) with {} fields!",
1303 shape.blue(),
1304 st.fields.len()
1305 );
1306
1307 trace!("Beginning pushback");
1309 self.stack.push(Instruction::ListItemOrListClose);
1310 return Ok(wip);
1311 }
1312 }
1313
1314 match shape.def {
1315 Def::Array(_) => {
1316 trace!("Array starting for array ({})!", shape.blue());
1317 }
1320 Def::Slice(_) => {
1321 trace!("Array starting for slice ({})!", shape.blue());
1322 }
1323 Def::List(_) => {
1324 trace!("Array starting for list ({})!", shape.blue());
1325 wip.set_default().map_err(|e| self.reflect_err(e))?;
1326 }
1327 _ => {
1328 if matches!(shape.def, Def::Pointer(_)) && smart_pointer_begun {
1330 trace!("Array starting for smart pointer slice ({})!", shape.blue());
1331 wip.begin_list().map_err(|e| self.reflect_err(e))?;
1332 } else if let Type::User(user_ty) = shape.ty {
1333 match user_ty {
1335 UserType::Enum(_) => {
1336 trace!("Array starting for enum ({})!", shape.blue());
1337 if let Some(variant) = wip.selected_variant() {
1339 use facet_core::StructKind;
1340 if variant.data.kind == StructKind::Tuple {
1341 self.enum_tuple_field_count =
1344 Some(variant.data.fields.len());
1345 self.enum_tuple_current_field = Some(0);
1346 } else {
1347 return Err(self.err(DeserErrorKind::UnsupportedType {
1348 got: shape,
1349 wanted: "tuple variant for array deserialization",
1350 }));
1351 }
1352 } else {
1353 return Err(self.err(DeserErrorKind::UnsupportedType {
1354 got: shape,
1355 wanted: "enum with variant selected",
1356 }));
1357 }
1358 }
1359 UserType::Struct(_) => {
1360 return Err(self.err(DeserErrorKind::UnsupportedType {
1363 got: shape,
1364 wanted: "array, list, tuple, or slice",
1365 }));
1366 }
1367 _ => {
1368 return Err(self.err(DeserErrorKind::UnsupportedType {
1369 got: shape,
1370 wanted: "array, list, tuple, or slice",
1371 }));
1372 }
1373 }
1374 } else {
1375 return Err(self.err(DeserErrorKind::UnsupportedType {
1376 got: shape,
1377 wanted: "array, list, tuple, or slice",
1378 }));
1379 }
1380 }
1381 }
1382 trace!("Beginning pushback");
1383 self.stack.push(Instruction::ListItemOrListClose);
1384
1385 match shape.def {
1387 Def::List(_) => {
1388 wip.begin_list().map_err(|e| self.reflect_err(e))?;
1389 }
1390 Def::Array(_) => {
1391 self.array_indices.push(0);
1394 }
1395 Def::Slice(_) => {
1396 }
1399 _ => {
1400 }
1402 }
1403 }
1404 Outcome::ListEnded => {
1405 trace!("List closing");
1406 let shape = wip.shape();
1408 if matches!(shape.def, Def::Array(_)) {
1409 self.array_indices.pop();
1410 }
1411 wip.end().map_err(|e| self.reflect_err(e))?;
1412 }
1413 Outcome::ObjectStarted => {
1414 let shape = wip.shape();
1415 match shape.def {
1416 Def::Map(_md) => {
1417 trace!("Object starting for map value ({})!", shape.blue());
1418 wip.begin_map().map_err(|e| self.reflect_err(e))?;
1419 }
1420 _ => {
1421 if let Type::User(user_ty) = shape.ty {
1423 match user_ty {
1424 UserType::Enum(_) => {
1425 trace!("Object starting for enum value ({})!", shape.blue());
1426 }
1428 UserType::Struct(_) => {
1429 trace!("Object starting for struct value ({})!", shape.blue());
1430 }
1432 _ => {
1433 return Err(self.err(DeserErrorKind::UnsupportedType {
1434 got: shape,
1435 wanted: "map, enum, or struct",
1436 }));
1437 }
1438 }
1439 } else if let Type::User(UserType::Struct(struct_type)) = shape.ty {
1440 if struct_type.kind == StructKind::Tuple {
1441 trace!(
1444 "Object starting for tuple ({}) with {} fields - unusual but handling",
1445 shape.blue(),
1446 struct_type.fields.len()
1447 );
1448 }
1450 } else {
1451 return Err(self.err(DeserErrorKind::UnsupportedType {
1452 got: shape,
1453 wanted: "map, enum, struct, or tuple",
1454 }));
1455 }
1456 }
1457 }
1458
1459 self.stack.push(Instruction::ObjectKeyOrObjectClose);
1460 }
1461 Outcome::ObjectEnded => todo!(),
1462 }
1463 Ok(wip)
1464 }
1465
1466 fn object_key_or_object_close<'facet>(
1467 &mut self,
1468 mut wip: Partial<'facet>,
1469 outcome: Spanned<Outcome<'input>>,
1470 ) -> Result<Partial<'facet>, DeserError<'input>>
1471 where
1472 'input: 'facet,
1473 {
1474 trace!(
1475 "STACK: {:?} {}",
1476 self.stack.green(),
1477 "(OK/OC)".bright_yellow()
1478 );
1479 match outcome.node {
1480 Outcome::Scalar(Scalar::String(key)) => {
1481 trace!("Parsed object key: {}", key.cyan());
1482
1483 let mut ignore = false;
1484 let mut needs_pop = true;
1485 let mut handled_by_flatten = false;
1486
1487 let shape = wip.shape();
1488 match shape.ty {
1489 Type::User(UserType::Struct(sd)) => {
1490 if let Some(index) = wip.field_index(&key) {
1492 trace!("It's a struct field");
1493 wip.begin_nth_field(index)
1494 .map_err(|e| self.reflect_err(e))?;
1495 } else {
1496 trace!(
1497 "Did not find direct field match in innermost shape {}",
1498 shape.blue()
1499 );
1500
1501 let mut found_in_flatten = false;
1503 for (index, field) in sd.fields.iter().enumerate() {
1504 if field.flags.contains(FieldFlags::FLATTEN) {
1505 trace!("Found flattened field #{index}");
1506 wip.begin_nth_field(index)
1508 .map_err(|e| self.reflect_err(e))?;
1509
1510 if let Some(subfield_index) = wip.field_index(&key) {
1512 trace!("Found key {key} in flattened field");
1513 wip.begin_nth_field(subfield_index)
1514 .map_err(|e| self.reflect_err(e))?;
1515 found_in_flatten = true;
1516 handled_by_flatten = true;
1517 break;
1518 } else if let Some((_variant_index, _variant)) =
1519 wip.find_variant(&key)
1520 {
1521 trace!("Found key {key} in flattened field");
1522 wip.select_variant_named(&key)
1523 .map_err(|e| self.reflect_err(e))?;
1524 found_in_flatten = true;
1525 break;
1526 } else {
1527 wip.end().map_err(|e| self.reflect_err(e))?;
1529 }
1530 }
1531 }
1532
1533 if !found_in_flatten {
1534 if wip.shape().has_deny_unknown_fields_attr() {
1535 trace!(
1536 "It's not a struct field AND we're denying unknown fields"
1537 );
1538 return Err(self.err(DeserErrorKind::UnknownField {
1539 field_name: key.to_string(),
1540 shape: wip.shape(),
1541 }));
1542 } else {
1543 trace!(
1544 "It's not a struct field and we're ignoring unknown fields"
1545 );
1546 ignore = true;
1547 }
1548 }
1549 }
1550 }
1551 Type::User(UserType::Enum(_ed)) => match wip.find_variant(&key) {
1552 Some((index, variant)) => {
1553 trace!(
1554 "Selecting variant {}::{}",
1555 wip.shape().blue(),
1556 variant.name.yellow(),
1557 );
1558 wip.select_nth_variant(index)
1559 .map_err(|e| self.reflect_err(e))?;
1560
1561 if matches!(variant.data.kind, StructKind::Tuple)
1563 && variant.data.fields.len() == 1
1564 {
1565 trace!(
1566 "Tuple variant {}::{} encountered, pushing field 0",
1567 wip.shape().blue(),
1568 variant.name.yellow()
1569 );
1570 wip.begin_nth_field(0).map_err(|e| self.reflect_err(e))?;
1571 self.stack.push(Instruction::Pop(PopReason::ObjectVal));
1572 }
1573
1574 needs_pop = false;
1575 }
1576 None => {
1577 if let Some(_variant_index) = wip.selected_variant() {
1578 trace!(
1579 "Already have a variant selected, treating {} as struct field of {}::{}",
1580 key,
1581 wip.shape().blue(),
1582 wip.selected_variant().unwrap().name.yellow(),
1583 );
1584 if let Some(index) = wip.field_index(&key) {
1586 trace!("Found field {} in selected variant", key.blue());
1587 wip.begin_nth_field(index)
1588 .map_err(|e| self.reflect_err(e))?;
1589 } else if wip.shape().has_deny_unknown_fields_attr() {
1590 trace!("Unknown field in variant and denying unknown fields");
1591 return Err(self.err(DeserErrorKind::UnknownField {
1592 field_name: key.to_string(),
1593 shape: wip.shape(),
1594 }));
1595 } else {
1596 trace!(
1597 "Ignoring unknown field '{}' in variant '{}::{}'",
1598 key,
1599 wip.shape(),
1600 wip.selected_variant().unwrap().name
1601 );
1602 ignore = true;
1603 }
1604 } else {
1605 return Err(self.err(DeserErrorKind::NoSuchVariant {
1606 name: key.to_string(),
1607 enum_shape: wip.shape(),
1608 }));
1609 }
1610 }
1611 },
1612 _ => {
1613 if let Def::Map(map_def) = shape.def {
1615 wip.begin_key().map_err(|e| self.reflect_err(e))?;
1616
1617 let key_shape = map_def.k();
1619 if key_shape.inner.is_some() {
1620 wip.begin_inner().map_err(|e| self.reflect_err(e))?;
1624 wip.set(key.to_string()).map_err(|e| self.reflect_err(e))?;
1625 wip.end().map_err(|e| self.reflect_err(e))?; } else {
1627 wip.set(key.to_string()).map_err(|e| self.reflect_err(e))?;
1629 }
1630
1631 wip.end().map_err(|e| self.reflect_err(e))?; wip.begin_value().map_err(|e| self.reflect_err(e))?;
1633 } else {
1634 return Err(self.err(DeserErrorKind::Unimplemented(
1635 "object key for non-struct/map",
1636 )));
1637 }
1638 }
1639 }
1640
1641 self.stack.push(Instruction::ObjectKeyOrObjectClose);
1642 if ignore {
1643 self.stack.push(Instruction::SkipValue);
1644 } else {
1645 if needs_pop && !handled_by_flatten {
1646 trace!("Pushing Pop insn to stack (ObjectVal)");
1647 self.stack.push(Instruction::Pop(PopReason::ObjectVal));
1648 } else if handled_by_flatten {
1649 trace!("Pushing Pop insn to stack (ObjectVal) for flattened field");
1652 self.stack.push(Instruction::Pop(PopReason::ObjectVal));
1653 }
1654 self.stack.push(Instruction::Value(ValueReason::ObjectVal));
1655 }
1656 Ok(wip)
1657 }
1658 Outcome::ObjectEnded => {
1659 trace!("Object closing");
1660 Ok(wip)
1661 }
1662 _ => Err(self.err(DeserErrorKind::UnexpectedOutcome {
1663 got: outcome.node.into_owned(),
1664 wanted: "scalar or object close",
1665 })),
1666 }
1667 }
1668
1669 fn list_item_or_list_close<'facet>(
1670 &mut self,
1671 mut wip: Partial<'facet>,
1672 outcome: Spanned<Outcome<'input>>,
1673 ) -> Result<Partial<'facet>, DeserError<'input>>
1674 where
1675 'input: 'facet,
1676 {
1677 trace!(
1678 "--- STACK has {:?} {}",
1679 self.stack.green(),
1680 "(LI/LC)".bright_yellow()
1681 );
1682 match outcome.node {
1683 Outcome::ListEnded => {
1684 trace!("List close");
1685 let shape = wip.shape();
1687 if matches!(shape.def, Def::Array(_)) {
1688 self.array_indices.pop();
1689 }
1690
1691 if let Type::User(UserType::Enum(_)) = shape.ty {
1693 if self.enum_tuple_field_count.is_some() {
1694 trace!("Enum tuple variant list ended");
1695 self.enum_tuple_field_count = None;
1696 self.enum_tuple_current_field = None;
1697 }
1698 }
1699
1700 if let Type::User(UserType::Struct(st)) = shape.ty {
1702 if st.kind == StructKind::Tuple && st.fields.is_empty() {
1703 trace!("Empty tuple parsed from []");
1704 }
1706 }
1707
1708 Ok(wip)
1710 }
1711 _ => {
1712 self.stack.push(Instruction::ListItemOrListClose);
1713 self.stack.push(Instruction::Pop(PopReason::ListVal));
1714
1715 trace!(
1716 "Expecting list item, doing a little push before doing value with outcome {}",
1717 outcome.magenta()
1718 );
1719 trace!("Before push, wip.shape is {}", wip.shape().blue());
1720
1721 let shape = wip.shape();
1723 match shape.def {
1724 Def::Array(ad) => {
1725 if let Some(current_index) = self.array_indices.last().copied() {
1727 if current_index >= ad.n {
1729 return Err(self.err(DeserErrorKind::ArrayOverflow {
1730 shape,
1731 max_len: ad.n,
1732 }));
1733 }
1734
1735 wip.begin_nth_field(current_index)
1737 .map_err(|e| self.reflect_err(e))?;
1738
1739 if let Some(last) = self.array_indices.last_mut() {
1741 *last += 1;
1742 }
1743 } else {
1744 return Err(self.err(DeserErrorKind::Unimplemented(
1746 "Array index tracking not initialized",
1747 )));
1748 }
1749 }
1750 Def::List(_) => {
1751 wip.begin_list_item().map_err(|e| self.reflect_err(e))?;
1752 }
1753 _ => {
1754 if matches!(shape.def, Def::Pointer(_)) {
1756 trace!("List item for smart pointer slice");
1757 wip.begin_list_item().map_err(|e| self.reflect_err(e))?;
1758 }
1759 else if let Type::User(UserType::Enum(_)) = shape.ty {
1761 if let (Some(field_count), Some(current_field)) =
1762 (self.enum_tuple_field_count, self.enum_tuple_current_field)
1763 {
1764 if current_field >= field_count {
1765 return Err(self.err(DeserErrorKind::ArrayOverflow {
1767 shape,
1768 max_len: field_count,
1769 }));
1770 }
1771
1772 wip.begin_nth_field(current_field)
1774 .map_err(|e| self.reflect_err(e))?;
1775
1776 self.enum_tuple_current_field = Some(current_field + 1);
1778 } else {
1779 return Err(self.err(DeserErrorKind::UnsupportedType {
1780 got: shape,
1781 wanted: "enum with tuple variant selected",
1782 }));
1783 }
1784 }
1785 else if let Type::User(UserType::Struct(struct_type)) = shape.ty {
1787 if struct_type.kind == StructKind::Tuple {
1788 let mut field_index = None;
1791 for i in 0..struct_type.fields.len() {
1792 if !wip.is_field_set(i).map_err(|e| self.reflect_err(e))? {
1793 field_index = Some(i);
1794 break;
1795 }
1796 }
1797
1798 if let Some(idx) = field_index {
1799 wip.begin_nth_field(idx).map_err(|e| self.reflect_err(e))?;
1800 } else {
1801 return Err(self.err(DeserErrorKind::ArrayOverflow {
1803 shape,
1804 max_len: struct_type.fields.len(),
1805 }));
1806 }
1807 } else {
1808 return Err(self.err(DeserErrorKind::UnsupportedType {
1810 got: shape,
1811 wanted: "array, list, or tuple",
1812 }));
1813 }
1814 } else {
1815 return Err(self.err(DeserErrorKind::UnsupportedType {
1817 got: shape,
1818 wanted: "array, list, or tuple",
1819 }));
1820 }
1821 }
1822 }
1823
1824 trace!(" After push, wip.shape is {}", wip.shape().cyan());
1825
1826 if matches!(outcome.node, Outcome::ListStarted) {
1829 if let Type::User(UserType::Struct(st)) = wip.shape().ty {
1830 if st.kind == StructKind::Tuple && st.fields.is_empty() {
1831 trace!(
1832 "Empty tuple field with list start - initializing empty tuple and expecting immediate close"
1833 );
1834 wip.set_default().map_err(|e| self.reflect_err(e))?;
1836 }
1838 }
1839 }
1840
1841 wip = self.value(wip, outcome)?;
1842 Ok(wip)
1843 }
1844 }
1845 }
1846}
1847
1848#[cfg(test)]
1849mod tests {
1850 #[test]
1851 fn it_works() {}
1852}