inlean-runtime 0.1.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Conversions between Rust values and Lean objects, chosen by the Lean type.
//!
//! Several Lean types share one Rust type: `Array α` and `List α` are both `Vec<T>`, and
//! `ByteArray` and `Array UInt8` are both `Vec<u8>`. A conversion therefore cannot be found
//! from the Rust type alone. Generated code names it instead, as a type that implements
//! [`Codec`] and mirrors the Lean type: `Array<List<Plain<Nat>>>` converts a
//! `Vec<Vec<Nat>>` to and from a Lean `Array (List Nat)`.

use crate::object::{self as o, box_, dec, inc, Obj};
use crate::types::{FromLean, ToLean};
use std::marker::PhantomData;

/// A conversion between a Rust type and the Lean type the implementor stands for.
pub trait Codec {
    type Rust;

    /// A new Lean object with the value, owned by the caller.
    fn to_lean(value: &Self::Rust) -> Obj;

    /// Reads the value out of `object` and gives up one reference to it.
    ///
    /// # Safety
    /// `object` must be a value of the Lean type this codec stands for, produced by this
    /// runtime, and the caller must own a reference to it.
    unsafe fn from_lean(object: Obj) -> Self::Rust;
}

/// A type whose Lean counterpart follows from the Rust type: the scalars, `Nat`, `Int`,
/// `String`.
pub struct Plain<T>(PhantomData<T>);

impl<T: ToLean + FromLean> Codec for Plain<T> {
    type Rust = T;

    fn to_lean(value: &T) -> Obj {
        value.to_lean()
    }

    unsafe fn from_lean(object: Obj) -> T {
        T::from_lean(object)
    }
}

/// Lean's `Array α` as a `Vec`.
pub struct Array<C>(PhantomData<C>);

impl<C: Codec> Array<C> {
    pub fn from_slice(items: &[C::Rust]) -> Obj {
        crate::array::from_vec(items.iter().map(C::to_lean).collect())
    }
}

impl<C: Codec> Codec for Array<C> {
    type Rust = Vec<C::Rust>;

    fn to_lean(value: &Vec<C::Rust>) -> Obj {
        Self::from_slice(value)
    }

    unsafe fn from_lean(object: Obj) -> Vec<C::Rust> {
        let items = crate::array::elements(object)
            .iter()
            .map(|&item| {
                inc(item);
                C::from_lean(item)
            })
            .collect();
        dec(object);
        items
    }
}

/// Lean's `List α` as a `Vec`.
pub struct List<C>(PhantomData<C>);

impl<C: Codec> List<C> {
    pub fn from_slice(items: &[C::Rust]) -> Obj {
        let mut list = box_(0);
        for item in items.iter().rev() {
            // `List.cons head tail`.
            unsafe {
                let cell = o::alloc_ctor(1, 2, 0, 0);
                o::ctor_set(cell, 0, C::to_lean(item));
                o::ctor_set(cell, 1, list);
                list = cell;
            }
        }
        list
    }
}

impl<C: Codec> Codec for List<C> {
    type Rust = Vec<C::Rust>;

    fn to_lean(value: &Vec<C::Rust>) -> Obj {
        Self::from_slice(value)
    }

    unsafe fn from_lean(object: Obj) -> Vec<C::Rust> {
        let mut items = Vec::new();
        let mut rest = object;
        while !o::is_scalar(rest) {
            let head = o::ctor_get(rest, 0);
            inc(head);
            items.push(C::from_lean(head));
            rest = o::ctor_get(rest, 1);
        }
        dec(object);
        items
    }
}

/// Lean's `Option α`.
pub struct Option<C>(PhantomData<C>);

impl<C: Codec> Codec for Option<C> {
    type Rust = ::core::option::Option<C::Rust>;

    fn to_lean(value: &Self::Rust) -> Obj {
        match value {
            None => box_(0),
            Some(value) => unsafe {
                let some = o::alloc_ctor(1, 1, 0, 0);
                o::ctor_set(some, 0, C::to_lean(value));
                some
            },
        }
    }

