1use crate::error::{Error, Result};
16use serde::{
17 de, ser,
18 ser::{SerializeMap, SerializeStruct},
19 Deserialize, Serialize,
20};
21use std::{
22 cell::{Ref, RefCell, RefMut},
23 collections::{btree_map::Entry, BTreeMap},
24 ops::DerefMut,
25 rc::Rc,
26};
27
28#[derive(Serialize, Deserialize, Debug, Eq, Clone, PartialEq)]
30#[serde(rename_all = "UPPERCASE")]
31pub enum Format {
32 Variable(#[serde(with = "not_implemented")] Variable<Format>),
34 TypeName(String),
36
37 Unit,
39 Bool,
40 I8,
41 I16,
42 I32,
43 I64,
44 I128,
45 U8,
46 U16,
47 U32,
48 U64,
49 U128,
50 F32,
51 F64,
52 Char,
53 Str,
54 Bytes,
55
56 Option(Box<Format>),
58 Seq(Box<Format>),
60 #[serde(rename_all = "UPPERCASE")]
62 Map {
63 key: Box<Format>,
64 value: Box<Format>,
65 },
66
67 Tuple(Vec<Format>),
69 #[serde(rename_all = "UPPERCASE")]
72 TupleArray {
73 content: Box<Format>,
74 size: usize,
75 },
76}
77
78#[derive(Serialize, Deserialize, Debug, Eq, Clone, PartialEq)]
81#[serde(rename_all = "UPPERCASE")]
82pub enum ContainerFormat {
83 UnitStruct,
85 NewTypeStruct(Box<Format>),
87 TupleStruct(Vec<Format>),
89 Struct(Vec<Named<Format>>),
91 Enum(BTreeMap<u32, Named<VariantFormat>>),
94}
95
96#[derive(Debug, Clone, Default, Eq, PartialEq)]
97pub struct Named<T> {
100 pub name: String,
101 pub value: T,
102}
103
104#[derive(Debug, Clone, Default, Eq, PartialEq)]
105pub struct Variable<T>(Rc<RefCell<Option<T>>>);
107
108#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
109#[serde(rename_all = "UPPERCASE")]
110pub enum VariantFormat {
112 Variable(#[serde(with = "not_implemented")] Variable<VariantFormat>),
114 Unit,
116 NewType(Box<Format>),
118 Tuple(Vec<Format>),
120 Struct(Vec<Named<Format>>),
122}
123
124pub trait FormatHolder {
126 fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()>;
129
130 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()>;
135
136 fn unify(&mut self, other: Self) -> Result<()>;
145
146 fn normalize(&mut self) -> Result<()> {
150 self.visit_mut(&mut |format: &mut Format| {
151 let normalized = match format {
152 Format::Tuple(formats) => {
153 let size = formats.len();
154 if size <= 1 {
155 return Ok(());
156 }
157 let format0 = &formats[0];
158 for format in formats.iter().skip(1) {
159 if format != format0 {
160 return Ok(());
161 }
162 }
163 Format::TupleArray {
164 content: Box::new(std::mem::take(&mut formats[0])),
165 size,
166 }
167 }
168 _ => {
169 return Ok(());
170 }
171 };
172 *format = normalized;
173 Ok(())
174 })
175 }
176
177 fn reduce(&mut self) {
180 self.visit_mut(&mut |_| Ok(())).unwrap_or(())
181 }
182
183 fn is_unknown(&self) -> bool;
185}
186
187fn unification_error<T1, T2>(v1: T1, v2: T2) -> Error
188where
189 T1: std::fmt::Debug,
190 T2: std::fmt::Debug,
191{
192 Error::Incompatible(format!("{:?}", v1), format!("{:?}", v2))
193}
194
195impl FormatHolder for VariantFormat {
196 fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
197 match self {
198 Self::Variable(variable) => variable.visit(f)?,
199 Self::Unit => (),
200 Self::NewType(format) => format.visit(f)?,
201 Self::Tuple(formats) => {
202 for format in formats {
203 format.visit(f)?;
204 }
205 }
206 Self::Struct(named_formats) => {
207 for format in named_formats {
208 format.visit(f)?;
209 }
210 }
211 }
212 Ok(())
213 }
214
215 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
216 match self {
217 Self::Variable(variable) => {
218 variable.visit_mut(f)?;
219 *self = std::mem::take(variable)
222 .into_inner()
223 .expect("variable is known");
224 }
225 Self::Unit => (),
226 Self::NewType(format) => {
227 format.visit_mut(f)?;
228 }
229 Self::Tuple(formats) => {
230 for format in formats {
231 format.visit_mut(f)?;
232 }
233 }
234 Self::Struct(named_formats) => {
235 for format in named_formats {
236 format.visit_mut(f)?;
237 }
238 }
239 }
240 Ok(())
241 }
242
243 fn unify(&mut self, format: VariantFormat) -> Result<()> {
244 match (self, format) {
245 (format1, Self::Variable(variable2)) => {
246 if let Some(format2) = variable2.borrow_mut().deref_mut() {
247 format1.unify(std::mem::take(format2))?;
248 }
249 *variable2.borrow_mut() = Some(format1.clone());
250 }
251 (Self::Variable(variable1), format2) => {
252 let inner_variable = match variable1.borrow_mut().deref_mut() {
253 value1 @ None => {
254 *value1 = Some(format2);
255 None
256 }
257 Some(format1) => {
258 format1.unify(format2)?;
259 match format1 {
260 Self::Variable(variable) => Some(variable.clone()),
261 _ => None,
262 }
263 }
264 };
265 if let Some(variable) = inner_variable {
267 *variable1 = variable;
268 }
269 }
270
271 (Self::Unit, Self::Unit) => (),
272
273 (Self::NewType(format1), Self::NewType(format2)) => {
274 format1.as_mut().unify(*format2)?;
275 }
276
277 (Self::Tuple(formats1), Self::Tuple(formats2)) if formats1.len() == formats2.len() => {
278 for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
279 format1.unify(format2)?;
280 }
281 }
282
283 (Self::Struct(named_formats1), Self::Struct(named_formats2))
284 if named_formats1.len() == named_formats2.len() =>
285 {
286 for (format1, format2) in named_formats1.iter_mut().zip(named_formats2.into_iter())
287 {
288 format1.unify(format2)?;
289 }
290 }
291
292 (format1, format2) => {
293 return Err(unification_error(format1, format2));
294 }
295 }
296 Ok(())
297 }
298
299 fn is_unknown(&self) -> bool {
300 if let Self::Variable(v) = self {
301 return v.is_unknown();
302 }
303 false
304 }
305}
306
307impl<T> FormatHolder for Named<T>
308where
309 T: FormatHolder + std::fmt::Debug,
310{
311 fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
312 self.value.visit(f)
313 }
314
315 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
316 self.value.visit_mut(f)
317 }
318
319 fn unify(&mut self, other: Named<T>) -> Result<()> {
320 if self.name != other.name {
321 return Err(unification_error(&*self, &other));
322 }
323 self.value.unify(other.value)
324 }
325
326 fn is_unknown(&self) -> bool {
327 false
328 }
329}
330
331impl<T> Variable<T> {
332 pub(crate) fn new(content: Option<T>) -> Self {
333 Self(Rc::new(RefCell::new(content)))
334 }
335
336 pub fn borrow(&self) -> Ref<Option<T>> {
337 self.0.as_ref().borrow()
338 }
339
340 pub fn borrow_mut(&self) -> RefMut<Option<T>> {
341 self.0.as_ref().borrow_mut()
342 }
343}
344
345impl<T> Variable<T>
346where
347 T: Clone,
348{
349 fn into_inner(self) -> Option<T> {
350 match Rc::try_unwrap(self.0) {
351 Ok(cell) => cell.into_inner(),
352 Err(rc) => rc.borrow().clone(),
353 }
354 }
355}
356
357mod not_implemented {
358 pub fn serialize<T, S>(_: &T, _serializer: S) -> Result<S::Ok, S::Error>
359 where
360 S: serde::ser::Serializer,
361 {
362 use serde::ser::Error;
363 Err(S::Error::custom("Cannot serialize variables"))
364 }
365
366 pub fn deserialize<'de, T, D>(_deserializer: D) -> Result<T, D::Error>
367 where
368 D: serde::de::Deserializer<'de>,
369 {
370 use serde::de::Error;
371 Err(D::Error::custom("Cannot deserialize variables"))
372 }
373}
374
375impl<T> FormatHolder for Variable<T>
376where
377 T: FormatHolder + std::fmt::Debug + Clone,
378{
379 fn visit<'a>(&'a self, _f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
380 Err(Error::NotSupported(
381 "Cannot immutability visit formats with variables",
382 ))
383 }
384
385 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
386 match self.borrow_mut().deref_mut() {
387 None => Err(Error::UnknownFormat),
388 Some(value) => value.visit_mut(f),
389 }
390 }
391
392 fn unify(&mut self, _other: Variable<T>) -> Result<()> {
393 Err(Error::NotSupported("Cannot unify variables directly"))
396 }
397
398 fn is_unknown(&self) -> bool {
399 match self.borrow().as_ref() {
400 None => true,
401 Some(format) => format.is_unknown(),
402 }
403 }
404}
405
406impl FormatHolder for ContainerFormat {
407 fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
408 match self {
409 Self::UnitStruct => (),
410 Self::NewTypeStruct(format) => format.visit(f)?,
411 Self::TupleStruct(formats) => {
412 for format in formats {
413 format.visit(f)?;
414 }
415 }
416 Self::Struct(named_formats) => {
417 for format in named_formats {
418 format.visit(f)?;
419 }
420 }
421 Self::Enum(variants) => {
422 for variant in variants {
423 variant.1.visit(f)?;
424 }
425 }
426 }
427 Ok(())
428 }
429
430 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
431 match self {
432 Self::UnitStruct => (),
433 Self::NewTypeStruct(format) => format.visit_mut(f)?,
434 Self::TupleStruct(formats) => {
435 for format in formats {
436 format.visit_mut(f)?;
437 }
438 }
439 Self::Struct(named_formats) => {
440 for format in named_formats {
441 format.visit_mut(f)?;
442 }
443 }
444 Self::Enum(variants) => {
445 for variant in variants {
446 variant.1.visit_mut(f)?;
447 }
448 }
449 }
450 Ok(())
451 }
452
453 fn unify(&mut self, format: ContainerFormat) -> Result<()> {
454 match (self, format) {
455 (Self::UnitStruct, Self::UnitStruct) => (),
456
457 (Self::NewTypeStruct(format1), Self::NewTypeStruct(format2)) => {
458 format1.as_mut().unify(*format2)?;
459 }
460
461 (Self::TupleStruct(formats1), Self::TupleStruct(formats2))
462 if formats1.len() == formats2.len() =>
463 {
464 for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
465 format1.unify(format2)?;
466 }
467 }
468
469 (Self::Struct(named_formats1), Self::Struct(named_formats2))
470 if named_formats1.len() == named_formats2.len() =>
471 {
472 for (format1, format2) in named_formats1.iter_mut().zip(named_formats2.into_iter())
473 {
474 format1.unify(format2)?;
475 }
476 }
477
478 (Self::Enum(variants1), Self::Enum(variants2)) => {
479 for (index2, variant2) in variants2.into_iter() {
480 match variants1.entry(index2) {
481 Entry::Vacant(e) => {
482 e.insert(variant2);
484 }
485 Entry::Occupied(mut e) => {
486 e.get_mut().unify(variant2)?;
487 }
488 }
489 }
490 }
491
492 (format1, format2) => {
493 return Err(unification_error(format1, format2));
494 }
495 }
496 Ok(())
497 }
498
499 fn is_unknown(&self) -> bool {
500 false
501 }
502}
503
504impl FormatHolder for Format {
505 fn visit<'a>(&'a self, f: &mut dyn FnMut(&'a Format) -> Result<()>) -> Result<()> {
506 match self {
507 Self::Variable(variable) => variable.visit(f)?,
508 Self::TypeName(_)
509 | Self::Unit
510 | Self::Bool
511 | Self::I8
512 | Self::I16
513 | Self::I32
514 | Self::I64
515 | Self::I128
516 | Self::U8
517 | Self::U16
518 | Self::U32
519 | Self::U64
520 | Self::U128
521 | Self::F32
522 | Self::F64
523 | Self::Char
524 | Self::Str
525 | Self::Bytes => (),
526
527 Self::Option(format)
528 | Self::Seq(format)
529 | Self::TupleArray {
530 content: format, ..
531 } => {
532 format.visit(f)?;
533 }
534
535 Self::Map { key, value } => {
536 key.visit(f)?;
537 value.visit(f)?;
538 }
539
540 Self::Tuple(formats) => {
541 for format in formats {
542 format.visit(f)?;
543 }
544 }
545 }
546 f(self)
547 }
548
549 fn visit_mut(&mut self, f: &mut dyn FnMut(&mut Format) -> Result<()>) -> Result<()> {
550 match self {
551 Self::Variable(variable) => {
552 variable.visit_mut(f)?;
553 *self = std::mem::take(variable)
556 .into_inner()
557 .expect("variable is known");
558 }
559 Self::TypeName(_)
560 | Self::Unit
561 | Self::Bool
562 | Self::I8
563 | Self::I16
564 | Self::I32
565 | Self::I64
566 | Self::I128
567 | Self::U8
568 | Self::U16
569 | Self::U32
570 | Self::U64
571 | Self::U128
572 | Self::F32
573 | Self::F64
574 | Self::Char
575 | Self::Str
576 | Self::Bytes => (),
577
578 Self::Option(format)
579 | Self::Seq(format)
580 | Self::TupleArray {
581 content: format, ..
582 } => {
583 format.visit_mut(f)?;
584 }
585
586 Self::Map { key, value } => {
587 key.visit_mut(f)?;
588 value.visit_mut(f)?;
589 }
590
591 Self::Tuple(formats) => {
592 for format in formats {
593 format.visit_mut(f)?;
594 }
595 }
596 }
597 f(self)
598 }
599
600 fn unify(&mut self, format: Format) -> Result<()> {
603 match (self, format) {
604 (format1, Self::Variable(variable2)) => {
605 if let Some(format2) = variable2.borrow_mut().deref_mut() {
606 format1.unify(std::mem::take(format2))?;
607 }
608 *variable2.borrow_mut() = Some(format1.clone());
609 }
610 (Self::Variable(variable1), format2) => {
611 let inner_variable = match variable1.borrow_mut().deref_mut() {
612 value1 @ None => {
613 *value1 = Some(format2);
614 None
615 }
616 Some(format1) => {
617 format1.unify(format2)?;
618 match format1 {
619 Self::Variable(variable) => Some(variable.clone()),
620 _ => None,
621 }
622 }
623 };
624 if let Some(variable) = inner_variable {
626 *variable1 = variable;
627 }
628 }
629
630 (Self::Unit, Self::Unit)
631 | (Self::Bool, Self::Bool)
632 | (Self::I8, Self::I8)
633 | (Self::I16, Self::I16)
634 | (Self::I32, Self::I32)
635 | (Self::I64, Self::I64)
636 | (Self::I128, Self::I128)
637 | (Self::U8, Self::U8)
638 | (Self::U16, Self::U16)
639 | (Self::U32, Self::U32)
640 | (Self::U64, Self::U64)
641 | (Self::U128, Self::U128)
642 | (Self::F32, Self::F32)
643 | (Self::F64, Self::F64)
644 | (Self::Char, Self::Char)
645 | (Self::Str, Self::Str)
646 | (Self::Bytes, Self::Bytes) => (),
647
648 (Self::TypeName(name1), Self::TypeName(name2)) if *name1 == name2 => (),
649
650 (Self::Option(format1), Self::Option(format2))
651 | (Self::Seq(format1), Self::Seq(format2)) => {
652 format1.as_mut().unify(*format2)?;
653 }
654
655 (Self::Tuple(formats1), Self::Tuple(formats2)) if formats1.len() == formats2.len() => {
656 for (format1, format2) in formats1.iter_mut().zip(formats2.into_iter()) {
657 format1.unify(format2)?;
658 }
659 }
660
661 (
662 Self::Map {
663 key: key1,
664 value: value1,
665 },
666 Self::Map {
667 key: key2,
668 value: value2,
669 },
670 ) => {
671 key1.as_mut().unify(*key2)?;
672 value1.as_mut().unify(*value2)?;
673 }
674
675 (format1, format2) => {
676 return Err(unification_error(format1, format2));
677 }
678 }
679 Ok(())
680 }
681
682 fn is_unknown(&self) -> bool {
683 if let Self::Variable(v) = self {
684 return v.is_unknown();
685 }
686 false
687 }
688}
689
690pub(crate) trait ContainerFormatEntry {
692 fn unify(self, format: ContainerFormat) -> Result<()>;
693}
694
695impl<'a, K> ContainerFormatEntry for Entry<'a, K, ContainerFormat>
696where
697 K: std::cmp::Ord,
698{
699 fn unify(self, format: ContainerFormat) -> Result<()> {
700 match self {
701 Entry::Vacant(e) => {
702 e.insert(format);
703 Ok(())
704 }
705 Entry::Occupied(e) => e.into_mut().unify(format),
706 }
707 }
708}
709
710impl Format {
711 pub fn unknown() -> Self {
713 Self::Variable(Variable::new(None))
714 }
715}
716
717impl VariantFormat {
718 pub fn unknown() -> Self {
720 Self::Variable(Variable::new(None))
721 }
722}
723
724impl Default for Format {
725 fn default() -> Self {
726 Self::unknown()
727 }
728}
729
730impl Default for VariantFormat {
731 fn default() -> Self {
732 Self::unknown()
733 }
734}
735
736impl<T> Serialize for Named<T>
739where
740 T: Serialize,
741{
742 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
743 where
744 S: ser::Serializer,
745 {
746 if serializer.is_human_readable() {
747 let mut map = serializer.serialize_map(Some(1))?;
748 map.serialize_entry(&self.name, &self.value)?;
749 map.end()
750 } else {
751 let mut inner = serializer.serialize_struct("Named", 2)?;
752 inner.serialize_field("name", &self.name)?;
753 inner.serialize_field("value", &self.value)?;
754 inner.end()
755 }
756 }
757}
758
759struct NamedVisitor<T> {
760 marker: std::marker::PhantomData<T>,
761}
762
763impl<T> NamedVisitor<T> {
764 fn new() -> Self {
765 Self {
766 marker: std::marker::PhantomData,
767 }
768 }
769}
770
771impl<'de, T> de::Visitor<'de> for NamedVisitor<T>
772where
773 T: Deserialize<'de>,
774{
775 type Value = Named<T>;
776
777 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
778 formatter.write_str("a single entry map")
779 }
780
781 fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
782 where
783 M: de::MapAccess<'de>,
784 {
785 let named_value = match access.next_entry::<String, T>()? {
786 Some((name, value)) => Named { name, value },
787 _ => {
788 return Err(de::Error::custom("Missing entry"));
789 }
790 };
791 if access.next_entry::<String, T>()?.is_some() {
792 return Err(de::Error::custom("Too many entries"));
793 }
794 Ok(named_value)
795 }
796}
797
798#[derive(Deserialize)]
800#[serde(rename = "Named")]
801struct NamedInternal<T> {
802 name: String,
803 value: T,
804}
805
806impl<'de, T> Deserialize<'de> for Named<T>
807where
808 T: Deserialize<'de>,
809{
810 fn deserialize<D>(deserializer: D) -> Result<Named<T>, D::Error>
811 where
812 D: de::Deserializer<'de>,
813 {
814 if deserializer.is_human_readable() {
815 deserializer.deserialize_map(NamedVisitor::new())
816 } else {
817 let NamedInternal { name, value } = NamedInternal::deserialize(deserializer)?;
818 Ok(Self { name, value })
819 }
820 }
821}