inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Lean's heap objects: the representation, reference counting, constructor objects,
//! boxing and closures.
//!
//! A value of a Lean type that is not an unboxed scalar is an [`Obj`]: either a pointer to a
//! heap object that starts with a [`Header`], or a number stored in the pointer bits with the
//! lowest bit set. The functions here are the ones generated code calls, with the semantics
//! of the functions of the same names in Lean's `lean.h`. They are `unsafe` in the same way:
//! the caller, which is code Lean's compiler produced, owns the reference counting.

use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
use std::cell::Cell;
use std::mem::size_of;
use std::sync::OnceLock;

/// Largest tag of a constructor object. Larger tags are the kinds below.
pub const MAX_CTOR_TAG: u8 = 243;
pub const TAG_CLOSURE: u8 = 245;
pub const TAG_ARRAY: u8 = 246;
pub const TAG_SARRAY: u8 = 248;
pub const TAG_STRING: u8 = 249;
pub const TAG_MPZ: u8 = 250;
/// An object that stands for an external value without holding it: see `Lent`. Lean uses this
/// tag for a reference cell, which this runtime has no primitive to make.
pub const TAG_LENT: u8 = 253;
/// A value of a type the runtime does not know. Lean uses this tag for the same purpose.
pub const TAG_EXTERNAL: u8 = 254;

/// Most arguments a closure's function takes as separate parameters.
pub const CLOSURE_MAX_ARGS: usize = 16;

/// What every heap object starts with.
#[repr(C)]
pub struct Header {
    /// Positive: the number of references, owned by one thread. Zero: the object is
    /// persistent, lives forever, and is never counted or mutated.
    rc: Cell<i32>,
    /// For a constructor object, its size in bytes.
    size: u16,
    /// For a constructor object, the number of object fields.
    other: u8,
    tag: u8,
}

const WORD: usize = size_of::<usize>();
const HEADER: usize = size_of::<Header>();
/// The alignment of every block an object is made in.
const BLOCK_ALIGN: usize = if WORD > 8 { WORD } else { 8 };

/// A Lean value that is not an unboxed scalar.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(transparent)]
pub struct Obj(*mut Header);

/// A number in the pointer bits. `n` must fit in a word minus one bit.
#[inline(always)]
pub fn box_(n: usize) -> Obj {
    Obj(std::ptr::without_provenance_mut((n << 1) | 1))
}

#[inline(always)]
pub fn unbox(o: Obj) -> usize {
    o.0.addr() >> 1
}

#[inline(always)]
pub fn is_scalar(o: Obj) -> bool {
    o.0.addr() & 1 == 1
}

impl Obj {
    #[inline(always)]
    pub(crate) fn from_header(header: *mut Header) -> Obj {
        Obj(header)
    }

    #[inline(always)]
    pub(crate) fn header(self) -> *mut Header {
        self.0
    }
}

impl Header {
    /// The kind-specific byte of the header.
    pub(crate) fn other(&self) -> u8 {
        self.other
    }
}

pub(crate) fn new_header(tag: u8, other: u8, size: u16) -> Header {
    Header { rc: Cell::new(1), size, other, tag }
}

#[inline(always)]
unsafe fn rc(o: Obj) -> &'static Cell<i32> {
    &(*o.0).rc
}

/// The kind of a heap object.
#[inline(always)]
pub unsafe fn ptr_tag(o: Obj) -> u8 {
    (*o.0).tag
}

/// The constructor index of a value of an inductive type.
#[inline(always)]
pub unsafe fn obj_tag(o: Obj) -> u32 {
    if is_scalar(o) {
        unbox(o) as u32
    } else {
        ptr_tag(o) as u32
    }
}

#[inline(always)]
pub unsafe fn inc_ref(o: Obj) {
    let count = rc(o);
    if count.get() > 0 {
        count.set(count.get() + 1);
    }
}

#[inline(always)]
pub unsafe fn inc_ref_n(o: Obj, n: u32) {
    let count = rc(o);
    if count.get() > 0 {
        count.set(count.get() + n as i32);
    }
}