    unsafe fn from_lean(object: Obj) -> Self::Rust {
        if o::is_scalar(object) {
            return None;
        }
        let value = o::ctor_get(object, 0);
        inc(value);
        dec(object);
        Some(C::from_lean(value))
    }
}

/// Lean's `α × β` as a pair.
pub struct Pair<A, B>(PhantomData<(A, B)>);

impl<A: Codec, B: Codec> Codec for Pair<A, B> {
    type Rust = (A::Rust, B::Rust);

    fn to_lean(value: &Self::Rust) -> Obj {
        unsafe {
            let pair = o::alloc_ctor(0, 2, 0, 0);
            o::ctor_set(pair, 0, A::to_lean(&value.0));
            o::ctor_set(pair, 1, B::to_lean(&value.1));
            pair
        }
    }

    unsafe fn from_lean(object: Obj) -> Self::Rust {
        let (first, second) = (o::ctor_get(object, 0), o::ctor_get(object, 1));
        inc(first);
        inc(second);
        dec(object);
        (A::from_lean(first), B::from_lean(second))
    }
}

/// A value that the Rust type keeps in a `Box`, as recursive types must.
pub struct Boxed<C>(PhantomData<C>);

impl<C: Codec> Codec for Boxed<C> {
    type Rust = Box<C::Rust>;

    fn to_lean(value: &Self::Rust) -> Obj {
        C::to_lean(value)
    }

    unsafe fn from_lean(object: Obj) -> Self::Rust {
        Box::new(C::from_lean(object))
    }
}

/// Lean's `ByteArray` as a `Vec<u8>`.
pub struct ByteArray;

impl Codec for ByteArray {
    type Rust = Vec<u8>;

    fn to_lean(value: &Vec<u8>) -> Obj {
        crate::sarray::byte_array_from_vec(value.clone())
    }

    unsafe fn from_lean(object: Obj) -> Vec<u8> {
        crate::sarray::byte_array_into_vec(object)
    }
}

/// Lean's `FloatArray` as a `Vec<f64>`.
pub struct FloatArray;

impl Codec for FloatArray {
    type Rust = Vec<f64>;

    fn to_lean(value: &Vec<f64>) -> Obj {
        crate::sarray::float_array_from_vec(value.clone())
    }

    unsafe fn from_lean(object: Obj) -> Vec<f64> {
        crate::sarray::float_array_into_vec(object)
    }
}

impl<A: Codec, B: Codec> Pair<A, B> {
    /// The Lean pair of two values held separately, as the entries of a Rust map are.
    pub fn from_refs(first: &A::Rust, second: &B::Rust) -> Obj {
        unsafe {
            let pair = o::alloc_ctor(0, 2, 0, 0);
            o::ctor_set(pair, 0, A::to_lean(first));
            o::ctor_set(pair, 1, B::to_lean(second));
            pair
        }
    }
}

/// Lean's `Except ε α` as a `Result`. Lean names the error type first, Rust the value type.
pub struct Except<E, A>(PhantomData<(E, A)>);

impl<E: Codec, A: Codec> Codec for Except<E, A> {
    type Rust = Result<A::Rust, E::Rust>;

    fn to_lean(value: &Self::Rust) -> Obj {
        // `Except.error` is constructor 0 and `Except.ok` constructor 1, each with one field.
        let (tag, field) = match value {
            Err(error) => (0, E::to_lean(error)),
            Ok(value) => (1, A::to_lean(value)),
        };
        unsafe {
            let object = o::alloc_ctor(tag, 1, 0, 0);
            o::ctor_set(object, 0, field);
            object
        }
    }

    unsafe fn from_lean(object: Obj) -> Self::Rust {
        let field = o::ctor_get(object, 0);
        inc(field);
        let ok = o::obj_tag(object) == 1;
        dec(object);
        if ok {
            Ok(A::from_lean(field))
        } else {
            Err(E::from_lean(field))
        }
    }
}