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/// Allocates `sz` bytes for an object (`lean_alloc_object`). The header is not initialized.
149#[inline]
150pub unsafe fn lean_alloc_object(sz: usize) -> Obj {
151    let layout = layout_of(sz);
152    let p = alloc::alloc(layout);
153    if p.is_null() {
154        alloc::handle_alloc_error(layout);
155    }
156    p as Obj
157}
158
159#[inline]
160pub unsafe fn lean_alloc_small_object(sz: usize) -> Obj {
161    lean_alloc_object(sz)
162}
163
164/// `lean_set_st_header`: single-threaded header with RC 1.
165#[inline]
166pub unsafe fn lean_set_st_header(o: Obj, tag: u32, other: u32) {
167    rc_set(o, 1);
168    (*o).m_tag = tag as u8;
169    (*o).m_other = other as u8;
170    (*o).m_cs_sz = 0;
171}
172
173/// `lean_set_non_heap_header`: persistent header (RC 0).
174#[inline]
175pub unsafe fn lean_set_non_heap_header(o: Obj, sz: usize, tag: u32, other: u32) {
176    rc_set(o, 0);
177    (*o).m_tag = tag as u8;
178    (*o).m_other = other as u8;
179    (*o).m_cs_sz = sz as u16;
180}
181
182/// Size in bytes of the memory block of an object (`lean_object_byte_size`).
183pub unsafe fn lean_object_byte_size(o: Obj) -> usize {
184    let tag = (*o).m_tag;
185    if tag <= LEAN_MAX_CTOR_TAG {
186        return (*o).m_cs_sz as usize;
187    }
188    match tag {
189        LEAN_CLOSURE => {
190            size_of::<ClosureObject>()
191                + size_of::<Obj>() * (*(o as *mut ClosureObject)).m_arity as usize
192        }
193        LEAN_ARRAY => {
194            size_of::<ArrayObject>() + size_of::<Obj>() * (*(o as *mut ArrayObject)).m_capacity
195        }
196        LEAN_SCALAR_ARRAY => {
197            size_of::<SArrayObject>()
198                + lean_sarray_elem_size(o) as usize * (*(o as *mut SArrayObject)).m_capacity
199        }
200        LEAN_STRING => size_of::<StringObject>() + (*(o as *mut StringObject)).m_capacity,
201        LEAN_MPZ => size_of::<MpzObject>(),
202        LEAN_THUNK => size_of::<ThunkObject>(),
203        LEAN_TASK => size_of::<TaskObject>(),
204        LEAN_REF => size_of::<RefObject>(),
205        LEAN_EXTERNAL => size_of::<ExternalObject>(),
206        _ => lean_internal_panic_unreachable(),
207    }
208}
209
210/// Number of freed objects whose memory is kept to detect use after free.
211#[cfg(all(debug_assertions, not(miri)))]
212const QUARANTINE: usize = 1 << 14;
213
214#[cfg(all(debug_assertions, not(miri)))]
215thread_local! {
216    static FREED: core::cell::RefCell<std::collections::VecDeque<(*mut u8, Layout)>> =
217        const { core::cell::RefCell::new(std::collections::VecDeque::new()) };
218}
219
220/// Returns the memory block of an object of `sz` bytes to the allocator.
221#[inline]
222pub unsafe fn lean_dealloc(o: Obj, sz: usize) {
223    let layout = layout_of(sz);
224    #[cfg(debug_assertions)]
225    {
226        rc_set(o, FREED_RC);
227    }
228    #[cfg(all(debug_assertions, not(miri)))]
229    {
230        let evicted = FREED.with(|q| {
231            let mut q = q.borrow_mut();
232            q.push_back((o as *mut u8, layout));
233            if q.len() > QUARANTINE {
234                q.pop_front()
235            } else {
236                None
237            }
238        });
239        if let Some((p, l)) = evicted {
240            alloc::dealloc(p, l);
241        }
242    }
243    #[cfg(not(all(debug_assertions, not(miri))))]
244    alloc::dealloc(o as *mut u8, layout);
245}
246
247/// Frees the memory of an object without touching its fields (`lean_free_object`).
248pub unsafe fn lean_free_object(o: Obj) {
249    debug_check_live(o, "free");
250    if (*o).m_tag == LEAN_MPZ {
251        ptr::drop_in_place(ptr::addr_of_mut!((*(o as *mut MpzObject)).m_value));
252    }
253    lean_dealloc(o, lean_object_byte_size(o));
254}
255
256#[inline]
257pub unsafe fn lean_free_small_object(o: Obj) {
258    lean_free_object(o);
259}
260
261/* Scalars */
262
263#[inline]
264pub fn lean_is_scalar(o: Obj) -> bool {
265    o.addr() & 1 == 1
266}
267
268#[inline]
269pub fn lean_box(n: usize) -> Obj {
270    ptr::without_provenance_mut((n << 1) | 1)
271}
272
273#[inline]
274pub fn lean_unbox(o: Obj) -> usize {
275    o.addr() >> 1
276}
277
278/* Reference counting */
279
280/// The count of `o` as an atomic: every read and write of `m_rc` goes through it, since an
281/// object shared between threads has its count updated by all of them.
282#[inline(always)]
283unsafe fn rc_cell<'a>(o: Obj) -> &'a AtomicI32 {
284    AtomicI32::from_ptr(ptr::addr_of_mut!((*o).m_rc))
285}
286
287#[inline(always)]
288unsafe fn rc_get(o: Obj) -> i32 {
289    rc_cell(o).load(Ordering::Relaxed)
290}
291
292#[inline(always)]
293unsafe fn rc_set(o: Obj, rc: i32) {
294    rc_cell(o).store(rc, Ordering::Relaxed)
295}
296
297#[cold]
298#[inline(never)]
299fn rc_error(o: Obj, rc: i32, op: &str) -> ! {
300    if rc == FREED_RC {
301        panic!("leanfran-runtime: {op} of the freed object {o:p}");
302    }
303    panic!("leanfran-runtime: {op} of the object {o:p} with the reference count {rc}");
304}
305
306/// Panics (with `debug_assertions`) if `o` is a freed object.
307#[inline(always)]
308pub unsafe fn debug_check_live(o: Obj, op: &str) {
309    #[cfg(debug_assertions)]
310    if !lean_is_scalar(o) && rc_get(o) == FREED_RC {
311        rc_error(o, FREED_RC, op);
312    }
313    let _ = (o, op);
314}
315
316#[inline]
317pub unsafe fn lean_is_st(o: Obj) -> bool {
318    rc_get(o) > 0
319}
320
321#[inline]
322pub unsafe fn lean_is_mt(o: Obj) -> bool {
323    rc_get(o) < 0
324}
325
326#[inline]
327pub unsafe fn lean_is_persistent(o: Obj) -> bool {
328    rc_get(o) == 0
329}
330
331#[inline]
332pub unsafe fn lean_has_rc(o: Obj) -> bool {
333    rc_get(o) != 0
334}
335
336#[inline]
337pub unsafe fn lean_inc_ref_n(o: Obj, n: usize) {
338    let rc = rc_get(o);
339    if rc > 0 {
340        match rc.checked_add(n as i32) {
341            Some(r) if n <= i32::MAX as usize => rc_set(o, r),
342            _ => lean_internal_panic_rc_overflow(),
343        }
344    } else if rc != 0 {
345        lean_inc_ref_n_mt(o, rc, n);
346    }
347}
348
349#[inline]
350pub unsafe fn lean_inc_ref(o: Obj) {
351    let rc = rc_get(o);
352    if rc > 0 {
353        #[cfg(debug_assertions)]
354        if rc == i32::MAX {
355            lean_internal_panic_rc_overflow();
356        }
357        rc_set(o, rc + 1);
358    } else if rc != 0 {
359        lean_inc_ref_n_mt(o, rc, 1);
360    }
361}
362
363/// Adds `n` references to the object `o` shared between threads, whose count was read as `rc`.
364#[cold]
365unsafe fn lean_inc_ref_n_mt(o: Obj, rc: i32, n: usize) {
366    if cfg!(debug_assertions) && rc == FREED_RC {
367        rc_error(o, rc, "increment");
368    }
369    if n > (i32::MAX / 2) as usize {
370        lean_internal_panic_rc_overflow();
371    }
372    if rc_cell(o).fetch_sub(n as i32, Ordering::Relaxed) < i32::MIN / 2 {
373        lean_internal_panic_rc_overflow();
374    }
375}
376
377/// Removes one reference from the object `o` shared between threads, whose count was read as
378/// `rc`; true when it was the last one.
379#[inline]
380unsafe fn lean_dec_ref_mt(o: Obj, rc: i32) -> bool {
381    if cfg!(debug_assertions) && rc == FREED_RC {
382        rc_error(o, rc, "decrement");
383    }
384    rc_cell(o).fetch_add(1, Ordering::AcqRel) == -1
385}
386
387#[inline]
388pub unsafe fn lean_inc(o: Obj) {
389    if !lean_is_scalar(o) {
390        lean_inc_ref(o);
391    }
392}
393
394#[inline]
395pub unsafe fn lean_inc_n(o: Obj, n: usize) {
396    if !lean_is_scalar(o) {
397        lean_inc_ref_n(o, n);
398    }
399}
400
401#[inline]
402pub unsafe fn lean_dec_ref(o: Obj) {
403    let rc = rc_get(o);
404    if rc > 1 {
405        rc_set(o, rc - 1);
406    } else if rc != 0 {
407        lean_dec_ref_cold(o);
408    }
409}
410
411#[inline]
412pub unsafe fn lean_dec(o: Obj) {
413    if !lean_is_scalar(o) {
414        lean_dec_ref(o);
415    }
416}
417
418thread_local! {
419    static DEL_TODO: Cell<Vec<Obj>> = const { Cell::new(Vec::new()) };
420}
421
422/// Pushes the children of `o` with a single-threaded count to `todo`.
423unsafe fn for_each_child(o: Obj, f: &mut impl FnMut(Obj)) {
424    let tag = (*o).m_tag;
425    if tag <= LEAN_MAX_CTOR_TAG {
426        let objs = lean_ctor_obj_cptr(o);
427        for i in 0..lean_ctor_num_objs(o) as usize {
428            f(*objs.add(i));
429        }
430        return;
431    }
432    match tag {
433        LEAN_CLOSURE => {
434            let c = o as *mut ClosureObject;
435            let objs = lean_closure_arg_cptr(o);
436            for i in 0..(*c).m_num_fixed as usize {
437                f(*objs.add(i));
438            }
439        }
440        LEAN_ARRAY => {
441            let data = lean_array_cptr(o);
442            for i in 0..(*(o as *mut ArrayObject)).m_size {
443                f(*data.add(i));
444            }
445        }
446        LEAN_THUNK => {
447            let t = o as *mut ThunkObject;
448            if !(*t).m_value.is_null() {
449                f((*t).m_value);
450            }
451            if !(*t).m_closure.is_null() {
452                f((*t).m_closure);
453            }
454        }
455        LEAN_TASK => {
456            let t = o as *mut TaskObject;
457            if !(*t).m_value.is_null() {
458                f((*t).m_value);
459            }
460        }
461        LEAN_REF => {
462            let r = o as *mut RefObject;
463            if !(*r).m_value.is_null() {
464                f((*r).m_value);
465            }
466        }
467        _ => {}
468    }
469}
470
471/// Removes one reference from `o`, whose count is 1 or the count of an object shared between
472/// threads. When it was the last reference, frees `o` and every object only reachable from it,
473/// with an explicit work list instead of recursion (`lean_del`).
474#[cold]
475#[inline(never)]
476pub unsafe fn lean_dec_ref_cold(o: Obj) {
477    let rc = rc_get(o);
478    if rc < 0 && !lean_dec_ref_mt(o, rc) {
479        return;
480    }
481    let mut todo = DEL_TODO.take();
482    todo.push(o);
483    while let Some(o) = todo.pop() {
484        let mut child = |c: Obj| {
485            if lean_is_scalar(c) {
486                return;
487            }
488            let rc = rc_get(c);
489            if rc > 1 {
490                rc_set(c, rc - 1);
491            } else if rc == 1 {
492                rc_set(c, 0);
493                todo.push(c);
494            } else if rc < 0 && lean_dec_ref_mt(c, rc) {
495                todo.push(c);
496            }
497        };
498        for_each_child(o, &mut child);
499        if (*o).m_tag == LEAN_EXTERNAL {
500            let e = o as *mut ExternalObject;
501            ((*(*e).m_class).m_finalize)((*e).m_data);
502        }
503        lean_free_object_unchecked(o);
504    }
505    DEL_TODO.set(todo);
506}
507
508unsafe fn lean_free_object_unchecked(o: Obj) {
509    if (*o).m_tag == LEAN_MPZ {
510        ptr::drop_in_place(ptr::addr_of_mut!((*(o as *mut MpzObject)).m_value));
511    }
512    lean_dealloc(o, lean_object_byte_size(o));
513}
514
515/// Marks `o` and every object reachable from it as persistent (RC 0).
516pub unsafe fn lean_mark_persistent(o: Obj) {
517    let mut todo = vec![o];
518    while let Some(o) = todo.pop() {
519        if lean_is_scalar(o) || !lean_has_rc(o) {
520            continue;
521        }
522        debug_check_live(o, "mark_persistent");
523        rc_set(o, 0);
524        if (*o).m_tag == LEAN_EXTERNAL {
525            let e = o as *mut ExternalObject;
526            let f = crate::closure::lean_alloc_closure(mark_persistent_fn as *const (), 1, 0);
527            ((*(*e).m_class).m_foreach)((*e).m_data, f);
528            lean_dec(f);
529        } else {
530            for_each_child(o, &mut |c| todo.push(c));
531        }
532    }
533}
534
535unsafe fn mark_persistent_fn(o: Obj) -> Obj {
536    lean_mark_persistent(o);
537    lean_box(0)
538}
539
540/// Marks `o` and every object reachable from it as shared between threads (`lean_mark_mt`):
541/// their counts are negated and updated atomically from then on. Objects that are already
542/// shared or persistent, and what they reach, are left alone. The caller must be the only
543/// thread that can reach the objects still owned by one thread.
544pub unsafe fn lean_mark_mt(o: Obj) {
545    if lean_is_scalar(o) || !lean_is_st(o) {
546        return;
547    }
548    let mut todo = vec![o];
549    while let Some(o) = todo.pop() {
550        if lean_is_scalar(o) {
551            continue;
552        }
553        let rc = rc_get(o);
554        if rc <= 0 {
555            debug_check_live(o, "mark_mt");
556            continue;
557        }
558        rc_set(o, -rc);
559        if (*o).m_tag == LEAN_EXTERNAL {
560            let e = o as *mut ExternalObject;
561            let f = crate::closure::lean_alloc_closure(mark_mt_fn as *const (), 1, 0);
562            ((*(*e).m_class).m_foreach)((*e).m_data, f);
563            lean_dec(f);
564        } else {
565            for_each_child(o, &mut |c| todo.push(c));
566        }
567    }
568}
569
570unsafe fn mark_mt_fn(o: Obj) -> Obj {
571    lean_mark_mt(o);
572    lean_box(0)
573}
574
575/* Tags */
576
577#[inline]
578pub unsafe fn lean_ptr_tag(o: Obj) -> u8 {
579    debug_check_live(o, "tag read");
580    (*o).m_tag
581}
582
583#[inline]
584pub unsafe fn lean_ptr_other(o: Obj) -> u32 {
585    (*o).m_other as u32
586}
587
588#[inline]
589pub unsafe fn lean_obj_tag(o: Obj) -> u32 {
590    if lean_is_scalar(o) {
591        lean_unbox(o) as u32
592    } else {
593        lean_ptr_tag(o) as u32
594    }
595}
596
597#[inline]
598pub unsafe fn lean_is_exclusive(o: Obj) -> bool {
599    if lean_is_scalar(o) {
600        return false;
601    }
602    debug_check_live(o, "exclusivity check");
603    rc_get(o) == 1
604}
605
606#[inline]
607pub unsafe fn lean_is_exclusive_obj(o: Obj) -> u8 {
608    lean_is_exclusive(o) as u8
609}
610
611#[inline]
612pub unsafe fn lean_is_shared(o: Obj) -> bool {
613    !lean_is_scalar(o) && rc_get(o) > 1
614}
615
616#[inline]
617pub unsafe fn lean_nonzero_rc(o: Obj) -> bool {
618    rc_get(o) != 0
619}
620
621#[inline]
622pub fn lean_ptr_addr(o: Obj) -> usize {
623    o.addr()
624}
625
626#[inline]
627pub unsafe fn lean_is_ctor(o: Obj) -> bool {
628    lean_ptr_tag(o) <= LEAN_MAX_CTOR_TAG
629}
630#[inline]
631pub unsafe fn lean_is_closure(o: Obj) -> bool {
632    lean_ptr_tag(o) == LEAN_CLOSURE
633}
634#[inline]
635pub unsafe fn lean_is_array(o: Obj) -> bool {
636    lean_ptr_tag(o) == LEAN_ARRAY
637}
638#[inline]
639pub unsafe fn lean_is_sarray(o: Obj) -> bool {
640    lean_ptr_tag(o) == LEAN_SCALAR_ARRAY
641}
642#[inline]
643pub unsafe fn lean_is_string(o: Obj) -> bool {
644    lean_ptr_tag(o) == LEAN_STRING
645}
646#[inline]
647pub unsafe fn lean_is_mpz(o: Obj) -> bool {
648    lean_ptr_tag(o) == LEAN_MPZ
649}
650#[inline]
651pub unsafe fn lean_is_thunk(o: Obj) -> bool {
652    lean_ptr_tag(o) == LEAN_THUNK
653}
654#[inline]
655pub unsafe fn lean_is_task(o: Obj) -> bool {
656    lean_ptr_tag(o) == LEAN_TASK
657}
658#[inline]
659pub unsafe fn lean_is_external(o: Obj) -> bool {
660    lean_ptr_tag(o) == LEAN_EXTERNAL
661}
662#[inline]
663pub unsafe fn lean_is_ref(o: Obj) -> bool {
664    lean_ptr_tag(o) == LEAN_REF
665}
666
667/* Constructor objects */
668
669#[inline]
670pub unsafe fn lean_ctor_num_objs(o: Obj) -> u32 {
671    (*o).m_other as u32
672}
673
674#[inline]
675pub unsafe fn lean_ctor_obj_cptr(o: Obj) -> *mut Obj {
676    (o as *mut u8).add(CTOR_OBJS) as *mut Obj
677}
678
679#[inline]
680pub unsafe fn lean_ctor_scalar_cptr(o: Obj) -> *mut u8 {
681    lean_ctor_obj_cptr(o).add(lean_ctor_num_objs(o) as usize) as *mut u8
682}
683
684/// Allocates a constructor object; the object fields are left for `lean_ctor_set`, the scalar
685/// area is zeroed.
686#[inline]
687pub unsafe fn lean_alloc_ctor(tag: u32, num_objs: u32, scalar_sz: u32) -> Obj {
688    debug_assert!(tag <= LEAN_MAX_CTOR_TAG as u32 && num_objs < 256);
689    let objs_end = CTOR_OBJS + size_of::<Obj>() * num_objs as usize;
690    let sz = (objs_end + scalar_sz as usize + 7) & !7;
691    if sz > u16::MAX as usize {
692        lean_internal_panic("constructor object is too big");
693    }
694    let o = lean_alloc_object(sz);
695    lean_set_st_header(o, tag, num_objs);
696    (*o).m_cs_sz = sz as u16;
697    ptr::write_bytes((o as *mut u8).add(objs_end), 0, sz - objs_end);
698    o
699}
700
701#[inline]
702pub unsafe fn lean_ctor_get(o: Obj, i: u32) -> Obj {
703    debug_check_live(o, "field read");
704    debug_assert!(i < lean_ctor_num_objs(o));
705    *lean_ctor_obj_cptr(o).add(i as usize)
706}
707
708#[inline]
709pub unsafe fn lean_ctor_set(o: Obj, i: u32, v: Obj) {
710    debug_check_live(o, "field write");
711    debug_assert!(i < lean_ctor_num_objs(o));
712    *lean_ctor_obj_cptr(o).add(i as usize) = v;
713}
714
715#[inline]
716pub unsafe fn lean_ctor_set_tag(o: Obj, new_tag: u32) {
717    debug_check_live(o, "tag write");
718    (*o).m_tag = new_tag as u8;
719}
720
721#[inline]
722pub unsafe fn lean_ctor_release(o: Obj, i: u32) {
723    let objs = lean_ctor_obj_cptr(o);
724    lean_dec(*objs.add(i as usize));
725    *objs.add(i as usize) = lean_box(0);
726}
727
728#[inline]
729pub unsafe fn lean_ctor_get_usize(o: Obj, i: u32) -> usize {
730    debug_check_live(o, "field read");
731    ptr::read_unaligned(lean_ctor_obj_cptr(o).add(i as usize) as *const usize)
732}
733
734#[inline]
735pub unsafe fn lean_ctor_set_usize(o: Obj, i: u32, v: usize) {
736    debug_check_live(o, "field write");
737    ptr::write_unaligned(lean_ctor_obj_cptr(o).add(i as usize) as *mut usize, v)
738}
739
740macro_rules! ctor_scalar {
741    ($get:ident, $set:ident, $t:ty) => {
742        /// Reads a scalar field at `offset` bytes from the start of the object fields.
743        #[inline]
744        pub unsafe fn $get(o: Obj, offset: u32) -> $t {
745            debug_check_live(o, "field read");
746            ptr::read_unaligned(
747                (lean_ctor_obj_cptr(o) as *const u8).add(offset as usize) as *const $t
748            )
749        }
750        /// Writes a scalar field at `offset` bytes from the start of the object fields.
751        #[inline]
752        pub unsafe fn $set(o: Obj, offset: u32, v: $t) {
753            debug_check_live(o, "field write");
754            ptr::write_unaligned(
755                (lean_ctor_obj_cptr(o) as *mut u8).add(offset as usize) as *mut $t,
756                v,
757            )
758        }
759    };
760}
761
762ctor_scalar!(lean_ctor_get_uint8, lean_ctor_set_uint8, u8);
763ctor_scalar!(lean_ctor_get_uint16, lean_ctor_set_uint16, u16);
764ctor_scalar!(lean_ctor_get_uint32, lean_ctor_set_uint32, u32);
765ctor_scalar!(lean_ctor_get_uint64, lean_ctor_set_uint64, u64);
766ctor_scalar!(lean_ctor_get_float, lean_ctor_set_float, f64);
767ctor_scalar!(lean_ctor_get_float32, lean_ctor_set_float32, f32);
768
769/* Boxing of scalars that do not fit a tagged pointer */
770
771#[inline]
772pub unsafe fn lean_box_uint32(v: u32) -> Obj {
773    lean_box(v as usize)
774}
775
776#[inline]
777pub unsafe fn lean_unbox_uint32(o: Obj) -> u32 {
778    lean_unbox(o) as u32
779}
780
781#[inline]
782pub unsafe fn lean_box_uint64(v: u64) -> Obj {
783    let r = lean_alloc_ctor(0, 0, 8);
784    lean_ctor_set_uint64(r, 0, v);
785    r
786}
787
788#[inline]
789pub unsafe fn lean_unbox_uint64(o: Obj) -> u64 {
790    lean_ctor_get_uint64(o, 0)
791}
792
793#[inline]
794pub unsafe fn lean_box_usize(v: usize) -> Obj {
795    let r = lean_alloc_ctor(0, 0, size_of::<usize>() as u32);
796    lean_ctor_set_usize(r, 0, v);
797    r
798}
799
800#[inline]
801pub unsafe fn lean_unbox_usize(o: Obj) -> usize {
802    lean_ctor_get_usize(o, 0)
803}
804
805#[inline]
806pub unsafe fn lean_box_float(v: f64) -> Obj {
807    let r = lean_alloc_ctor(0, 0, 8);
808    lean_ctor_set_float(r, 0, v);
809    r
810}
811
812#[inline]
813pub unsafe fn lean_unbox_float(o: Obj) -> f64 {
814    lean_ctor_get_float(o, 0)
815}
816
817#[inline]
818pub unsafe fn lean_box_float32(v: f32) -> Obj {
819    let r = lean_alloc_ctor(0, 0, 4);
820    lean_ctor_set_float32(r, 0, v);
821    r
822}
823
824#[inline]
825pub unsafe fn lean_unbox_float32(o: Obj) -> f32 {
826    lean_ctor_get_float32(o, 0)
827}
828
829/* Ref objects (`ST.Ref`) */
830
831#[inline]
832pub unsafe fn lean_alloc_ref(v: Obj) -> Obj {
833    let o = lean_alloc_small_object(size_of::<RefObject>());
834    lean_set_st_header(o, LEAN_REF as u32, 0);
835    (*(o as *mut RefObject)).m_value = v;
836    o
837}
838
839/* External objects */
840
841#[inline]
842pub unsafe fn lean_alloc_external(cls: *const ExternalClass, data: *mut c_void) -> Obj {
843    let o = lean_alloc_small_object(size_of::<ExternalObject>());
844    lean_set_st_header(o, LEAN_EXTERNAL as u32, 0);
845    let e = o as *mut ExternalObject;
846    (*e).m_class = cls;
847    (*e).m_data = data;
848    o
849}
850
851#[inline]
852pub unsafe fn lean_get_external_class(o: Obj) -> *const ExternalClass {
853    (*(o as *mut ExternalObject)).m_class
854}
855
856#[inline]
857pub unsafe fn lean_get_external_data(o: Obj) -> *mut c_void {
858    (*(o as *mut ExternalObject)).m_data
859}
860
861pub unsafe fn lean_set_external_data(o: Obj, data: *mut c_void) -> Obj {
862    if lean_is_exclusive(o) {
863        (*(o as *mut ExternalObject)).m_data = data;
864        o
865    } else {
866        let r = lean_alloc_external(lean_get_external_class(o), data);
867        lean_dec_ref(o);
868        r
869    }
870}
871
872/* Helpers shared by the other modules */
873
874#[inline]
875pub unsafe fn lean_closure_arg_cptr(o: Obj) -> *mut Obj {
876    (o as *mut u8).add(offset_of!(ClosureObject, m_objs)) as *mut Obj
877}
878
879#[inline]
880pub unsafe fn lean_array_cptr(o: Obj) -> *mut Obj {
881    (o as *mut u8).add(offset_of!(ArrayObject, m_data)) as *mut Obj
882}
883
884#[inline]
885pub unsafe fn lean_sarray_elem_size(o: Obj) -> u32 {
886    ((*o).m_other & !LEAN_LINEAR_MARK_MASK) as u32
887}
888
889pub use crate::panic::{
890    lean_internal_panic, lean_internal_panic_out_of_memory, lean_internal_panic_rc_overflow,
891    lean_internal_panic_unreachable,
892};
893
894/// Frees the memory of `o` unless it is a scalar (`del` in the IR).
895#[inline]
896pub unsafe fn lean_del_object(o: Obj) {
897    if !lean_is_scalar(o) {
898        lean_free_object(o);
899    }
900}