#[inline(always)]
pub unsafe fn inc(o: Obj) {
    if !is_scalar(o) {
        inc_ref(o);
    }
}

#[inline(always)]
pub unsafe fn inc_n(o: Obj, n: u32) {
    if !is_scalar(o) {
        inc_ref_n(o, n);
    }
}

#[inline(always)]
pub unsafe fn dec_ref(o: Obj) {
    let count = rc(o);
    if count.get() > 1 {
        count.set(count.get() - 1);
    } else if count.get() == 1 {
        free(o);
    }
}

#[inline(always)]
pub unsafe fn dec(o: Obj) {
    if !is_scalar(o) {
        dec_ref(o);
    }
}

/// Whether this is the only reference to the object, so that it may be updated in place.
#[inline(always)]
pub unsafe fn is_exclusive(o: Obj) -> bool {
    !is_scalar(o) && rc(o).get() == 1
}

/// Whether the object is one that is never counted and never freed: a constant, or part of
/// one. Nothing writes to such an object, so any thread may read it.
#[inline(always)]
pub(crate) unsafe fn is_persistent(o: Obj) -> bool {
    !is_scalar(o) && rc(o).get() == 0
}

thread_local! {
    static LIVE: Cell<isize> = const { Cell::new(0) };
}

/// Notes that a heap object was created (`1`) or freed (`-1`) on this thread.
#[inline(always)]
pub(crate) fn count_object(change: isize) {
    if cfg!(debug_assertions) {
        LIVE.with(|live| live.set(live.get() + change));
    }
}

/// The number of heap objects this thread created and has not freed, for finding leaks in
/// tests. Persistent objects, which are never freed, count. Always zero in a release build.
pub fn live_objects() -> isize {
    LIVE.with(Cell::get)
}

/// Objects of up to this many bytes are recycled through [`Pool`].
const POOLED: usize = 128;
const GRAIN: usize = 8;

/// The freed small objects of this thread, by size, each list threaded through the first
/// word of its blocks. Lean code allocates and frees small objects at a high rate, and a
/// list makes both a few instructions. A list is only touched by its own thread, so no lock
/// is needed. An object can be freed on another thread than the one that made it, when a
/// `Nat` or an `Int` is sent there: its block then joins that thread's lists, which is sound
/// because every block is an allocation of its own.
struct Pool {
    free: [Cell<*mut u8>; POOLED / GRAIN],
    /// Set once the thread has arranged for the lists to be emptied when it ends.
    guarded: Cell<bool>,
    /// Set when the thread is ending and the lists have gone back to the system.
    closed: Cell<bool>,
}

/// Returns the blocks of the pool to the system at the end of the thread. It is apart from
/// the pool so that the pool itself needs no destructor, which would cost a check on every
/// allocation.
struct PoolGuard;

impl Drop for PoolGuard {
    fn drop(&mut self) {
        POOL.with(|pool| {
            pool.closed.set(true);
            for (class, list) in pool.free.iter().enumerate() {
                let mut block = list.replace(std::ptr::null_mut());
                while !block.is_null() {
                    unsafe {
                        let next = block.cast::<*mut u8>().read();
                        dealloc(block, Layout::from_size_align_unchecked((class + 1) * GRAIN, BLOCK_ALIGN));
                        block = next;
                    }
                }
            }
        });
    }
}

thread_local! {
    static POOL: Pool = const {
        Pool {
            free: [const { Cell::new(std::ptr::null_mut()) }; POOLED / GRAIN],
            guarded: Cell::new(false),
            closed: Cell::new(false),
        }
    };
    static POOL_GUARD: PoolGuard = const { PoolGuard };
}

/// The layout of a block for an object of `size` bytes, and its list in the pool if it is
/// small enough for one.
#[inline(always)]
fn block(size: usize) -> (Layout, Option<usize>) {
    let size = size.next_multiple_of(GRAIN).max(GRAIN);
    let layout = unsafe { Layout::from_size_align_unchecked(size, BLOCK_ALIGN) };
    (layout, (size <= POOLED).then(|| size / GRAIN - 1))
}

