Skip to main content

inlean_runtime/
codec.rs

1//! Conversions between Rust values and Lean objects, chosen by the Lean type.
2//!
3//! Several Lean types share one Rust type: `Array α` and `List α` are both `Vec<T>`, and
4//! `ByteArray` and `Array UInt8` are both `Vec<u8>`. A conversion therefore cannot be found
5//! from the Rust type alone. Generated code names it instead, as a type that implements
6//! [`Codec`] and mirrors the Lean type: `Array<List<Plain<Nat>>>` converts a
7//! `Vec<Vec<Nat>>` to and from a Lean `Array (List Nat)`.
8
9use crate::object::{self as o, box_, dec, inc, Obj};
10use crate::types::{FromLean, ToLean};
11use std::marker::PhantomData;
12
13/// A conversion between a Rust type and the Lean type the implementor stands for.
14pub trait Codec {
15    type Rust;
16
17    /// A new Lean object with the value, owned by the caller.
18    fn to_lean(value: &Self::Rust) -> Obj;
19
20    /// Reads the value out of `object` and gives up one reference to it.
21    ///
22    /// # Safety
23    /// `object` must be a value of the Lean type this codec stands for, produced by this
24    /// runtime, and the caller must own a reference to it.
25    unsafe fn from_lean(object: Obj) -> Self::Rust;
26}
27
28/// A type whose Lean counterpart follows from the Rust type: the scalars, `Nat`, `Int`,
29/// `String`.
30pub struct Plain<T>(PhantomData<T>);
31
32impl<T: ToLean + FromLean> Codec for Plain<T> {
33    type Rust = T;
34
35    fn to_lean(value: &T) -> Obj {
36        value.to_lean()
37    }
38
39    unsafe fn from_lean(object: Obj) -> T {
40        T::from_lean(object)
41    }
42}
43
44/// Lean's `Array α` as a `Vec`.
45pub struct Array<C>(PhantomData<C>);
46
47impl<C: Codec> Array<C> {
48    pub fn from_slice(items: &[C::Rust]) -> Obj {
49        crate::array::from_vec(items.iter().map(C::to_lean).collect())
50    }
51}
52
53impl<C: Codec> Codec for Array<C> {
54    type Rust = Vec<C::Rust>;
55
56    fn to_lean(value: &Vec<C::Rust>) -> Obj {
57        Self::from_slice(value)
58    }
59
60    unsafe fn from_lean(object: Obj) -> Vec<C::Rust> {
61        let items = crate::array::elements(object)
62            .iter()
63            .map(|&item| {
64                inc(item);
65                C::from_lean(item)
66            })
67            .collect();
68        dec(object);
69        items
70    }
71}
72
73/// Lean's `List α` as a `Vec`.
74pub struct List<C>(PhantomData<C>);
75
76impl<C: Codec> List<C> {
77    pub fn from_slice(items: &[C::Rust]) -> Obj {
78        let mut list = box_(0);
79        for item in items.iter().rev() {
80            // `List.cons head tail`.
81            unsafe {
82                let cell = o::alloc_ctor(1, 2, 0, 0);
83                o::ctor_set(cell, 0, C::to_lean(item));
84                o::ctor_set(cell, 1, list);
85                list = cell;
86            }
87        }
88        list
89    }
90}
91
92impl<C: Codec> Codec for List<C> {
93    type Rust = Vec<C::Rust>;
94
95    fn to_lean(value: &Vec<C::Rust>) -> Obj {
96        Self::from_slice(value)
97    }
98
99    unsafe fn from_lean(object: Obj) -> Vec<C::Rust> {
100        let mut items = Vec::new();
101        let mut rest = object;
102        while !o::is_scalar(rest) {
103            let head = o::ctor_get(rest, 0);
104            inc(head);
105            items.push(C::from_lean(head));
106            rest = o::ctor_get(rest, 1);
107        }
108        dec(object);
109        items
110    }
111}
112
113/// Lean's `Option α`.
114pub struct Option<C>(PhantomData<C>);
115
116impl<C: Codec> Codec for Option<C> {
117    type Rust = ::core::option::Option<C::Rust>;
118
119    fn to_lean(value: &Self::Rust) -> Obj {
120        match value {
121            None => box_(0),
122            Some(value) => unsafe {
123                let some = o::alloc_ctor(1, 1, 0, 0);
124                o::ctor_set(some, 0, C::to_lean(value));
125                some
126            },
127        }
128    }
129
130    unsafe fn from_lean(object: Obj) -> Self::Rust {
131        if o::is_scalar(object) {
132            return None;
133        }
134        let value = o::ctor_get(object, 0);
135        inc(value);
136        dec(object);
137        Some(C::from_lean(value))
138    }
139}
140
141/// Lean's `α × β` as a pair.
142pub struct Pair<A, B>(PhantomData<(A, B)>);
143
144impl<A: Codec, B: Codec> Codec for Pair<A, B> {
145    type Rust = (A::Rust, B::Rust);
146
147    fn to_lean(value: &Self::Rust) -> Obj {
148        unsafe {
149            let pair = o::alloc_ctor(0, 2, 0, 0);
150            o::ctor_set(pair, 0, A::to_lean(&value.0));
151            o::ctor_set(pair, 1, B::to_lean(&value.1));
152            pair
153        }
154    }
155
156    unsafe fn from_lean(object: Obj) -> Self::Rust {
157        let (first, second) = (o::ctor_get(object, 0), o::ctor_get(object, 1));
158        inc(first);
159        inc(second);
160        dec(object);
161        (A::from_lean(first), B::from_lean(second))
162    }
163}
164
165/// A value that the Rust type keeps in a `Box`, as recursive types must.
166pub struct Boxed<C>(PhantomData<C>);
167
168impl<C: Codec> Codec for Boxed<C> {
169    type Rust = Box<C::Rust>;
170
171    fn to_lean(value: &Self::Rust) -> Obj {
172        C::to_lean(value)
173    }
174
175    unsafe fn from_lean(object: Obj) -> Self::Rust {
176        Box::new(C::from_lean(object))
177    }
178}
179
180/// Lean's `ByteArray` as a `Vec<u8>`.
181pub struct ByteArray;
182
183impl Codec for ByteArray {
184    type Rust = Vec<u8>;
185
186    fn to_lean(value: &Vec<u8>) -> Obj {
187        crate::sarray::byte_array_from_vec(value.clone())
188    }
189
190    unsafe fn from_lean(object: Obj) -> Vec<u8> {
191        crate::sarray::byte_array_into_vec(object)
192    }
193}
194
195/// Lean's `FloatArray` as a `Vec<f64>`.
196pub struct FloatArray;
197
198impl Codec for FloatArray {
199    type Rust = Vec<f64>;
200
201    fn to_lean(value: &Vec<f64>) -> Obj {
202        crate::sarray::float_array_from_vec(value.clone())
203    }
204
205    unsafe fn from_lean(object: Obj) -> Vec<f64> {
206        crate::sarray::float_array_into_vec(object)
207    }
208}
209
210impl<A: Codec, B: Codec> Pair<A, B> {
211    /// The Lean pair of two values held separately, as the entries of a Rust map are.
212    pub fn from_refs(first: &A::Rust, second: &B::Rust) -> Obj {
213        unsafe {
214            let pair = o::alloc_ctor(0, 2, 0, 0);
215            o::ctor_set(pair, 0, A::to_lean(first));
216            o::ctor_set(pair, 1, B::to_lean(second));
217            pair
218        }
219    }
220}
221
222/// Lean's `Except ε α` as a `Result`. Lean names the error type first, Rust the value type.
223pub struct Except<E, A>(PhantomData<(E, A)>);
224
225impl<E: Codec, A: Codec> Codec for Except<E, A> {
226    type Rust = Result<A::Rust, E::Rust>;
227
228    fn to_lean(value: &Self::Rust) -> Obj {
229        // `Except.error` is constructor 0 and `Except.ok` constructor 1, each with one field.
230        let (tag, field) = match value {
231            Err(error) => (0, E::to_lean(error)),
232            Ok(value) => (1, A::to_lean(value)),
233        };
234        unsafe {
235            let object = o::alloc_ctor(tag, 1, 0, 0);
236            o::ctor_set(object, 0, field);
237            object
238        }
239    }
240
241    unsafe fn from_lean(object: Obj) -> Self::Rust {
242        let field = o::ctor_get(object, 0);
243        inc(field);
244        let ok = o::obj_tag(object) == 1;
245        dec(object);
246        if ok {
247            Ok(A::from_lean(field))
248        } else {
249            Err(E::from_lean(field))
250        }
251    }
252}