mlang_rs/rt/serde/
de.rs

1use std::{
2    marker::PhantomData,
3    num::{ParseFloatError, ParseIntError},
4};
5
6use crate::rt::opcode::{Path, Target, Variable};
7
8/// Error used by [`Visitor`]
9#[derive(Debug, thiserror::Error, PartialEq)]
10pub enum Error {
11    #[error(transparent)]
12    ParseIntError(#[from] ParseIntError),
13
14    #[error(transparent)]
15    ParseFloatError(#[from] ParseFloatError),
16
17    #[error("Deserialize sequence out of range({0}), expect {1}")]
18    OutOfRange(usize, usize),
19
20    #[error("Unknown opcode type_id: {0}")]
21    UnknownType(usize),
22
23    #[error("Unknown opcode: {0}")]
24    UnknownTypeName(String),
25
26    #[error("Unexpect {0}")]
27    Unexpect(Kind),
28
29    #[error("Unknown variant `{1}` of enum({0})")]
30    UnknownVariant(String, String),
31
32    #[error("Unknown variant index({1}) of enum({0})")]
33    UnknownVariantIndex(String, usize),
34}
35
36/// Unexpect kind .
37#[derive(Debug, thiserror::Error, PartialEq)]
38pub enum Kind {
39    #[error("kind: bool.")]
40    Bool,
41    #[error("kind: string.")]
42    String,
43    #[error("kind: byte.")]
44    Byte,
45    #[error("kind: utype.")]
46    Ubyte,
47    #[error("kind: short.")]
48    Short,
49    #[error("kind: ushort.")]
50    Ushort,
51    #[error("kind: int.")]
52    Int,
53    #[error("kind: uint.")]
54    Uint,
55    #[error("kind: long.")]
56    Long,
57    #[error("kind: ulong.")]
58    Ulong,
59    #[error("kind: float.")]
60    Float,
61    #[error("kind: double.")]
62    Double,
63    #[error("kind: enum.")]
64    Enum,
65    #[error("kind: data.")]
66    Data,
67    #[error("kind: element.")]
68    Element,
69    #[error("kind: leaf.")]
70    Leaf,
71    #[error("kind: attr.")]
72    Attr,
73    #[error("kind: opcode({0}).")]
74    Opcode(usize),
75
76    #[error("kind: opcode({0}).")]
77    NamedOpcode(String),
78    #[error("kind: none.")]
79    None,
80    #[error("kind: some.")]
81    Some,
82    #[error("kind: seq.")]
83    Seq,
84    #[error("kind: variable.")]
85    Variable,
86    #[error("kind: Variable::Constant.")]
87    Constant,
88    #[error("kind: pop.")]
89    Pop,
90}
91
92/// This trait represents a visitor that walks through a deserializer.
93pub trait Visitor: Sized {
94    /// The value produced by this visitor.
95    type Value: 'static;
96
97    fn is_element(&self, name: &str) -> bool {
98        let _ = name;
99        false
100    }
101
102    fn is_leaf(&self, name: &str) -> bool {
103        let _ = name;
104        false
105    }
106
107    /// The input contains a opcode.
108    ///
109    /// The default implementation fails with a type error.
110    fn visit_opcode<D>(self, type_id: usize, deserializer: D) -> Result<Self::Value, D::Error>
111    where
112        D: Deserializer,
113    {
114        let _ = type_id;
115        let _ = deserializer;
116
117        Err(Error::Unexpect(Kind::Opcode(type_id)).into())
118    }
119
120    /// The input contains a opcode with `name`.
121    ///
122    /// The default implementation fails with a type error.
123    fn visit_opcode_with<D>(self, name: &str, deserializer: D) -> Result<Self::Value, D::Error>
124    where
125        D: Deserializer,
126    {
127        let _ = name;
128        let _ = deserializer;
129
130        Err(Error::Unexpect(Kind::NamedOpcode(name.to_string())).into())
131    }
132
133    /// The input contains attrs with one opcode.
134    ///
135    /// The default implementation fails with a type error.
136    fn visit_opcode_with_attrs<D>(
137        self,
138        name: &str,
139        deserializer: D,
140    ) -> Result<Vec<Self::Value>, D::Error>
141    where
142        D: AttrsNodeAccess,
143    {
144        let _ = name;
145        let _ = deserializer;
146
147        Err(Error::Unexpect(Kind::NamedOpcode(name.to_string())).into())
148    }
149
150    /// The input contains a pop opcode.
151    fn visit_pop<E>(self) -> Result<Self::Value, E>
152    where
153        E: From<Error>,
154    {
155        Err(Error::Unexpect(Kind::Pop).into())
156    }
157
158    /// The input contains a element node.
159    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
160    where
161        D: Deserializer,
162    {
163        let _ = deserializer;
164
165        Err(Error::Unexpect(Kind::Some).into())
166    }
167
168    /// The input contains a element node.
169    fn visit_constant<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
170    where
171        D: Deserializer,
172    {
173        let _ = deserializer;
174
175        Err(Error::Unexpect(Kind::Constant).into())
176    }
177
178    /// The input contains a element node.
179    fn visit_variable<E>(self, path: Path, target: Target) -> Result<Self::Value, E>
180    where
181        E: From<Error>,
182    {
183        let _ = path;
184        let _ = target;
185
186        Err(Error::Unexpect(Kind::Variable).into())
187    }
188
189    /// The input contains a data.
190    fn visit_node<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
191    where
192        D: NodeAccess,
193    {
194        let _ = deserializer;
195
196        Err(Error::Unexpect(Kind::Data).into())
197    }
198
199    /// The input contains a enum data.
200    fn visit_enum<D>(self, variant_index: usize, deserializer: D) -> Result<Self::Value, D::Error>
201    where
202        D: NodeAccess,
203    {
204        let _ = variant_index;
205        let _ = deserializer;
206
207        Err(Error::Unexpect(Kind::Enum).into())
208    }
209
210    /// The input contains a enum data.
211    fn visit_enum_with<D>(
212        self,
213        variant_name: &str,
214        deserializer: D,
215    ) -> Result<Self::Value, D::Error>
216    where
217        D: NodeAccess,
218    {
219        let _ = variant_name;
220        let _ = deserializer;
221
222        Err(Error::Unexpect(Kind::Enum).into())
223    }
224
225    /// The input contains a enum data.
226    fn visit_seq<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
227    where
228        D: SeqAccess,
229    {
230        let _ = deserializer;
231
232        Err(Error::Unexpect(Kind::Seq).into())
233    }
234
235    /// The input contains a `string` value.
236    fn visit_string<E>(self, value: &str) -> Result<Self::Value, E>
237    where
238        E: From<Error>,
239    {
240        let _ = value;
241
242        Err(Error::Unexpect(Kind::String).into())
243    }
244
245    /// The input contains a `bool` value.
246    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
247    where
248        E: From<Error>,
249    {
250        let _ = value;
251
252        Err(Error::Unexpect(Kind::Bool).into())
253    }
254
255    /// The input contains a `byte` value.
256    fn visit_byte<E>(self, value: i8) -> Result<Self::Value, E>
257    where
258        E: From<Error>,
259    {
260        let _ = value;
261
262        Err(Error::Unexpect(Kind::Byte).into())
263    }
264
265    /// The input contains a `ubyte` value.
266    fn visit_ubyte<E>(self, value: u8) -> Result<Self::Value, E>
267    where
268        E: From<Error>,
269    {
270        let _ = value;
271
272        Err(Error::Unexpect(Kind::Ubyte).into())
273    }
274
275    /// The input contains a `short` value.
276    fn visit_short<E>(self, value: i16) -> Result<Self::Value, E>
277    where
278        E: From<Error>,
279    {
280        let _ = value;
281
282        Err(Error::Unexpect(Kind::Short).into())
283    }
284
285    /// The input contains a `ushort` value.
286    fn visit_ushort<E>(self, value: u16) -> Result<Self::Value, E>
287    where
288        E: From<Error>,
289    {
290        let _ = value;
291
292        Err(Error::Unexpect(Kind::Ushort).into())
293    }
294
295    /// The input contains a `int` value.
296    fn visit_int<E>(self, value: i32) -> Result<Self::Value, E>
297    where
298        E: From<Error>,
299    {
300        let _ = value;
301
302        Err(Error::Unexpect(Kind::Int).into())
303    }
304
305    /// The input contains a `uint` value.
306    fn visit_uint<E>(self, value: u32) -> Result<Self::Value, E>
307    where
308        E: From<Error>,
309    {
310        let _ = value;
311
312        Err(Error::Unexpect(Kind::Uint).into())
313    }
314
315    /// The input contains a `long` value.
316    fn visit_long<E>(self, value: i64) -> Result<Self::Value, E>
317    where
318        E: From<Error>,
319    {
320        let _ = value;
321
322        Err(Error::Unexpect(Kind::Long).into())
323    }
324
325    /// The input contains a `ulong` value.
326    fn visit_ulong<E>(self, value: u64) -> Result<Self::Value, E>
327    where
328        E: From<Error>,
329    {
330        let _ = value;
331
332        Err(Error::Unexpect(Kind::Ulong).into())
333    }
334
335    /// The input contains a `float` value.
336    fn visit_float<E>(self, value: f32) -> Result<Self::Value, E>
337    where
338        E: From<Error>,
339    {
340        let _ = value;
341
342        Err(Error::Unexpect(Kind::Float).into())
343    }
344
345    /// The input contains a `double` value.
346    fn visit_double<E>(self, value: f64) -> Result<Self::Value, E>
347    where
348        E: From<Error>,
349    {
350        let _ = value;
351
352        Err(Error::Unexpect(Kind::Double).into())
353    }
354}
355
356/// Trait to access a sequence value.
357pub trait SeqAccess {
358    type Error: From<Error>;
359
360    /// This returns Ok(Some(value)) for the next value in the sequence, or Ok(None) if there are no more remaining items.
361    fn next_item<T>(&mut self) -> Result<Option<T::Value>, Self::Error>
362    where
363        T: Deserialize;
364}
365
366/// Trait to access applied attrs.
367pub trait AttrsNodeAccess {
368    type Error: From<Error>;
369
370    /// Returns a iterator over the attribute names.
371    fn attrs(&self) -> impl Iterator<Item = &str>;
372
373    /// This returns Ok(Some(value)) for the next value in the sequence, or Ok(None) if there are no more remaining items.
374    fn deserialize_attr<V>(&mut self, name: &str, visitor: V) -> Result<V::Value, Self::Error>
375    where
376        V: Visitor;
377
378    /// derserialize a element node.
379    fn deserialize_node<V>(self, name: &str, visitor: V) -> Result<V::Value, Self::Error>
380    where
381        V: Visitor;
382}
383
384/// Trait to access a sequence value.
385pub trait NodeAccess {
386    type Error: From<Error>;
387
388    /// Deserialize next filed.
389    fn deserialize_field<T>(
390        &mut self,
391        ty: &str,
392        index: usize,
393        field_name: Option<&str>,
394    ) -> Result<T::Value, Self::Error>
395    where
396        T: Deserialize;
397}
398
399/// A data format that can deserialize any data structure supported by `mlang`.
400pub trait Deserializer {
401    /// Error type used by this `deserializer`.
402    type Error: From<Error> + 'static;
403
404    /// derserialize a list of opcodes.
405    fn deserialize_opcode<V>(self, visitor: V) -> Result<Option<Vec<V::Value>>, Self::Error>
406    where
407        V: Visitor;
408
409    /// derserialize a element node.
410    fn deserialize_element<V>(
411        self,
412        type_id: usize,
413        name: &str,
414        visitor: V,
415    ) -> Result<V::Value, Self::Error>
416    where
417        V: Visitor;
418
419    /// derserialize a element node.
420    fn deserialize_leaf<V>(
421        self,
422        type_id: usize,
423        name: &str,
424        visitor: V,
425    ) -> Result<V::Value, Self::Error>
426    where
427        V: Visitor;
428
429    /// derserialize a element node.
430    fn deserialize_attr<V>(
431        self,
432        type_id: usize,
433        name: &str,
434        visitor: V,
435    ) -> Result<V::Value, Self::Error>
436    where
437        V: Visitor;
438
439    /// derserialize a element node.
440    fn deserialize_data<V>(
441        self,
442        type_id: usize,
443        name: &str,
444        visitor: V,
445    ) -> Result<V::Value, Self::Error>
446    where
447        V: Visitor;
448
449    /// derserialize a enum data.
450    fn deserialize_enum<V>(
451        self,
452        type_id: usize,
453        name: &str,
454        visitor: V,
455    ) -> Result<V::Value, Self::Error>
456    where
457        V: Visitor;
458
459    /// derserialize a sequence data.
460    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
461    where
462        V: Visitor;
463
464    /// derserialize a option value.
465    fn deserialize_option<V>(self, visitor: V) -> Result<Option<V::Value>, Self::Error>
466    where
467        V: Visitor;
468
469    /// derserialize a variable value.
470    fn deserialize_variable<V>(self, visitor: V) -> Result<V::Value, Self::Error>
471    where
472        V: Visitor;
473
474    /// derserialize a string value.
475    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
476    where
477        V: Visitor;
478
479    /// derserialize a bool value.
480    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
481    where
482        V: Visitor;
483
484    /// derserialize a byte value.
485    fn deserialize_byte<V>(self, visitor: V) -> Result<V::Value, Self::Error>
486    where
487        V: Visitor;
488
489    /// derserialize a ubyte value.
490    fn deserialize_ubyte<V>(self, visitor: V) -> Result<V::Value, Self::Error>
491    where
492        V: Visitor;
493
494    /// derserialize a short value.
495    fn deserialize_short<V>(self, visitor: V) -> Result<V::Value, Self::Error>
496    where
497        V: Visitor;
498
499    /// derserialize a ushort value.
500    fn deserialize_ushort<V>(self, visitor: V) -> Result<V::Value, Self::Error>
501    where
502        V: Visitor;
503
504    /// derserialize a int value.
505    fn deserialize_int<V>(self, visitor: V) -> Result<V::Value, Self::Error>
506    where
507        V: Visitor;
508
509    /// derserialize a uint value.
510    fn deserialize_uint<V>(self, visitor: V) -> Result<V::Value, Self::Error>
511    where
512        V: Visitor;
513    /// derserialize a long value.
514    fn deserialize_long<V>(self, visitor: V) -> Result<V::Value, Self::Error>
515    where
516        V: Visitor;
517
518    /// derserialize a ulong value.
519    fn deserialize_ulong<V>(self, visitor: V) -> Result<V::Value, Self::Error>
520    where
521        V: Visitor;
522
523    /// derserialize a float value.
524    fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, Self::Error>
525    where
526        V: Visitor;
527
528    /// derserialize a double value.
529    fn deserialize_double<V>(self, visitor: V) -> Result<V::Value, Self::Error>
530    where
531        V: Visitor;
532}
533
534/// Implement this trait to support derserializing from any data format.
535pub trait Deserialize: Sized {
536    type Value: 'static;
537    /// Derserialize this value from given `derserializer`.
538    fn deserialize<D>(deserializer: D) -> Result<Self::Value, D::Error>
539    where
540        D: Deserializer;
541}
542
543impl Deserialize for String {
544    type Value = String;
545    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
546    where
547        D: Deserializer,
548    {
549        struct V;
550
551        impl Visitor for V {
552            type Value = String;
553
554            fn visit_string<E>(self, value: &str) -> Result<Self::Value, E>
555            where
556                E: From<Error>,
557            {
558                Ok(value.to_string())
559            }
560        }
561
562        deserializer.deserialize_string(V)
563    }
564}
565
566impl Deserialize for bool {
567    type Value = bool;
568    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
569    where
570        D: Deserializer,
571    {
572        struct V;
573
574        impl Visitor for V {
575            type Value = bool;
576
577            fn visit_string<E>(self, value: &str) -> Result<Self::Value, E>
578            where
579                E: From<Error>,
580            {
581                Ok(if value == "1" { true } else { false })
582            }
583
584            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
585            where
586                E: From<Error>,
587            {
588                Ok(value)
589            }
590        }
591
592        deserializer.deserialize_bool(V)
593    }
594}
595
596macro_rules! impl_deserilaize_num {
597    ($ty:ident, $visit:ident, $deserialize:ident) => {
598        impl Deserialize for $ty {
599            type Value = $ty;
600
601            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
602            where
603                D: Deserializer,
604            {
605                struct V;
606
607                impl Visitor for V {
608                    type Value = $ty;
609
610                    fn visit_string<E>(self, value: &str) -> Result<Self::Value, E>
611                    where
612                        E: From<Error>,
613                    {
614                        let value = value.parse::<$ty>().map_err(|err| Error::from(err))?;
615                        Ok(value)
616                    }
617
618                    fn $visit<E>(self, value: $ty) -> Result<Self::Value, E>
619                    where
620                        E: From<Error>,
621                    {
622                        Ok(value)
623                    }
624                }
625
626                deserializer.$deserialize(V)
627            }
628        }
629    };
630}
631
632impl_deserilaize_num!(i8, visit_byte, deserialize_byte);
633impl_deserilaize_num!(u8, visit_ubyte, deserialize_ubyte);
634impl_deserilaize_num!(i16, visit_short, deserialize_short);
635impl_deserilaize_num!(u16, visit_ushort, deserialize_ushort);
636impl_deserilaize_num!(i32, visit_int, deserialize_int);
637impl_deserilaize_num!(u32, visit_uint, deserialize_uint);
638impl_deserilaize_num!(i64, visit_long, deserialize_long);
639impl_deserilaize_num!(u64, visit_ulong, deserialize_ulong);
640impl_deserilaize_num!(f32, visit_float, deserialize_float);
641impl_deserilaize_num!(f64, visit_double, deserialize_double);
642
643impl<'de, T> Deserialize for Option<T>
644where
645    T: Deserialize,
646{
647    type Value = Option<T::Value>;
648    fn deserialize<D>(deserializer: D) -> Result<Self::Value, D::Error>
649    where
650        D: Deserializer,
651    {
652        struct V<T>(PhantomData<T>);
653
654        impl<'de, T> Visitor for V<T>
655        where
656            T: Deserialize,
657        {
658            type Value = T::Value;
659
660            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
661            where
662                D: Deserializer,
663            {
664                T::deserialize(deserializer)
665            }
666        }
667
668        deserializer.deserialize_option(V::<T>(PhantomData::default()))
669    }
670}
671
672impl<'de, T> Deserialize for Variable<T>
673where
674    T: Deserialize,
675{
676    type Value = Variable<T::Value>;
677    fn deserialize<D>(deserializer: D) -> Result<Self::Value, D::Error>
678    where
679        D: Deserializer,
680    {
681        struct V<T>(PhantomData<T>);
682
683        impl<'de, T> Visitor for V<T>
684        where
685            T: Deserialize,
686        {
687            type Value = Variable<T::Value>;
688
689            fn visit_variable<E>(self, path: Path, target: Target) -> Result<Self::Value, E>
690            where
691                E: From<Error>,
692            {
693                Ok(Variable::Reference { path, target })
694            }
695
696            fn visit_constant<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
697            where
698                D: Deserializer,
699            {
700                Ok(Variable::Constant(T::deserialize(deserializer)?))
701            }
702        }
703
704        deserializer.deserialize_variable(V::<T>(PhantomData::default()))
705    }
706}
707
708impl<'de, T> Deserialize for Vec<T>
709where
710    T: Deserialize,
711{
712    type Value = Vec<T::Value>;
713    fn deserialize<D>(deserializer: D) -> Result<Self::Value, D::Error>
714    where
715        D: Deserializer,
716    {
717        struct V<T>(PhantomData<T>);
718
719        impl<'de, T> Visitor for V<T>
720        where
721            T: Deserialize,
722        {
723            type Value = Vec<T::Value>;
724
725            fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
726            where
727                S: SeqAccess,
728            {
729                let mut values = vec![];
730
731                while let Some(value) = seq.next_item::<T>()? {
732                    values.push(value);
733                }
734
735                Ok(values)
736            }
737        }
738
739        deserializer.deserialize_seq(V::<T>(PhantomData::default()))
740    }
741}
742
743impl<'de, T, const N: usize> Deserialize for [T; N]
744where
745    T: Deserialize,
746{
747    type Value = [T::Value; N];
748    fn deserialize<D>(deserializer: D) -> Result<Self::Value, D::Error>
749    where
750        D: Deserializer,
751    {
752        struct V<T>(PhantomData<T>);
753
754        impl<'de, T> Visitor for V<T>
755        where
756            T: Deserialize,
757        {
758            type Value = Vec<T::Value>;
759
760            fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
761            where
762                S: SeqAccess,
763            {
764                let mut values = vec![];
765
766                while let Some(value) = seq.next_item::<T>()? {
767                    values.push(value);
768                }
769
770                Ok(values)
771            }
772        }
773
774        let values = deserializer.deserialize_seq(V::<T>(PhantomData::default()))?;
775
776        Ok(values
777            .try_into()
778            .map_err(|err: Vec<T::Value>| Error::OutOfRange(err.len(), N))?)
779    }
780}