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
//! Lean's `Nat`: a natural number of any size.
//!
//! A number that fits in a word minus one bit is stored in the pointer bits; anything larger
//! is a heap object holding limbs. Every function keeps that invariant, so equal numbers have
//! equal representations. As in `lean.h`, arguments are borrowed and results are owned,
//! except for the `_mk` conversions, which consume their argument.

use crate::bignum;
use crate::object::{box_, dec, inc, is_scalar, new_header, unbox, Header, Obj, TAG_MPZ};
use std::cmp::Ordering;

/// The largest number stored in the pointer bits.
pub const MAX_SMALL: usize = usize::MAX >> 1;

/// A number too large for the pointer bits: this header, then the limbs, in one allocation.
/// `Int` uses the same object, with a sign.
#[repr(C)]
struct Big {
    header: Header,
    negative: bool,
    len: usize,
}

/// A new big-number object. The caller keeps the invariants of `Nat` or `Int`.
pub(crate) fn alloc_big(limbs: &[u64], negative: bool) -> Obj {
    unsafe {
        let big = crate::object::allocate(size_of::<Big>() + size_of_val(limbs)).cast::<Big>();
        big.write(Big { header: new_header(TAG_MPZ, 0, 0), negative, len: limbs.len() });
        std::ptr::copy_nonoverlapping(limbs.as_ptr(), big.add(1).cast::<u64>(), limbs.len());
        Obj::from_header(big.cast())
    }
}

/// The sign and the limbs of a big-number object.
pub(crate) unsafe fn big_parts<'a>(o: Obj) -> (bool, &'a [u64]) {
    let big = o.header().cast::<Big>();
    ((*big).negative, std::slice::from_raw_parts(big.add(1).cast::<u64>(), (*big).len))
}

/// A number equal to `o` that shares no count with it, for a Rust `Nat` or `Int` to hold:
/// `o` itself when it is in the pointer bits or is never counted, and a copy otherwise.
#[inline(always)]
pub(crate) unsafe fn unshared(o: Obj) -> Obj {
    // Most numbers are in the pointer bits, and for those this is all there is to do.
    if is_scalar(o) {
        return o;
    }
    unshared_object(o)
}

#[inline(never)]
unsafe fn unshared_object(o: Obj) -> Obj {
    if crate::object::is_persistent(o) {
        return o;
    }
    let (negative, limbs) = big_parts(o);
    alloc_big(limbs, negative)
}

/// The number `o` as a Rust `Nat` or `Int` holds it, giving up the reference to `o`: `o`
/// itself when nothing else counts on it, and a copy otherwise.
///
/// A Rust `Nat` or `Int` may be read from any thread and dropped on any thread, and Lean
/// counts references without synchronization. So the object one holds is never one that
/// something else counts: it is the only reference, or the object is never counted at all.
#[inline(always)]
pub(crate) unsafe fn owned(o: Obj) -> Obj {
    if is_scalar(o) || crate::object::is_exclusive(o) {
        return o;
    }
    owned_shared(o)
}

#[inline(never)]
unsafe fn owned_shared(o: Obj) -> Obj {
    let copy = unshared_object(o);
    // A number that is never counted came back as itself, and has no count to give up.
    dec(o);
    copy
}

pub(crate) unsafe fn free_big(o: Obj) {
    let big = o.header().cast::<Big>();
    crate::object::deallocate(big.cast(), size_of::<Big>() + (*big).len * size_of::<u64>());
}

/// The limbs of a number. `small` is scratch space for a number stored in the pointer bits.
unsafe fn limbs<'a>(o: Obj, small: &'a mut [u64; 1]) -> &'a [u64] {
    if is_scalar(o) {
        small[0] = unbox(o) as u64;
        if small[0] == 0 {
            &[]
        } else {
            small
        }
    } else {
        big_parts(o).1
    }
}

/// The number with these limbs. Only a number of 2^63 or more allocates.
fn from_limbs(mut limbs: &[u64]) -> Obj {
    // Equal numbers must have equal representations, whatever produced the limbs.
    while let [rest @ .., 0] = limbs {
        limbs = rest;
    }
    match limbs {
        [] => box_(0),
        [single] if *single <= MAX_SMALL as u64 => box_(*single as usize),
        _ => alloc_big(limbs, false),
    }
}