/// Arranges for this thread's pool to be emptied when the thread ends, and says whether it
/// could: a thread that is ending already has no one left to empty it.
#[cold]
fn guard_pool(pool: &Pool) -> bool {
    let guarded = POOL_GUARD.try_with(|_| ()).is_ok();
    pool.guarded.set(guarded);
    guarded
}

/// A block from the system. The first one a thread takes arranges for its pool to be
/// emptied when the thread ends.
#[cold]
unsafe fn allocate_fresh(layout: Layout) -> *mut u8 {
    POOL.with(|pool| {
        guard_pool(pool);
    });
    let memory = alloc(layout);
    if memory.is_null() {
        handle_alloc_error(layout);
    }
    memory
}

#[inline]
pub(crate) unsafe fn allocate(size: usize) -> *mut Header {
    count_object(1);
    let (layout, class) = block(size);
    if let Some(class) = class {
        let recycled = POOL.with(|pool| {
            let block = pool.free[class].get();
            if !block.is_null() {
                pool.free[class].set(block.cast::<*mut u8>().read());
            }
            block
        });
        if !recycled.is_null() {
            return recycled.cast();
        }
    }
    allocate_fresh(layout).cast()
}

#[inline]
pub(crate) unsafe fn deallocate(header: *mut Header, size: usize) {
    count_object(-1);
    let (layout, class) = block(size);
    let memory = header.cast::<u8>();
    let pooled = class.is_some_and(|class| {
        POOL.with(|pool| {
            if pool.closed.get() {
                return false;
            }
            // A thread that only frees what others made has a pool to empty as well. If it
            // is too late to arrange that, the block goes back to the system now.
            if !pool.guarded.get() && !guard_pool(pool) {
                return false;
            }
            memory.cast::<*mut u8>().write(pool.free[class].get());
            pool.free[class].set(memory);
            true
        })
    });
    if !pooled {
        dealloc(memory, layout);
    }
}

// Held values: a Rust value inside a Lean object. A string is a `String` in an object, an
// array a `Vec` of objects, and so on; what differs between them is only the value.

/// A Rust value that a Lean object can hold. Lean shares objects freely, so a holder that
/// wants a value of its own, to change it or to take it away, may have to copy it.
pub(crate) trait Hold: Sized {
    /// The kind of the objects that hold a value of this type.
    const TAG: u8;
    /// The kind-specific byte of their headers.
    const OTHER: u8 = 0;

    /// A value equal to this one, for another holder. A value that refers to Lean objects
    /// takes a reference to each of them.
    unsafe fn copy(&self) -> Self;
}

/// A value in a Lean object: what every object starts with, then the value. The order of
/// the fields is fixed so that a pointer to the object is a pointer to its header.
#[repr(C)]
struct Held<T> {
    header: Header,
    value: T,
}

/// Whether an object that holds a `T` fits the blocks of [`allocate`], which are aligned
/// for a word. A type that needs more, such as one with a `u128` in it, gets a block of its
/// own from the system.
const fn fits_blocks<T>() -> bool {
    align_of::<Held<T>>() <= BLOCK_ALIGN
}

/// A new object that holds `value`.
pub(crate) fn hold<T: Hold>(value: T) -> Obj {
    unsafe {
        let held = if fits_blocks::<T>() {
            allocate(size_of::<Held<T>>()).cast::<Held<T>>()
        } else {
            count_object(1);
            let layout = Layout::new::<Held<T>>();
            let memory = alloc(layout);
            if memory.is_null() {
                handle_alloc_error(layout);
            }
            memory.cast::<Held<T>>()
        };
        held.write(Held { header: new_header(T::TAG, T::OTHER, 0), value });
        Obj(held.cast())
    }
}

/// The value an object holds.
#[inline(always)]
pub(crate) unsafe fn held<'a, T: Hold>(o: Obj) -> &'a T {
    &(*o.0.cast::<Held<T>>()).value
}

