Skip to main content

inlean_runtime/
object.rs

1//! Lean's heap objects: the representation, reference counting, constructor objects,
2//! boxing and closures.
3//!
4//! A value of a Lean type that is not an unboxed scalar is an [`Obj`]: either a pointer to a
5//! heap object that starts with a [`Header`], or a number stored in the pointer bits with the
6//! lowest bit set. The functions here are the ones generated code calls, with the semantics
7//! of the functions of the same names in Lean's `lean.h`. They are `unsafe` in the same way:
8//! the caller, which is code Lean's compiler produced, owns the reference counting.
9
10use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
11use std::cell::Cell;
12use std::mem::size_of;
13use std::sync::OnceLock;
14
15/// Largest tag of a constructor object. Larger tags are the kinds below.
16pub const MAX_CTOR_TAG: u8 = 243;
17pub const TAG_CLOSURE: u8 = 245;
18pub const TAG_ARRAY: u8 = 246;
19pub const TAG_SARRAY: u8 = 248;
20pub const TAG_STRING: u8 = 249;
21pub const TAG_MPZ: u8 = 250;
22/// An object that stands for an external value without holding it: see `Lent`. Lean uses this
23/// tag for a reference cell, which this runtime has no primitive to make.
24pub const TAG_LENT: u8 = 253;
25/// A value of a type the runtime does not know. Lean uses this tag for the same purpose.
26pub const TAG_EXTERNAL: u8 = 254;
27
28/// Most arguments a closure's function takes as separate parameters.
29pub const CLOSURE_MAX_ARGS: usize = 16;
30
31/// What every heap object starts with.
32#[repr(C)]
33pub struct Header {
34    /// Positive: the number of references, owned by one thread. Zero: the object is
35    /// persistent, lives forever, and is never counted or mutated.
36    rc: Cell<i32>,
37    /// For a constructor object, its size in bytes.
38    size: u16,
39    /// For a constructor object, the number of object fields.
40    other: u8,
41    tag: u8,
42}
43
44const WORD: usize = size_of::<usize>();
45const HEADER: usize = size_of::<Header>();
46/// The alignment of every block an object is made in.
47const BLOCK_ALIGN: usize = if WORD > 8 { WORD } else { 8 };
48
49/// A Lean value that is not an unboxed scalar.
50#[derive(Clone, Copy, PartialEq, Eq, Debug)]
51#[repr(transparent)]
52pub struct Obj(*mut Header);
53
54/// A number in the pointer bits. `n` must fit in a word minus one bit.
55#[inline(always)]
56pub fn box_(n: usize) -> Obj {
57    Obj(std::ptr::without_provenance_mut((n << 1) | 1))
58}
59
60#[inline(always)]
61pub fn unbox(o: Obj) -> usize {
62    o.0.addr() >> 1
63}
64
65#[inline(always)]
66pub fn is_scalar(o: Obj) -> bool {
67    o.0.addr() & 1 == 1
68}
69
70impl Obj {
71    #[inline(always)]
72    pub(crate) fn from_header(header: *mut Header) -> Obj {
73        Obj(header)
74    }
75
76    #[inline(always)]
77    pub(crate) fn header(self) -> *mut Header {
78        self.0
79    }
80}
81
82impl Header {
83    /// The kind-specific byte of the header.
84    pub(crate) fn other(&self) -> u8 {
85        self.other
86    }
87}
88
89pub(crate) fn new_header(tag: u8, other: u8, size: u16) -> Header {
90    Header { rc: Cell::new(1), size, other, tag }
91}
92
93#[inline(always)]
94unsafe fn rc(o: Obj) -> &'static Cell<i32> {
95    &(*o.0).rc
96}
97
98/// The kind of a heap object.
99#[inline(always)]
100pub unsafe fn ptr_tag(o: Obj) -> u8 {
101    (*o.0).tag
102}
103
104/// The constructor index of a value of an inductive type.
105#[inline(always)]
106pub unsafe fn obj_tag(o: Obj) -> u32 {
107    if is_scalar(o) {
108        unbox(o) as u32
109    } else {
110        ptr_tag(o) as u32
111    }
112}
113
114#[inline(always)]
115pub unsafe fn inc_ref(o: Obj) {
116    let count = rc(o);
117    if count.get() > 0 {
118        count.set(count.get() + 1);
119    }
120}
121
122#[inline(always)]
123pub unsafe fn inc_ref_n(o: Obj, n: u32) {
124    let count = rc(o);
125    if count.get() > 0 {
126        count.set(count.get() + n as i32);
127    }
128}
129
130#[inline(always)]
131pub unsafe fn inc(o: Obj) {
132    if !is_scalar(o) {
133        inc_ref(o);
134    }
135}
136
137#[inline(always)]
138pub unsafe fn inc_n(o: Obj, n: u32) {
139    if !is_scalar(o) {
140        inc_ref_n(o, n);
141    }
142}
143
144#[inline(always)]
145pub unsafe fn dec_ref(o: Obj) {
146    let count = rc(o);
147    if count.get() > 1 {
148        count.set(count.get() - 1);
149    } else if count.get() == 1 {
150        free(o);
151    }
152}
153
154#[inline(always)]
155pub unsafe fn dec(o: Obj) {
156    if !is_scalar(o) {
157        dec_ref(o);
158    }
159}
160
161/// Whether this is the only reference to the object, so that it may be updated in place.
162#[inline(always)]
163pub unsafe fn is_exclusive(o: Obj) -> bool {
164    !is_scalar(o) && rc(o).get() == 1
165}
166
167/// Whether the object is one that is never counted and never freed: a constant, or part of
168/// one. Nothing writes to such an object, so any thread may read it.
169#[inline(always)]
170pub(crate) unsafe fn is_persistent(o: Obj) -> bool {
171    !is_scalar(o) && rc(o).get() == 0
172}
173
174thread_local! {
175    static LIVE: Cell<isize> = const { Cell::new(0) };
176}
177
178/// Notes that a heap object was created (`1`) or freed (`-1`) on this thread.
179#[inline(always)]
180pub(crate) fn count_object(change: isize) {
181    if cfg!(debug_assertions) {
182        LIVE.with(|live| live.set(live.get() + change));
183    }
184}
185
186/// The number of heap objects this thread created and has not freed, for finding leaks in
187/// tests. Persistent objects, which are never freed, count. Always zero in a release build.
188pub fn live_objects() -> isize {
189    LIVE.with(Cell::get)
190}
191
192/// Objects of up to this many bytes are recycled through [`Pool`].
193const POOLED: usize = 128;
194const GRAIN: usize = 8;
195
196/// The freed small objects of this thread, by size, each list threaded through the first
197/// word of its blocks. Lean code allocates and frees small objects at a high rate, and a
198/// list makes both a few instructions. A list is only touched by its own thread, so no lock
199/// is needed. An object can be freed on another thread than the one that made it, when a
200/// `Nat` or an `Int` is sent there: its block then joins that thread's lists, which is sound
201/// because every block is an allocation of its own.
202struct Pool {
203    free: [Cell<*mut u8>; POOLED / GRAIN],
204    /// Set once the thread has arranged for the lists to be emptied when it ends.
205    guarded: Cell<bool>,
206    /// Set when the thread is ending and the lists have gone back to the system.
207    closed: Cell<bool>,
208}
209
210/// Returns the blocks of the pool to the system at the end of the thread. It is apart from
211/// the pool so that the pool itself needs no destructor, which would cost a check on every
212/// allocation.
213struct PoolGuard;
214
215impl Drop for PoolGuard {
216    fn drop(&mut self) {
217        POOL.with(|pool| {
218            pool.closed.set(true);
219            for (class, list) in pool.free.iter().enumerate() {
220                let mut block = list.replace(std::ptr::null_mut());
221                while !block.is_null() {
222                    unsafe {
223                        let next = block.cast::<*mut u8>().read();
224                        dealloc(block, Layout::from_size_align_unchecked((class + 1) * GRAIN, BLOCK_ALIGN));
225                        block = next;
226                    }
227                }
228            }
229        });
230    }
231}
232
233thread_local! {
234    static POOL: Pool = const {
235        Pool {
236            free: [const { Cell::new(std::ptr::null_mut()) }; POOLED / GRAIN],
237            guarded: Cell::new(false),
238            closed: Cell::new(false),
239        }
240    };
241    static POOL_GUARD: PoolGuard = const { PoolGuard };
242}
243
244/// The layout of a block for an object of `size` bytes, and its list in the pool if it is
245/// small enough for one.
246#[inline(always)]
247fn block(size: usize) -> (Layout, Option<usize>) {
248    let size = size.next_multiple_of(GRAIN).max(GRAIN);
249    let layout = unsafe { Layout::from_size_align_unchecked(size, BLOCK_ALIGN) };
250    (layout, (size <= POOLED).then(|| size / GRAIN - 1))
251}
252
253/// Arranges for this thread's pool to be emptied when the thread ends, and says whether it
254/// could: a thread that is ending already has no one left to empty it.
255#[cold]
256fn guard_pool(pool: &Pool) -> bool {
257    let guarded = POOL_GUARD.try_with(|_| ()).is_ok();
258    pool.guarded.set(guarded);
259    guarded
260}
261
262/// A block from the system. The first one a thread takes arranges for its pool to be
263/// emptied when the thread ends.
264#[cold]
265unsafe fn allocate_fresh(layout: Layout) -> *mut u8 {
266    POOL.with(|pool| {
267        guard_pool(pool);
268    });
269    let memory = alloc(layout);
270    if memory.is_null() {
271        handle_alloc_error(layout);
272    }
273    memory
274}
275
276#[inline]
277pub(crate) unsafe fn allocate(size: usize) -> *mut Header {
278    count_object(1);
279    let (layout, class) = block(size);
280    if let Some(class) = class {
281        let recycled = POOL.with(|pool| {
282            let block = pool.free[class].get();
283            if !block.is_null() {
284                pool.free[class].set(block.cast::<*mut u8>().read());
285            }
286            block
287        });
288        if !recycled.is_null() {
289            return recycled.cast();
290        }
291    }
292    allocate_fresh(layout).cast()
293}
294
295#[inline]
296pub(crate) unsafe fn deallocate(header: *mut Header, size: usize) {
297    count_object(-1);
298    let (layout, class) = block(size);
299    let memory = header.cast::<u8>();
300    let pooled = class.is_some_and(|class| {
301        POOL.with(|pool| {
302            if pool.closed.get() {
303                return false;
304            }
305            // A thread that only frees what others made has a pool to empty as well. If it
306            // is too late to arrange that, the block goes back to the system now.
307            if !pool.guarded.get() && !guard_pool(pool) {
308                return false;
309            }
310            memory.cast::<*mut u8>().write(pool.free[class].get());
311            pool.free[class].set(memory);
312            true
313        })
314    });
315    if !pooled {
316        dealloc(memory, layout);
317    }
318}
319
320// Held values: a Rust value inside a Lean object. A string is a `String` in an object, an
321// array a `Vec` of objects, and so on; what differs between them is only the value.
322
323/// A Rust value that a Lean object can hold. Lean shares objects freely, so a holder that
324/// wants a value of its own, to change it or to take it away, may have to copy it.
325pub(crate) trait Hold: Sized {
326    /// The kind of the objects that hold a value of this type.
327    const TAG: u8;
328    /// The kind-specific byte of their headers.
329    const OTHER: u8 = 0;
330
331    /// A value equal to this one, for another holder. A value that refers to Lean objects
332    /// takes a reference to each of them.
333    unsafe fn copy(&self) -> Self;
334}
335
336/// A value in a Lean object: what every object starts with, then the value. The order of
337/// the fields is fixed so that a pointer to the object is a pointer to its header.
338#[repr(C)]
339struct Held<T> {
340    header: Header,
341    value: T,
342}
343
344/// Whether an object that holds a `T` fits the blocks of [`allocate`], which are aligned
345/// for a word. A type that needs more, such as one with a `u128` in it, gets a block of its
346/// own from the system.
347const fn fits_blocks<T>() -> bool {
348    align_of::<Held<T>>() <= BLOCK_ALIGN
349}
350
351/// A new object that holds `value`.
352pub(crate) fn hold<T: Hold>(value: T) -> Obj {
353    unsafe {
354        let held = if fits_blocks::<T>() {
355            allocate(size_of::<Held<T>>()).cast::<Held<T>>()
356        } else {
357            count_object(1);
358            let layout = Layout::new::<Held<T>>();
359            let memory = alloc(layout);
360            if memory.is_null() {
361                handle_alloc_error(layout);
362            }
363            memory.cast::<Held<T>>()
364        };
365        held.write(Held { header: new_header(T::TAG, T::OTHER, 0), value });
366        Obj(held.cast())
367    }
368}
369
370/// The value an object holds.
371#[inline(always)]
372pub(crate) unsafe fn held<'a, T: Hold>(o: Obj) -> &'a T {
373    &(*o.0.cast::<Held<T>>()).value
374}
375
376/// The value out of an object nothing else refers to. Gives up the object, and leaves what
377/// the value refers to with the value.
378pub(crate) unsafe fn take_held<T: Hold>(o: Obj) -> T {
379    let held = o.0.cast::<Held<T>>();
380    let value = std::ptr::addr_of!((*held).value).read();
381    if fits_blocks::<T>() {
382        deallocate(o.0, size_of::<Held<T>>());
383    } else {
384        count_object(-1);
385        dealloc(o.0.cast(), Layout::new::<Held<T>>());
386    }
387    value
388}
389
390/// The value of an object the caller owns, for changing in place: `o` itself if nothing
391/// else refers to it, and otherwise a copy, with the reference to `o` given up.
392pub(crate) unsafe fn held_mut<'a, T: Hold>(o: Obj) -> (Obj, &'a mut T) {
393    let o = if is_exclusive(o) {
394        o
395    } else {
396        let copy = hold(held::<T>(o).copy());
397        dec_ref(o);
398        copy
399    };
400    (o, &mut (*o.0.cast::<Held<T>>()).value)
401}
402
403/// The value an object holds, giving up one reference to the object: the value itself if
404/// nothing else refers to the object, and a copy otherwise.
405pub(crate) unsafe fn into_held<T: Hold>(o: Obj) -> T {
406    if is_exclusive(o) {
407        return take_held(o);
408    }
409    let copy = held::<T>(o).copy();
410    dec_ref(o);
411    copy
412}
413
414// External values: a value of a type the runtime does not know, such as the Rust type a
415// crate names for an opaque Lean type. Lean never looks inside one. It only shares the
416// object and gives it up, so all the runtime has to know is how to free it.
417
418/// What the runtime knows about the type of an external value.
419pub(crate) struct Class {
420    /// Frees an object that holds a value of the type, and drops the value.
421    free: unsafe fn(Obj),
422}
423
424/// An external value as an object holds it: with its class first, so that the class is
425/// found without knowing the type.
426#[repr(C)]
427struct External<T> {
428    class: &'static Class,
429    value: T,
430}
431
432impl<T: Clone + 'static> External<T> {
433    const CLASS: &'static Class = &Class { free: free_external::<T> };
434}
435
436impl<T: Clone + 'static> Hold for External<T> {
437    const TAG: u8 = TAG_EXTERNAL;
438    /// Where the class is in the object, which depends on the alignment of the value.
439    const OTHER: u8 = {
440        let offset = std::mem::offset_of!(Held<External<T>>, value);
441        assert!(offset <= u8::MAX as usize, "inlean: an external type is aligned to more than a header can say");
442        offset as u8
443    };
444
445    unsafe fn copy(&self) -> External<T> {
446        External { class: self.class, value: self.value.clone() }
447    }
448}
449
450unsafe fn free_external<T: Clone + 'static>(o: Obj) {
451    drop(take_held::<External<T>>(o));
452}
453
454/// A new object that holds the external value `value`.
455pub(crate) fn hold_external<T: Clone + 'static>(value: T) -> Obj {
456    hold(External { class: External::<T>::CLASS, value })
457}
458
459/// An external value that an object stands for without holding it: the address of a value
460/// that belongs to the caller of an exported function, who lends it for the call.
461///
462/// Lean treats the object as it treats any external value: it shares it and gives it up. What
463/// it must never do is take the value out, since the value is not the object's to give. So the
464/// two places that read an external value look at the kind of the object first, and freeing
465/// the object frees only the object.
466struct Lent(*const ());
467
468impl Hold for Lent {
469    const TAG: u8 = TAG_LENT;
470
471    unsafe fn copy(&self) -> Lent {
472        Lent(self.0)
473    }
474}
475
476/// A new object that stands for `value` while the caller's borrow of it lasts.
477///
478/// # Safety
479/// Every reference to the object is given up before the borrow of `value` ends. An exported
480/// function meets this by converting what Lean returns before it returns itself: a value
481/// that comes back out is a clone, and Lean keeps nothing from one call to the next but
482/// constants, which cannot depend on an argument.
483pub(crate) unsafe fn lend_external<T: Clone + 'static>(value: &T) -> Obj {
484    hold(Lent(std::ptr::from_ref(value).cast()))
485}
486
487/// Whether the object stands for a value that is lent to it, which must not be taken out.
488///
489/// # Safety
490/// `o` is an object, not a scalar.
491#[inline(always)]
492pub(crate) unsafe fn is_lent(o: Obj) -> bool {
493    ptr_tag(o) == TAG_LENT
494}
495
496/// The external value an object holds or stands for.
497///
498/// # Safety
499/// `o` was made by [`hold_external`] or [`lend_external`] for a value of type `T`.
500pub(crate) unsafe fn external<'a, T: Clone + 'static>(o: Obj) -> &'a T {
501    if is_lent(o) {
502        return &*held::<Lent>(o).0.cast::<T>();
503    }
504    &held::<External<T>>(o).value
505}
506
507/// The external value out of an object nothing else refers to. Gives up the object.
508///
509/// # Safety
510/// `o` was made by [`hold_external`] for a value of type `T`, and the caller owns the only
511/// reference to it.
512pub(crate) unsafe fn take_external<T: Clone + 'static>(o: Obj) -> T {
513    take_held::<External<T>>(o).value
514}
515
516/// Frees an object that holds an external value of whatever type.
517unsafe fn free_any_external(o: Obj) {
518    let class = o.0.cast::<u8>().add((*o.0).other as usize).cast::<&'static Class>().read();
519    (class.free)(o);
520}
521
522/// The objects an object refers to.
523unsafe fn children(o: Obj) -> &'static [Obj] {
524    match ptr_tag(o) {
525        tag if tag <= MAX_CTOR_TAG => std::slice::from_raw_parts(ctor_fields(o), (*o.0).other as usize),
526        TAG_CLOSURE => {
527            let closure = o.0.cast::<Closure>();
528            std::slice::from_raw_parts(closure_args(o), (*closure).num_fixed as usize)
529        }
530        TAG_ARRAY => crate::array::elements(o),
531        _ => &[],
532    }
533}
534
535/// Releases the memory of an object without touching the objects it refers to.
536pub unsafe fn free_object(o: Obj) {
537    if is_scalar(o) {
538        return;
539    }
540    match ptr_tag(o) {
541        tag if tag <= MAX_CTOR_TAG => deallocate(o.0, (*o.0).size as usize),
542        TAG_CLOSURE => {
543            let closure = o.0.cast::<Closure>();
544            deallocate(o.0, closure_size((*closure).num_fixed as usize));
545        }
546        TAG_ARRAY => crate::array::free(o),
547        TAG_SARRAY => crate::sarray::free(o),
548        TAG_STRING => crate::string::free(o),
549        TAG_MPZ => crate::nat::free_big(o),
550        TAG_EXTERNAL => free_any_external(o),
551        TAG_LENT => deallocate(o.0, size_of::<Held<Lent>>()),
552        tag => unreachable!("inlean: object of unknown kind {tag}"),
553    }
554}
555
556/// Frees an object whose last reference is gone, and everything only it kept alive. The
557/// work list is on the heap, so a long list does not overflow the stack.
558unsafe fn free(o: Obj) {
559    if ptr_tag(o) == TAG_MPZ {
560        // A number refers to nothing, and numbers are what arithmetic frees all the time.
561        return crate::nat::free_big(o);
562    }
563    let mut pending: Vec<Obj> = Vec::new();
564    let mut current = o;
565    loop {
566        for &child in children(current) {
567            if is_scalar(child) {
568                continue;
569            }
570            let count = rc(child);
571            if count.get() > 1 {
572                count.set(count.get() - 1);
573            } else if count.get() == 1 && ptr_tag(child) == TAG_MPZ {
574                crate::nat::free_big(child);
575            } else if count.get() == 1 {
576                pending.push(child);
577            }
578        }
579        free_object(current);
580        match pending.pop() {
581            Some(next) => current = next,
582            None => return,
583        }
584    }
585}
586
587/// Makes an object and everything it refers to persistent: never counted, never freed,
588/// never updated in place, and therefore safe to read from any thread.
589pub unsafe fn mark_persistent(o: Obj) {
590    let mut pending = vec![o];
591    while let Some(current) = pending.pop() {
592        if is_scalar(current) || rc(current).get() == 0 {
593            continue;
594        }
595        rc(current).set(0);
596        pending.extend_from_slice(children(current));
597    }
598}
599
600// Constructor objects: header, object fields, then `usize` fields, then other scalars.
601
602#[inline(always)]
603unsafe fn ctor_fields(o: Obj) -> *mut Obj {
604    o.0.cast::<u8>().add(HEADER).cast()
605}
606
607/// A constructor object with `num_objs` object fields, `num_usize` word-sized scalar fields
608/// and `scalar_size` bytes of other scalar fields, all uninitialized.
609pub unsafe fn alloc_ctor(tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32) -> Obj {
610    let size = HEADER + (num_objs + num_usize) as usize * WORD + scalar_size as usize;
611    let size = size.next_multiple_of(WORD.max(8));
612    let header = allocate(size);
613    header.write(new_header(tag as u8, num_objs as u8, size as u16));
614    Obj(header)
615}
616
617#[inline(always)]
618pub unsafe fn ctor_get(o: Obj, i: u32) -> Obj {
619    *ctor_fields(o).add(i as usize)
620}
621
622#[inline(always)]
623pub unsafe fn ctor_set(o: Obj, i: u32, value: Obj) {
624    *ctor_fields(o).add(i as usize) = value;
625}
626
627#[inline(always)]
628pub unsafe fn ctor_set_tag(o: Obj, tag: u32) {
629    (*o.0).tag = tag as u8;
630}
631
632/// Drops field `i` of a constructor object that is about to be reused.
633#[inline(always)]
634pub unsafe fn ctor_release(o: Obj, i: u32) {
635    let field = ctor_fields(o).add(i as usize);
636    dec(*field);
637    // The object may still be freed instead of reused; the field must not be dropped twice.
638    *field = box_(0);
639}
640
641/// Prepares constructor object `o`, which has `num_objs` object fields, for reuse: returns
642/// its memory if nothing else refers to it, and otherwise drops the reference and returns
643/// `box_(0)`.
644pub unsafe fn reset(o: Obj, num_objs: u32) -> Obj {
645    if is_exclusive(o) {
646        for i in 0..num_objs {
647            ctor_release(o, i);
648        }
649        o
650    } else {
651        dec_ref(o);
652        box_(0)
653    }
654}
655
656/// A constructor object for the given constructor, in the memory `reset` returned if it
657/// returned any.
658pub unsafe fn reuse(memory: Obj, tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32, update_tag: bool) -> Obj {
659    if is_scalar(memory) {
660        alloc_ctor(tag, num_objs, num_usize, scalar_size)
661    } else {
662        if update_tag {
663            ctor_set_tag(memory, tag);
664        }
665        memory
666    }
667}
668
669#[inline(always)]
670pub unsafe fn ctor_get_usize(o: Obj, slot: u32) -> usize {
671    ctor_fields(o).add(slot as usize).cast::<usize>().read()
672}
673
674#[inline(always)]
675pub unsafe fn ctor_set_usize(o: Obj, slot: u32, value: usize) {
676    ctor_fields(o).add(slot as usize).cast::<usize>().write(value);
677}
678
679macro_rules! ctor_scalars {
680    ($($get:ident $set:ident $ty:ty),*) => {$(
681        /// Reads the scalar `offset` bytes after the first `slots` word-sized fields.
682        #[inline(always)]
683        pub unsafe fn $get(o: Obj, slots: u32, offset: u32) -> $ty {
684            ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().read_unaligned()
685        }
686
687        /// Writes the scalar `offset` bytes after the first `slots` word-sized fields.
688        #[inline(always)]
689        pub unsafe fn $set(o: Obj, slots: u32, offset: u32, value: $ty) {
690            ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().write_unaligned(value);
691        }
692    )*};
693}
694
695ctor_scalars!(
696    ctor_get_uint8 ctor_set_uint8 u8,
697    ctor_get_uint16 ctor_set_uint16 u16,
698    ctor_get_uint32 ctor_set_uint32 u32,
699    ctor_get_uint64 ctor_set_uint64 u64,
700    ctor_get_float ctor_set_float f64,
701    ctor_get_float32 ctor_set_float32 f32
702);
703
704// Boxing: a scalar where an object is expected, as in a field of a polymorphic structure.
705
706/// A `u32` fits in the pointer bits of a 64-bit target only.
707#[inline(always)]
708pub unsafe fn box_uint32(value: u32) -> Obj {
709    if WORD == 4 {
710        let o = alloc_ctor(0, 0, 0, 4);
711        ctor_set_uint32(o, 0, 0, value);
712        o
713    } else {
714        box_(value as usize)
715    }
716}
717
718#[inline(always)]
719pub unsafe fn unbox_uint32(o: Obj) -> u32 {
720    if WORD == 4 {
721        ctor_get_uint32(o, 0, 0)
722    } else {
723        unbox(o) as u32
724    }
725}
726
727pub unsafe fn box_uint64(value: u64) -> Obj {
728    let o = alloc_ctor(0, 0, 0, 8);
729    ctor_set_uint64(o, 0, 0, value);
730    o
731}
732
733#[inline(always)]
734pub unsafe fn unbox_uint64(o: Obj) -> u64 {
735    ctor_get_uint64(o, 0, 0)
736}
737
738pub unsafe fn box_usize(value: usize) -> Obj {
739    let o = alloc_ctor(0, 0, 1, 0);
740    ctor_set_usize(o, 0, value);
741    o
742}
743
744#[inline(always)]
745pub unsafe fn unbox_usize(o: Obj) -> usize {
746    ctor_get_usize(o, 0)
747}
748
749pub unsafe fn box_float(value: f64) -> Obj {
750    let o = alloc_ctor(0, 0, 0, 8);
751    ctor_set_float(o, 0, 0, value);
752    o
753}
754
755#[inline(always)]
756pub unsafe fn unbox_float(o: Obj) -> f64 {
757    ctor_get_float(o, 0, 0)
758}
759
760pub unsafe fn box_float32(value: f32) -> Obj {
761    let o = alloc_ctor(0, 0, 0, 4);
762    ctor_set_float32(o, 0, 0, value);
763    o
764}
765
766#[inline(always)]
767pub unsafe fn unbox_float32(o: Obj) -> f32 {
768    ctor_get_float32(o, 0, 0)
769}
770
771// Closures: a function and the first `num_fixed` of its `arity` arguments.
772
773#[repr(C)]
774struct Closure {
775    header: Header,
776    /// `unsafe fn(Obj, ..., Obj) -> Obj` with `arity` parameters.
777    function: *const (),
778    arity: u16,
779    num_fixed: u16,
780}
781
782fn closure_size(num_fixed: usize) -> usize {
783    size_of::<Closure>() + num_fixed * WORD
784}
785
786#[inline(always)]
787unsafe fn closure_args(o: Obj) -> *mut Obj {
788    o.0.cast::<u8>().add(size_of::<Closure>()).cast()
789}
790
791/// A closure of `function`, which takes `arity` objects and returns an object, with room
792/// for `num_fixed` arguments that [`closure_set`] must fill.
793pub unsafe fn alloc_closure(function: *const (), arity: u32, num_fixed: u32) -> Obj {
794    let closure = allocate(closure_size(num_fixed as usize)).cast::<Closure>();
795    closure.write(Closure {
796        header: new_header(TAG_CLOSURE, 0, 0),
797        function,
798        arity: arity as u16,
799        num_fixed: num_fixed as u16,
800    });
801    Obj(closure.cast())
802}
803
804#[inline(always)]
805pub unsafe fn closure_set(o: Obj, i: u32, value: Obj) {
806    *closure_args(o).add(i as usize) = value;
807}
808
809unsafe fn call(function: *const (), args: &[Obj]) -> Obj {
810    use std::mem::transmute as cast;
811    type O = Obj;
812    let a = args;
813    match a.len() {
814        1 => cast::<_, unsafe fn(O) -> O>(function)(a[0]),
815        2 => cast::<_, unsafe fn(O, O) -> O>(function)(a[0], a[1]),
816        3 => cast::<_, unsafe fn(O, O, O) -> O>(function)(a[0], a[1], a[2]),
817        4 => cast::<_, unsafe fn(O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3]),
818        5 => cast::<_, unsafe fn(O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4]),
819        6 => cast::<_, unsafe fn(O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5]),
820        7 => cast::<_, unsafe fn(O, O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5], a[6]),
821        8 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]),
822        9 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O) -> O>(function)(
823            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8],
824        ),
825        10 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O) -> O>(function)(
826            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9],
827        ),
828        11 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
829            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10],
830        ),
831        12 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
832            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11],
833        ),
834        13 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
835            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12],
836        ),
837        14 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
838            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13],
839        ),
840        15 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
841            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14],
842        ),
843        16 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O) -> O>(function)(
844            a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
845        ),
846        n => panic!("inlean: a function of {n} arguments cannot be called through a closure"),
847    }
848}
849
850/// Applies closure `f` to `args`. Consumes `f` and the arguments.
851///
852/// With fewer arguments than the function still needs, the result is a new closure. With
853/// more, the function's result is applied to the rest.
854pub unsafe fn apply(f: Obj, args: &[Obj]) -> Obj {
855    let closure = f.0.cast::<Closure>();
856    let (function, arity, fixed) = ((*closure).function, (*closure).arity as usize, (*closure).num_fixed as usize);
857    let stored = std::slice::from_raw_parts(closure_args(f), fixed);
858    if fixed + args.len() < arity {
859        let extended = alloc_closure(function, arity as u32, (fixed + args.len()) as u32);
860        for (i, &arg) in stored.iter().chain(args).enumerate() {
861            closure_set(extended, i as u32, arg);
862        }
863        take_stored(f, stored);
864        return extended;
865    }
866    let (now, later) = args.split_at(arity - fixed);
867    let mut all = [box_(0); CLOSURE_MAX_ARGS];
868    assert!(arity <= CLOSURE_MAX_ARGS, "inlean: a function of {arity} arguments cannot be called through a closure");
869    all[..fixed].copy_from_slice(stored);
870    all[fixed..arity].copy_from_slice(now);
871    take_stored(f, stored);
872    let result = call(function, &all[..arity]);
873    if later.is_empty() {
874        result
875    } else {
876        apply(result, later)
877    }
878}
879
880/// A Lean function that a declaration bound to Rust was given: a closure, and a reference
881/// to it.
882pub struct Function(Obj);
883
884impl Function {
885    /// # Safety
886    /// `raw` is a closure of this runtime, and the caller owns a reference to it. A value
887    /// that only stands in for a function Lean holds, and is not dropped, may wrap any.
888    #[inline(always)]
889    pub unsafe fn from_raw(raw: Obj) -> Function {
890        Function(raw)
891    }
892
893    /// Calls the function with `arguments`, which it takes over, and gives what it returns.
894    ///
895    /// # Safety
896    /// `arguments` are the objects the function takes, as many as it takes and each a value
897    /// of the type it expects, and the caller owns a reference to each.
898    #[inline]
899    pub unsafe fn call(&self, arguments: &[Obj]) -> Obj {
900        // Applying a closure gives up a reference to it, and this one is kept.
901        inc(self.0);
902        apply(self.0, arguments)
903    }
904}
905
906impl Drop for Function {
907    #[inline]
908    fn drop(&mut self) {
909        unsafe { dec(self.0) };
910    }
911}
912
913/// Gives up a reference to closure `f` whose stored arguments were just copied out: the
914/// copies become owners of the arguments.
915unsafe fn take_stored(f: Obj, stored: &[Obj]) {
916    if is_exclusive(f) {
917        free_object(f);
918    } else {
919        for &arg in stored {
920            inc(arg);
921        }
922        dec_ref(f);
923    }
924}
925
926/// A Lean constant that is an object: computed on first use, then persistent.
927pub struct Constant(OnceLock<Shared>);
928
929struct Shared(Obj);
930
931// A persistent object is immutable and is never counted, so any thread may read it.
932unsafe impl Send for Shared {}
933unsafe impl Sync for Shared {}
934
935impl Constant {
936    #[allow(clippy::new_without_default)]
937    pub const fn new() -> Constant {
938        Constant(OnceLock::new())
939    }
940
941    /// The value of the constant; `init` computes it if this is the first use. The result is
942    /// a borrowed reference: counting it has no effect.
943    pub unsafe fn get(&self, init: unsafe fn() -> Obj) -> Obj {
944        self.0
945            .get_or_init(|| {
946                let value = init();
947                mark_persistent(value);
948                Shared(value)
949            })
950            .0
951    }
952}