inlean-runtime 0.1.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
//! 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;
/// `Inlean.Map`. Lean uses this tag for objects foreign to its runtime.
pub const TAG_MAP: 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>();

/// 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
}

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)
}

unsafe fn allocate(size: usize) -> *mut Header {
    count_object(1);
    let layout = Layout::from_size_align_unchecked(size, WORD.max(8));
    let memory = alloc(layout);
    if memory.is_null() {
        handle_alloc_error(layout);
    }
    memory.cast()
}

unsafe fn deallocate(header: *mut Header, size: usize) {
    count_object(-1);
    dealloc(header.cast(), Layout::from_size_align_unchecked(size, WORD.max(8)));
}

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

/// 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_MAP => crate::map::free(o),
        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) {
    let mut pending: Vec<Obj> = Vec::new();
    let mut current = o;
    loop {
        for &child in children(current).into_iter().flatten() {
            if is_scalar(child) {
                continue;
            }
            let count = rc(child);
            if count.get() > 1 {
                count.set(count.get() - 1);
            } 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);
        for run in children(current) {
            pending.extend_from_slice(run);
        }
    }
}

// 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)
    }
}

/// 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
    }
}