Skip to main content

inlean_runtime/
nat.rs

1//! Lean's `Nat`: a natural number of any size.
2//!
3//! A number that fits in a word minus one bit is stored in the pointer bits; anything larger
4//! is a heap object holding limbs. Every function keeps that invariant, so equal numbers have
5//! equal representations. As in `lean.h`, arguments are borrowed and results are owned,
6//! except for the `_mk` conversions, which consume their argument.
7
8use crate::bignum;
9use crate::object::{box_, dec, inc, is_scalar, new_header, unbox, Header, Obj, TAG_MPZ};
10use std::cmp::Ordering;
11
12/// The largest number stored in the pointer bits.
13pub const MAX_SMALL: usize = usize::MAX >> 1;
14
15/// A number too large for the pointer bits: this header, then the limbs, in one allocation.
16/// `Int` uses the same object, with a sign.
17#[repr(C)]
18struct Big {
19    header: Header,
20    negative: bool,
21    len: usize,
22}
23
24/// A new big-number object. The caller keeps the invariants of `Nat` or `Int`.
25pub(crate) fn alloc_big(limbs: &[u64], negative: bool) -> Obj {
26    unsafe {
27        let big = crate::object::allocate(size_of::<Big>() + size_of_val(limbs)).cast::<Big>();
28        big.write(Big { header: new_header(TAG_MPZ, 0, 0), negative, len: limbs.len() });
29        std::ptr::copy_nonoverlapping(limbs.as_ptr(), big.add(1).cast::<u64>(), limbs.len());
30        Obj::from_header(big.cast())
31    }
32}
33
34/// The sign and the limbs of a big-number object.
35pub(crate) unsafe fn big_parts<'a>(o: Obj) -> (bool, &'a [u64]) {
36    let big = o.header().cast::<Big>();
37    ((*big).negative, std::slice::from_raw_parts(big.add(1).cast::<u64>(), (*big).len))
38}
39
40/// A number equal to `o` that shares no count with it, for a Rust `Nat` or `Int` to hold:
41/// `o` itself when it is in the pointer bits or is never counted, and a copy otherwise.
42#[inline(always)]
43pub(crate) unsafe fn unshared(o: Obj) -> Obj {
44    // Most numbers are in the pointer bits, and for those this is all there is to do.
45    if is_scalar(o) {
46        return o;
47    }
48    unshared_object(o)
49}
50
51#[inline(never)]
52unsafe fn unshared_object(o: Obj) -> Obj {
53    if crate::object::is_persistent(o) {
54        return o;
55    }
56    let (negative, limbs) = big_parts(o);
57    alloc_big(limbs, negative)
58}
59
60/// The number `o` as a Rust `Nat` or `Int` holds it, giving up the reference to `o`: `o`
61/// itself when nothing else counts on it, and a copy otherwise.
62///
63/// A Rust `Nat` or `Int` may be read from any thread and dropped on any thread, and Lean
64/// counts references without synchronization. So the object one holds is never one that
65/// something else counts: it is the only reference, or the object is never counted at all.
66#[inline(always)]
67pub(crate) unsafe fn owned(o: Obj) -> Obj {
68    if is_scalar(o) || crate::object::is_exclusive(o) {
69        return o;
70    }
71    owned_shared(o)
72}
73
74#[inline(never)]
75unsafe fn owned_shared(o: Obj) -> Obj {
76    let copy = unshared_object(o);
77    // A number that is never counted came back as itself, and has no count to give up.
78    dec(o);
79    copy
80}
81
82pub(crate) unsafe fn free_big(o: Obj) {
83    let big = o.header().cast::<Big>();
84    crate::object::deallocate(big.cast(), size_of::<Big>() + (*big).len * size_of::<u64>());
85}
86
87/// The limbs of a number. `small` is scratch space for a number stored in the pointer bits.
88unsafe fn limbs<'a>(o: Obj, small: &'a mut [u64; 1]) -> &'a [u64] {
89    if is_scalar(o) {
90        small[0] = unbox(o) as u64;
91        if small[0] == 0 {
92            &[]
93        } else {
94            small
95        }
96    } else {
97        big_parts(o).1
98    }
99}
100
101/// The number with these limbs. Only a number of 2^63 or more allocates.
102fn from_limbs(mut limbs: &[u64]) -> Obj {
103    // Equal numbers must have equal representations, whatever produced the limbs.
104    while let [rest @ .., 0] = limbs {
105        limbs = rest;
106    }
107    match limbs {
108        [] => box_(0),
109        [single] if *single <= MAX_SMALL as u64 => box_(*single as usize),
110        _ => alloc_big(limbs, false),
111    }
112}
113
114fn from_u64(value: u64) -> Obj {
115    from_limbs(&[value])
116}
117
118fn from_u128(value: u128) -> Obj {
119    from_limbs(&[value as u64, (value >> 64) as u64])
120}
121
122/// Applies `op` to the limbs of two numbers.
123unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> bignum::Limbs) -> Obj {
124    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
125    from_limbs(&op(limbs(a, &mut sa), limbs(b, &mut sb)))
126}
127
128unsafe fn compare(a: Obj, b: Obj) -> Ordering {
129    if is_scalar(a) && is_scalar(b) {
130        return unbox(a).cmp(&unbox(b));
131    }
132    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
133    bignum::compare(limbs(a, &mut sa), limbs(b, &mut sb))
134}
135
136/// The value as a machine word, if it is small enough to be an amount of memory.
137unsafe fn small(o: Obj) -> Option<usize> {
138    is_scalar(o).then(|| unbox(o))
139}
140
141pub fn usize_to_nat(n: usize) -> Obj {
142    from_u64(n as u64)
143}
144
145pub fn unsigned_to_nat(n: u32) -> Obj {
146    from_u64(n as u64)
147}
148
149pub fn uint64_to_nat(n: u64) -> Obj {
150    from_u64(n)
151}
152
153pub fn uint8_to_nat(n: u8) -> Obj {
154    box_(n as usize)
155}
156
157pub fn uint16_to_nat(n: u16) -> Obj {
158    box_(n as usize)
159}
160
161pub fn uint32_to_nat(n: u32) -> Obj {
162    from_u64(n as u64)
163}
164
165/// A literal too large for [`unsigned_to_nat`], from its decimal digits.
166pub fn cstr_to_nat(digits: &str) -> Obj {
167    from_limbs(&bignum::from_decimal(digits).expect("inlean: malformed Nat literal"))
168}
169
170/// The lowest 64 bits of a number.
171unsafe fn low_bits(o: Obj) -> u64 {
172    let mut scratch = [0u64; 1];
173    limbs(o, &mut scratch).first().copied().unwrap_or(0)
174}
175
176macro_rules! of_nat {
177    ($($name:ident $mk:ident $ty:ty),*) => {$(
178        /// The number modulo the width of the result.
179        pub unsafe fn $name(a: Obj) -> $ty {
180            low_bits(a) as $ty
181        }
182
183        /// Like the function without `_mk`, but consumes the argument.
184        pub unsafe fn $mk(a: Obj) -> $ty {
185            let result = low_bits(a) as $ty;
186            dec(a);
187            result
188        }
189    )*};
190}
191
192of_nat!(
193    uint8_of_nat uint8_of_nat_mk u8,
194    uint16_of_nat uint16_of_nat_mk u16,
195    uint32_of_nat uint32_of_nat_mk u32,
196    uint64_of_nat uint64_of_nat_mk u64,
197    usize_of_nat usize_of_nat_mk usize
198);
199
200pub unsafe fn int8_of_nat(a: Obj) -> u8 {
201    low_bits(a) as u8
202}
203
204pub unsafe fn int16_of_nat(a: Obj) -> u16 {
205    low_bits(a) as u16
206}
207
208pub unsafe fn int32_of_nat(a: Obj) -> u32 {
209    low_bits(a) as u32
210}
211
212pub unsafe fn int64_of_nat(a: Obj) -> u64 {
213    low_bits(a)
214}
215
216pub unsafe fn isize_of_nat(a: Obj) -> usize {
217    low_bits(a) as usize
218}
219
220pub unsafe fn nat_succ(a: Obj) -> Obj {
221    nat_add(a, box_(1))
222}
223
224pub unsafe fn nat_add(a: Obj, b: Obj) -> Obj {
225    if is_scalar(a) && is_scalar(b) {
226        // Each is below 2^63, so the sum fits a word.
227        return from_u64(unbox(a) as u64 + unbox(b) as u64);
228    }
229    binary(a, b, bignum::add)
230}
231
232/// Truncated subtraction: zero when `b` is larger.
233pub unsafe fn nat_sub(a: Obj, b: Obj) -> Obj {
234    if is_scalar(a) && is_scalar(b) {
235        return box_(unbox(a).saturating_sub(unbox(b)));
236    }
237    if compare(a, b) == Ordering::Less {
238        return box_(0);
239    }
240    binary(a, b, bignum::sub)
241}
242
243pub unsafe fn nat_pred(a: Obj) -> Obj {
244    nat_sub(a, box_(1))
245}
246
247pub unsafe fn nat_mul(a: Obj, b: Obj) -> Obj {
248    if is_scalar(a) && is_scalar(b) {
249        return from_u128(unbox(a) as u128 * unbox(b) as u128);
250    }
251    binary(a, b, bignum::mul)
252}
253
254/// Division rounding down; zero when the divisor is zero.
255pub unsafe fn nat_div(a: Obj, b: Obj) -> Obj {
256    if is_scalar(a) && is_scalar(b) {
257        return box_(unbox(a).checked_div(unbox(b)).unwrap_or(0));
258    }
259    if b == box_(0) {
260        return box_(0);
261    }
262    binary(a, b, |x, y| match bignum::power_of_two(y) {
263        Some(bits) => bignum::shr(x, bits),
264        None => bignum::divrem(x, y).0,
265    })
266}
267
268/// Division of a number by one of its divisors.
269pub unsafe fn nat_div_exact(a: Obj, b: Obj) -> Obj {
270    nat_div(a, b)
271}
272
273/// Remainder; the dividend when the divisor is zero.
274pub unsafe fn nat_mod(a: Obj, b: Obj) -> Obj {
275    if is_scalar(a) && is_scalar(b) {
276        return box_(unbox(a).checked_rem(unbox(b)).unwrap_or(unbox(a)));
277    }
278    let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
279    let (x, y) = (limbs(a, &mut sa), limbs(b, &mut sb));
280    // The dividend is its own remainder when the divisor is zero or larger. With a power of
281    // two as the divisor, which is how Lean reduces a `BitVec`, that is the usual case.
282    let bits = bignum::power_of_two(y);
283    let unchanged = match bits {
284        Some(bits) => bignum::bit_length(x) <= bits,
285        None => y.is_empty() || bignum::compare(x, y) == Ordering::Less,
286    };
287    if unchanged {
288        inc(a);
289        return a;
290    }
291    from_limbs(&match bits {
292        Some(bits) => bignum::low_bits(x, bits),
293        None => bignum::divrem(x, y).1,
294    })
295}
296
297pub unsafe fn nat_dec_eq(a: Obj, b: Obj) -> u8 {
298    (compare(a, b) == Ordering::Equal) as u8
299}
300
301pub unsafe fn nat_dec_lt(a: Obj, b: Obj) -> u8 {
302    (compare(a, b) == Ordering::Less) as u8
303}
304
305pub unsafe fn nat_dec_le(a: Obj, b: Obj) -> u8 {
306    (compare(a, b) != Ordering::Greater) as u8
307}
308
309pub unsafe fn nat_land(a: Obj, b: Obj) -> Obj {
310    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p & q))
311}
312
313pub unsafe fn nat_lor(a: Obj, b: Obj) -> Obj {
314    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p | q))
315}
316
317pub unsafe fn nat_lxor(a: Obj, b: Obj) -> Obj {
318    binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p ^ q))
319}
320
321/// A result this large cannot be stored; Lean's runtime gives up the same way.
322fn too_large(what: &str) -> ! {
323    panic!("inlean: out of memory: {what} is too large")
324}
325
326pub unsafe fn nat_shiftl(a: Obj, b: Obj) -> Obj {
327    if a == box_(0) {
328        return a;
329    }
330    let bits = small(b).unwrap_or_else(|| too_large("the shift amount"));
331    binary(a, b, |x, _| bignum::shl(x, bits))
332}
333
334pub unsafe fn nat_shiftr(a: Obj, b: Obj) -> Obj {
335    match small(b) {
336        Some(bits) => binary(a, b, |x, _| bignum::shr(x, bits)),
337        // Shifting out more bits than fit in memory leaves nothing.
338        None => box_(0),
339    }
340}
341
342pub unsafe fn nat_pow(a: Obj, b: Obj) -> Obj {
343    if a == box_(0) || a == box_(1) {
344        // 0^0 = 1, 0^n = 0, 1^n = 1, whatever the size of n.
345        return if b == box_(0) { box_(1) } else { a };
346    }
347    let exponent = small(b).unwrap_or_else(|| too_large("the exponent"));
348    binary(a, b, |x, _| bignum::pow(x, exponent))
349}
350
351pub unsafe fn nat_gcd(a: Obj, b: Obj) -> Obj {
352    binary(a, b, bignum::gcd)
353}
354
355/// The position of the highest set bit; zero for zero.
356pub unsafe fn nat_log2(a: Obj) -> Obj {
357    let mut scratch = [0u64; 1];
358    box_(bignum::bit_length(limbs(a, &mut scratch)).saturating_sub(1))
359}
360
361pub unsafe fn nat_powmod(base: Obj, exponent: Obj, modulus: Obj) -> Obj {
362    let (mut sb, mut se, mut sm) = ([0u64; 1], [0u64; 1], [0u64; 1]);
363    let (base, exponent, modulus) = (limbs(base, &mut sb), limbs(exponent, &mut se), limbs(modulus, &mut sm));
364    if modulus.is_empty() {
365        // Lean's `Nat.powMod b e 0` is `b ^ e % 0`, which is `b ^ e`.
366        let exponent = match exponent {
367            [] => 0,
368            [single] if *single <= MAX_SMALL as u64 => *single as usize,
369            _ => too_large("the exponent"),
370        };
371        return from_limbs(&bignum::pow(base, exponent));
372    }
373    let reduce = |x: &[u64]| bignum::divrem(x, modulus).1;
374    let mut result = reduce(&[1]);
375    let mut square = reduce(base);
376    for bit in 0..bignum::bit_length(exponent) {
377        if exponent[bit / 64] >> (bit % 64) & 1 == 1 {
378            result = reduce(&bignum::mul(&result, &square));
379        }
380        square = reduce(&bignum::mul(&square, &square));
381    }
382    from_limbs(&result)
383}
384
385/// The nearest `f64`.
386pub unsafe fn float_of_nat(a: Obj) -> f64 {
387    let mut scratch = [0u64; 1];
388    let limbs = limbs(a, &mut scratch);
389    match limbs {
390        [] => 0.0,
391        [single] => *single as f64,
392        _ => {
393            // Keep the top 64 bits, with a sticky bit for everything below, so that the
394            // conversion of that word rounds as the whole number would.
395            let bits = bignum::bit_length(limbs);
396            let shift = bits - 64;
397            let mut top = bignum::shr(limbs, shift)[0];
398            if *bignum::shl(&[top], shift) != *limbs {
399                top |= 1;
400            }
401            (top as f64) * 2f64.powi(shift as i32)
402        }
403    }
404}
405
406/// The decimal digits of a number.
407pub unsafe fn to_decimal(a: Obj) -> String {
408    let mut scratch = [0u64; 1];
409    bignum::to_decimal(limbs(a, &mut scratch))
410}
411
412/// The number as a `u128`, if it fits.
413pub unsafe fn to_u128(a: Obj) -> Option<u128> {
414    let mut scratch = [0u64; 1];
415    match limbs(a, &mut scratch) {
416        [] => Some(0),
417        [low] => Some(*low as u128),
418        [low, high] => Some((*high as u128) << 64 | *low as u128),
419        _ => None,
420    }
421}
422
423pub fn of_u128(value: u128) -> Obj {
424    from_u128(value)
425}
426
427pub unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
428    compare(a, b)
429}
430
431/// The functions of this module that generated code may call, named as in `lean.h` without
432/// the `lean_` prefix.
433/// The number with these limbs, least significant first. Only a number of 2^63 or more
434/// allocates.
435pub(crate) fn of_limbs(limbs: &[u64]) -> Obj {
436    from_limbs(limbs)
437}
438
439/// Calls `read` with the limbs of a number, least significant first and without leading zeros.
440pub(crate) unsafe fn with_limbs<R>(a: Obj, read: impl FnOnce(&[u64]) -> R) -> R {
441    let mut scratch = [0u64; 1];
442    read(limbs(a, &mut scratch))
443}
444
445pub(crate) const OPS: &[&str] = &[
446    "usize_to_nat", "uint64_to_nat", "uint8_to_nat", "uint16_to_nat", "uint32_to_nat",
447    "uint8_of_nat", "uint16_of_nat", "uint32_of_nat", "uint64_of_nat", "usize_of_nat",
448    "uint8_of_nat_mk", "uint16_of_nat_mk", "uint32_of_nat_mk", "uint64_of_nat_mk", "usize_of_nat_mk",
449    "int8_of_nat", "int16_of_nat", "int32_of_nat", "int64_of_nat", "isize_of_nat",
450    "nat_succ", "nat_add", "nat_sub", "nat_pred", "nat_mul", "nat_div", "nat_div_exact", "nat_mod",
451    "nat_dec_eq", "nat_dec_lt", "nat_dec_le", "nat_land", "nat_lor", "nat_lxor", "nat_shiftl",
452    "nat_shiftr", "nat_pow", "nat_gcd", "nat_log2", "nat_powmod", "float_of_nat",
453];