Skip to main content

leanfran_runtime/
handle.rs

1//! Handles of Lean values: [`Lean<L>`] keeps a value as the Lean object, without converting it
2//! to a Rust value.
3//!
4//! The type argument `L` names the Lean type by the Rust type of the public functions
5//! (`u64`, `String`, `Option<T>`, `Result<T, E>`, `(A, B)`, generated structs and enums); a
6//! Lean `List α` is [`List<T>`] and an `Array α` is [`Array<T>`], since both are `Vec<T>` in
7//! Rust. [`LeanRepr::Value`] is the Rust value of `L`.
8//!
9//! The object of a handle is shared between threads: creating the handle marks every object
10//! reachable from it with [`lean_mark_mt`], so that its reference counts are updated atomically.
11//! Lean functions that receive such an object build new objects instead of updating it in place.
12
13use crate::marshal::*;
14use crate::object::*;
15use core::fmt;
16use core::marker::PhantomData;
17
18/// A Rust type that names a Lean type whose values a [`Lean`] handle can hold.
19///
20/// # Safety
21///
22/// `to_obj` must return an owned object of the Lean type and `from_obj` must read one without
23/// taking ownership; the type must be data (no closures, thunks, tasks or references), since
24/// handles of it are shared between threads. Generated modules implement it for their types.
25pub unsafe trait LeanRepr {
26    /// The Rust value of the Lean type.
27    type Value;
28
29    /// The owned boxed object of `value`.
30    ///
31    /// # Safety
32    ///
33    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
34    #[doc(hidden)]
35    unsafe fn to_obj(value: Self::Value) -> Obj;
36
37    /// The Rust value of the borrowed boxed object `o`.
38    ///
39    /// # Safety
40    ///
41    /// `o` must be a valid Lean value of the type `Self` names.
42    #[doc(hidden)]
43    unsafe fn from_obj(o: Obj) -> Self::Value;
44}
45
46/// The Lean type `List α`; its Rust value is `Vec<T::Value>`.
47pub struct List<T>(PhantomData<fn() -> T>);
48
49/// The Lean type `Array α`; its Rust value is `Vec<T::Value>`.
50pub struct Array<T>(PhantomData<fn() -> T>);
51
52/// The Lean type `Fin N`; its Rust value is `usize`.
53pub struct Fin<const N: u64>;
54
55/// A Lean value of the type named by `L`, kept as the Lean object.
56///
57/// `Lean::new` converts a Rust value once and `get` converts it back. The functions of the
58/// `lean` module of a generated module take handles and return them without converting.
59/// Cloning a handle adds a reference to the same object.
60pub struct Lean<L: LeanRepr> {
61    obj: Obj,
62    ty: PhantomData<fn() -> L>,
63}
64
65// SAFETY: the object and everything it reaches is shared between threads (`lean_mark_mt`) or
66// persistent, so its reference counts are atomic or never written, and such objects are never
67// updated in place. The types `L` are data: no closures, thunks, tasks or references.
68unsafe impl<L: LeanRepr> Send for Lean<L> {}
69unsafe impl<L: LeanRepr> Sync for Lean<L> {}
70
71impl<L: LeanRepr> Lean<L> {
72    /// The handle of the Lean value of `value`.
73    pub fn new(value: L::Value) -> Self {
74        unsafe { Self::from_owned(L::to_obj(value)) }
75    }
76
77    /// The Rust value of the handle.
78    pub fn get(&self) -> L::Value {
79        unsafe { L::from_obj(self.obj) }
80    }
81
82    /// The handle that owns `obj`.
83    ///
84    /// # Safety
85    ///
86    /// `obj` must be an owned Lean value of the type `L` names, and no other thread may reach
87    /// the objects under it that are still owned by one thread.
88    #[doc(hidden)]
89    pub unsafe fn from_owned(obj: Obj) -> Self {
90        lean_mark_mt(obj);
91        Lean {
92            obj,
93            ty: PhantomData,
94        }
95    }
96
97    /// The object of the handle, borrowed.
98    #[doc(hidden)]
99    pub fn as_obj(&self) -> Obj {
100        self.obj
101    }
102}
103
104impl<L: LeanRepr> Clone for Lean<L> {
105    fn clone(&self) -> Self {
106        unsafe { lean_inc(self.obj) };
107        Lean {
108            obj: self.obj,
109            ty: PhantomData,
110        }
111    }
112}
113
114impl<L: LeanRepr> Drop for Lean<L> {
115    fn drop(&mut self) {
116        unsafe { lean_dec(self.obj) };
117    }
118}
119
120impl<L: LeanRepr> fmt::Debug for Lean<L>
121where
122    L::Value: fmt::Debug,
123{
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.debug_tuple("Lean").field(&self.get()).finish()
126    }
127}
128
129/// An argument of a function of the `lean` module of a generated module: the Rust value of
130/// `L` (converted for the call), a `&Lean<L>` or a `Lean<L>`.
131///
132/// # Safety
133///
134/// `into_obj` must return an owned object of the Lean type `L` names.
135pub unsafe trait IntoLean<L: LeanRepr> {
136    /// The owned boxed object of the argument.
137    ///
138    /// # Safety
139    ///
140    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
141    #[doc(hidden)]
142    unsafe fn into_obj(self) -> Obj;
143}
144
145unsafe impl<L: LeanRepr> IntoLean<L> for Lean<L> {
146    unsafe fn into_obj(self) -> Obj {
147        let obj = self.obj;
148        core::mem::forget(self);
149        obj
150    }
151}
152
153unsafe impl<L: LeanRepr> IntoLean<L> for &Lean<L> {
154    unsafe fn into_obj(self) -> Obj {
155        lean_inc(self.obj);
156        self.obj
157    }
158}
159
160macro_rules! prim_repr {
161    ($($t:ty),*) => {$(
162        unsafe impl LeanRepr for $t {
163            type Value = $t;
164            unsafe fn to_obj(value: $t) -> Obj {
165                ToLean::to_lean(value)
166            }
167            unsafe fn from_obj(o: Obj) -> $t {
168                <$t as FromLean>::from_lean(o)
169            }
170        }
171        unsafe impl IntoLean<$t> for $t {
172            unsafe fn into_obj(self) -> Obj {
173                ToLean::to_lean(self)
174            }
175        }
176    )*};
177}
178
179prim_repr!(
180    Nat,
181    Int,
182    bool,
183    char,
184    String,
185    u8,
186    u16,
187    u32,
188    u64,
189    usize,
190    i8,
191    i16,
192    i32,
193    i64,
194    isize,
195    f64,
196    f32,
197    ()
198);
199
200unsafe impl IntoLean<String> for &str {
201    unsafe fn into_obj(self) -> Obj {
202        ToLean::to_lean(self)
203    }
204}
205
206unsafe impl IntoLean<String> for &String {
207    unsafe fn into_obj(self) -> Obj {
208        ToLean::to_lean(self.as_str())
209    }
210}
211
212unsafe impl<T: LeanRepr> LeanRepr for List<T> {
213    type Value = Vec<T::Value>;
214    unsafe fn to_obj(value: Self::Value) -> Obj {
215        list_to_lean(value, |v| T::to_obj(v))
216    }
217    unsafe fn from_obj(o: Obj) -> Self::Value {
218        list_from_lean(o, |v| T::from_obj(v))
219    }
220}
221
222unsafe impl<T: LeanRepr> IntoLean<List<T>> for Vec<T::Value> {
223    unsafe fn into_obj(self) -> Obj {
224        List::<T>::to_obj(self)
225    }
226}
227
228unsafe impl<T: LeanRepr> LeanRepr for Array<T> {
229    type Value = Vec<T::Value>;
230    unsafe fn to_obj(value: Self::Value) -> Obj {
231        array_to_lean(value, |v| T::to_obj(v))
232    }
233    unsafe fn from_obj(o: Obj) -> Self::Value {
234        array_from_lean(o, |v| T::from_obj(v))
235    }
236}
237
238unsafe impl<T: LeanRepr> IntoLean<Array<T>> for Vec<T::Value> {
239    unsafe fn into_obj(self) -> Obj {
240        Array::<T>::to_obj(self)
241    }
242}
243
244unsafe impl<T: LeanRepr> LeanRepr for Option<T> {
245    type Value = Option<T::Value>;
246    unsafe fn to_obj(value: Self::Value) -> Obj {
247        option_to_lean(value, |v| T::to_obj(v))
248    }
249    unsafe fn from_obj(o: Obj) -> Self::Value {
250        option_from_lean(o, |v| T::from_obj(v))
251    }
252}
253
254unsafe impl<T: LeanRepr> IntoLean<Option<T>> for Option<T::Value> {
255    unsafe fn into_obj(self) -> Obj {
256        Option::<T>::to_obj(self)
257    }
258}
259
260unsafe impl<T: LeanRepr, E: LeanRepr> LeanRepr for Result<T, E> {
261    type Value = Result<T::Value, E::Value>;
262    unsafe fn to_obj(value: Self::Value) -> Obj {
263        except_to_lean(value, |v| E::to_obj(v), |v| T::to_obj(v))
264    }
265    unsafe fn from_obj(o: Obj) -> Self::Value {
266        except_from_lean(o, |v| E::from_obj(v), |v| T::from_obj(v))
267    }
268}
269
270unsafe impl<T: LeanRepr, E: LeanRepr> IntoLean<Result<T, E>> for Result<T::Value, E::Value> {
271    unsafe fn into_obj(self) -> Obj {
272        Result::<T, E>::to_obj(self)
273    }
274}
275
276unsafe impl<A: LeanRepr, B: LeanRepr> LeanRepr for (A, B) {
277    type Value = (A::Value, B::Value);
278    unsafe fn to_obj(value: Self::Value) -> Obj {
279        prod_to_lean(value, |v| A::to_obj(v), |v| B::to_obj(v))
280    }
281    unsafe fn from_obj(o: Obj) -> Self::Value {
282        prod_from_lean(o, |v| A::from_obj(v), |v| B::from_obj(v))
283    }
284}
285
286unsafe impl<A: LeanRepr, B: LeanRepr> IntoLean<(A, B)> for (A::Value, B::Value) {
287    unsafe fn into_obj(self) -> Obj {
288        <(A, B)>::to_obj(self)
289    }
290}
291
292unsafe impl<const N: u64> LeanRepr for Fin<N> {
293    type Value = usize;
294    unsafe fn to_obj(value: usize) -> Obj {
295        fin_to_lean(value, N as usize)
296    }
297    unsafe fn from_obj(o: Obj) -> usize {
298        fin_from_lean(o)
299    }
300}
301
302unsafe impl<const N: u64> IntoLean<Fin<N>> for usize {
303    unsafe fn into_obj(self) -> Obj {
304        Fin::<N>::to_obj(self)
305    }
306}