/// The value out of an object nothing else refers to. Gives up the object, and leaves what
/// the value refers to with the value.
pub(crate) unsafe fn take_held<T: Hold>(o: Obj) -> T {
    let held = o.0.cast::<Held<T>>();
    let value = std::ptr::addr_of!((*held).value).read();
    if fits_blocks::<T>() {
        deallocate(o.0, size_of::<Held<T>>());
    } else {
        count_object(-1);
        dealloc(o.0.cast(), Layout::new::<Held<T>>());
    }
    value
}

/// The value of an object the caller owns, for changing in place: `o` itself if nothing
/// else refers to it, and otherwise a copy, with the reference to `o` given up.
pub(crate) unsafe fn held_mut<'a, T: Hold>(o: Obj) -> (Obj, &'a mut T) {
    let o = if is_exclusive(o) {
        o
    } else {
        let copy = hold(held::<T>(o).copy());
        dec_ref(o);
        copy
    };
    (o, &mut (*o.0.cast::<Held<T>>()).value)
}

/// The value an object holds, giving up one reference to the object: the value itself if
/// nothing else refers to the object, and a copy otherwise.
pub(crate) unsafe fn into_held<T: Hold>(o: Obj) -> T {
    if is_exclusive(o) {
        return take_held(o);
    }
    let copy = held::<T>(o).copy();
    dec_ref(o);
    copy
}

// External values: a value of a type the runtime does not know, such as the Rust type a
// crate names for an opaque Lean type. Lean never looks inside one. It only shares the
// object and gives it up, so all the runtime has to know is how to free it.

/// What the runtime knows about the type of an external value.
pub(crate) struct Class {
    /// Frees an object that holds a value of the type, and drops the value.
    free: unsafe fn(Obj),
}

/// An external value as an object holds it: with its class first, so that the class is
/// found without knowing the type.
#[repr(C)]
struct External<T> {
    class: &'static Class,
    value: T,
}

impl<T: Clone + 'static> External<T> {
    const CLASS: &'static Class = &Class { free: free_external::<T> };
}

impl<T: Clone + 'static> Hold for External<T> {
    const TAG: u8 = TAG_EXTERNAL;
    /// Where the class is in the object, which depends on the alignment of the value.
    const OTHER: u8 = {
        let offset = std::mem::offset_of!(Held<External<T>>, value);
        assert!(offset <= u8::MAX as usize, "inlean: an external type is aligned to more than a header can say");
        offset as u8
    };

    unsafe fn copy(&self) -> External<T> {
        External { class: self.class, value: self.value.clone() }
    }
}

unsafe fn free_external<T: Clone + 'static>(o: Obj) {
    drop(take_held::<External<T>>(o));
}

/// A new object that holds the external value `value`.
pub(crate) fn hold_external<T: Clone + 'static>(value: T) -> Obj {
    hold(External { class: External::<T>::CLASS, value })
}

/// An external value that an object stands for without holding it: the address of a value
/// that belongs to the caller of an exported function, who lends it for the call.
///
/// Lean treats the object as it treats any external value: it shares it and gives it up. What
/// it must never do is take the value out, since the value is not the object's to give. So the
/// two places that read an external value look at the kind of the object first, and freeing
/// the object frees only the object.
struct Lent(*const ());

impl Hold for Lent {
    const TAG: u8 = TAG_LENT;

    unsafe fn copy(&self) -> Lent {
        Lent(self.0)
    }
}

/// A new object that stands for `value` while the caller's borrow of it lasts.
///
/// # Safety
/// Every reference to the object is given up before the borrow of `value` ends. An exported
/// function meets this by converting what Lean returns before it returns itself: a value
/// that comes back out is a clone, and Lean keeps nothing from one call to the next but
/// constants, which cannot depend on an argument.
pub(crate) unsafe fn lend_external<T: Clone + 'static>(value: &T) -> Obj {
    hold(Lent(std::ptr::from_ref(value).cast()))
}

