Skip to main content

leanfran_runtime/
object.rs

1//! Object model of `lean.h`: object layouts, allocation, reference counting, boxing and
2//! constructor objects.
3//!
4//! The layouts are the ones of `lean.h` on a 64-bit machine. Reference counting follows
5//! `lean.h`: `m_rc > 0` is the count of an object owned by one thread, `m_rc < 0` is the negated
6//! count of an object shared between threads (updated atomically, see [`lean_mark_mt`]), and
7//! `m_rc == 0` marks a persistent object (inc/dec are no-ops). With `debug_assertions` a freed
8//! object has its count set to [`FREED_RC`] and its memory is kept for a while, so that a later
9//! increment, decrement or field access of it panics.
10
11use core::ffi::c_void;
12use core::mem::{offset_of, size_of};
13use core::ptr;
14use core::sync::atomic::{AtomicI32, Ordering};
15use num_bigint::BigInt;
16use std::alloc::{self, Layout};
17use std::cell::Cell;
18
19/// Header of every heap object (`lean_object`).
20#[repr(C)]
21pub struct Object {
22    pub m_rc: i32,
23    pub m_cs_sz: u16,
24    pub m_other: u8,
25    pub m_tag: u8,
26}
27
28/// A Lean value: a pointer to a heap object, or a scalar `(n << 1) | 1`.
29pub type Obj = *mut Object;
30
31pub const LEAN_MAX_CTOR_TAG: u8 = 244;
32pub const LEAN_PROMISE: u8 = 244;
33pub const LEAN_CLOSURE: u8 = 245;
34pub const LEAN_ARRAY: u8 = 246;
35pub const LEAN_STRUCT_ARRAY: u8 = 247;
36pub const LEAN_SCALAR_ARRAY: u8 = 248;
37pub const LEAN_STRING: u8 = 249;
38pub const LEAN_MPZ: u8 = 250;
39pub const LEAN_THUNK: u8 = 251;
40pub const LEAN_TASK: u8 = 252;
41pub const LEAN_REF: u8 = 253;
42pub const LEAN_EXTERNAL: u8 = 254;
43pub const LEAN_RESERVED: u8 = 255;
44
45/// Linearity marker bit in `m_other` of arrays, scalar arrays and strings.
46pub const LEAN_LINEAR_MARK_MASK: u8 = 0x80;
47
48/// Reference count written into a freed object when `debug_assertions` are enabled.
49pub const FREED_RC: i32 = -0x5EAD_DEAD;
50
51#[repr(C)]
52pub struct CtorObject {
53    pub m_header: Object,
54    pub m_objs: [Obj; 0],
55}
56
57#[repr(C)]
58pub struct ArrayObject {
59    pub m_header: Object,
60    pub m_size: usize,
61    pub m_capacity: usize,
62    pub m_data: [Obj; 0],
63}
64
65#[repr(C)]
66pub struct SArrayObject {
67    pub m_header: Object,
68    pub m_size: usize,
69    pub m_capacity: usize,
70    pub m_data: [u8; 0],
71}
72
73#[repr(C)]
74pub struct StringObject {
75    pub m_header: Object,
76    /// Byte length including the `'\0'` terminator.
77    pub m_size: usize,
78    pub m_capacity: usize,
79    /// Number of code points.
80    pub m_length: usize,
81    pub m_data: [u8; 0],
82}
83
84#[repr(C)]
85pub struct ClosureObject {
86    pub m_header: Object,
87    pub m_fun: *const (),
88    pub m_arity: u16,
89    pub m_num_fixed: u16,
90    pub m_objs: [Obj; 0],
91}
92
93#[repr(C)]
94pub struct RefObject {
95    pub m_header: Object,
96    pub m_value: Obj,
97}
98
99#[repr(C)]
100pub struct ThunkObject {
101    pub m_header: Object,
102    pub m_value: Obj,
103    pub m_closure: Obj,
104}
105
106/// Tasks run synchronously when they are created, so `m_imp` is always null and `m_value` is
107/// set.
108#[repr(C)]
109pub struct TaskObject {
110    pub m_header: Object,
111    pub m_value: Obj,
112    pub m_imp: *mut c_void,
113}
114
115/// `lean_external_class`.
116#[repr(C)]
117pub struct ExternalClass {
118    pub m_finalize: unsafe fn(*mut c_void),
119    pub m_foreach: unsafe fn(*mut c_void, Obj),
120}
121
122#[repr(C)]
123pub struct ExternalObject {
124    pub m_header: Object,
125    pub m_class: *const ExternalClass,
126    pub m_data: *mut c_void,
127}
128
129/// A big natural number or integer (`mpz_object`), holding a `num-bigint` value.
130#[repr(C)]
131pub struct MpzObject {
132    pub m_header: Object,
133    pub m_value: BigInt,
134}
135
136const CTOR_OBJS: usize = offset_of!(CtorObject, m_objs);
137
138/* Allocation */
139
140#[inline]
141fn layout_of(sz: usize) -> Layout {
142    match Layout::from_size_align((sz + 7) & !7, 8) {
143        Ok(l) => l,
144        Err(_) => lean_internal_panic_out_of_memory(),
145    }
146}
147
148/// Free memory blocks of small objects, kept per thread and reused by the next allocation of
149/// the same size (the small object allocator of Lean's runtime). A block freed on another
150/// thread than the one that allocated it joins the list of the freeing thread.
151#[cfg(not(any(debug_assertions, miri)))]
152mod pool {
153    use super::layout_of;
154    use std::alloc;
155    use std::cell::UnsafeCell;
156
157    /// Blocks of up to this many bytes are pooled.
158    pub const MAX_SIZE: usize = 128;
159    const CLASSES: usize = MAX_SIZE / 8 + 1;
160    /// Blocks kept per size; more are returned to the allocator.
161    const MAX_BLOCKS: u32 = 1 << 14;
162
163    struct Pool {
164        heads: UnsafeCell<[*mut u8; CLASSES]>,
165        counts: UnsafeCell<[u32; CLASSES]>,
166    }
167
168    impl Drop for Pool {
169        fn drop(&mut self) {
170            for (class, head) in self.heads.get_mut().iter_mut().enumerate() {
171                let mut p = core::mem::replace(head, core::ptr::null_mut());
172                while !p.is_null() {
173                    unsafe {
174                        let next = *(p as *mut *mut u8);
175                        alloc::dealloc(p, layout_of(class * 8));
176                        p = next;
177                    }
178                }
179            }
180        }
181    }
182
183    thread_local! {
184        static POOL: Pool = const {
185            Pool {
186                heads: UnsafeCell::new([core::ptr::null_mut(); CLASSES]),
187                counts: UnsafeCell::new([0; CLASSES]),
188            }
189        };
190    }
191
192    /// A free block of `size` bytes (a multiple of 8, at least 8, at most `MAX_SIZE`).
193    #[inline]
194    pub unsafe fn take(size: usize) -> *mut u8 {
195        let class = size / 8;
196        POOL.try_with(|pool| {
197            let head = (pool.heads.get() as *mut *mut u8).add(class);
198            let p = *head;
199            if !p.is_null() {
200                *head = *(p as *mut *mut u8);
201                *(pool.counts.get() as *mut u32).add(class) -= 1;
202            }
203            p
204        })
205        .unwrap_or(core::ptr::null_mut())
206    }
207
208    /// Keeps the block `p` of `size` bytes; false when the list of that size is full.
209    #[inline]
210    pub unsafe fn give(p: *mut u8, size: usize) -> bool {
211        let class = size / 8;
212        POOL.try_with(|pool| {
213            let count = (pool.counts.get() as *mut u32).add(class);
214            if *count >= MAX_BLOCKS {
215                return false;
216            }
217            *count += 1;
218            let head = (pool.heads.get() as *mut *mut u8).add(class);
219            *(p as *mut *mut u8) = *head;
220            *head = p;
221            true
222        })
223        .unwrap_or(false)
224    }
225}
226
227/// Allocates `sz` bytes for an object (`lean_alloc_object`). The header is not initialized.
228#[inline]
229pub unsafe fn lean_alloc_object(sz: usize) -> Obj {
230    let layout = layout_of(sz);
231    #[cfg(not(any(debug_assertions, miri)))]
232    if layout.size() <= pool::MAX_SIZE && layout.size() >= 8 {
233        let p = pool::take(layout.size());
234        if !p.is_null() {
235            return p as Obj;
236        }
237    }
238    let p = alloc::alloc(layout);
239    if p.is_null() {
240        alloc::handle_alloc_error(layout);
241    }
242    p as Obj
243}
244
245#[inline]
246pub unsafe fn lean_alloc_small_object(sz: usize) -> Obj {
247    lean_alloc_object(sz)
248}
249
250/// `lean_set_st_header`: single-threaded header with RC 1.
251#[inline]
252pub unsafe fn lean_set_st_header(o: Obj, tag: u32, other: u32) {
253    rc_set(o, 1);
254    (*o).m_tag = tag as u8;
255    (*o).m_other = other as u8;
256    (*o).m_cs_sz = 0;
257}
258
259/// `lean_set_non_heap_header`: persistent header (RC 0).
260#[inline]
261pub unsafe fn lean_set_non_heap_header(o: Obj, sz: usize, tag: u32, other: u32) {
262    rc_set(o, 0);
263    (*o).m_tag = tag as u8;
264    (*o).m_other = other as u8;
265    (*o).m_cs_sz = sz as u16;
266}
267
268/// Size in bytes of the memory block of an object (`lean_object_byte_size`).
269pub unsafe fn lean_object_byte_size(o: Obj) -> usize {
270    let tag = (*o).m_tag;
271    if tag <= LEAN_MAX_CTOR_TAG {
272        return (*o).m_cs_sz as usize;
273    }
274    match tag {
275        LEAN_CLOSURE => {
276            size_of::<ClosureObject>()
277                + size_of::<Obj>() * (*(o as *mut ClosureObject)).m_arity as usize
278        }
279        LEAN_ARRAY => {
280            size_of::<ArrayObject>() + size_of::<Obj>() * (*(o as *mut ArrayObject)).m_capacity
281        }
282        LEAN_SCALAR_ARRAY => {
283            size_of::<SArrayObject>()
284                + lean_sarray_elem_size(o) as usize * (*(o as *mut SArrayObject)).m_capacity
285        }
286        LEAN_STRING => size_of::<StringObject>() + (*(o as *mut StringObject)).m_capacity,
287        LEAN_MPZ => size_of::<MpzObject>(),
288        LEAN_THUNK => size_of::<ThunkObject>(),
289        LEAN_TASK => size_of::<TaskObject>(),
290        LEAN_REF => size_of::<RefObject>(),
291        LEAN_EXTERNAL => size_of::<ExternalObject>(),
292        _ => lean_internal_panic_unreachable(),
293    }
294}
295
296/// Number of freed objects whose memory is kept to detect use after free.
297#[cfg(all(debug_assertions, not(miri)))]
298const QUARANTINE: usize = 1 << 14;
299
300#[cfg(all(debug_assertions, not(miri)))]
301thread_local! {
302    static FREED: core::cell::RefCell<std::collections::VecDeque<(*mut u8, Layout)>> =
303        const { core::cell::RefCell::new(std::collections::VecDeque::new()) };
304}
305
306/// Returns the memory block of an object of `sz` bytes to the allocator.
307#[inline]
308pub unsafe fn lean_dealloc(o: Obj, sz: usize) {
309    let layout = layout_of(sz);
310    #[cfg(debug_assertions)]
311    {
312        rc_set(o, FREED_RC);
313    }
314    #[cfg(all(debug_assertions, not(miri)))]
315    {
316        let evicted = FREED.with(|q| {
317            let mut q = q.borrow_mut();
318            q.push_back((o as *mut u8, layout));
319            if q.len() > QUARANTINE {
320                q.pop_front()
321            } else {
322                None
323            }
324        });
325        if let Some((p, l)) = evicted {
326            alloc::dealloc(p, l);
327        }
328    }
329    #[cfg(not(any(debug_assertions, miri)))]
330    if layout.size() <= pool::MAX_SIZE
331        && layout.size() >= 8
332        && pool::give(o as *mut u8, layout.size())
333    {
334        return;
335    }
336    #[cfg(not(all(debug_assertions, not(miri))))]
337    alloc::dealloc(o as *mut u8, layout);
338}
339
340/// Frees the memory of an object without touching its fields (`lean_free_object`).
341pub unsafe fn lean_free_object(o: Obj) {
342    debug_check_live(o, "free");
343    if (*o).m_tag == LEAN_MPZ {
344        ptr::drop_in_place(ptr::addr_of_mut!((*(o as *mut MpzObject)).m_value));
345    }
346    lean_dealloc(o, lean_object_byte_size(o));
347}
348
349#[inline]
350pub unsafe fn lean_free_small_object(o: Obj) {
351    lean_free_object(o);
352}
353
354/* Scalars */
355
356#[inline]
357pub fn lean_is_scalar(o: Obj) -> bool {
358    o.addr() & 1 == 1
359}
360
361#[inline]
362pub fn lean_box(n: usize) -> Obj {
363    ptr::without_provenance_mut((n << 1) | 1)
364}
365
366#[inline]
367pub fn lean_unbox(o: Obj) -> usize {
368    o.addr() >> 1
369}
370
371/* Reference counting */
372
373/// The count of `o` as an atomic: every read and write of `m_rc` goes through it, since an
374/// object shared between threads has its count updated by all of them.
375#[inline(always)]
376unsafe fn rc_cell<'a>(o: Obj) -> &'a AtomicI32 {
377    AtomicI32::from_ptr(ptr::addr_of_mut!((*o).m_rc))
378}
379
380#[inline(always)]
381unsafe fn rc_get(o: Obj) -> i32 {
382    rc_cell(o).load(Ordering::Relaxed)
383}
384
385#[inline(always)]
386unsafe fn rc_set(o: Obj, rc: i32) {
387    rc_cell(o).store(rc, Ordering::Relaxed)
388}
389
390#[cold]
391#[inline(never)]
392fn rc_error(o: Obj, rc: i32, op: &str) -> ! {
393    if rc == FREED_RC {
394        panic!("leanfran-runtime: {op} of the freed object {o:p}");
395    }
396    panic!("leanfran-runtime: {op} of the object {o:p} with the reference count {rc}");
397}
398
399/// Panics (with `debug_assertions`) if `o` is a freed object.
400#[inline(always)]
401pub unsafe fn debug_check_live(o: Obj, op: &str) {
402    #[cfg(debug_assertions)]
403    if !lean_is_scalar(o) && rc_get(o) == FREED_RC {
404        rc_error(o, FREED_RC, op);
405    }
406    let _ = (o, op);
407}
408
409#[inline]
410pub unsafe fn lean_is_st(o: Obj) -> bool {
411    rc_get(o) > 0
412}
413
414#[inline]
415pub unsafe fn lean_is_mt(o: Obj) -> bool {
416    rc_get(o) < 0
417}
418
419#[inline]
420pub unsafe fn lean_is_persistent(o: Obj) -> bool {
421    rc_get(o) == 0
422}
423
424#[inline]
425pub unsafe fn lean_has_rc(o: Obj) -> bool {
426    rc_get(o) != 0
427}
428
429#[inline]
430pub unsafe fn lean_inc_ref_n(o: Obj, n: usize) {
431    let rc = rc_get(o);
432    if rc > 0 {
433        match rc.checked_add(n as i32) {
434            Some(r) if n <= i32::MAX as usize => rc_set(o, r),
435            _ => lean_internal_panic_rc_overflow(),
436        }
437    } else if rc != 0 {
438        lean_inc_ref_n_mt(o, rc, n);
439    }
440}
441
442#[inline]
443pub unsafe fn lean_inc_ref(o: Obj) {
444    let rc = rc_get(o);
445    if rc > 0 {
446        #[cfg(debug_assertions)]
447        if rc == i32::MAX {
448            lean_internal_panic_rc_overflow();
449        }
450        rc_set(o, rc + 1);
451    } else if rc != 0 {
452        lean_inc_ref_n_mt(o, rc, 1);
453    }
454}
455
456/// Adds `n` references to the object `o` shared between threads, whose count was read as `rc`.
457#[cold]
458unsafe fn lean_inc_ref_n_mt(o: Obj, rc: i32, n: usize) {
459    if cfg!(debug_assertions) && rc == FREED_RC {
460        rc_error(o, rc, "increment");
461    }
462    if n > (i32::MAX / 2) as usize {
463        lean_internal_panic_rc_overflow();
464    }
465    if rc_cell(o).fetch_sub(n as i32, Ordering::Relaxed) < i32::MIN / 2 {
466        lean_internal_panic_rc_overflow();
467    }
468}
469
470/// Removes one reference from the object `o` shared between threads, whose count was read as
471/// `rc`; true when it was the last one.
472#[inline]
473unsafe fn lean_dec_ref_mt(o: Obj, rc: i32) -> bool {
474    if cfg!(debug_assertions) && rc == FREED_RC {
475        rc_error(o, rc, "decrement");
476    }
477    rc_cell(o).fetch_add(1, Ordering::AcqRel) == -1
478}
479
480#[inline]
481pub unsafe fn lean_inc(o: Obj) {
482    if !lean_is_scalar(o) {
483        lean_inc_ref(o);
484    }
485}
486
487#[inline]
488pub unsafe fn lean_inc_n(o: Obj, n: usize) {
489    if !lean_is_scalar(o) {
490        lean_inc_ref_n(o, n);
491    }
492}
493
494#[inline]
495pub unsafe fn lean_dec_ref(o: Obj) {
496    let rc = rc_get(o);
497    if rc > 1 {
498        rc_set(o, rc - 1);
499    } else if rc != 0 {
500        lean_dec_ref_cold(o);
501    }
502}
503
504#[inline]
505pub unsafe fn lean_dec(o: Obj) {
506    if !lean_is_scalar(o) {
507        lean_dec_ref(o);
508    }
509}
510
511thread_local! {
512    static DEL_TODO: Cell<Vec<Obj>> = const { Cell::new(Vec::new()) };
513}
514
515/// Pushes the children of `o` with a single-threaded count to `todo`.
516unsafe fn for_each_child(o: Obj, f: &mut impl FnMut(Obj)) {
517    let tag = (*o).m_tag;
518    if tag <= LEAN_MAX_CTOR_TAG {
519        let objs = lean_ctor_obj_cptr(o);
520        for i in 0..lean_ctor_num_objs(o) as usize {
521            f(*objs.add(i));
522        }
523        return;
524    }
525    match tag {
526        LEAN_CLOSURE => {
527            let c = o as *mut ClosureObject;
528            let objs = lean_closure_arg_cptr(o);
529            for i in 0..(*c).m_num_fixed as usize {
530                f(*objs.add(i));
531            }
532        }
533        LEAN_ARRAY => {
534            let data = lean_array_cptr(o);
535            for i in 0..(*(o as *mut ArrayObject)).m_size {
536                f(*data.add(i));
537            }
538        }
539        LEAN_THUNK => {
540            let t = o as *mut ThunkObject;
541            if !(*t).m_value.is_null() {
542                f((*t).m_value);
543            }
544            if !(*t).m_closure.is_null() {
545                f((*t).m_closure);
546            }
547        }
548        LEAN_TASK => {
549            let t = o as *mut TaskObject;
550            if !(*t).m_value.is_null() {
551                f((*t).m_value);
552            }
553        }
554        LEAN_REF => {
555            let r = o as *mut RefObject;
556            if !(*r).m_value.is_null() {
557                f((*r).m_value);
558            }
559        }
560        _ => {}
561    }
562}
563
564/// Removes one reference from `o`, whose count is 1 or the count of an object shared between
565/// threads. When it was the last reference, frees `o` and every object only reachable from it,
566/// with an explicit work list instead of recursion (`lean_del`).
567#[cold]
568#[inline(never)]
569pub unsafe fn lean_dec_ref_cold(o: Obj) {
570    let rc = rc_get(o);
571    if rc < 0 && !lean_dec_ref_mt(o, rc) {
572        return;
573    }
574    let mut todo = DEL_TODO.take();
575    todo.push(o);
576    while let Some(o) = todo.pop() {
577        let mut child = |c: Obj| {
578            if lean_is_scalar(c) {
579                return;
580            }
581            let rc = rc_get(c);
582            if rc > 1 {
583                rc_set(c, rc - 1);
584            } else if rc == 1 {
585                rc_set(c, 0);
586                todo.push(c);
587            } else if rc < 0 && lean_dec_ref_mt(c, rc) {
588                todo.push(c);
589            }
590        };
591        for_each_child(o, &mut child);
592        if (*o).m_tag == LEAN_EXTERNAL {
593            let e = o as *mut ExternalObject;
594            ((*(*e).m_class).m_finalize)((*e).m_data);
595        }
596        lean_free_object_unchecked(o);
597    }
598    DEL_TODO.set(todo);
599}
600
601unsafe fn lean_free_object_unchecked(o: Obj) {
602    if (*o).m_tag == LEAN_MPZ {
603        ptr::drop_in_place(ptr::addr_of_mut!((*(o as *mut MpzObject)).m_value));
604    }
605    lean_dealloc(o, lean_object_byte_size(o));
606}
607
608/// Marks `o` and every object reachable from it as persistent (RC 0).
609pub unsafe fn lean_mark_persistent(o: Obj) {
610    let mut todo = vec![o];
611    while let Some(o) = todo.pop() {
612        if lean_is_scalar(o) || !lean_has_rc(o) {
613            continue;
614        }
615        debug_check_live(o, "mark_persistent");
616        rc_set(o, 0);
617        if (*o).m_tag == LEAN_EXTERNAL {
618            let e = o as *mut ExternalObject;
619            let f = crate::closure::lean_alloc_closure(mark_persistent_fn as *const (), 1, 0);
620            ((*(*e).m_class).m_foreach)((*e).m_data, f);
621            lean_dec(f);
622        } else {
623            for_each_child(o, &mut |c| todo.push(c));
624        }
625    }
626}
627
628unsafe fn mark_persistent_fn(o: Obj) -> Obj {
629    lean_mark_persistent(o);
630    lean_box(0)
631}
632
633/// Marks `o` and every object reachable from it as shared between threads (`lean_mark_mt`):
634/// their counts are negated and updated atomically from then on. Objects that are already
635/// shared or persistent, and what they reach, are left alone. The caller must be the only
636/// thread that can reach the objects still owned by one thread.
637pub unsafe fn lean_mark_mt(o: Obj) {
638    if lean_is_scalar(o) || !lean_is_st(o) {
639        return;
640    }
641    let mut todo = vec![o];
642    while let Some(o) = todo.pop() {
643        if lean_is_scalar(o) {
644            continue;
645        }
646        let rc = rc_get(o);
647        if rc <= 0 {
648            debug_check_live(o, "mark_mt");
649            continue;
650        }
651        rc_set(o, -rc);
652        if (*o).m_tag == LEAN_EXTERNAL {
653            let e = o as *mut ExternalObject;
654            let f = crate::closure::lean_alloc_closure(mark_mt_fn as *const (), 1, 0);
655            ((*(*e).m_class).m_foreach)((*e).m_data, f);
656            lean_dec(f);
657        } else {
658            for_each_child(o, &mut |c| todo.push(c));
659        }
660    }
661}
662
663unsafe fn mark_mt_fn(o: Obj) -> Obj {
664    lean_mark_mt(o);
665    lean_box(0)
666}
667
668/* Tags */
669
670#[inline]
671pub unsafe fn lean_ptr_tag(o: Obj) -> u8 {
672    debug_check_live(o, "tag read");
673    (*o).m_tag
674}
675
676#[inline]
677pub unsafe fn lean_ptr_other(o: Obj) -> u32 {
678    (*o).m_other as u32
679}
680
681#[inline]
682pub unsafe fn lean_obj_tag(o: Obj) -> u32 {
683    if lean_is_scalar(o) {
684        lean_unbox(o) as u32
685    } else {
686        lean_ptr_tag(o) as u32
687    }
688}
689
690#[inline]
691pub unsafe fn lean_is_exclusive(o: Obj) -> bool {
692    if lean_is_scalar(o) {
693        return false;
694    }
695    debug_check_live(o, "exclusivity check");
696    rc_get(o) == 1
697}
698
699#[inline]
700pub unsafe fn lean_is_exclusive_obj(o: Obj) -> u8 {
701    lean_is_exclusive(o) as u8
702}
703
704#[inline]
705pub unsafe fn lean_is_shared(o: Obj) -> bool {
706    !lean_is_scalar(o) && rc_get(o) > 1
707}
708
709#[inline]
710pub unsafe fn lean_nonzero_rc(o: Obj) -> bool {
711    rc_get(o) != 0
712}
713
714#[inline]
715pub fn lean_ptr_addr(o: Obj) -> usize {
716    o.addr()
717}
718
719#[inline]
720pub unsafe fn lean_is_ctor(o: Obj) -> bool {
721    lean_ptr_tag(o) <= LEAN_MAX_CTOR_TAG
722}
723#[inline]
724pub unsafe fn lean_is_closure(o: Obj) -> bool {
725    lean_ptr_tag(o) == LEAN_CLOSURE
726}
727#[inline]
728pub unsafe fn lean_is_array(o: Obj) -> bool {
729    lean_ptr_tag(o) == LEAN_ARRAY
730}
731#[inline]
732pub unsafe fn lean_is_sarray(o: Obj) -> bool {
733    lean_ptr_tag(o) == LEAN_SCALAR_ARRAY
734}
735#[inline]
736pub unsafe fn lean_is_string(o: Obj) -> bool {
737    lean_ptr_tag(o) == LEAN_STRING
738}
739#[inline]
740pub unsafe fn lean_is_mpz(o: Obj) -> bool {
741    lean_ptr_tag(o) == LEAN_MPZ
742}
743#[inline]
744pub unsafe fn lean_is_thunk(o: Obj) -> bool {
745    lean_ptr_tag(o) == LEAN_THUNK
746}
747#[inline]
748pub unsafe fn lean_is_task(o: Obj) -> bool {
749    lean_ptr_tag(o) == LEAN_TASK
750}
751#[inline]
752pub unsafe fn lean_is_external(o: Obj) -> bool {
753    lean_ptr_tag(o) == LEAN_EXTERNAL
754}
755#[inline]
756pub unsafe fn lean_is_ref(o: Obj) -> bool {
757    lean_ptr_tag(o) == LEAN_REF
758}
759
760/* Constructor objects */
761
762#[inline]
763pub unsafe fn lean_ctor_num_objs(o: Obj) -> u32 {
764    (*o).m_other as u32
765}
766
767#[inline]
768pub unsafe fn lean_ctor_obj_cptr(o: Obj) -> *mut Obj {
769    (o as *mut u8).add(CTOR_OBJS) as *mut Obj
770}
771
772#[inline]
773pub unsafe fn lean_ctor_scalar_cptr(o: Obj) -> *mut u8 {
774    lean_ctor_obj_cptr(o).add(lean_ctor_num_objs(o) as usize) as *mut u8
775}
776
777/// Allocates a constructor object; the object fields are left for `lean_ctor_set`, the scalar
778/// area is zeroed.
779#[inline]
780pub unsafe fn lean_alloc_ctor(tag: u32, num_objs: u32, scalar_sz: u32) -> Obj {
781    debug_assert!(tag <= LEAN_MAX_CTOR_TAG as u32 && num_objs < 256);
782    let objs_end = CTOR_OBJS + size_of::<Obj>() * num_objs as usize;
783    let sz = (objs_end + scalar_sz as usize + 7) & !7;
784    if sz > u16::MAX as usize {
785        lean_internal_panic("constructor object is too big");
786    }
787    let o = lean_alloc_object(sz);
788    lean_set_st_header(o, tag, num_objs);
789    (*o).m_cs_sz = sz as u16;
790    ptr::write_bytes((o as *mut u8).add(objs_end), 0, sz - objs_end);
791    o
792}
793
794#[inline]
795pub unsafe fn lean_ctor_get(o: Obj, i: u32) -> Obj {
796    debug_check_live(o, "field read");
797    debug_assert!(i < lean_ctor_num_objs(o));
798    *lean_ctor_obj_cptr(o).add(i as usize)
799}
800
801#[inline]
802pub unsafe fn lean_ctor_set(o: Obj, i: u32, v: Obj) {
803    debug_check_live(o, "field write");
804    debug_assert!(i < lean_ctor_num_objs(o));
805    *lean_ctor_obj_cptr(o).add(i as usize) = v;
806}
807
808#[inline]
809pub unsafe fn lean_ctor_set_tag(o: Obj, new_tag: u32) {
810    debug_check_live(o, "tag write");
811    (*o).m_tag = new_tag as u8;
812}
813
814#[inline]
815pub unsafe fn lean_ctor_release(o: Obj, i: u32) {
816    let objs = lean_ctor_obj_cptr(o);
817    lean_dec(*objs.add(i as usize));
818    *objs.add(i as usize) = lean_box(0);
819}
820
821#[inline]
822pub unsafe fn lean_ctor_get_usize(o: Obj, i: u32) -> usize {
823    debug_check_live(o, "field read");
824    ptr::read_unaligned(lean_ctor_obj_cptr(o).add(i as usize) as *const usize)
825}
826
827#[inline]
828pub unsafe fn lean_ctor_set_usize(o: Obj, i: u32, v: usize) {
829    debug_check_live(o, "field write");
830    ptr::write_unaligned(lean_ctor_obj_cptr(o).add(i as usize) as *mut usize, v)
831}
832
833macro_rules! ctor_scalar {
834    ($get:ident, $set:ident, $t:ty) => {
835        /// Reads a scalar field at `offset` bytes from the start of the object fields.
836        #[inline]
837        pub unsafe fn $get(o: Obj, offset: u32) -> $t {
838            debug_check_live(o, "field read");
839            ptr::read_unaligned(
840                (lean_ctor_obj_cptr(o) as *const u8).add(offset as usize) as *const $t
841            )
842        }
843        /// Writes a scalar field at `offset` bytes from the start of the object fields.
844        #[inline]
845        pub unsafe fn $set(o: Obj, offset: u32, v: $t) {
846            debug_check_live(o, "field write");
847            ptr::write_unaligned(
848                (lean_ctor_obj_cptr(o) as *mut u8).add(offset as usize) as *mut $t,
849                v,
850            )
851        }
852    };
853}
854
855ctor_scalar!(lean_ctor_get_uint8, lean_ctor_set_uint8, u8);
856ctor_scalar!(lean_ctor_get_uint16, lean_ctor_set_uint16, u16);
857ctor_scalar!(lean_ctor_get_uint32, lean_ctor_set_uint32, u32);
858ctor_scalar!(lean_ctor_get_uint64, lean_ctor_set_uint64, u64);
859ctor_scalar!(lean_ctor_get_float, lean_ctor_set_float, f64);
860ctor_scalar!(lean_ctor_get_float32, lean_ctor_set_float32, f32);
861
862/* Boxing of scalars that do not fit a tagged pointer */
863
864#[inline]
865pub unsafe fn lean_box_uint32(v: u32) -> Obj {
866    lean_box(v as usize)
867}
868
869#[inline]
870pub unsafe fn lean_unbox_uint32(o: Obj) -> u32 {
871    lean_unbox(o) as u32
872}
873
874#[inline]
875pub unsafe fn lean_box_uint64(v: u64) -> Obj {
876    let r = lean_alloc_ctor(0, 0, 8);
877    lean_ctor_set_uint64(r, 0, v);
878    r
879}
880
881#[inline]
882pub unsafe fn lean_unbox_uint64(o: Obj) -> u64 {
883    lean_ctor_get_uint64(o, 0)
884}
885
886#[inline]
887pub unsafe fn lean_box_usize(v: usize) -> Obj {
888    let r = lean_alloc_ctor(0, 0, size_of::<usize>() as u32);
889    lean_ctor_set_usize(r, 0, v);
890    r
891}
892
893#[inline]
894pub unsafe fn lean_unbox_usize(o: Obj) -> usize {
895    lean_ctor_get_usize(o, 0)
896}
897
898#[inline]
899pub unsafe fn lean_box_float(v: f64) -> Obj {
900    let r = lean_alloc_ctor(0, 0, 8);
901    lean_ctor_set_float(r, 0, v);
902    r
903}
904
905#[inline]
906pub unsafe fn lean_unbox_float(o: Obj) -> f64 {
907    lean_ctor_get_float(o, 0)
908}
909
910#[inline]
911pub unsafe fn lean_box_float32(v: f32) -> Obj {
912    let r = lean_alloc_ctor(0, 0, 4);
913    lean_ctor_set_float32(r, 0, v);
914    r
915}
916
917#[inline]
918pub unsafe fn lean_unbox_float32(o: Obj) -> f32 {
919    lean_ctor_get_float32(o, 0)
920}
921
922/* Ref objects (`ST.Ref`) */
923
924#[inline]
925pub unsafe fn lean_alloc_ref(v: Obj) -> Obj {
926    let o = lean_alloc_small_object(size_of::<RefObject>());
927    lean_set_st_header(o, LEAN_REF as u32, 0);
928    (*(o as *mut RefObject)).m_value = v;
929    o
930}
931
932/* External objects */
933
934#[inline]
935pub unsafe fn lean_alloc_external(cls: *const ExternalClass, data: *mut c_void) -> Obj {
936    let o = lean_alloc_small_object(size_of::<ExternalObject>());
937    lean_set_st_header(o, LEAN_EXTERNAL as u32, 0);
938    let e = o as *mut ExternalObject;
939    (*e).m_class = cls;
940    (*e).m_data = data;
941    o
942}
943
944#[inline]
945pub unsafe fn lean_get_external_class(o: Obj) -> *const ExternalClass {
946    (*(o as *mut ExternalObject)).m_class
947}
948
949#[inline]
950pub unsafe fn lean_get_external_data(o: Obj) -> *mut c_void {
951    (*(o as *mut ExternalObject)).m_data
952}
953
954pub unsafe fn lean_set_external_data(o: Obj, data: *mut c_void) -> Obj {
955    if lean_is_exclusive(o) {
956        (*(o as *mut ExternalObject)).m_data = data;
957        o
958    } else {
959        let r = lean_alloc_external(lean_get_external_class(o), data);
960        lean_dec_ref(o);
961        r
962    }
963}
964
965/* Helpers shared by the other modules */
966
967#[inline]
968pub unsafe fn lean_closure_arg_cptr(o: Obj) -> *mut Obj {
969    (o as *mut u8).add(offset_of!(ClosureObject, m_objs)) as *mut Obj
970}
971
972#[inline]
973pub unsafe fn lean_array_cptr(o: Obj) -> *mut Obj {
974    (o as *mut u8).add(offset_of!(ArrayObject, m_data)) as *mut Obj
975}
976
977#[inline]
978pub unsafe fn lean_sarray_elem_size(o: Obj) -> u32 {
979    ((*o).m_other & !LEAN_LINEAR_MARK_MASK) as u32
980}
981
982pub use crate::panic::{
983    lean_internal_panic, lean_internal_panic_out_of_memory, lean_internal_panic_rc_overflow,
984    lean_internal_panic_unreachable,
985};
986
987/// Frees the memory of `o` unless it is a scalar (`del` in the IR).
988#[inline]
989pub unsafe fn lean_del_object(o: Obj) {
990    if !lean_is_scalar(o) {
991        lean_free_object(o);
992    }
993}