inlean-runtime 0.1.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! 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, 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. `Int` uses the same object, with a sign.
#[repr(C)]
struct Big {
    header: Header,
    negative: bool,
    limbs: Vec<u64>,
}

/// A new big-number object. The caller keeps the invariants of `Nat` or `Int`.
pub(crate) fn alloc_big(limbs: Vec<u64>, negative: bool) -> Obj {
    crate::object::count_object(1);
    let big = Box::new(Big { header: new_header(TAG_MPZ, 0, 0), negative, limbs });
    Obj::from_header(Box::into_raw(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, &big.limbs)
}

pub(crate) unsafe fn free_big(o: Obj) {
    crate::object::count_object(-1);
    drop(Box::from_raw(o.header().cast::<Big>()));
}

/// 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 {
        &(*o.header().cast::<Big>()).limbs
    }
}

fn from_limbs(mut limbs: Vec<u64>) -> Obj {
    // Equal numbers must have equal representations, whatever produced the limbs.
    while limbs.last() == Some(&0) {
        limbs.pop();
    }
    match limbs.as_slice() {
        [] => 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(if value == 0 { Vec::new() } else { vec![value] })
}

fn from_u128(value: u128) -> Obj {
    let mut limbs = vec![value as u64, (value >> 64) as u64];
    while limbs.last() == Some(&0) {
        limbs.pop();
    }
    from_limbs(limbs)
}

/// Applies `op` to the limbs of two numbers.
unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> Vec<u64>) -> 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| 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)));
    }
    if b == box_(0) {
        return binary(a, b, |x, _| x.to_vec());
    }
    binary(a, b, |x, y| 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.
pub(crate) fn of_limbs(limbs: Vec<u64>) -> Obj {
    from_limbs(limbs)
}

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",
];