Skip to main content

inlean_runtime/
codec.rs

1//! Conversions between Rust values and Lean values, 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. Each type of this module stands for the Lean type of
7//! the same name, so `Array<Option<String>>` converts a `Vec<Option<String>>` to and from a
8//! Lean `Array (Option String)`.
9//!
10//! A conversion moves what it can. [`Codec::into_lean`] takes the Rust value and builds the
11//! Lean value around its buffers. [`Codec::from_lean`] takes out of the Lean value whatever
12//! nothing else refers to, as Lean's own compiled code does when it takes a value apart.
13//! Only [`Codec::to_lean`], which leaves the Rust value with the caller, always copies.
14//!
15//! The conversions are safe functions because of [`Value`]: a Lean value together with its
16//! type and the one reference to it that the holder owns. The single unsafe claim at the
17//! boundary is [`Value::from_raw`], where generated code says what a Lean function returned.
18
19use crate::object::{self as o, box_, dec, dec_ref, inc, Obj};
20use std::marker::PhantomData;
21
22/// How Lean passes a value of a type: as an object, or as a scalar it keeps unboxed.
23pub trait Repr: Copy {
24    /// The value as an object: the form it has as an element of an array, an argument of a
25    /// closure or a field of a polymorphic type. The object takes over the reference.
26    fn into_object(self) -> Obj;
27
28    /// The value out of an object that [`Repr::into_object`] made, whose reference is given
29    /// up.
30    ///
31    /// # Safety
32    /// `object` holds a value of this representation and the caller owns a reference to it.
33    unsafe fn take(object: Obj) -> Self;
34
35    /// The value out of an object that stays with its owner: one more reference to an
36    /// object, a copy of a scalar.
37    ///
38    /// # Safety
39    /// `object` holds a value of this representation.
40    unsafe fn share(object: Obj) -> Self;
41
42    /// Gives up the reference the value holds. A scalar holds none.
43    ///
44    /// # Safety
45    /// The caller owns the reference.
46    unsafe fn release(self);
47
48    /// The same value with a reference of its own.
49    ///
50    /// # Safety
51    /// The value is alive.
52    unsafe fn retain(self) -> Self;
53}
54
55impl Repr for Obj {
56    #[inline(always)]
57    fn into_object(self) -> Obj {
58        self
59    }
60
61    #[inline(always)]
62    unsafe fn take(object: Obj) -> Obj {
63        object
64    }
65
66    #[inline(always)]
67    unsafe fn share(object: Obj) -> Obj {
68        inc(object);
69        object
70    }
71
72    #[inline(always)]
73    unsafe fn release(self) {
74        dec(self)
75    }
76
77    #[inline(always)]
78    unsafe fn retain(self) -> Obj {
79        inc(self);
80        self
81    }
82}
83
84/// A representation that is a plain number, with no reference to count.
85pub trait Scalar: Repr {}
86
87macro_rules! scalar_reprs {
88    ($($ty:ty: |$value:ident| $boxed:expr, |$object:ident| $unboxed:expr;)*) => {$(
89        impl Repr for $ty {
90            #[inline(always)]
91            fn into_object(self) -> Obj {
92                let $value = self;
93                // Allocation aside, boxing has no precondition.
94                #[allow(unused_unsafe)]
95                unsafe {
96                    $boxed
97                }
98            }
99
100            #[inline(always)]
101            unsafe fn take($object: Obj) -> $ty {
102                let value = $unboxed;
103                dec($object);
104                value
105            }
106
107            #[inline(always)]
108            unsafe fn share($object: Obj) -> $ty {
109                $unboxed
110            }
111
112            #[inline(always)]
113            unsafe fn release(self) {}
114
115            #[inline(always)]
116            unsafe fn retain(self) -> $ty {
117                self
118            }
119        }
120
121        impl Scalar for $ty {}
122    )*};
123}
124
125scalar_reprs! {
126    u8: |v| box_(v as usize), |x| o::unbox(x) as u8;
127    u16: |v| box_(v as usize), |x| o::unbox(x) as u16;
128    u32: |v| o::box_uint32(v), |x| o::unbox_uint32(x);
129    u64: |v| o::box_uint64(v), |x| o::unbox_uint64(x);
130    usize: |v| o::box_usize(v), |x| o::unbox_usize(x);
131    f64: |v| o::box_float(v), |x| o::unbox_float(x);
132    f32: |v| o::box_float32(v), |x| o::unbox_float32(x);
133}
134
135/// A Lean value of the type `C` stands for, with the one reference to it that the holder
136/// owns. Dropping it gives the reference up.
137///
138/// A value of a type that Lean passes as a scalar is that scalar. A codec of such a type
139/// accepts every scalar in [`Codec::from_lean`], which is what lets [`Value::from_scalar`]
140/// be safe.
141#[repr(transparent)]
142pub struct Value<C: Codec>(C::Repr, PhantomData<C>);
143
144impl<C: Codec> Value<C> {
145    /// # Safety
146    /// `repr` is a value of the Lean type `C` stands for, produced by this runtime, and the
147    /// caller owns a reference to it.
148    #[inline(always)]
149    pub unsafe fn from_raw(repr: C::Repr) -> Value<C> {
150        Value(repr, PhantomData)
151    }
152
153    /// The value of a type that Lean passes as a scalar.
154    #[inline(always)]
155    pub fn from_scalar(repr: C::Repr) -> Value<C>
156    where
157        C::Repr: Scalar,
158    {
159        Value(repr, PhantomData)
160    }
161
162    /// The representation, with the reference.
163    #[inline(always)]
164    pub fn into_raw(self) -> C::Repr {
165        let repr = self.0;
166        std::mem::forget(self);
167        repr
168    }
169
170    /// The representation, for a function that borrows it. The reference stays here.
171    #[inline(always)]
172    pub fn as_raw(&self) -> C::Repr {
173        self.0
174    }
175
176    /// The value as an object; see [`Repr::into_object`].
177    #[inline(always)]
178    pub fn into_object(self) -> Obj {
179        self.into_raw().into_object()
180    }
181
182    /// The value out of an object whose reference is given up.
183    ///
184    /// # Safety
185    /// `object` holds a value of the Lean type `C` stands for, in the form
186    /// [`Value::into_object`] gives it, and the caller owns a reference to it.
187    #[inline(always)]
188    pub unsafe fn take(object: Obj) -> Value<C> {
189        Value(C::Repr::take(object), PhantomData)
190    }
191
192    /// The value out of an object that stays with its owner.
193    ///
194    /// # Safety
195    /// `object` holds a value of the Lean type `C` stands for, in the form
196    /// [`Value::into_object`] gives it.
197    #[inline(always)]
198    pub unsafe fn share(object: Obj) -> Value<C> {
199        Value(C::Repr::share(object), PhantomData)
200    }
201
202    /// The same Lean value, with a reference of its own.
203    #[inline(always)]
204    pub fn retain(&self) -> Value<C> {
205        Value(unsafe { self.0.retain() }, PhantomData)
206    }
207
208    /// The same value under another codec.
209    ///
210    /// # Safety
211    /// `D` stands for the same Lean type as `C`.
212    #[inline(always)]
213    pub unsafe fn cast<D: Codec<Repr = C::Repr>>(self) -> Value<D> {
214        Value(self.into_raw(), PhantomData)
215    }
216}
217
218impl<C: Codec> Drop for Value<C> {
219    #[inline(always)]
220    fn drop(&mut self) {
221        unsafe { self.0.release() }
222    }
223}
224
225/// A conversion between a Rust type and the Lean type the implementor stands for.
226pub trait Codec: Sized {
227    /// The Rust type that owns a value.
228    type Rust;
229
230    /// How Lean passes a value of the type.
231    type Repr: Repr;
232
233    /// The Lean value of a Rust value that is given up. What can move is moved.
234    fn into_lean(value: Self::Rust) -> Value<Self>;
235
236    /// The Lean value of a Rust value that stays with the caller. A copy.
237    fn to_lean(value: &Self::Rust) -> Value<Self>;
238
239    /// The Rust value of a Lean value. What nothing else refers to is taken out of it, and
240    /// the rest is copied.
241    ///
242    /// A codec whose representation is a scalar must accept every value of that scalar
243    /// here, since [`Value::from_scalar`] makes a value of it from any.
244    fn from_lean(value: Value<Self>) -> Self::Rust;
245
246    /// The Lean value of a Rust value that the caller of an exported function passed by
247    /// reference. The default converts it, as `to_lean` does. A codec whose Lean object holds
248    /// the Rust value makes an object that stands for the caller's value instead, so that
249    /// nothing is copied until Lean needs a value of its own.
250    ///
251    /// # Safety
252    /// The value returned, and every reference Lean takes to it, is given up before the borrow
253    /// of `value` ends.
254    #[doc(hidden)]
255    unsafe fn lent(value: &Self::Rust) -> Value<Self> {
256        Self::to_lean(value)
257    }
258
259    /// Calls `f` with the Rust form of a Lean value that is only lent: the lender keeps its
260    /// reference. This is how a Rust function bound to a Lean declaration receives an argument
261    /// that Lean passes with `@&`.
262    ///
263    /// The default copies the value out for the length of the call. A codec whose Lean object
264    /// holds the Rust value lends that value itself.
265    fn lend<R>(value: &Value<Self>, f: impl FnOnce(&Self::Rust) -> R) -> R {
266        let copy = Self::from_lean(value.retain());
267        f(&copy)
268    }
269}
270
271/// A type whose values Lean may keep in a constant that every thread reads: one that is `Sync`.
272///
273/// The trait and the function below exist for their names, which are what rustc shows when a
274/// type falls short: the type is not `Sync`, it has to be to implement this trait, and the
275/// bound is that of a function named after the reason.
276pub trait KeptByLeanForAllThreads {}
277
278impl<T: Sync> KeptByLeanForAllThreads for T {}
279
280/// States that `T` is the type of a value that a trusted function returns to Lean.
281///
282/// Lean computes a closed term once and keeps the result for all threads. A value of an opaque
283/// or foreign type that a trusted function returns can be part of such a term, so the type must
284/// be `Sync`. A value that only comes in through an argument of an exported function cannot be.
285#[inline(always)]
286pub fn returned_by_a_trusted_function<T: KeptByLeanForAllThreads>() {}
287
288/// States that `T` is the type of a value that a trusted function gives to a Lean function it
289/// was passed.
290///
291/// The Lean function can make the value part of what it returns, and that goes back into Lean
292/// as it is. So the value can end up in a closed term as one that the trusted function returns
293/// can, and the type must be `Sync` for the same reason.
294#[inline(always)]
295pub fn given_to_a_lean_function<T: KeptByLeanForAllThreads>() {}
296
297macro_rules! scalars {
298    ($($name:ident: $rust:ty as $repr:ty, |$value:ident| $to:expr, |$raw:ident| $from:expr;)*) => {$(
299        #[doc = concat!("Lean's `", stringify!($name), "`.")]
300        pub struct $name;
301
302        impl Codec for $name {
303            type Rust = $rust;
304            type Repr = $repr;
305
306            #[inline(always)]
307            fn into_lean($value: $rust) -> Value<$name> {
308                Value::from_scalar($to)
309            }
310
311            #[inline(always)]
312            fn to_lean(value: &$rust) -> Value<$name> {
313                Self::into_lean(*value)
314            }
315
316            #[inline(always)]
317            fn from_lean(value: Value<$name>) -> $rust {
318                let $raw = value.into_raw();
319                $from
320            }
321        }
322    )*};
323}
324
325// A signed integer is the unsigned one of its width in Lean's IR, with the same bits. A
326// `Bool` is a byte, and a `Char` is a `u32` that Lean proved to be a Unicode scalar value.
327scalars! {
328    UInt8: u8 as u8, |v| v, |r| r;
329    UInt16: u16 as u16, |v| v, |r| r;
330    UInt32: u32 as u32, |v| v, |r| r;
331    UInt64: u64 as u64, |v| v, |r| r;
332    USize: usize as usize, |v| v, |r| r;
333    Int8: i8 as u8, |v| v as u8, |r| r as i8;
334    Int16: i16 as u16, |v| v as u16, |r| r as i16;
335    Int32: i32 as u32, |v| v as u32, |r| r as i32;
336    Int64: i64 as u64, |v| v as u64, |r| r as i64;
337    ISize: isize as usize, |v| v as usize, |r| r as isize;
338    Bool: bool as u8, |v| v as u8, |r| r != 0;
339    Char: char as u32, |v| v as u32, |r| crate::char_of_u32(r);
340    Float: f64 as f64, |v| v, |r| r;
341    Float32: f32 as f32, |v| v, |r| r;
342}
343
344/// A value of a type that a declaration bound to Rust is generic in, as [`crate::Generic`]:
345/// the Lean object, passed on as it is. `N` is the type's place among the declaration's
346/// type parameters.
347pub struct Generic<'a, const N: usize>(PhantomData<&'a ()>);
348
349impl<'a, const N: usize> Codec for Generic<'a, N> {
350    type Rust = crate::Generic<'a, N>;
351    type Repr = Obj;
352
353    #[inline]
354    fn into_lean(value: crate::Generic<'a, N>) -> Value<Self> {
355        unsafe { Value::from_raw(value.into_raw()) }
356    }
357
358    #[inline]
359    fn to_lean(value: &crate::Generic<'a, N>) -> Value<Self> {
360        Self::into_lean(value.clone())
361    }
362
363    #[inline]
364    fn from_lean(value: Value<Self>) -> crate::Generic<'a, N> {
365        unsafe { crate::Generic::from_raw(value.into_raw()) }
366    }
367}
368
369/// Lean's `Unit`, where it is part of another type.
370pub struct Unit;
371
372impl Codec for Unit {
373    type Rust = ();
374    type Repr = Obj;
375
376    fn into_lean(_value: ()) -> Value<Unit> {
377        unsafe { Value::from_raw(box_(0)) }
378    }
379
380    fn to_lean(_value: &()) -> Value<Unit> {
381        unsafe { Value::from_raw(box_(0)) }
382    }
383
384    fn from_lean(_value: Value<Unit>) {}
385}
386
387/// Lean's `Nat` as [`crate::Nat`], which is the Lean object itself where nothing else holds
388/// the object, and a copy of it otherwise.
389pub struct Nat;
390
391impl Codec for Nat {
392    type Rust = crate::Nat;
393    type Repr = Obj;
394
395    #[inline]
396    fn into_lean(value: crate::Nat) -> Value<Nat> {
397        unsafe { Value::from_raw(value.into_raw()) }
398    }
399
400    #[inline]
401    fn to_lean(value: &crate::Nat) -> Value<Nat> {
402        Self::into_lean(value.clone())
403    }
404
405    #[inline]
406    fn from_lean(value: Value<Nat>) -> crate::Nat {
407        unsafe { crate::Nat::owning(value.into_raw()) }
408    }
409
410    #[inline]
411    fn lend<R>(value: &Value<Nat>, f: impl FnOnce(&crate::Nat) -> R) -> R {
412        // A `Nat` is the object itself. This one does not own its reference.
413        let nat = std::mem::ManuallyDrop::new(unsafe { crate::Nat::from_raw(value.as_raw()) });
414        f(&nat)
415    }
416}
417
418/// Lean's `Int` as [`crate::Int`], which is the Lean object itself where nothing else holds
419/// the object, and a copy of it otherwise.
420pub struct Int;
421
422impl Codec for Int {
423    type Rust = crate::Int;
424    type Repr = Obj;
425
426    #[inline]
427    fn into_lean(value: crate::Int) -> Value<Int> {
428        unsafe { Value::from_raw(value.into_raw()) }
429    }
430
431    #[inline]
432    fn to_lean(value: &crate::Int) -> Value<Int> {
433        Self::into_lean(value.clone())
434    }
435
436    #[inline]
437    fn from_lean(value: Value<Int>) -> crate::Int {
438        unsafe { crate::Int::owning(value.into_raw()) }
439    }
440
441    #[inline]
442    fn lend<R>(value: &Value<Int>, f: impl FnOnce(&crate::Int) -> R) -> R {
443        let int = std::mem::ManuallyDrop::new(unsafe { crate::Int::from_raw(value.as_raw()) });
444        f(&int)
445    }
446}
447
448/// Lean's `String`. The Lean object holds a Rust `String`, so a value moves both ways.
449pub struct String;
450
451impl Codec for String {
452    type Rust = std::string::String;
453    type Repr = Obj;
454
455    fn into_lean(value: std::string::String) -> Value<String> {
456        unsafe { Value::from_raw(crate::string::from_string(value)) }
457    }
458
459    fn to_lean(value: &std::string::String) -> Value<String> {
460        unsafe { Value::from_raw(crate::string::mk_string(value)) }
461    }
462
463    fn from_lean(value: Value<String>) -> std::string::String {
464        unsafe { crate::string::into_string(value.into_raw()) }
465    }
466
467    fn lend<R>(value: &Value<String>, f: impl FnOnce(&std::string::String) -> R) -> R {
468        f(unsafe { crate::string::held_string(value.as_raw()) })
469    }
470}
471
472/// Lean's `ByteArray`. The Lean object holds a `Vec<u8>`, so a value moves both ways.
473pub struct ByteArray;
474
475impl Codec for ByteArray {
476    type Rust = Vec<u8>;
477    type Repr = Obj;
478
479    fn into_lean(value: Vec<u8>) -> Value<ByteArray> {
480        unsafe { Value::from_raw(crate::sarray::byte_array_from_vec(value)) }
481    }
482
483    fn to_lean(value: &Vec<u8>) -> Value<ByteArray> {
484        Self::into_lean(value.clone())
485    }
486
487    fn from_lean(value: Value<ByteArray>) -> Vec<u8> {
488        unsafe { crate::sarray::byte_array_into_vec(value.into_raw()) }
489    }
490
491    fn lend<R>(value: &Value<ByteArray>, f: impl FnOnce(&Vec<u8>) -> R) -> R {
492        f(unsafe { crate::sarray::held_bytes(value.as_raw()) })
493    }
494}
495
496/// Lean's `FloatArray`. The Lean object holds a `Vec<f64>`, so a value moves both ways.
497pub struct FloatArray;
498
499impl Codec for FloatArray {
500    type Rust = Vec<f64>;
501    type Repr = Obj;
502
503    fn into_lean(value: Vec<f64>) -> Value<FloatArray> {
504        unsafe { Value::from_raw(crate::sarray::float_array_from_vec(value)) }
505    }
506
507    fn to_lean(value: &Vec<f64>) -> Value<FloatArray> {
508        Self::into_lean(value.clone())
509    }
510
511    fn from_lean(value: Value<FloatArray>) -> Vec<f64> {
512        unsafe { crate::sarray::float_array_into_vec(value.into_raw()) }
513    }
514
515    fn lend<R>(value: &Value<FloatArray>, f: impl FnOnce(&Vec<f64>) -> R) -> R {
516        f(unsafe { crate::sarray::held_floats(value.as_raw()) })
517    }
518}
519
520/// Objects whose references the holder owns and has not handed on yet. They are released
521/// if a conversion panics before that, so that a failing conversion of the user's leaves
522/// nothing behind.
523struct Owned(Vec<Obj>);
524
525impl Owned {
526    fn into_vec(mut self) -> Vec<Obj> {
527        std::mem::take(&mut self.0)
528    }
529}
530
531impl Drop for Owned {
532    fn drop(&mut self) {
533        for &object in &self.0 {
534            unsafe { dec(object) }
535        }
536    }
537}
538
539/// [`Owned`] for objects that are being handed on one by one.
540struct Rest(std::vec::IntoIter<Obj>);
541
542impl Drop for Rest {
543    fn drop(&mut self) {
544        for object in &mut self.0 {
545            unsafe { dec(object) }
546        }
547    }
548}
549
550/// The fields of a constructor object whose reference the caller gives up. They are taken
551/// when nothing else refers to the object, and shared with it otherwise: the rule Lean's
552/// compiled code follows when it takes a value apart.
553pub struct Fields {
554    object: Obj,
555    exclusive: bool,
556}
557
558impl Fields {
559    /// # Safety
560    /// `object` is a constructor object on the heap, and the caller owns a reference to it.
561    /// Every object field must be read once with [`Fields::object`] before [`Fields::done`].
562    #[inline(always)]
563    pub unsafe fn of(object: Obj) -> Fields {
564        Fields { object, exclusive: o::is_exclusive(object) }
565    }
566
567    /// Object field `i`, as a value of the Lean type `C` stands for.
568    ///
569    /// # Safety
570    /// The field holds such a value.
571    #[inline(always)]
572    pub unsafe fn object<C: Codec>(&self, i: u32) -> Value<C> {
573        let field = o::ctor_get(self.object, i);
574        if self.exclusive {
575            Value::take(field)
576        } else {
577            Value::share(field)
578        }
579    }
580
581    /// Gives the object up.
582    ///
583    /// # Safety
584    /// Every object field has been read once.
585    #[inline(always)]
586    pub unsafe fn done(self) {
587        if self.exclusive {
588            o::free_object(self.object)
589        } else {
590            dec_ref(self.object)
591        }
592    }
593}
594
595/// Lean's `Array α` as a `Vec`.
596pub struct Array<C>(PhantomData<C>);
597
598impl<C: Codec> Array<C> {
599    /// The array of the values `items` yields.
600    pub fn from_values(items: impl ExactSizeIterator<Item = Value<C>>) -> Value<Self> {
601        let mut objects = Owned(Vec::with_capacity(items.len()));
602        for item in items {
603            objects.0.push(item.into_object());
604        }
605        unsafe { Value::from_raw(crate::array::from_vec(objects.into_vec())) }
606    }
607}
608
609impl<C: Codec> Codec for Array<C> {
610    type Rust = Vec<C::Rust>;
611    type Repr = Obj;
612
613    fn into_lean(value: Vec<C::Rust>) -> Value<Self> {
614        Self::from_values(value.into_iter().map(C::into_lean))
615    }
616
617    fn to_lean(value: &Vec<C::Rust>) -> Value<Self> {
618        Self::from_values(value.iter().map(C::to_lean))
619    }
620
621    fn from_lean(value: Value<Self>) -> Vec<C::Rust> {
622        let object = value.into_raw();
623        unsafe {
624            if o::is_exclusive(object) {
625                // The array is ours alone: its elements are taken, not copied.
626                let mut rest = Rest(crate::array::into_vec(object).into_iter());
627                let mut items = Vec::with_capacity(rest.0.len());
628                while let Some(item) = rest.0.next() {
629                    items.push(C::from_lean(Value::take(item)));
630                }
631                items
632            } else {
633                // Still referred to from elsewhere: gives up the reference only once the
634                // elements are read, so that a panic on the way leaves the array intact.
635                let _shared = Value::<Self>::from_raw(object);
636                crate::array::elements(object).iter().map(|&item| C::from_lean(Value::share(item))).collect()
637            }
638        }
639    }
640}
641
642/// Lean's `List α` as a `Vec`.
643pub struct List<C>(PhantomData<C>);
644
645impl<C: Codec> List<C> {
646    /// The list of what `items` yields from its last item to its first.
647    fn build(items: impl Iterator<Item = Obj>) -> Value<Self> {
648        // A list is built from its end. Held as a value, the part built so far is released
649        // if a conversion panics.
650        let mut list: Value<Self> = unsafe { Value::from_raw(box_(0)) };
651        for item in items {
652            unsafe {
653                // `List.cons head tail`.
654                let cell = o::alloc_ctor(1, 2, 0, 0);
655                o::ctor_set(cell, 0, item);
656                o::ctor_set(cell, 1, list.into_raw());
657                list = Value::from_raw(cell);
658            }
659        }
660        list
661    }
662}
663
664impl<C: Codec> Codec for List<C> {
665    type Rust = Vec<C::Rust>;
666    type Repr = Obj;
667
668    fn into_lean(value: Vec<C::Rust>) -> Value<Self> {
669        Self::build(value.into_iter().rev().map(|item| C::into_lean(item).into_object()))
670    }
671
672    fn to_lean(value: &Vec<C::Rust>) -> Value<Self> {
673        Self::build(value.iter().rev().map(|item| C::to_lean(item).into_object()))
674    }
675
676    fn from_lean(value: Value<Self>) -> Vec<C::Rust> {
677        let mut items = Vec::new();
678        let mut rest = value;
679        loop {
680            let cell = rest.into_raw();
681            if o::is_scalar(cell) {
682                return items;
683            }
684            unsafe {
685                let fields = Fields::of(cell);
686                let head = fields.object::<C>(0);
687                let tail = fields.object::<Self>(1);
688                fields.done();
689                rest = tail;
690                items.push(C::from_lean(head));
691            }
692        }
693    }
694}
695
696/// Lean's `Option α`.
697pub struct Option<C>(PhantomData<C>);
698
699impl<C: Codec> Option<C> {
700    fn some(field: Value<C>) -> Value<Self> {
701        unsafe {
702            let some = o::alloc_ctor(1, 1, 0, 0);
703            o::ctor_set(some, 0, field.into_object());
704            Value::from_raw(some)
705        }
706    }
707}
708
709impl<C: Codec> Codec for Option<C> {
710    type Rust = core::option::Option<C::Rust>;
711    type Repr = Obj;
712
713    fn into_lean(value: Self::Rust) -> Value<Self> {
714        match value {
715            None => unsafe { Value::from_raw(box_(0)) },
716            Some(value) => Self::some(C::into_lean(value)),
717        }
718    }
719
720    fn to_lean(value: &Self::Rust) -> Value<Self> {
721        match value {
722            None => unsafe { Value::from_raw(box_(0)) },
723            Some(value) => Self::some(C::to_lean(value)),
724        }
725    }
726
727    fn from_lean(value: Value<Self>) -> Self::Rust {
728        let object = value.into_raw();
729        if o::is_scalar(object) {
730            return None;
731        }
732        unsafe {
733            let fields = Fields::of(object);
734            let field = fields.object::<C>(0);
735            fields.done();
736            Some(C::from_lean(field))
737        }
738    }
739}
740
741/// Lean's `α × β` as a pair.
742pub struct Prod<A, B>(PhantomData<(A, B)>);
743
744impl<A: Codec, B: Codec> Prod<A, B> {
745    fn pair(first: Value<A>, second: Value<B>) -> Value<Self> {
746        unsafe {
747            let pair = o::alloc_ctor(0, 2, 0, 0);
748            o::ctor_set(pair, 0, first.into_object());
749            o::ctor_set(pair, 1, second.into_object());
750            Value::from_raw(pair)
751        }
752    }
753
754    /// The Lean pair of two values held separately, as the entries of a Rust map are.
755    pub fn from_refs(first: &A::Rust, second: &B::Rust) -> Value<Self> {
756        Self::pair(A::to_lean(first), B::to_lean(second))
757    }
758}
759
760impl<A: Codec, B: Codec> Codec for Prod<A, B> {
761    type Rust = (A::Rust, B::Rust);
762    type Repr = Obj;
763
764    fn into_lean(value: Self::Rust) -> Value<Self> {
765        let first = A::into_lean(value.0);
766        Self::pair(first, B::into_lean(value.1))
767    }
768
769    fn to_lean(value: &Self::Rust) -> Value<Self> {
770        Self::from_refs(&value.0, &value.1)
771    }
772
773    fn from_lean(value: Value<Self>) -> Self::Rust {
774        unsafe {
775            let fields = Fields::of(value.into_raw());
776            let (first, second) = (fields.object::<A>(0), fields.object::<B>(1));
777            fields.done();
778            let first = A::from_lean(first);
779            (first, B::from_lean(second))
780        }
781    }
782}
783
784/// Lean's `Except ε α` as a `Result`. Lean names the error type first, Rust the value type.
785pub struct Except<E, A>(PhantomData<(E, A)>);
786
787impl<E: Codec, A: Codec> Except<E, A> {
788    /// `Except.error` is constructor 0 and `Except.ok` constructor 1, each with one field.
789    fn with(tag: u32, field: Obj) -> Value<Self> {
790        unsafe {
791            let object = o::alloc_ctor(tag, 1, 0, 0);
792            o::ctor_set(object, 0, field);
793            Value::from_raw(object)
794        }
795    }
796}
797
798impl<E: Codec, A: Codec> Codec for Except<E, A> {
799    type Rust = Result<A::Rust, E::Rust>;
800    type Repr = Obj;
801
802    fn into_lean(value: Self::Rust) -> Value<Self> {
803        match value {
804            Err(error) => Self::with(0, E::into_lean(error).into_object()),
805            Ok(value) => Self::with(1, A::into_lean(value).into_object()),
806        }
807    }
808
809    fn to_lean(value: &Self::Rust) -> Value<Self> {
810        match value {
811            Err(error) => Self::with(0, E::to_lean(error).into_object()),
812            Ok(value) => Self::with(1, A::to_lean(value).into_object()),
813        }
814    }
815
816    fn from_lean(value: Value<Self>) -> Self::Rust {
817        let object = value.into_raw();
818        unsafe {
819            let ok = o::obj_tag(object) == 1;
820            let fields = Fields::of(object);
821            if ok {
822                let field = fields.object::<A>(0);
823                fields.done();
824                Ok(A::from_lean(field))
825            } else {
826                let field = fields.object::<E>(0);
827                fields.done();
828                Err(E::from_lean(field))
829            }
830        }
831    }
832}
833
834/// A value that the Rust type keeps in a `Box`, as recursive types must.
835pub struct Boxed<C>(PhantomData<C>);
836
837impl<C: Codec> Codec for Boxed<C> {
838    type Rust = Box<C::Rust>;
839    type Repr = C::Repr;
840
841    fn into_lean(value: Self::Rust) -> Value<Self> {
842        unsafe { C::into_lean(*value).cast() }
843    }
844
845    fn to_lean(value: &Self::Rust) -> Value<Self> {
846        unsafe { C::to_lean(value).cast() }
847    }
848
849    fn from_lean(value: Value<Self>) -> Self::Rust {
850        Box::new(C::from_lean(unsafe { value.cast() }))
851    }
852}
853
854/// A type the block declares `opaque`. Lean cannot look inside a value of it or make one, so
855/// nothing is converted: the value is the Rust value itself, in an object. It moves into Lean
856/// and moves back out. A value the caller keeps is cloned, and so is one that Lean still
857/// holds somewhere else when it comes out, which is why the type must be `Clone`.
858pub struct Opaque<T>(PhantomData<T>);
859
860impl<T: Clone + 'static> Codec for Opaque<T> {
861    type Rust = T;
862    type Repr = Obj;
863
864    fn into_lean(value: T) -> Value<Self> {
865        unsafe { Value::from_raw(o::hold_external(value)) }
866    }
867
868    fn to_lean(value: &T) -> Value<Self> {
869        Self::into_lean(value.clone())
870    }
871
872    unsafe fn lent(value: &T) -> Value<Self> {
873        Value::from_raw(o::lend_external(value))
874    }
875
876    fn from_lean(value: Value<Self>) -> T {
877        unsafe {
878            // A value that is only lent to the object is not the object's to give.
879            if o::is_exclusive(value.as_raw()) && !o::is_lent(value.as_raw()) {
880                o::take_external(value.into_raw())
881            } else {
882                // The reference is given up when `value` goes out of scope, also if the
883                // clone panics.
884                o::external::<T>(value.as_raw()).clone()
885            }
886        }
887    }
888
889    fn lend<R>(value: &Value<Self>, f: impl FnOnce(&T) -> R) -> R {
890        f(unsafe { o::external::<T>(value.as_raw()) })
891    }
892}
893
894/// `limbs` padded with zeros to `N` limbs, or `None` when there are more.
895pub(crate) fn fixed_limbs<const N: usize>(limbs: &[u64]) -> core::option::Option<[u64; N]> {
896    let mut out = [0u64; N];
897    out.get_mut(..limbs.len())?.copy_from_slice(limbs);
898    Some(out)
899}
900
901/// A Rust type that holds exactly the values of a `BitVec w`: an unsigned integer of `w`
902/// bits, or `w / 64` limbs with the least significant first.
903pub trait Word: Copy {
904    #[doc(hidden)]
905    fn to_nat(self) -> Obj;
906
907    /// # Safety
908    /// `nat` must be a `Nat` of this runtime that is below 2^w.
909    #[doc(hidden)]
910    unsafe fn of_nat(nat: Obj) -> Self;
911}
912
913macro_rules! words {
914    ($($ty:ty),*) => {$(
915        impl Word for $ty {
916            fn to_nat(self) -> Obj {
917                crate::nat::uint64_to_nat(self as u64)
918            }
919
920            unsafe fn of_nat(nat: Obj) -> $ty {
921                crate::nat::with_limbs(nat, |limbs| limbs.first().copied().unwrap_or(0)) as $ty
922            }
923        }
924    )*};
925}
926
927words!(u8, u16, u32, u64);
928
929impl Word for u128 {
930    fn to_nat(self) -> Obj {
931        crate::nat::of_u128(self)
932    }
933
934    unsafe fn of_nat(nat: Obj) -> u128 {
935        let [low, high] = <[u64; 2]>::of_nat(nat);
936        (high as u128) << 64 | low as u128
937    }
938}
939
940impl<const N: usize> Word for [u64; N] {
941    fn to_nat(self) -> Obj {
942        crate::nat::of_limbs(&self)
943    }
944
945    unsafe fn of_nat(nat: Obj) -> [u64; N] {
946        match crate::nat::with_limbs(nat, fixed_limbs) {
947            Some(limbs) => limbs,
948            None => panic!("inlean: Lean returned a BitVec wider than its type"),
949        }
950    }
951}
952
953/// Lean's `BitVec w` as the unsigned integer or the limbs `W`. Lean keeps a bit vector as the
954/// natural number it encodes, so a value crosses with one copy of its limbs, and one that is
955/// below 2^63 without an allocation.
956pub struct BitVec<W>(PhantomData<W>);
957
958impl<W: Word> Codec for BitVec<W> {
959    type Rust = W;
960    type Repr = Obj;
961
962    fn into_lean(value: W) -> Value<Self> {
963        unsafe { Value::from_raw(value.to_nat()) }
964    }
965
966    fn to_lean(value: &W) -> Value<Self> {
967        Self::into_lean(*value)
968    }
969
970    fn from_lean(value: Value<Self>) -> W {
971        // The number is released when `value` goes out of scope.
972        unsafe { W::of_nat(value.as_raw()) }
973    }
974}
975
976/// A primitive type of your own: a Rust type of your choice in place of the one inlean gives
977/// a Lean type.
978///
979/// Signatures and generated types then use [`Primitive::Rust`], with no conversion left to
980/// the caller. The trait is implemented for a marker type, so the Rust type can come from any
981/// crate. To have a 256-bit integer of a library stand for `BitVec 256`:
982///
983/// ```
984/// # #[derive(Clone, Copy)] pub struct U256([u64; 4]);
985/// pub struct U256Primitive;
986///
987/// impl inlean_runtime::Primitive for U256Primitive {
988///     type Lean = [u64; 4]; // what inlean uses for `BitVec 256`
989///     type Rust = U256;
990///
991///     fn to_lean(value: &U256) -> [u64; 4] {
992///         value.0
993///     }
994///
995///     fn from_lean(limbs: [u64; 4]) -> U256 {
996///         U256(limbs)
997///     }
998/// }
999/// ```
1000///
1001/// and name the marker in `Cargo.toml`, by a path that starts with `crate::` or `::`:
1002///
1003/// ```toml
1004/// [package.metadata.inlean.types]
1005/// "BitVec 256" = "crate::U256Primitive"
1006/// ```
1007///
1008/// Both functions must be total, and a value that goes to Lean and comes back must be the
1009/// same value: a function written in Lean is proved for every value of its Lean types, and
1010/// that is only worth something if every Rust value is one of them.
1011pub trait Primitive {
1012    /// The Rust type inlean gives the Lean type by default.
1013    type Lean;
1014    /// The type to use instead.
1015    type Rust;
1016
1017    /// The default type's value of a value that stays with the caller.
1018    fn to_lean(value: &Self::Rust) -> Self::Lean;
1019
1020    /// The default type's value of a value that is given up. Implement it when the value
1021    /// owns something that can move into the result, such as a buffer; the default copies.
1022    fn into_lean(value: Self::Rust) -> Self::Lean {
1023        Self::to_lean(&value)
1024    }
1025
1026    fn from_lean(value: Self::Lean) -> Self::Rust;
1027}
1028
1029/// The Lean type of codec `C` as the Rust type the primitive `P` chose.
1030pub struct Via<C, P>(PhantomData<(C, P)>);
1031
1032impl<C: Codec, P: Primitive<Lean = C::Rust>> Codec for Via<C, P> {
1033    type Rust = P::Rust;
1034    type Repr = C::Repr;
1035
1036    fn into_lean(value: P::Rust) -> Value<Self> {
1037        unsafe { C::into_lean(P::into_lean(value)).cast() }
1038    }
1039
1040    fn to_lean(value: &P::Rust) -> Value<Self> {
1041        // The default type's value is ours, so it moves into Lean.
1042        unsafe { C::into_lean(P::to_lean(value)).cast() }
1043    }
1044
1045    fn from_lean(value: Value<Self>) -> P::Rust {
1046        P::from_lean(C::from_lean(unsafe { value.cast() }))
1047    }
1048}
1049
1050/// An argument of type `T` for a function written in Lean: the value itself, which moves
1051/// into Lean, or a reference to it. A reference to a value that Lean converts, such as a
1052/// `String`, is copied. A reference to a value that Lean holds as it is, of an opaque or a
1053/// foreign type or a collection of `import Inlean`, is lent for the call: Lean reads the
1054/// caller's value, and clones it only where it needs one of its own.
1055///
1056/// A value may also come in what holds it: a `Box`, a reference to a `Box`, an `Rc` or an
1057/// `Arc`, or a `Cow`. A `String` also takes a `&str`, and a `Vec<T>` a slice or an array of
1058/// `T`.
1059///
1060/// ```
1061/// # fn shout(text: impl inlean_runtime::Pass<String>) {}
1062/// let name = String::from("ada");
1063/// shout(&name);  // copied: a `String` is converted
1064/// shout("ada");  // copied
1065/// shout(name);   // moved: Lean's string is this buffer
1066/// ```
1067pub trait Pass<T>: Sized {
1068    /// The Lean value of the argument under the codec the function names.
1069    #[doc(hidden)]
1070    fn pass<C: Codec<Rust = T>>(self) -> Value<C>;
1071
1072    /// The same for an exported function, which holds the argument for as long as Lean runs.
1073    /// A reference is then lent where the codec can lend: the Lean value stands for what the
1074    /// reference points at, and nothing is copied until Lean needs a value of its own.
1075    ///
1076    /// # Safety
1077    /// The value returned, and every reference Lean takes to it, is given up before the
1078    /// argument's borrow ends.
1079    #[doc(hidden)]
1080    #[inline]
1081    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
1082        self.pass()
1083    }
1084}
1085
1086impl<T> Pass<T> for T {
1087    #[inline]
1088    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1089        C::into_lean(self)
1090    }
1091}
1092
1093impl<T> Pass<T> for &T {
1094    #[inline]
1095    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1096        C::to_lean(self)
1097    }
1098
1099    #[inline]
1100    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
1101        C::lent(self)
1102    }
1103}
1104
1105impl Pass<std::string::String> for &str {
1106    #[inline]
1107    fn pass<C: Codec<Rust = std::string::String>>(self) -> Value<C> {
1108        C::into_lean(self.to_owned())
1109    }
1110}
1111
1112impl<T: Clone> Pass<Vec<T>> for &[T] {
1113    #[inline]
1114    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
1115        C::into_lean(self.to_vec())
1116    }
1117}
1118
1119impl<T: Clone, const N: usize> Pass<Vec<T>> for &[T; N] {
1120    #[inline]
1121    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
1122        C::into_lean(self.to_vec())
1123    }
1124}
1125
1126impl<T, const N: usize> Pass<Vec<T>> for [T; N] {
1127    #[inline]
1128    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
1129        C::into_lean(Vec::from(self))
1130    }
1131}
1132
1133impl<T> Pass<T> for Box<T> {
1134    #[inline]
1135    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1136        C::into_lean(*self)
1137    }
1138}
1139
1140impl<T> Pass<T> for &Box<T> {
1141    #[inline]
1142    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1143        C::to_lean(self)
1144    }
1145
1146    #[inline]
1147    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
1148        C::lent(self)
1149    }
1150}
1151
1152impl<T> Pass<T> for &std::rc::Rc<T> {
1153    #[inline]
1154    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1155        C::to_lean(self)
1156    }
1157
1158    #[inline]
1159    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
1160        C::lent(self)
1161    }
1162}
1163
1164impl<T> Pass<T> for &std::sync::Arc<T> {
1165    #[inline]
1166    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1167        C::to_lean(self)
1168    }
1169
1170    #[inline]
1171    unsafe fn lend<C: Codec<Rust = T>>(self) -> Value<C> {
1172        C::lent(self)
1173    }
1174}
1175
1176impl<T: Clone> Pass<T> for std::borrow::Cow<'_, T> {
1177    #[inline]
1178    fn pass<C: Codec<Rust = T>>(self) -> Value<C> {
1179        C::into_lean(self.into_owned())
1180    }
1181}
1182
1183impl Pass<std::string::String> for std::borrow::Cow<'_, str> {
1184    #[inline]
1185    fn pass<C: Codec<Rust = std::string::String>>(self) -> Value<C> {
1186        C::into_lean(self.into_owned())
1187    }
1188}
1189
1190impl<T: Clone> Pass<Vec<T>> for std::borrow::Cow<'_, [T]> {
1191    #[inline]
1192    fn pass<C: Codec<Rust = Vec<T>>>(self) -> Value<C> {
1193        C::into_lean(self.into_owned())
1194    }
1195}