/// Whether the object stands for a value that is lent to it, which must not be taken out.
///
/// # Safety
/// `o` is an object, not a scalar.
#[inline(always)]
pub(crate) unsafe fn is_lent(o: Obj) -> bool {
    ptr_tag(o) == TAG_LENT
}

/// The external value an object holds or stands for.
///
/// # Safety
/// `o` was made by [`hold_external`] or [`lend_external`] for a value of type `T`.
pub(crate) unsafe fn external<'a, T: Clone + 'static>(o: Obj) -> &'a T {
    if is_lent(o) {
        return &*held::<Lent>(o).0.cast::<T>();
    }
    &held::<External<T>>(o).value
}

/// The external value out of an object nothing else refers to. Gives up the object.
///
/// # Safety
/// `o` was made by [`hold_external`] for a value of type `T`, and the caller owns the only
/// reference to it.
pub(crate) unsafe fn take_external<T: Clone + 'static>(o: Obj) -> T {
    take_held::<External<T>>(o).value
}

/// Frees an object that holds an external value of whatever type.
unsafe fn free_any_external(o: Obj) {
    let class = o.0.cast::<u8>().add((*o.0).other as usize).cast::<&'static Class>().read();
    (class.free)(o);
}

/// The objects an object refers to.
unsafe fn children(o: Obj) -> &'static [Obj] {
    match ptr_tag(o) {
        tag if tag <= MAX_CTOR_TAG => std::slice::from_raw_parts(ctor_fields(o), (*o.0).other as usize),
        TAG_CLOSURE => {
            let closure = o.0.cast::<Closure>();
            std::slice::from_raw_parts(closure_args(o), (*closure).num_fixed as usize)
        }
        TAG_ARRAY => crate::array::elements(o),
        _ => &[],
    }
}

/// Releases the memory of an object without touching the objects it refers to.
pub unsafe fn free_object(o: Obj) {
    if is_scalar(o) {
        return;
    }
    match ptr_tag(o) {
        tag if tag <= MAX_CTOR_TAG => deallocate(o.0, (*o.0).size as usize),
        TAG_CLOSURE => {
            let closure = o.0.cast::<Closure>();
            deallocate(o.0, closure_size((*closure).num_fixed as usize));
        }
        TAG_ARRAY => crate::array::free(o),
        TAG_SARRAY => crate::sarray::free(o),
        TAG_STRING => crate::string::free(o),
        TAG_MPZ => crate::nat::free_big(o),
        TAG_EXTERNAL => free_any_external(o),
        TAG_LENT => deallocate(o.0, size_of::<Held<Lent>>()),
        tag => unreachable!("inlean: object of unknown kind {tag}"),
    }
}

/// Frees an object whose last reference is gone, and everything only it kept alive. The
/// work list is on the heap, so a long list does not overflow the stack.
unsafe fn free(o: Obj) {
    if ptr_tag(o) == TAG_MPZ {
        // A number refers to nothing, and numbers are what arithmetic frees all the time.
        return crate::nat::free_big(o);
    }
    let mut pending: Vec<Obj> = Vec::new();
    let mut current = o;
    loop {
        for &child in children(current) {
            if is_scalar(child) {
                continue;
            }
            let count = rc(child);
            if count.get() > 1 {
                count.set(count.get() - 1);
            } else if count.get() == 1 && ptr_tag(child) == TAG_MPZ {
                crate::nat::free_big(child);
            } else if count.get() == 1 {
                pending.push(child);
            }
        }
        free_object(current);
        match pending.pop() {
            Some(next) => current = next,
            None => return,
        }
    }
}

/// Makes an object and everything it refers to persistent: never counted, never freed,
/// never updated in place, and therefore safe to read from any thread.
pub unsafe fn mark_persistent(o: Obj) {
    let mut pending = vec![o];
    while let Some(current) = pending.pop() {
        if is_scalar(current) || rc(current).get() == 0 {
            continue;
        }
        rc(current).set(0);
        pending.extend_from_slice(children(current));
    }
}

// Constructor objects: header, object fields, then `usize` fields, then other scalars.