fn from_u64(value: u64) -> Obj {
    from_limbs(&[value])
}

fn from_u128(value: u128) -> Obj {
    from_limbs(&[value as u64, (value >> 64) as u64])
}

/// Applies `op` to the limbs of two numbers.
unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> bignum::Limbs) -> Obj {
    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
    from_limbs(&op(limbs(a, &mut sa), limbs(b, &mut sb)))
}

unsafe fn compare(a: Obj, b: Obj) -> Ordering {
    if is_scalar(a) && is_scalar(b) {
        return unbox(a).cmp(&unbox(b));
    }
    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
    bignum::compare(limbs(a, &mut sa), limbs(b, &mut sb))
}

/// The value as a machine word, if it is small enough to be an amount of memory.
unsafe fn small(o: Obj) -> Option<usize> {
    is_scalar(o).then(|| unbox(o))
}

pub fn usize_to_nat(n: usize) -> Obj {
    from_u64(n as u64)
}

pub fn unsigned_to_nat(n: u32) -> Obj {
    from_u64(n as u64)
}

pub fn uint64_to_nat(n: u64) -> Obj {
    from_u64(n)
}

pub fn uint8_to_nat(n: u8) -> Obj {
    box_(n as usize)
}

pub fn uint16_to_nat(n: u16) -> Obj {
    box_(n as usize)
}

pub fn uint32_to_nat(n: u32) -> Obj {
    from_u64(n as u64)
}

/// A literal too large for [`unsigned_to_nat`], from its decimal digits.
pub fn cstr_to_nat(digits: &str) -> Obj {
    from_limbs(&bignum::from_decimal(digits).expect("inlean: malformed Nat literal"))
}

/// The lowest 64 bits of a number.
unsafe fn low_bits(o: Obj) -> u64 {
    let mut scratch = [0u64; 1];
    limbs(o, &mut scratch).first().copied().unwrap_or(0)
}

macro_rules! of_nat {
    ($($name:ident $mk:ident $ty:ty),*) => {$(
        /// The number modulo the width of the result.
        pub unsafe fn $name(a: Obj) -> $ty {
            low_bits(a) as $ty
        }

        /// Like the function without `_mk`, but consumes the argument.
        pub unsafe fn $mk(a: Obj) -> $ty {
            let result = low_bits(a) as $ty;
            dec(a);
            result
        }
    )*};
}

of_nat!(
    uint8_of_nat uint8_of_nat_mk u8,
    uint16_of_nat uint16_of_nat_mk u16,
    uint32_of_nat uint32_of_nat_mk u32,
    uint64_of_nat uint64_of_nat_mk u64,
    usize_of_nat usize_of_nat_mk usize
);

pub unsafe fn int8_of_nat(a: Obj) -> u8 {
    low_bits(a) as u8
}

pub unsafe fn int16_of_nat(a: Obj) -> u16 {
    low_bits(a) as u16
}

pub unsafe fn int32_of_nat(a: Obj) -> u32 {
    low_bits(a) as u32
}

pub unsafe fn int64_of_nat(a: Obj) -> u64 {
    low_bits(a)
}

pub unsafe fn isize_of_nat(a: Obj) -> usize {
    low_bits(a) as usize
}

pub unsafe fn nat_succ(a: Obj) -> Obj {
    nat_add(a, box_(1))
}

pub unsafe fn nat_add(a: Obj, b: Obj) -> Obj {
    if is_scalar(a) && is_scalar(b) {
        // Each is below 2^63, so the sum fits a word.
        return from_u64(unbox(a) as u64 + unbox(b) as u64);
    }
    binary(a, b, bignum::add)
}

/// Truncated subtraction: zero when `b` is larger.
pub unsafe fn nat_sub(a: Obj, b: Obj) -> Obj {
    if is_scalar(a) && is_scalar(b) {
        return box_(unbox(a).saturating_sub(unbox(b)));
    }
    if compare(a, b) == Ordering::Less {
        return box_(0);
    }
    binary(a, b, bignum::sub)
}

pub unsafe fn nat_pred(a: Obj) -> Obj {
    nat_sub(a, box_(1))
}

