moonproof-runtime-ir 0.2.0

Rust consumer for compactc's contract.mpir — language-agnostic Compact contract IR. Loads, validates, and (eventually) interprets the IR to drive moonproof's contract runtime.
Documentation
//! Deserialize a typed `T: Deserialize` directly from an in-memory
//! [`RuntimeValue`] tree — no CBOR/JSON round-trip.
//!
//! The IR embeds nested fragments (a circuit `Expression`, a
//! `TypeDescriptor`, a lambda `Statement`) as dynamically-typed
//! `RuntimeValue` subtrees inside vm-op `ref`/`type` slots and lambda
//! bodies. Recovering the typed form previously re-serialized the
//! subtree to a CBOR buffer and parsed it back (`ciborium` round-trip)
//! purely to cross the type boundary while preserving byte-strings.
//!
//! [`from_runtime_value`] does it in place: it drives the target's
//! `Deserialize` straight off the `RuntimeValue` enum. `Bytes` maps to
//! `visit_bytes` (the byte-string fidelity the JSON bridge can't keep),
//! `Int(i128)` to `visit_i128`, objects/arrays to map/seq access —
//! self-describing, so serde's internally-tagged enums (`tag = "expr"`,
//! `"type-name"`, `"stmt"`, …) resolve through `deserialize_any`.

use std::collections::btree_map;
use std::fmt;
use std::slice;

use serde::de::value::BorrowedStrDeserializer;
use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::forward_to_deserialize_any;

use crate::value::RuntimeValue;

/// Error from deserializing a typed value out of a [`RuntimeValue`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromValueError(String);

impl fmt::Display for FromValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for FromValueError {}

impl de::Error for FromValueError {
    fn custom<T: fmt::Display>(msg: T) -> Self {
        FromValueError(msg.to_string())
    }
}

/// Deserialize `T` directly from a borrowed [`RuntimeValue`] — the
/// in-place replacement for a `ciborium`/`serde_json` round-trip.
pub fn from_runtime_value<'de, T: serde::Deserialize<'de>>(
    value: &'de RuntimeValue,
) -> Result<T, FromValueError> {
    T::deserialize(value)
}

impl<'de> Deserializer<'de> for &'de RuntimeValue {
    type Error = FromValueError;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self {
            RuntimeValue::Null => visitor.visit_unit(),
            RuntimeValue::Bool(b) => visitor.visit_bool(*b),
            // Hand out the narrowest integer width that fits. serde's
            // internally-tagged enum buffering (`Content`) — used by
            // every `tag = "..."` enum the IR decodes into — has no
            // `i128`/`u128` arm, so `visit_i128` on a small value fails
            // with "expected any value". `i64`/`u64` are always present
            // (and this mirrors how the former CBOR round-trip fed
            // small ints back). Genuinely-huge values (only `Uint<128>`
            // maxvals, which `IntLit` serializes as strings anyway)
            // fall through to `visit_i128`.
            RuntimeValue::Int(i) => {
                if let Ok(v) = i64::try_from(*i) {
                    visitor.visit_i64(v)
                } else if let Ok(v) = u64::try_from(*i) {
                    visitor.visit_u64(v)
                } else {
                    visitor.visit_i128(*i)
                }
            }
            RuntimeValue::Bytes(b) => visitor.visit_bytes(b),
            RuntimeValue::String(s) => visitor.visit_borrowed_str(s),
            RuntimeValue::Array(a) => visitor.visit_seq(SeqDe { iter: a.iter() }),
            RuntimeValue::Object(o) => visitor.visit_map(MapDe {
                iter: o.iter(),
                value: None,
            }),
        }
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self {
            RuntimeValue::Null => visitor.visit_none(),
            other => visitor.visit_some(other),
        }
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error> {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        match self {
            RuntimeValue::Bytes(b) => visitor.visit_bytes(b),
            other => other.deserialize_any(visitor),
        }
    }

    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
        self.deserialize_bytes(visitor)
    }

    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        unit unit_struct seq tuple tuple_struct map struct enum identifier
        ignored_any
    }
}

struct SeqDe<'de> {
    iter: slice::Iter<'de, RuntimeValue>,
}

impl<'de> SeqAccess<'de> for SeqDe<'de> {
    type Error = FromValueError;

    fn next_element_seed<T: DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, Self::Error> {
        match self.iter.next() {
            Some(v) => seed.deserialize(v).map(Some),
            None => Ok(None),
        }
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.iter.len())
    }
}

struct MapDe<'de> {
    iter: btree_map::Iter<'de, String, RuntimeValue>,
    value: Option<&'de RuntimeValue>,
}

impl<'de> MapAccess<'de> for MapDe<'de> {
    type Error = FromValueError;

    fn next_key_seed<K: DeserializeSeed<'de>>(
        &mut self,
        seed: K,
    ) -> Result<Option<K::Value>, Self::Error> {
        match self.iter.next() {
            Some((k, v)) => {
                self.value = Some(v);
                seed.deserialize(BorrowedStrDeserializer::new(k)).map(Some)
            }
            None => Ok(None),
        }
    }

    fn next_value_seed<T: DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<T::Value, Self::Error> {
        let value = self
            .value
            .take()
            .expect("next_value_seed called before next_key_seed");
        seed.deserialize(value)
    }

    fn size_hint(&self) -> Option<usize> {
        Some(self.iter.len())
    }
}