#[inline(always)]
unsafe fn ctor_fields(o: Obj) -> *mut Obj {
    o.0.cast::<u8>().add(HEADER).cast()
}

/// A constructor object with `num_objs` object fields, `num_usize` word-sized scalar fields
/// and `scalar_size` bytes of other scalar fields, all uninitialized.
pub unsafe fn alloc_ctor(tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32) -> Obj {
    let size = HEADER + (num_objs + num_usize) as usize * WORD + scalar_size as usize;
    let size = size.next_multiple_of(WORD.max(8));
    let header = allocate(size);
    header.write(new_header(tag as u8, num_objs as u8, size as u16));
    Obj(header)
}

#[inline(always)]
pub unsafe fn ctor_get(o: Obj, i: u32) -> Obj {
    *ctor_fields(o).add(i as usize)
}

#[inline(always)]
pub unsafe fn ctor_set(o: Obj, i: u32, value: Obj) {
    *ctor_fields(o).add(i as usize) = value;
}

#[inline(always)]
pub unsafe fn ctor_set_tag(o: Obj, tag: u32) {
    (*o.0).tag = tag as u8;
}

/// Drops field `i` of a constructor object that is about to be reused.
#[inline(always)]
pub unsafe fn ctor_release(o: Obj, i: u32) {
    let field = ctor_fields(o).add(i as usize);
    dec(*field);
    // The object may still be freed instead of reused; the field must not be dropped twice.
    *field = box_(0);
}

/// Prepares constructor object `o`, which has `num_objs` object fields, for reuse: returns
/// its memory if nothing else refers to it, and otherwise drops the reference and returns
/// `box_(0)`.
pub unsafe fn reset(o: Obj, num_objs: u32) -> Obj {
    if is_exclusive(o) {
        for i in 0..num_objs {
            ctor_release(o, i);
        }
        o
    } else {
        dec_ref(o);
        box_(0)
    }
}

/// A constructor object for the given constructor, in the memory `reset` returned if it
/// returned any.
pub unsafe fn reuse(memory: Obj, tag: u32, num_objs: u32, num_usize: u32, scalar_size: u32, update_tag: bool) -> Obj {
    if is_scalar(memory) {
        alloc_ctor(tag, num_objs, num_usize, scalar_size)
    } else {
        if update_tag {
            ctor_set_tag(memory, tag);
        }
        memory
    }
}

#[inline(always)]
pub unsafe fn ctor_get_usize(o: Obj, slot: u32) -> usize {
    ctor_fields(o).add(slot as usize).cast::<usize>().read()
}

#[inline(always)]
pub unsafe fn ctor_set_usize(o: Obj, slot: u32, value: usize) {
    ctor_fields(o).add(slot as usize).cast::<usize>().write(value);
}

macro_rules! ctor_scalars {
    ($($get:ident $set:ident $ty:ty),*) => {$(
        /// Reads the scalar `offset` bytes after the first `slots` word-sized fields.
        #[inline(always)]
        pub unsafe fn $get(o: Obj, slots: u32, offset: u32) -> $ty {
            ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().read_unaligned()
        }

        /// Writes the scalar `offset` bytes after the first `slots` word-sized fields.
        #[inline(always)]
        pub unsafe fn $set(o: Obj, slots: u32, offset: u32, value: $ty) {
            ctor_fields(o).cast::<u8>().add(slots as usize * WORD + offset as usize).cast::<$ty>().write_unaligned(value);
        }
    )*};
}

ctor_scalars!(
    ctor_get_uint8 ctor_set_uint8 u8,
    ctor_get_uint16 ctor_set_uint16 u16,
    ctor_get_uint32 ctor_set_uint32 u32,
    ctor_get_uint64 ctor_set_uint64 u64,
    ctor_get_float ctor_set_float f64,
    ctor_get_float32 ctor_set_float32 f32
);

// Boxing: a scalar where an object is expected, as in a field of a polymorphic structure.

/// A `u32` fits in the pointer bits of a 64-bit target only.
#[inline(always)]
pub unsafe fn box_uint32(value: u32) -> Obj {
    if WORD == 4 {
        let o = alloc_ctor(0, 0, 0, 4);
        ctor_set_uint32(o, 0, 0, value);
        o
    } else {
        box_(value as usize)
    }
}

