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::cell::Cell;
20use core::fmt;
21use core::marker::PhantomData;
22
23/// A Rust type that names a Lean type whose values a [`Lean`] handle can hold.
24///
25/// # Safety
26///
27/// `to_obj` must return an owned object of the Lean type that nothing else refers to, and
28/// `from_obj` must read one without taking ownership; the type must be data (no closures, thunks, tasks or references), since
29/// handles of it are shared between threads. Generated modules implement it for their types.
30pub unsafe trait LeanRepr {
31    /// The Rust value of the Lean type.
32    type Value;
33
34    /// The owned boxed object of `value`.
35    ///
36    /// # Safety
37    ///
38    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
39    #[doc(hidden)]
40    unsafe fn to_obj(value: Self::Value) -> Obj;
41
42    /// The Rust value of the borrowed boxed object `o`.
43    ///
44    /// # Safety
45    ///
46    /// `o` must be a valid Lean value of the type `Self` names.
47    #[doc(hidden)]
48    unsafe fn from_obj(o: Obj) -> Self::Value;
49}
50
51/// The Lean type `List α`; its Rust value is `Vec<T::Value>`.
52pub struct List<T>(PhantomData<fn() -> T>);
53
54/// The Lean type `Array α`; its Rust value is `Vec<T::Value>`.
55pub struct Array<T>(PhantomData<fn() -> T>);
56
57/// The Lean type `Fin N`; its Rust value is `usize`.
58pub struct Fin<const N: u64>;
59
60/// A Lean value of the type named by `L`, kept as the Lean object.
61///
62/// `Lean::new` converts a Rust value once and `get` converts it back. The functions of the
63/// `lean` module of a generated module take handles and return them without converting.
64/// Cloning a handle adds a reference to the same object.
65pub struct Lean<L: LeanRepr> {
66    obj: Obj,
67    ty: PhantomData<fn() -> L>,
68}
69
70// SAFETY: the object and everything it reaches is shared between threads (`lean_mark_mt`) or
71// persistent, so its reference counts are atomic or never written, and such objects are never
72// updated in place. The types `L` are data: no closures, thunks, tasks or references.
73unsafe impl<L: LeanRepr> Send for Lean<L> {}
74unsafe impl<L: LeanRepr> Sync for Lean<L> {}
75
76impl<L: LeanRepr> Lean<L> {
77    /// The handle of the Lean value of `value`.
78    pub fn new(value: L::Value) -> Self {
79        unsafe { Self::from_owned(L::to_obj(value)) }
80    }
81
82    /// The Rust value of the handle.
83    pub fn get(&self) -> L::Value {
84        unsafe { L::from_obj(self.obj) }
85    }
86
87    /// The handle that owns `obj`.
88    ///
89    /// # Safety
90    ///
91    /// `obj` must be an owned Lean value of the type `L` names, and no other thread may reach
92    /// the objects under it that are still owned by one thread.
93    #[doc(hidden)]
94    pub unsafe fn from_owned(obj: Obj) -> Self {
95        lean_mark_mt(obj);
96        Lean {
97            obj,
98            ty: PhantomData,
99        }
100    }
101
102    /// The object of the handle, borrowed.
103    #[doc(hidden)]
104    pub fn as_obj(&self) -> Obj {
105        self.obj
106    }
107}
108
109impl<L: LeanRepr> Lean<L> {
110    /// A handle of the same object for this thread. The object stays shared between threads,
111    /// so Lean functions do not update it in place.
112    pub fn to_local(&self) -> Local<L> {
113        unsafe {
114            lean_inc(self.obj);
115            Local::from_owned(self.obj)
116        }
117    }
118}
119
120impl<L: LeanRepr> Clone for Lean<L> {
121    fn clone(&self) -> Self {
122        unsafe { lean_inc(self.obj) };
123        Lean {
124            obj: self.obj,
125            ty: PhantomData,
126        }
127    }
128}
129
130impl<L: LeanRepr> Drop for Lean<L> {
131    fn drop(&mut self) {
132        unsafe { lean_dec(self.obj) };
133    }
134}
135
136impl<L: LeanRepr> fmt::Debug for Lean<L>
137where
138    L::Value: fmt::Debug,
139{
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.debug_tuple("Lean").field(&self.get()).finish()
142    }
143}
144
145/// A Lean value of the type named by `L`, kept as the Lean object on the thread that made it.
146///
147/// The functions of the `local` module of a generated module return this handle. Its objects
148/// keep the reference counts of one thread: passing the only handle of a value by value lets
149/// the Lean function update the value in place, where a [`Lean`] handle makes it build new
150/// objects. A `Local` cannot be sent to or shared with another thread; [`Local::share`] turns
151/// it into a [`Lean`] that can.
152///
153/// ```compile_fail,E0277
154/// let local = leanfran_runtime::Local::<u8>::new(1);
155/// std::thread::spawn(move || drop(local));
156/// ```
157///
158/// ```compile_fail,E0277
159/// let local = leanfran_runtime::Local::<u8>::new(1);
160/// std::thread::scope(|s| {
161///     s.spawn(|| local.get());
162/// });
163/// ```
164pub struct Local<L: LeanRepr> {
165    obj: Obj,
166    /// The scope of [`Owned::with`] that made the handle, or 0.
167    scope: u64,
168    ty: PhantomData<fn() -> L>,
169    thread: PhantomData<*mut ()>,
170}
171
172thread_local! {
173    /// The scope of `Owned::with` that is running on this thread (0: none), the number of its
174    /// handles that are alive, and the last scope number used.
175    static SCOPE: Cell<u64> = const { Cell::new(0) };
176    static SCOPE_LIVE: Cell<usize> = const { Cell::new(0) };
177    static SCOPE_LAST: Cell<u64> = const { Cell::new(0) };
178}
179
180/// A handle made in the running scope.
181#[inline]
182fn enter_scope() -> u64 {
183    let scope = SCOPE.get();
184    if scope != 0 {
185        SCOPE_LIVE.set(SCOPE_LIVE.get() + 1);
186    }
187    scope
188}
189
190/// A handle of `scope` goes away. Only handles of the running scope are counted, so the count
191/// of a scope is never below the number of its handles.
192#[inline]
193fn leave_scope(scope: u64) {
194    if scope != 0 && scope == SCOPE.get() {
195        SCOPE_LIVE.set(SCOPE_LIVE.get() - 1);
196    }
197}
198
199impl<L: LeanRepr> Local<L> {
200    /// The handle of the Lean value of `value`.
201    pub fn new(value: L::Value) -> Self {
202        unsafe { Self::from_owned(L::to_obj(value)) }
203    }
204
205    /// The Rust value of the handle.
206    pub fn get(&self) -> L::Value {
207        unsafe { L::from_obj(self.obj) }
208    }
209
210    /// The handle that can be sent to and shared with other threads. It marks the objects of
211    /// the value as shared, at a cost in proportion to the objects not yet shared.
212    pub fn share(self) -> Lean<L> {
213        unsafe { Lean::from_owned(self.release()) }
214    }
215
216    /// The object of a handle of another scope than the running one is shared with handles
217    /// that the running scope does not count: it is marked as shared between threads, which
218    /// is what keeps moving an [`Owned`] to another thread sound.
219    #[inline]
220    fn settle(&self) {
221        if self.scope != SCOPE.get() {
222            unsafe { lean_mark_mt(self.obj) };
223        }
224    }
225
226    /// The owned object of the handle, which goes away.
227    #[inline]
228    fn release(self) -> Obj {
229        self.settle();
230        leave_scope(self.scope);
231        let obj = self.obj;
232        core::mem::forget(self);
233        obj
234    }
235
236    /// The handle that owns `obj`.
237    ///
238    /// # Safety
239    ///
240    /// `obj` must be an owned Lean value of the type `L` names, made on this thread.
241    #[doc(hidden)]
242    pub unsafe fn from_owned(obj: Obj) -> Self {
243        Local {
244            obj,
245            scope: enter_scope(),
246            ty: PhantomData,
247            thread: PhantomData,
248        }
249    }
250
251    /// The object of the handle, borrowed.
252    #[doc(hidden)]
253    pub fn as_obj(&self) -> Obj {
254        self.obj
255    }
256}
257
258impl<L: LeanRepr> Clone for Local<L> {
259    fn clone(&self) -> Self {
260        self.settle();
261        unsafe {
262            lean_inc(self.obj);
263            Local::from_owned(self.obj)
264        }
265    }
266}
267
268impl<L: LeanRepr> Drop for Local<L> {
269    fn drop(&mut self) {
270        leave_scope(self.scope);
271        unsafe { lean_dec(self.obj) };
272    }
273}
274
275impl<L: LeanRepr> fmt::Debug for Local<L>
276where
277    L::Value: fmt::Debug,
278{
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_tuple("Local").field(&self.get()).finish()
281    }
282}
283
284/// An argument of a function of the `lean` or `local` module of a generated module: the Rust
285/// value of `L` (converted for the call), a `&Lean<L>`, a `Lean<L>`, a `&Local<L>` or a
286/// `Local<L>`.
287///
288/// # Safety
289///
290/// `into_obj` must return an owned object of the Lean type `L` names.
291pub unsafe trait IntoLean<L: LeanRepr> {
292    /// The owned boxed object of the argument.
293    ///
294    /// # Safety
295    ///
296    /// The result is an owned Lean object that must be released with `lean_dec` or passed on.
297    #[doc(hidden)]
298    unsafe fn into_obj(self) -> Obj;
299}
300
301unsafe impl<L: LeanRepr> IntoLean<L> for Lean<L> {
302    unsafe fn into_obj(self) -> Obj {
303        let obj = self.obj;
304        core::mem::forget(self);
305        obj
306    }
307}
308
309unsafe impl<L: LeanRepr> IntoLean<L> for &Lean<L> {
310    unsafe fn into_obj(self) -> Obj {
311        lean_inc(self.obj);
312        self.obj
313    }
314}
315
316unsafe impl<L: LeanRepr> IntoLean<L> for Local<L> {
317    unsafe fn into_obj(self) -> Obj {
318        self.release()
319    }
320}
321
322unsafe impl<L: LeanRepr> IntoLean<L> for &Local<L> {
323    unsafe fn into_obj(self) -> Obj {
324        self.settle();
325        lean_inc(self.obj);
326        self.obj
327    }
328}
329
330/// A Lean value of the type named by `L` with one owner, which can move between threads and
331/// is still updated in place.
332///
333/// The objects of the value keep the reference counts of one thread, like those of a
334/// [`Local`]. That is sound because nothing else refers to them while the `Owned` is at rest:
335/// it is made from a Rust value or from a [`Lean`], it cannot be cloned or shared (`Send`, not
336/// `Sync`), and [`Owned::with`] lends the value as a `Local` for the time of a closure only.
337/// A `Local` that outlives the closure is detected when the closure returns, and what it
338/// shares with the value is then marked as shared between threads, which costs the in-place
339/// updates of those objects and nothing else.
340///
341/// ```
342/// use leanfran_runtime::{List, Local, Owned};
343/// use std::sync::Mutex;
344///
345/// let numbers = Mutex::new(Owned::<List<u32>>::new(vec![1, 2, 3]));
346/// std::thread::scope(|s| {
347///     s.spawn(|| {
348///         let length = numbers.lock().unwrap().with(|list: Local<List<u32>>| {
349///             let length = list.get().len();
350///             (list, length)
351///         });
352///         assert_eq!(length, 3);
353///     });
354/// });
355/// ```
356///
357/// ```compile_fail,E0277
358/// let owned = leanfran_runtime::Owned::<u8>::new(1);
359/// std::thread::scope(|s| {
360///     s.spawn(|| owned.get());
361/// });
362/// ```
363pub struct Owned<L: LeanRepr> {
364    /// Null while `with` runs and after its closure panicked.
365    obj: Obj,
366    ty: PhantomData<fn() -> L>,
367}
368
369// SAFETY: at rest, the objects of the value that are owned by one thread are reachable from
370// this handle only (see `with`), so the thread that holds the handle is the only one that
371// reads or writes them and their reference counts. Blocks freed on another thread than the
372// one that allocated them join the small object pool of the freeing thread.
373unsafe impl<L: LeanRepr> Send for Owned<L> {}
374
375impl<L: LeanRepr> Owned<L> {
376    /// The handle of the Lean value of `value`.
377    pub fn new(value: L::Value) -> Self {
378        Owned {
379            obj: unsafe { L::to_obj(value) },
380            ty: PhantomData,
381        }
382    }
383
384    fn obj(&self) -> Obj {
385        assert!(
386            !self.obj.is_null(),
387            "the Owned value was lost: a closure of `with` panicked"
388        );
389        self.obj
390    }
391
392    /// The Rust value of the handle.
393    pub fn get(&self) -> L::Value {
394        unsafe { L::from_obj(self.obj()) }
395    }
396
397    /// Lends the value to `f` as a [`Local`] and takes the `Local` that `f` returns as the new
398    /// value. Passing the `Local` by value to a function of the `local` module of a generated
399    /// module updates the value in place.
400    ///
401    /// Every other `Local` made in `f` should be gone when `f` returns. If one is still alive
402    /// (kept in a captured variable or in the result), or if `f` returns a `Local` it got from
403    /// elsewhere, the new value is marked as shared between threads.
404    pub fn with<R>(&mut self, f: impl FnOnce(Local<L>) -> (Local<L>, R)) -> R {
405        struct Restore(u64, usize);
406        impl Drop for Restore {
407            fn drop(&mut self) {
408                SCOPE.set(self.0);
409                SCOPE_LIVE.set(self.1);
410            }
411        }
412        let obj = core::mem::replace(&mut self.obj, core::ptr::null_mut());
413        assert!(
414            !obj.is_null(),
415            "the Owned value was lost: a closure of `with` panicked"
416        );
417        let scope = SCOPE_LAST.get() + 1;
418        SCOPE_LAST.set(scope);
419        let restore = Restore(SCOPE.replace(scope), SCOPE_LIVE.replace(0));
420        let (value, result) = f(unsafe { Local::from_owned(obj) });
421        let alone = value.scope == scope && SCOPE_LIVE.get() == 1;
422        let obj = value.obj;
423        core::mem::forget(value);
424        if !alone {
425            unsafe { lean_mark_mt(obj) };
426        }
427        drop(restore);
428        self.obj = obj;
429        result
430    }
431
432    /// The handle that can be shared between threads.
433    pub fn share(self) -> Lean<L> {
434        let obj = self.obj();
435        core::mem::forget(self);
436        unsafe { Lean::from_owned(obj) }
437    }
438}
439
440impl<L: LeanRepr> From<Lean<L>> for Owned<L> {
441    /// The shared value with one more owner. Its objects stay shared; the objects that
442    /// functions build from it are owned.
443    fn from(value: Lean<L>) -> Self {
444        let obj = value.obj;
445        core::mem::forget(value);
446        Owned {
447            obj,
448            ty: PhantomData,
449        }
450    }
451}
452
453impl<L: LeanRepr> Drop for Owned<L> {
454    fn drop(&mut self) {
455        if !self.obj.is_null() {
456            unsafe { lean_dec(self.obj) };
457        }
458    }
459}
460
461impl<L: LeanRepr> fmt::Debug for Owned<L>
462where
463    L::Value: fmt::Debug,
464{
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        f.debug_tuple("Owned").field(&self.get()).finish()
467    }
468}
469
470macro_rules! prim_repr {
471    ($($t:ty),*) => {$(
472        unsafe impl LeanRepr for $t {
473            type Value = $t;
474            unsafe fn to_obj(value: $t) -> Obj {
475                ToLean::to_lean(value)
476            }
477            unsafe fn from_obj(o: Obj) -> $t {
478                <$t as FromLean>::from_lean(o)
479            }
480        }
481        unsafe impl IntoLean<$t> for $t {
482            unsafe fn into_obj(self) -> Obj {
483                ToLean::to_lean(self)
484            }
485        }
486    )*};
487}
488
489prim_repr!(
490    Nat,
491    Int,
492    bool,
493    char,
494    String,
495    u8,
496    u16,
497    u32,
498    u64,
499    usize,
500    i8,
501    i16,
502    i32,
503    i64,
504    isize,
505    f64,
506    f32,
507    ()
508);
509
510unsafe impl IntoLean<String> for &str {
511    unsafe fn into_obj(self) -> Obj {
512        ToLean::to_lean(self)
513    }
514}
515
516unsafe impl IntoLean<String> for &String {
517    unsafe fn into_obj(self) -> Obj {
518        ToLean::to_lean(self.as_str())
519    }
520}
521
522unsafe impl<T: LeanRepr> LeanRepr for List<T> {
523    type Value = Vec<T::Value>;
524    unsafe fn to_obj(value: Self::Value) -> Obj {
525        list_to_lean(value, |v| T::to_obj(v))
526    }
527    unsafe fn from_obj(o: Obj) -> Self::Value {
528        list_from_lean(o, |v| T::from_obj(v))
529    }
530}
531
532unsafe impl<T: LeanRepr> IntoLean<List<T>> for Vec<T::Value> {
533    unsafe fn into_obj(self) -> Obj {
534        List::<T>::to_obj(self)
535    }
536}
537
538unsafe impl<T: LeanRepr> LeanRepr for Array<T> {
539    type Value = Vec<T::Value>;
540    unsafe fn to_obj(value: Self::Value) -> Obj {
541        array_to_lean(value, |v| T::to_obj(v))
542    }
543    unsafe fn from_obj(o: Obj) -> Self::Value {
544        array_from_lean(o, |v| T::from_obj(v))
545    }
546}
547
548unsafe impl<T: LeanRepr> IntoLean<Array<T>> for Vec<T::Value> {
549    unsafe fn into_obj(self) -> Obj {
550        Array::<T>::to_obj(self)
551    }
552}
553
554unsafe impl<T: LeanRepr> LeanRepr for Option<T> {
555    type Value = Option<T::Value>;
556    unsafe fn to_obj(value: Self::Value) -> Obj {
557        option_to_lean(value, |v| T::to_obj(v))
558    }
559    unsafe fn from_obj(o: Obj) -> Self::Value {
560        option_from_lean(o, |v| T::from_obj(v))
561    }
562}
563
564unsafe impl<T: LeanRepr> IntoLean<Option<T>> for Option<T::Value> {
565    unsafe fn into_obj(self) -> Obj {
566        Option::<T>::to_obj(self)
567    }
568}
569
570unsafe impl<T: LeanRepr, E: LeanRepr> LeanRepr for Result<T, E> {
571    type Value = Result<T::Value, E::Value>;
572    unsafe fn to_obj(value: Self::Value) -> Obj {
573        except_to_lean(value, |v| E::to_obj(v), |v| T::to_obj(v))
574    }
575    unsafe fn from_obj(o: Obj) -> Self::Value {
576        except_from_lean(o, |v| E::from_obj(v), |v| T::from_obj(v))
577    }
578}
579
580unsafe impl<T: LeanRepr, E: LeanRepr> IntoLean<Result<T, E>> for Result<T::Value, E::Value> {
581    unsafe fn into_obj(self) -> Obj {
582        Result::<T, E>::to_obj(self)
583    }
584}
585
586unsafe impl<A: LeanRepr, B: LeanRepr> LeanRepr for (A, B) {
587    type Value = (A::Value, B::Value);
588    unsafe fn to_obj(value: Self::Value) -> Obj {
589        prod_to_lean(value, |v| A::to_obj(v), |v| B::to_obj(v))
590    }
591    unsafe fn from_obj(o: Obj) -> Self::Value {
592        prod_from_lean(o, |v| A::from_obj(v), |v| B::from_obj(v))
593    }
594}
595
596unsafe impl<A: LeanRepr, B: LeanRepr> IntoLean<(A, B)> for (A::Value, B::Value) {
597    unsafe fn into_obj(self) -> Obj {
598        <(A, B)>::to_obj(self)
599    }
600}
601
602unsafe impl<const N: u64> LeanRepr for Fin<N> {
603    type Value = usize;
604    unsafe fn to_obj(value: usize) -> Obj {
605        fin_to_lean(value, N as usize)
606    }
607    unsafe fn from_obj(o: Obj) -> usize {
608        fin_from_lean(o)
609    }
610}
611
612unsafe impl<const N: u64> IntoLean<Fin<N>> for usize {
613    unsafe fn into_obj(self) -> Obj {
614        Fin::<N>::to_obj(self)
615    }
616}