//! `Int`: tagged small ints, promoted to big integers outside 63 bits //! (ADR 0014). //! //! A big integer is a `TAG_BIGINT` block whose raw area holds an `i64` //! `len` (`|len|` limbs; its sign is the number's), then `|len|` 64-bit //! limbs of the magnitude, least significant first. It never holds a //! number in the 63-bit range: results are *canonical*, small whenever //! they fit, so two equal `Int`s are equal words or two blocks with equal //! limbs, and a small int never equals a big one. //! //! The inline fast paths in `louise_rt.h` (`tl_int_add`, `tl_int_sub`, //! `tl_int_mul`, `tl_int_div`, `tl_int_rem`, `tl_int_eq`, //! `tl_int_compare`) handle two small ints whose result is small; //! everything else (and a division by zero) comes here, to the `_slow` //! functions. Big arithmetic goes through `num-bigint`, as in the //! interpreter (`louise_interp`'s `int`), so both backends compute, print and //! hash alike. Like every `@extern` function these borrow their arguments. use num_bigint::{BigInt, BigUint, Sign}; use num_traits::ToPrimitive; use louise_rt_prims::{SMALL_INT, hash_limbs, mix}; use crate::abi::{Block, Ctx, TAG_BIGINT, Value, int, int_get, is_ptr}; use crate::heap::tl_alloc; use crate::prims::{boolean, order, panic_with}; const WORD: usize = size_of::(); /// The sign-and-length word and the limbs of a big integer (borrowed). /// /// # Safety /// `v` must be a live big integer. unsafe fn limbs<'a>(v: Value) -> (i64, &'a [u64]) { // SAFETY: a big integer's raw area is its length word, then the limbs. unsafe { let raw = Block::fields_ptr(v as *mut Block).cast::(); let len = raw.read(); let limbs = std::slice::from_raw_parts(raw.add(1).cast::(), len.unsigned_abs() as usize); (len, limbs) } } /// The value of an `Int` (borrowed). /// /// # Safety /// `v` must be a live `Int`. pub(crate) unsafe fn to_big(v: Value) -> BigInt { if !is_ptr(v) { return BigInt::from(int_get(v)); } // SAFETY: forwarded caller guarantee. let (len, limbs) = unsafe { limbs(v) }; let digits: Vec = limbs .iter() .flat_map(|l| [*l as u32, (l >> 32) as u32]) .collect(); let sign = if len < 0 { Sign::Minus } else { Sign::Plus }; BigInt::from_biguint(sign, BigUint::new(digits)) } /// `n` as an `Int` (owned): small if it fits in 63 bits. pub(crate) fn from_big(ctx: *mut Ctx, n: &BigInt) -> Value { if let Some(small) = n.to_i64().filter(|v| SMALL_INT.contains(v)) { return int(small); } let (sign, digits) = n.to_u64_digits(); let b = tl_alloc(ctx, TAG_BIGINT, 0, WORD * (1 + digits.len())); let len = digits.len() as i64; // SAFETY: the raw area holds the length word and `digits.len()` limbs. unsafe { let raw = Block::fields_ptr(b).cast::(); raw.write(if sign == Sign::Minus { -len } else { len }); std::ptr::copy_nonoverlapping(digits.as_ptr(), raw.add(1).cast::(), digits.len()); } b as Value } /// `n` as an `Int` (owned): small if it fits in 63 bits. pub(crate) fn from_i128(ctx: *mut Ctx, n: i128) -> Value { match i64::try_from(n) { Ok(small) if SMALL_INT.contains(&small) => int(small), _ => from_big(ctx, &BigInt::from(n)), } } /// An `Int` used as an index, a count, a size or a duration: the nearest /// `i64` (a big integer saturates). The interpreter does the same. /// /// # Safety /// `v` must be a live `Int`. pub(crate) unsafe fn saturating(v: Value) -> i64 { if !is_ptr(v) { return int_get(v); } // SAFETY: forwarded caller guarantee. if unsafe { limbs(v) }.0 < 0 { i64::MIN } else { i64::MAX } } /// A binary operation on two `Int`s: `small` when both are small, `big` /// otherwise. `small` computes in 64 bits, where 63-bit operands only /// overflow a product (it returns `None` then). Not in 128 bits: a /// 128-bit division is a library call, several times slower. /// /// # Safety /// `a` and `b` must be live `Int`s. unsafe fn binary( ctx: *mut Ctx, a: Value, b: Value, small: impl Fn(i64, i64) -> Option, big: impl Fn(BigInt, BigInt) -> BigInt, ) -> Value { if !is_ptr(a) && !is_ptr(b) && let Some(r) = small(int_get(a), int_get(b)) { return from_i128(ctx, i128::from(r)); } // SAFETY: forwarded caller guarantee. let (x, y) = unsafe { (to_big(a), to_big(b)) }; from_big(ctx, &big(x, y)) } /// `a + b` when it overflows 63 bits or an argument is big (`tl_int_add`'s /// slow path). /// /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_add_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x + y), |x, y| x + y) } } /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_sub_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x - y), |x, y| x - y) } } /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_mul_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, i64::checked_mul, |x, y| x * y) } } /// Truncating division; panics on division by zero. /// /// # Safety /// `ctx` must be the running actor's context; `a` and `b` live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_div_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { if b == int(0) { // SAFETY: caller guarantees the running actor's context. return unsafe { panic_with(ctx, "division by zero") }; } // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x / y), |x, y| x / y) } } /// The remainder of the truncating division (the sign of `a`); panics on /// division by zero. /// /// # Safety /// `ctx` must be the running actor's context; `a` and `b` live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_rem_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { if b == int(0) { // SAFETY: caller guarantees the running actor's context. return unsafe { panic_with(ctx, "division by zero") }; } // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x % y), |x, y| x % y) } } /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_eq_slow(_ctx: *mut Ctx, a: Value, b: Value) -> Value { // Canonical forms: a small int equals only the same word. if a == b || !is_ptr(a) || !is_ptr(b) { return boolean(a == b); } // SAFETY: both are live big integers. boolean(unsafe { limbs(a) == limbs(b) }) } /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_compare_slow(_ctx: *mut Ctx, a: Value, b: Value) -> Value { if !is_ptr(a) && !is_ptr(b) { return order(int_get(a).cmp(&int_get(b))); } // SAFETY: forwarded caller guarantee. order(unsafe { to_big(a).cmp(&to_big(b)) }) } /// Decimal, every digit. /// /// # Safety /// `a` must be a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_show(ctx: *mut Ctx, a: Value) -> Value { let text = if is_ptr(a) { // SAFETY: forwarded caller guarantee. unsafe { to_big(a) }.to_string() } else { int_get(a).to_string() }; // SAFETY: `text` is valid for its length. unsafe { crate::values::tl_string_from(ctx, text.as_ptr().cast(), text.len()) } } /// Small ints: mixed. Big integers: FNV-1a over the limbs, complemented /// when negative, then mixed (the interpreter's formula too). /// /// # Safety /// `a` must be a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_hash_int(_ctx: *mut Ctx, a: Value) -> Value { if !is_ptr(a) { return int(mix(int_get(a) as u64)); } // SAFETY: forwarded caller guarantee. let (len, limbs) = unsafe { limbs(a) }; int(mix(hash_limbs(len < 0, limbs))) } /// The `Int` written in `text`: an optional sign, then decimal digits (no /// other character), of any length. pub(crate) fn parse(text: &str) -> Option { let digits = text.strip_prefix(['+', '-']).unwrap_or(text); if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { return None; } let n: BigInt = digits.parse().ok()?; Some(if text.starts_with('-') { -n } else { n }) } /// The `i64` of an `Int` in C bindings: false when it does not fit. /// /// # Safety /// `v` must be a live `Int`; `out` valid for a write. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_to_i64(v: Value, out: *mut i64) -> bool { // SAFETY: forwarded caller guarantee. match unsafe { to_big(v) }.to_i64() { Some(n) => { // SAFETY: forwarded caller guarantee. unsafe { out.write(n) }; true } None => false, } } /// An `Int` (owned) from C bindings: big outside 63 bits. #[unsafe(no_mangle)] pub extern "C" fn tl_int_from_i64(ctx: *mut Ctx, n: i64) -> Value { from_i128(ctx, i128::from(n)) } // ---- bitwise operations (std/int, ADR 0035) ------------------------------------------ // // Two's complement with infinite sign extension, as num-bigint (and Python) // compute: `-1` is all ones, so a small and a big operand give the same // result as if both were big. The inline fast paths in `louise_rt.h` handle // two small operands; these are the rest. /// `int.and` when an argument is big. /// /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_and_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x & y), |x, y| x & y) } } /// `int.or` when an argument is big. /// /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_or_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x | y), |x, y| x | y) } } /// `int.xor` when an argument is big. /// /// # Safety /// `a` and `b` must be live `Int`s. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_xor_slow(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { binary(ctx, a, b, |x, y| Some(x ^ y), |x, y| x ^ y) } } /// `int.not` of a big integer: `-n - 1`. /// /// # Safety /// `a` must be a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_not_slow(ctx: *mut Ctx, a: Value) -> Value { // SAFETY: forwarded caller guarantee. from_big(ctx, &!unsafe { to_big(a) }) } /// `int.shift_left(n, k)` when the fast path can't: a big `n` or `k`, a /// result outside 63 bits, or a negative `k` (a panic). `k ≥ 2^32` of a /// non-zero `n` panics instead of exhausting memory. /// /// # Safety /// `n` and `k` must be live `Int`s; `ctx` the running actor's. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_shift_left_slow(ctx: *mut Ctx, n: Value, k: Value) -> Value { // SAFETY: forwarded caller guarantee. let (n, k) = unsafe { (to_big(n), to_big(k)) }; if k.sign() == Sign::Minus { // SAFETY: forwarded caller guarantee. return unsafe { panic_with( ctx, &louise_rt_prims::negative_shift("int.shift_left", &k.to_string()), ) }; } if n.sign() == Sign::NoSign { return int(0); } match k.to_u64().filter(|k| *k < louise_rt_prims::MAX_SHIFT) { Some(k) => from_big(ctx, &(n << k)), // SAFETY: forwarded caller guarantee. None => unsafe { panic_with(ctx, &louise_rt_prims::shift_too_large(&k.to_string())) }, } } /// `int.shift_right(n, k)`, arithmetic (rounds towards minus infinity), /// when the fast path can't: a big `n` or `k`, or a negative `k` (a panic). /// /// # Safety /// `n` and `k` must be live `Int`s; `ctx` the running actor's. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_shift_right_slow(ctx: *mut Ctx, n: Value, k: Value) -> Value { // SAFETY: forwarded caller guarantee. let (n, k) = unsafe { (to_big(n), to_big(k)) }; if k.sign() == Sign::Minus { // SAFETY: forwarded caller guarantee. return unsafe { panic_with( ctx, &louise_rt_prims::negative_shift("int.shift_right", &k.to_string()), ) }; } match k.to_u64().filter(|k| *k < louise_rt_prims::MAX_SHIFT) { Some(k) => from_big(ctx, &(n >> k)), // Every bit shifted out: the sign is what's left. None => int(if n.sign() == Sign::Minus { -1 } else { 0 }), } } /// `int.bit_length(n)`: the number of bits of `|n|` (0 for 0). /// /// # Safety /// `n` must be a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_int_bit_length(_ctx: *mut Ctx, n: Value) -> Value { if !is_ptr(n) { return int(i64::from(64 - int_get(n).unsigned_abs().leading_zeros())); } // SAFETY: forwarded caller guarantee. int(unsafe { to_big(n) }.bits() as i64) } /// `float.from_int(n)`: the nearest Float (ties to even); an infinity past /// the largest Float. /// /// # Safety /// `n` must be a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_float_from_int(ctx: *mut Ctx, n: Value) -> Value { let x = if is_ptr(n) { // SAFETY: forwarded caller guarantee. unsafe { to_big(n) }.to_f64().unwrap_or(f64::NAN) } else { int_get(n) as f64 }; crate::prims::tl_float_from(ctx, x) } /// The low 64 bits of an `Int`, two's complement (`-1` is all ones). /// /// # Safety /// `n` must be a live `Int`. pub(crate) unsafe fn low_u64(n: Value) -> u64 { if !is_ptr(n) { return int_get(n) as u64; } // SAFETY: forwarded caller guarantee. let big = unsafe { to_big(n) } & BigInt::from(u64::MAX); big.to_u64().unwrap_or(0) } #[cfg(test)] mod tests { use super::*; #[test] fn parsing_decimal_ints() { for (text, n) in [("0", 0), ("+7", 7), ("-12", -12), ("007", 7)] { assert_eq!(parse(text), Some(BigInt::from(n)), "{text:?}"); } let big = "-123456789012345678901234567890"; assert_eq!(parse(big).map(|n| n.to_string()).as_deref(), Some(big)); for text in [ "", "+", "-", "--1", "+-1", " 1", "1 ", "1_000", "0x10", "1e3", "١", ] { assert_eq!(parse(text), None, "{text:?}"); } } /// Small `Int`s need no block, so `saturating` and `to_big` read them /// without a heap. #[test] fn small_ints_read_as_themselves() { for n in [0, -1, (1 << 62) - 1, -(1 << 62)] { // SAFETY: small ints are not pointers. let (s, b) = unsafe { (saturating(int(n)), to_big(int(n))) }; assert_eq!((s, b), (n, BigInt::from(n))); } } }