#[inline(always)]
pub unsafe fn unbox_uint32(o: Obj) -> u32 {
    if WORD == 4 {
        ctor_get_uint32(o, 0, 0)
    } else {
        unbox(o) as u32
    }
}

pub unsafe fn box_uint64(value: u64) -> Obj {
    let o = alloc_ctor(0, 0, 0, 8);
    ctor_set_uint64(o, 0, 0, value);
    o
}

#[inline(always)]
pub unsafe fn unbox_uint64(o: Obj) -> u64 {
    ctor_get_uint64(o, 0, 0)
}

pub unsafe fn box_usize(value: usize) -> Obj {
    let o = alloc_ctor(0, 0, 1, 0);
    ctor_set_usize(o, 0, value);
    o
}

#[inline(always)]
pub unsafe fn unbox_usize(o: Obj) -> usize {
    ctor_get_usize(o, 0)
}

pub unsafe fn box_float(value: f64) -> Obj {
    let o = alloc_ctor(0, 0, 0, 8);
    ctor_set_float(o, 0, 0, value);
    o
}

#[inline(always)]
pub unsafe fn unbox_float(o: Obj) -> f64 {
    ctor_get_float(o, 0, 0)
}

pub unsafe fn box_float32(value: f32) -> Obj {
    let o = alloc_ctor(0, 0, 0, 4);
    ctor_set_float32(o, 0, 0, value);
    o
}

#[inline(always)]
pub unsafe fn unbox_float32(o: Obj) -> f32 {
    ctor_get_float32(o, 0, 0)
}

// Closures: a function and the first `num_fixed` of its `arity` arguments.

#[repr(C)]
struct Closure {
    header: Header,
    /// `unsafe fn(Obj, ..., Obj) -> Obj` with `arity` parameters.
    function: *const (),
    arity: u16,
    num_fixed: u16,
}

fn closure_size(num_fixed: usize) -> usize {
    size_of::<Closure>() + num_fixed * WORD
}

#[inline(always)]
unsafe fn closure_args(o: Obj) -> *mut Obj {
    o.0.cast::<u8>().add(size_of::<Closure>()).cast()
}

/// A closure of `function`, which takes `arity` objects and returns an object, with room
/// for `num_fixed` arguments that [`closure_set`] must fill.
pub unsafe fn alloc_closure(function: *const (), arity: u32, num_fixed: u32) -> Obj {
    let closure = allocate(closure_size(num_fixed as usize)).cast::<Closure>();
    closure.write(Closure {
        header: new_header(TAG_CLOSURE, 0, 0),
        function,
        arity: arity as u16,
        num_fixed: num_fixed as u16,
    });
    Obj(closure.cast())
}

#[inline(always)]
pub unsafe fn closure_set(o: Obj, i: u32, value: Obj) {
    *closure_args(o).add(i as usize) = value;
}

unsafe fn call(function: *const (), args: &[Obj]) -> Obj {
    use std::mem::transmute as cast;
    type O = Obj;
    let a = args;
    match a.len() {
        1 => cast::<_, unsafe fn(O) -> O>(function)(a[0]),
        2 => cast::<_, unsafe fn(O, O) -> O>(function)(a[0], a[1]),
        3 => cast::<_, unsafe fn(O, O, O) -> O>(function)(a[0], a[1], a[2]),
        4 => cast::<_, unsafe fn(O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3]),
        5 => cast::<_, unsafe fn(O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4]),
        6 => cast::<_, unsafe fn(O, O, O, O, O, O) -> O>(function)(a[0], a[1], a[2], a[3], a[4], a[5]),
        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]),
        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]),
        9 => cast::<_, unsafe fn(O, 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], a[8],
        ),
        10 => cast::<_, unsafe fn(O, O, 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], a[8], a[9],
        ),
        11 => cast::<_, unsafe fn(O, O, O, 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], a[8], a[9], a[10],
        ),
        12 => cast::<_, unsafe fn(O, O, O, O, 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], a[8], a[9], a[10], a[11],
        ),
        13 => cast::<_, unsafe fn(O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12],
        ),
        14 => cast::<_, unsafe fn(O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13],
        ),
        15 => cast::<_, unsafe fn(O, O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13], a[14],
        ),
        16 => cast::<_, unsafe fn(O, O, O, O, O, O, O, O, 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], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
        ),
        n => panic!("inlean: a function of {n} arguments cannot be called through a closure"),
    }
}

