Skip to main content

moonproof_runtime_ir/
de.rs

1//! Deserialize a typed `T: Deserialize` directly from an in-memory
2//! [`RuntimeValue`] tree — no CBOR/JSON round-trip.
3//!
4//! The IR embeds nested fragments (a circuit `Expression`, a
5//! `TypeDescriptor`, a lambda `Statement`) as dynamically-typed
6//! `RuntimeValue` subtrees inside vm-op `ref`/`type` slots and lambda
7//! bodies. Recovering the typed form previously re-serialized the
8//! subtree to a CBOR buffer and parsed it back (`ciborium` round-trip)
9//! purely to cross the type boundary while preserving byte-strings.
10//!
11//! [`from_runtime_value`] does it in place: it drives the target's
12//! `Deserialize` straight off the `RuntimeValue` enum. `Bytes` maps to
13//! `visit_bytes` (the byte-string fidelity the JSON bridge can't keep),
14//! `Int(i128)` to `visit_i128`, objects/arrays to map/seq access —
15//! self-describing, so serde's internally-tagged enums (`tag = "expr"`,
16//! `"type-name"`, `"stmt"`, …) resolve through `deserialize_any`.
17
18use std::collections::btree_map;
19use std::fmt;
20use std::slice;
21
22use serde::de::value::BorrowedStrDeserializer;
23use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
24use serde::forward_to_deserialize_any;
25
26use crate::value::RuntimeValue;
27
28/// Error from deserializing a typed value out of a [`RuntimeValue`].
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct FromValueError(String);
31
32impl fmt::Display for FromValueError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str(&self.0)
35    }
36}
37
38impl std::error::Error for FromValueError {}
39
40impl de::Error for FromValueError {
41    fn custom<T: fmt::Display>(msg: T) -> Self {
42        FromValueError(msg.to_string())
43    }
44}
45
46/// Deserialize `T` directly from a borrowed [`RuntimeValue`] — the
47/// in-place replacement for a `ciborium`/`serde_json` round-trip.
48pub fn from_runtime_value<'de, T: serde::Deserialize<'de>>(
49    value: &'de RuntimeValue,
50) -> Result<T, FromValueError> {
51    T::deserialize(value)
52}
53
54impl<'de> Deserializer<'de> for &'de RuntimeValue {
55    type Error = FromValueError;
56
57    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
58        match self {
59            RuntimeValue::Null => visitor.visit_unit(),
60            RuntimeValue::Bool(b) => visitor.visit_bool(*b),
61            // Hand out the narrowest integer width that fits. serde's
62            // internally-tagged enum buffering (`Content`) — used by
63            // every `tag = "..."` enum the IR decodes into — has no
64            // `i128`/`u128` arm, so `visit_i128` on a small value fails
65            // with "expected any value". `i64`/`u64` are always present
66            // (and this mirrors how the former CBOR round-trip fed
67            // small ints back). Genuinely-huge values (only `Uint<128>`
68            // maxvals, which `IntLit` serializes as strings anyway)
69            // fall through to `visit_i128`.
70            RuntimeValue::Int(i) => {
71                if let Ok(v) = i64::try_from(*i) {
72                    visitor.visit_i64(v)
73                } else if let Ok(v) = u64::try_from(*i) {
74                    visitor.visit_u64(v)
75                } else {
76                    visitor.visit_i128(*i)
77                }
78            }
79            RuntimeValue::Bytes(b) => visitor.visit_bytes(b),
80            RuntimeValue::String(s) => visitor.visit_borrowed_str(s),
81            RuntimeValue::Array(a) => visitor.visit_seq(SeqDe { iter: a.iter() }),
82            RuntimeValue::Object(o) => visitor.visit_map(MapDe {
83                iter: o.iter(),
84                value: None,
85            }),
86        }
87    }
88
89    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
90        match self {
91            RuntimeValue::Null => visitor.visit_none(),
92            other => visitor.visit_some(other),
93        }
94    }
95
96    fn deserialize_newtype_struct<V: Visitor<'de>>(
97        self,
98        _name: &'static str,
99        visitor: V,
100    ) -> Result<V::Value, Self::Error> {
101        visitor.visit_newtype_struct(self)
102    }
103
104    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
105        match self {
106            RuntimeValue::Bytes(b) => visitor.visit_bytes(b),
107            other => other.deserialize_any(visitor),
108        }
109    }
110
111    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
112        self.deserialize_bytes(visitor)
113    }
114
115    forward_to_deserialize_any! {
116        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
117        unit unit_struct seq tuple tuple_struct map struct enum identifier
118        ignored_any
119    }
120}
121
122struct SeqDe<'de> {
123    iter: slice::Iter<'de, RuntimeValue>,
124}
125
126impl<'de> SeqAccess<'de> for SeqDe<'de> {
127    type Error = FromValueError;
128
129    fn next_element_seed<T: DeserializeSeed<'de>>(
130        &mut self,
131        seed: T,
132    ) -> Result<Option<T::Value>, Self::Error> {
133        match self.iter.next() {
134            Some(v) => seed.deserialize(v).map(Some),
135            None => Ok(None),
136        }
137    }
138
139    fn size_hint(&self) -> Option<usize> {
140        Some(self.iter.len())
141    }
142}
143
144struct MapDe<'de> {
145    iter: btree_map::Iter<'de, String, RuntimeValue>,
146    value: Option<&'de RuntimeValue>,
147}
148
149impl<'de> MapAccess<'de> for MapDe<'de> {
150    type Error = FromValueError;
151
152    fn next_key_seed<K: DeserializeSeed<'de>>(
153        &mut self,
154        seed: K,
155    ) -> Result<Option<K::Value>, Self::Error> {
156        match self.iter.next() {
157            Some((k, v)) => {
158                self.value = Some(v);
159                seed.deserialize(BorrowedStrDeserializer::new(k)).map(Some)
160            }
161            None => Ok(None),
162        }
163    }
164
165    fn next_value_seed<T: DeserializeSeed<'de>>(
166        &mut self,
167        seed: T,
168    ) -> Result<T::Value, Self::Error> {
169        let value = self
170            .value
171            .take()
172            .expect("next_value_seed called before next_key_seed");
173        seed.deserialize(value)
174    }
175
176    fn size_hint(&self) -> Option<usize> {
177        Some(self.iter.len())
178    }
179}