pub unsafe fn nat_mul(a: Obj, b: Obj) -> Obj {
    if is_scalar(a) && is_scalar(b) {
        return from_u128(unbox(a) as u128 * unbox(b) as u128);
    }
    binary(a, b, bignum::mul)
}

/// Division rounding down; zero when the divisor is zero.
pub unsafe fn nat_div(a: Obj, b: Obj) -> Obj {
    if is_scalar(a) && is_scalar(b) {
        return box_(unbox(a).checked_div(unbox(b)).unwrap_or(0));
    }
    if b == box_(0) {
        return box_(0);
    }
    binary(a, b, |x, y| match bignum::power_of_two(y) {
        Some(bits) => bignum::shr(x, bits),
        None => bignum::divrem(x, y).0,
    })
}

/// Division of a number by one of its divisors.
pub unsafe fn nat_div_exact(a: Obj, b: Obj) -> Obj {
    nat_div(a, b)
}

/// Remainder; the dividend when the divisor is zero.
pub unsafe fn nat_mod(a: Obj, b: Obj) -> Obj {
    if is_scalar(a) && is_scalar(b) {
        return box_(unbox(a).checked_rem(unbox(b)).unwrap_or(unbox(a)));
    }
    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
    let (x, y) = (limbs(a, &mut sa), limbs(b, &mut sb));
    // The dividend is its own remainder when the divisor is zero or larger. With a power of
    // two as the divisor, which is how Lean reduces a `BitVec`, that is the usual case.
    let bits = bignum::power_of_two(y);
    let unchanged = match bits {
        Some(bits) => bignum::bit_length(x) <= bits,
        None => y.is_empty() || bignum::compare(x, y) == Ordering::Less,
    };
    if unchanged {
        inc(a);
        return a;
    }
    from_limbs(&match bits {
        Some(bits) => bignum::low_bits(x, bits),
        None => bignum::divrem(x, y).1,
    })
}

pub unsafe fn nat_dec_eq(a: Obj, b: Obj) -> u8 {
    (compare(a, b) == Ordering::Equal) as u8
}

pub unsafe fn nat_dec_lt(a: Obj, b: Obj) -> u8 {
    (compare(a, b) == Ordering::Less) as u8
}

pub unsafe fn nat_dec_le(a: Obj, b: Obj) -> u8 {
    (compare(a, b) != Ordering::Greater) as u8
}

pub unsafe fn nat_land(a: Obj, b: Obj) -> Obj {
    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p & q))
}

pub unsafe fn nat_lor(a: Obj, b: Obj) -> Obj {
    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p | q))
}

pub unsafe fn nat_lxor(a: Obj, b: Obj) -> Obj {
    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p ^ q))
}

/// A result this large cannot be stored; Lean's runtime gives up the same way.
fn too_large(what: &str) -> ! {
    panic!("inlean: out of memory: {what} is too large")
}

pub unsafe fn nat_shiftl(a: Obj, b: Obj) -> Obj {
    if a == box_(0) {
        return a;
    }
    let bits = small(b).unwrap_or_else(|| too_large("the shift amount"));
    binary(a, b, |x, _| bignum::shl(x, bits))
}

pub unsafe fn nat_shiftr(a: Obj, b: Obj) -> Obj {
    match small(b) {
        Some(bits) => binary(a, b, |x, _| bignum::shr(x, bits)),
        // Shifting out more bits than fit in memory leaves nothing.
        None => box_(0),
    }
}

pub unsafe fn nat_pow(a: Obj, b: Obj) -> Obj {
    if a == box_(0) || a == box_(1) {
        // 0^0 = 1, 0^n = 0, 1^n = 1, whatever the size of n.
        return if b == box_(0) { box_(1) } else { a };
    }
    let exponent = small(b).unwrap_or_else(|| too_large("the exponent"));
    binary(a, b, |x, _| bignum::pow(x, exponent))
}

pub unsafe fn nat_gcd(a: Obj, b: Obj) -> Obj {
    binary(a, b, bignum::gcd)
}

/// The position of the highest set bit; zero for zero.
pub unsafe fn nat_log2(a: Obj) -> Obj {
    let mut scratch = [0u64; 1];
    box_(bignum::bit_length(limbs(a, &mut scratch)).saturating_sub(1))
}

