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//!
13//! [`Local<L>`] is the handle that stays on the thread that made it: its objects keep the
14//! reference counts of one thread, so a Lean function that receives the only reference to an
15//! object updates it in place.
16
17use crate::marshal::*;
18use crate::object::*;
19use core::fmt;
20use core::marker::PhantomData;
21
22/// A Rust type that names a Lean type whose values a [`Lean`] handle can hold.
23///
24/// # Safety
25///
26/// `to_obj` must return an owned object of the Lean type and `from_obj` must read one without
27/// taking ownership; the type must be data (no closures, thunks, tasks or references), since
28/// handles of it are shared between threads. Generated modules implement it for their types.
29pub unsafe trait LeanRepr {
30    /// The Rust value of the Lean type.
31    type Value;
32
33    /// The owned boxed object of `value`.
34    ///
35    /// # Safety
36    ///
37    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
38    #[doc(hidden)]
39    unsafe fn to_obj(value: Self::Value) -> Obj;
40
41    /// The Rust value of the borrowed boxed object `o`.
42    ///
43    /// # Safety
44    ///
45    /// `o` must be a valid Lean value of the type `Self` names.
46    #[doc(hidden)]
47    unsafe fn from_obj(o: Obj) -> Self::Value;
48}
49
50/// The Lean type `List α`; its Rust value is `Vec<T::Value>`.
51pub struct List<T>(PhantomData<fn() -> T>);
52
53/// The Lean type `Array α`; its Rust value is `Vec<T::Value>`.
54pub struct Array<T>(PhantomData<fn() -> T>);
55
56/// The Lean type `Fin N`; its Rust value is `usize`.
57pub struct Fin<const N: u64>;
58
59/// A Lean value of the type named by `L`, kept as the Lean object.
60///
61/// `Lean::new` converts a Rust value once and `get` converts it back. The functions of the
62/// `lean` module of a generated module take handles and return them without converting.
63/// Cloning a handle adds a reference to the same object.
64pub struct Lean<L: LeanRepr> {
65    obj: Obj,
66    ty: PhantomData<fn() -> L>,
67}
68
69// SAFETY: the object and everything it reaches is shared between threads (`lean_mark_mt`) or
70// persistent, so its reference counts are atomic or never written, and such objects are never
71// updated in place. The types `L` are data: no closures, thunks, tasks or references.
72unsafe impl<L: LeanRepr> Send for Lean<L> {}
73unsafe impl<L: LeanRepr> Sync for Lean<L> {}
74
75impl<L: LeanRepr> Lean<L> {
76    /// The handle of the Lean value of `value`.
77    pub fn new(value: L::Value) -> Self {
78        unsafe { Self::from_owned(L::to_obj(value)) }
79    }
80
81    /// The Rust value of the handle.
82    pub fn get(&self) -> L::Value {
83        unsafe { L::from_obj(self.obj) }
84    }
85
86    /// The handle that owns `obj`.
87    ///
88    /// # Safety
89    ///
90    /// `obj` must be an owned Lean value of the type `L` names, and no other thread may reach
91    /// the objects under it that are still owned by one thread.
92    #[doc(hidden)]
93    pub unsafe fn from_owned(obj: Obj) -> Self {
94        lean_mark_mt(obj);
95        Lean {
96            obj,
97            ty: PhantomData,
98        }
99    }
100
101    /// The object of the handle, borrowed.
102    #[doc(hidden)]
103    pub fn as_obj(&self) -> Obj {
104        self.obj
105    }
106}
107
108impl<L: LeanRepr> Lean<L> {
109    /// A handle of the same object for this thread. The object stays shared between threads,
110    /// so Lean functions do not update it in place.
111    pub fn to_local(&self) -> Local<L> {
112        unsafe { lean_inc(self.obj) };
113        Local {
114            obj: self.obj,
115            ty: PhantomData,
116            thread: PhantomData,
117        }
118    }
119}
120
121impl<L: LeanRepr> Clone for Lean<L> {
122    fn clone(&self) -> Self {
123        unsafe { lean_inc(self.obj) };
124        Lean {
125            obj: self.obj,
126            ty: PhantomData,
127        }
128    }
129}
130
131impl<L: LeanRepr> Drop for Lean<L> {
132    fn drop(&mut self) {
133        unsafe { lean_dec(self.obj) };
134    }
135}
136
137impl<L: LeanRepr> fmt::Debug for Lean<L>
138where
139    L::Value: fmt::Debug,
140{
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.debug_tuple("Lean").field(&self.get()).finish()
143    }
144}
145
146/// A Lean value of the type named by `L`, kept as the Lean object on the thread that made it.
147///
148/// The functions of the `local` module of a generated module return this handle. Its objects
149/// keep the reference counts of one thread: passing the only handle of a value by value lets
150/// the Lean function update the value in place, where a [`Lean`] handle makes it build new
151/// objects. A `Local` cannot be sent to or shared with another thread; [`Local::share`] turns
152/// it into a [`Lean`] that can.
153///
154/// ```compile_fail,E0277
155/// let local = leanfran_runtime::Local::<u8>::new(1);
156/// std::thread::spawn(move || drop(local));
157/// ```
158///
159/// ```compile_fail,E0277
160/// let local = leanfran_runtime::Local::<u8>::new(1);
161/// std::thread::scope(|s| {
162///     s.spawn(|| local.get());
163/// });
164/// ```
165pub struct Local<L: LeanRepr> {
166    obj: Obj,
167    ty: PhantomData<fn() -> L>,
168    thread: PhantomData<*mut ()>,
169}
170
171impl<L: LeanRepr> Local<L> {
172    /// The handle of the Lean value of `value`.
173    pub fn new(value: L::Value) -> Self {
174        unsafe { Self::from_owned(L::to_obj(value)) }
175    }
176
177    /// The Rust value of the handle.
178    pub fn get(&self) -> L::Value {
179        unsafe { L::from_obj(self.obj) }
180    }
181
182    /// The handle that can be sent to and shared with other threads. It marks the objects of
183    /// the value as shared, at a cost in proportion to the objects not yet shared.
184    pub fn share(self) -> Lean<L> {
185        let obj = self.obj;
186        core::mem::forget(self);
187        unsafe { Lean::from_owned(obj) }
188    }
189
190    /// The handle that owns `obj`.
191    ///
192    /// # Safety
193    ///
194    /// `obj` must be an owned Lean value of the type `L` names, made on this thread.
195    #[doc(hidden)]
196    pub unsafe fn from_owned(obj: Obj) -> Self {
197        Local {
198            obj,
199            ty: PhantomData,
200            thread: PhantomData,
201        }
202    }
203
204    /// The object of the handle, borrowed.
205    #[doc(hidden)]
206    pub fn as_obj(&self) -> Obj {
207        self.obj
208    }
209}
210
211impl<L: LeanRepr> Clone for Local<L> {
212    fn clone(&self) -> Self {
213        unsafe { lean_inc(self.obj) };
214        Local {
215            obj: self.obj,
216            ty: PhantomData,
217            thread: PhantomData,
218        }
219    }
220}
221
222impl<L: LeanRepr> Drop for Local<L> {
223    fn drop(&mut self) {
224        unsafe { lean_dec(self.obj) };
225    }
226}
227
228impl<L: LeanRepr> fmt::Debug for Local<L>
229where
230    L::Value: fmt::Debug,
231{
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.debug_tuple("Local").field(&self.get()).finish()
234    }
235}
236
237/// An argument of a function of the `lean` or `local` module of a generated module: the Rust
238/// value of `L` (converted for the call), a `&Lean<L>`, a `Lean<L>`, a `&Local<L>` or a
239/// `Local<L>`.
240///
241/// # Safety
242///
243/// `into_obj` must return an owned object of the Lean type `L` names.
244pub unsafe trait IntoLean<L: LeanRepr> {
245    /// The owned boxed object of the argument.
246    ///
247    /// # Safety
248    ///
249    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
250    #[doc(hidden)]
251    unsafe fn into_obj(self) -> Obj;
252}
253
254unsafe impl<L: LeanRepr> IntoLean<L> for Lean<L> {
255    unsafe fn into_obj(self) -> Obj {
256        let obj = self.obj;
257        core::mem::forget(self);
258        obj
259    }
260}
261
262unsafe impl<L: LeanRepr> IntoLean<L> for &Lean<L> {
263    unsafe fn into_obj(self) -> Obj {
264        lean_inc(self.obj);
265        self.obj
266    }
267}
268
269unsafe impl<L: LeanRepr> IntoLean<L> for Local<L> {
270    unsafe fn into_obj(self) -> Obj {
271        let obj = self.obj;
272        core::mem::forget(self);
273        obj
274    }
275}
276
277unsafe impl<L: LeanRepr> IntoLean<L> for &Local<L> {
278    unsafe fn into_obj(self) -> Obj {
279        lean_inc(self.obj);
280        self.obj
281    }
282}
283
284macro_rules! prim_repr {
285    ($($t:ty),*) => {$(
286        unsafe impl LeanRepr for $t {
287            type Value = $t;
288            unsafe fn to_obj(value: $t) -> Obj {
289                ToLean::to_lean(value)
290            }
291            unsafe fn from_obj(o: Obj) -> $t {
292                <$t as FromLean>::from_lean(o)
293            }
294        }
295        unsafe impl IntoLean<$t> for $t {
296            unsafe fn into_obj(self) -> Obj {
297                ToLean::to_lean(self)
298            }
299        }
300    )*};
301}
302
303prim_repr!(
304    Nat,
305    Int,
306    bool,
307    char,
308    String,
309    u8,
310    u16,
311    u32,
312    u64,
313    usize,
314    i8,
315    i16,
316    i32,
317    i64,
318    isize,
319    f64,
320    f32,
321    ()
322);
323
324unsafe impl IntoLean<String> for &str {
325    unsafe fn into_obj(self) -> Obj {
326        ToLean::to_lean(self)
327    }
328}
329
330unsafe impl IntoLean<String> for &String {
331    unsafe fn into_obj(self) -> Obj {
332        ToLean::to_lean(self.as_str())
333    }
334}
335
336unsafe impl<T: LeanRepr> LeanRepr for List<T> {
337    type Value = Vec<T::Value>;
338    unsafe fn to_obj(value: Self::Value) -> Obj {
339        list_to_lean(value, |v| T::to_obj(v))
340    }
341    unsafe fn from_obj(o: Obj) -> Self::Value {
342        list_from_lean(o, |v| T::from_obj(v))
343    }
344}
345
346unsafe impl<T: LeanRepr> IntoLean<List<T>> for Vec<T::Value> {
347    unsafe fn into_obj(self) -> Obj {
348        List::<T>::to_obj(self)
349    }
350}
351
352unsafe impl<T: LeanRepr> LeanRepr for Array<T> {
353    type Value = Vec<T::Value>;
354    unsafe fn to_obj(value: Self::Value) -> Obj {
355        array_to_lean(value, |v| T::to_obj(v))
356    }
357    unsafe fn from_obj(o: Obj) -> Self::Value {
358        array_from_lean(o, |v| T::from_obj(v))
359    }
360}
361
362unsafe impl<T: LeanRepr> IntoLean<Array<T>> for Vec<T::Value> {
363    unsafe fn into_obj(self) -> Obj {
364        Array::<T>::to_obj(self)
365    }
366}
367
368unsafe impl<T: LeanRepr> LeanRepr for Option<T> {
369    type Value = Option<T::Value>;
370    unsafe fn to_obj(value: Self::Value) -> Obj {
371        option_to_lean(value, |v| T::to_obj(v))
372    }
373    unsafe fn from_obj(o: Obj) -> Self::Value {
374        option_from_lean(o, |v| T::from_obj(v))
375    }
376}
377
378unsafe impl<T: LeanRepr> IntoLean<Option<T>> for Option<T::Value> {
379    unsafe fn into_obj(self) -> Obj {
380        Option::<T>::to_obj(self)
381    }
382}
383
384unsafe impl<T: LeanRepr, E: LeanRepr> LeanRepr for Result<T, E> {
385    type Value = Result<T::Value, E::Value>;
386    unsafe fn to_obj(value: Self::Value) -> Obj {
387        except_to_lean(value, |v| E::to_obj(v), |v| T::to_obj(v))
388    }
389    unsafe fn from_obj(o: Obj) -> Self::Value {
390        except_from_lean(o, |v| E::from_obj(v), |v| T::from_obj(v))
391    }
392}
393
394unsafe impl<T: LeanRepr, E: LeanRepr> IntoLean<Result<T, E>> for Result<T::Value, E::Value> {
395    unsafe fn into_obj(self) -> Obj {
396        Result::<T, E>::to_obj(self)
397    }
398}
399
400unsafe impl<A: LeanRepr, B: LeanRepr> LeanRepr for (A, B) {
401    type Value = (A::Value, B::Value);
402    unsafe fn to_obj(value: Self::Value) -> Obj {
403        prod_to_lean(value, |v| A::to_obj(v), |v| B::to_obj(v))
404    }
405    unsafe fn from_obj(o: Obj) -> Self::Value {
406        prod_from_lean(o, |v| A::from_obj(v), |v| B::from_obj(v))
407    }
408}
409
410unsafe impl<A: LeanRepr, B: LeanRepr> IntoLean<(A, B)> for (A::Value, B::Value) {
411    unsafe fn into_obj(self) -> Obj {
412        <(A, B)>::to_obj(self)
413    }
414}
415
416unsafe impl<const N: u64> LeanRepr for Fin<N> {
417    type Value = usize;
418    unsafe fn to_obj(value: usize) -> Obj {
419        fin_to_lean(value, N as usize)
420    }
421    unsafe fn from_obj(o: Obj) -> usize {
422        fin_from_lean(o)
423    }
424}
425
426unsafe impl<const N: u64> IntoLean<Fin<N>> for usize {
427    unsafe fn into_obj(self) -> Obj {
428        Fin::<N>::to_obj(self)
429    }
430}