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