pub unsafe fn nat_powmod(base: Obj, exponent: Obj, modulus: Obj) -> Obj {
    let (mut sb, mut se, mut sm) = ([0u64; 1], [0u64; 1], [0u64; 1]);
    let (base, exponent, modulus) = (limbs(base, &mut sb), limbs(exponent, &mut se), limbs(modulus, &mut sm));
    if modulus.is_empty() {
        // Lean's `Nat.powMod b e 0` is `b ^ e % 0`, which is `b ^ e`.
        let exponent = match exponent {
            [] => 0,
            [single] if *single <= MAX_SMALL as u64 => *single as usize,
            _ => too_large("the exponent"),
        };
        return from_limbs(&bignum::pow(base, exponent));
    }
    let reduce = |x: &[u64]| bignum::divrem(x, modulus).1;
    let mut result = reduce(&[1]);
    let mut square = reduce(base);
    for bit in 0..bignum::bit_length(exponent) {
        if exponent[bit / 64] >> (bit % 64) & 1 == 1 {
            result = reduce(&bignum::mul(&result, &square));
        }
        square = reduce(&bignum::mul(&square, &square));
    }
    from_limbs(&result)
}

/// The nearest `f64`.
pub unsafe fn float_of_nat(a: Obj) -> f64 {
    let mut scratch = [0u64; 1];
    let limbs = limbs(a, &mut scratch);
    match limbs {
        [] => 0.0,
        [single] => *single as f64,
        _ => {
            // Keep the top 64 bits, with a sticky bit for everything below, so that the
            // conversion of that word rounds as the whole number would.
            let bits = bignum::bit_length(limbs);
            let shift = bits - 64;
            let mut top = bignum::shr(limbs, shift)[0];
            if *bignum::shl(&[top], shift) != *limbs {
                top |= 1;
            }
            (top as f64) * 2f64.powi(shift as i32)
        }
    }
}

/// The decimal digits of a number.
pub unsafe fn to_decimal(a: Obj) -> String {
    let mut scratch = [0u64; 1];
    bignum::to_decimal(limbs(a, &mut scratch))
}

/// The number as a `u128`, if it fits.
pub unsafe fn to_u128(a: Obj) -> Option<u128> {
    let mut scratch = [0u64; 1];
    match limbs(a, &mut scratch) {
        [] => Some(0),
        [low] => Some(*low as u128),
        [low, high] => Some((*high as u128) << 64 | *low as u128),
        _ => None,
    }
}

pub fn of_u128(value: u128) -> Obj {
    from_u128(value)
}

pub unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
    compare(a, b)
}

/// The functions of this module that generated code may call, named as in `lean.h` without
/// the `lean_` prefix.
/// The number with these limbs, least significant first. Only a number of 2^63 or more
/// allocates.
pub(crate) fn of_limbs(limbs: &[u64]) -> Obj {
    from_limbs(limbs)
}

/// Calls `read` with the limbs of a number, least significant first and without leading zeros.
pub(crate) unsafe fn with_limbs<R>(a: Obj, read: impl FnOnce(&[u64]) -> R) -> R {
    let mut scratch = [0u64; 1];
    read(limbs(a, &mut scratch))
}

pub(crate) const OPS: &[&str] = &[
    "usize_to_nat", "uint64_to_nat", "uint8_to_nat", "uint16_to_nat", "uint32_to_nat",
    "uint8_of_nat", "uint16_of_nat", "uint32_of_nat", "uint64_of_nat", "usize_of_nat",
    "uint8_of_nat_mk", "uint16_of_nat_mk", "uint32_of_nat_mk", "uint64_of_nat_mk", "usize_of_nat_mk",
    "int8_of_nat", "int16_of_nat", "int32_of_nat", "int64_of_nat", "isize_of_nat",
    "nat_succ", "nat_add", "nat_sub", "nat_pred", "nat_mul", "nat_div", "nat_div_exact", "nat_mod",
    "nat_dec_eq", "nat_dec_lt", "nat_dec_le", "nat_land", "nat_lor", "nat_lxor", "nat_shiftl",
    "nat_shiftr", "nat_pow", "nat_gcd", "nat_log2", "nat_powmod", "float_of_nat",
];