/// Applies closure `f` to `args`. Consumes `f` and the arguments.
///
/// With fewer arguments than the function still needs, the result is a new closure. With
/// more, the function's result is applied to the rest.
pub unsafe fn apply(f: Obj, args: &[Obj]) -> Obj {
    let closure = f.0.cast::<Closure>();
    let (function, arity, fixed) = ((*closure).function, (*closure).arity as usize, (*closure).num_fixed as usize);
    let stored = std::slice::from_raw_parts(closure_args(f), fixed);
    if fixed + args.len() < arity {
        let extended = alloc_closure(function, arity as u32, (fixed + args.len()) as u32);
        for (i, &arg) in stored.iter().chain(args).enumerate() {
            closure_set(extended, i as u32, arg);
        }
        take_stored(f, stored);
        return extended;
    }
    let (now, later) = args.split_at(arity - fixed);
    let mut all = [box_(0); CLOSURE_MAX_ARGS];
    assert!(arity <= CLOSURE_MAX_ARGS, "inlean: a function of {arity} arguments cannot be called through a closure");
    all[..fixed].copy_from_slice(stored);
    all[fixed..arity].copy_from_slice(now);
    take_stored(f, stored);
    let result = call(function, &all[..arity]);
    if later.is_empty() {
        result
    } else {
        apply(result, later)
    }
}

/// A Lean function that a declaration bound to Rust was given: a closure, and a reference
/// to it.
pub struct Function(Obj);

impl Function {
    /// # Safety
    /// `raw` is a closure of this runtime, and the caller owns a reference to it. A value
    /// that only stands in for a function Lean holds, and is not dropped, may wrap any.
    #[inline(always)]
    pub unsafe fn from_raw(raw: Obj) -> Function {
        Function(raw)
    }

    /// Calls the function with `arguments`, which it takes over, and gives what it returns.
    ///
    /// # Safety
    /// `arguments` are the objects the function takes, as many as it takes and each a value
    /// of the type it expects, and the caller owns a reference to each.
    #[inline]
    pub unsafe fn call(&self, arguments: &[Obj]) -> Obj {
        // Applying a closure gives up a reference to it, and this one is kept.
        inc(self.0);
        apply(self.0, arguments)
    }
}

impl Drop for Function {
    #[inline]
    fn drop(&mut self) {
        unsafe { dec(self.0) };
    }
}

/// Gives up a reference to closure `f` whose stored arguments were just copied out: the
/// copies become owners of the arguments.
unsafe fn take_stored(f: Obj, stored: &[Obj]) {
    if is_exclusive(f) {
        free_object(f);
    } else {
        for &arg in stored {
            inc(arg);
        }
        dec_ref(f);
    }
}

/// A Lean constant that is an object: computed on first use, then persistent.
pub struct Constant(OnceLock<Shared>);

struct Shared(Obj);

// A persistent object is immutable and is never counted, so any thread may read it.
unsafe impl Send for Shared {}
unsafe impl Sync for Shared {}

impl Constant {
    #[allow(clippy::new_without_default)]
    pub const fn new() -> Constant {
        Constant(OnceLock::new())
    }

    /// The value of the constant; `init` computes it if this is the first use. The result is
    /// a borrowed reference: counting it has no effect.
    pub unsafe fn get(&self, init: unsafe fn() -> Obj) -> Obj {
        self.0
            .get_or_init(|| {
                let value = init();
                mark_persistent(value);
                Shared(value)
            })
            .0
    }
}