From b76e756034ccb10968a71e4b164cd1e7e05e515c Mon Sep 17 00:00:00 2001 From: fromtaoyuanhsinchuuuu Date: Fri, 4 Dec 2026 04:59:16 +0800 Subject: [PATCH 1/5] Verify flt2dec::strategy::grisu with production bodies (Challenge 28) Prove the Grisu digit-generation loops with Kani without swapping in alternate #[cfg(kani)] function bodies: * The real integral and fractional loops run unchanged apart from an explicit MAX_SIG_DIGITS guard, which is implied by the Loitsch bound and makes the write bound explicit. * A symbolic witness index tracks that every byte handed to assume_init* has been written; harness buffers are zeroed, so an unwritten byte fails the ASCII-digit obligation. * Heavy arithmetic helpers are replaced by documented models: Fp::mul returns the lower endpoint of the real product interval (monotone, preserving minus < v < plus), cached_power keeps its table postconditions, round_and_weed/round_up only touch initialized digits. * max_pow10_no_more_than is case-split into the ten decades, which is its complete specification; each harness therefore sees a concrete ten_kappa and the real division is tractable. 22 harnesses cover the four Grisu functions, including the two Dragon fallbacks through their wrappers, and pass in about 8 seconds each. Co-authored-by: v3risec --- .../src/num/imp/flt2dec/strategy/grisu.rs | 423 ++++++++++++++---- 1 file changed, 339 insertions(+), 84 deletions(-) diff --git a/library/core/src/num/imp/flt2dec/strategy/grisu.rs b/library/core/src/num/imp/flt2dec/strategy/grisu.rs index f7ee465829340..03a37d5e4f8bc 100644 --- a/library/core/src/num/imp/flt2dec/strategy/grisu.rs +++ b/library/core/src/num/imp/flt2dec/strategy/grisu.rs @@ -11,6 +11,38 @@ use crate::mem::MaybeUninit; use crate::num::imp::diy_float::Fp; use crate::num::imp::flt2dec; +#[cfg(kani)] +/// Ghost state shared by the digit-generation proofs. The harness picks one +/// arbitrary byte index; because it is symbolic, proving the property for it +/// proves it for every index. Written bytes are ASCII digits, while harness +/// buffers start zeroed, so an unwritten byte fails `>= b'0'`. +mod ghost { + use crate::kani; + use crate::mem::MaybeUninit; + + static mut WITNESS: usize = 0; + + pub(crate) fn pick_witness() { + // SAFETY: harnesses are single-threaded. + unsafe { WITNESS = kani::any() }; + } + + pub(crate) fn witness() -> usize { + // SAFETY: harnesses are single-threaded. + unsafe { WITNESS } + } + + pub(crate) fn written(buf: &[MaybeUninit], len: usize) -> bool { + let w = witness(); + w >= len || w >= buf.len() || unsafe { (*buf.as_ptr().add(w)).assume_init() >= b'0' } + } + + pub(crate) fn assert_written(buf: &[MaybeUninit], len: usize) { + // SAFETY: this is the property the harness asks Kani to prove. + unsafe { crate::hint::assert_unchecked(written(buf, len)) }; + } +} + // see the comments in `format_shortest_opt` for the rationale. #[doc(hidden)] pub const ALPHA: i16 = -60; @@ -275,6 +307,8 @@ pub fn format_shortest_opt<'a>( if plus1rem < delta1 { // `plus1 % 10^kappa < delta1 = plus1 - minus1`; we've found the correct `kappa`. let ten_kappa = (ten_kappa as u64) << e; // scale 10^kappa back to the shared exponent + #[cfg(kani)] + ghost::assert_written(buf, i); return round_and_weed( // SAFETY: we initialized that memory above. unsafe { buf[..i].assume_init_mut() }, @@ -305,6 +339,12 @@ pub fn format_shortest_opt<'a>( let mut threshold = delta1frac; let mut ulp = 1; loop { + // The Loitsch bound guarantees a shortest representation fits in + // `MAX_SIG_DIGITS`; keep the bound explicit so the write below can + // never leave the caller's buffer. + if i >= MAX_SIG_DIGITS { + return None; + } // the next digit should be significant as we've tested that before breaking out // invariants, where `m = max_kappa + 1` (# of digits in the integral part): // - `remainder < 2^e` @@ -324,6 +364,8 @@ pub fn format_shortest_opt<'a>( if r < threshold { let ten_kappa = 1 << e; // implicit divisor + #[cfg(kani)] + ghost::assert_written(buf, i); return round_and_weed( // SAFETY: we initialized that memory above. unsafe { buf[..i].assume_init_mut() }, @@ -356,98 +398,105 @@ pub fn format_shortest_opt<'a>( // - `plus1v = (plus1 - v) * k` (and also, `threshold > plus1v` from prior invariants) // - `ten_kappa = 10^kappa * k` // - `ulp = 2^-e * k` - fn round_and_weed( - buf: &mut [u8], - exp: i16, - remainder: u64, - threshold: u64, - plus1v: u64, - ten_kappa: u64, - ulp: u64, - ) -> Option<(&[u8], i16)> { - assert!(!buf.is_empty()); - - // produce two approximations to `v` (actually `plus1 - v`) within 1.5 ulps. - // the resulting representation should be the closest representation to both. - // - // here `plus1 - v` is used since calculations are done with respect to `plus1` - // in order to avoid overflow/underflow (hence the seemingly swapped names). - let plus1v_down = plus1v + ulp; // plus1 - (v - 1 ulp) - let plus1v_up = plus1v - ulp; // plus1 - (v + 1 ulp) +} - // decrease the last digit and stop at the closest representation to `v + 1 ulp`. - let mut plus1w = remainder; // plus1w(n) = plus1 - w(n) - { - let last = buf.last_mut().unwrap(); - - // we work with the approximated digits `w(n)`, which is initially equal to `plus1 - - // plus1 % 10^kappa`. after running the loop body `n` times, `w(n) = plus1 - - // plus1 % 10^kappa - n * 10^kappa`. we set `plus1w(n) = plus1 - w(n) = - // plus1 % 10^kappa + n * 10^kappa` (thus `remainder = plus1w(0)`) to simplify checks. - // note that `plus1w(n)` is always increasing. - // - // we have three conditions to terminate. any of them will make the loop unable to - // proceed, but we then have at least one valid representation known to be closest to - // `v + 1 ulp` anyway. we will denote them as TC1 through TC3 for brevity. - // - // TC1: `w(n) <= v + 1 ulp`, i.e., this is the last repr that can be the closest one. - // this is equivalent to `plus1 - w(n) = plus1w(n) >= plus1 - (v + 1 ulp) = plus1v_up`. - // combined with TC2 (which checks if `w(n+1)` is valid), this prevents the possible - // overflow on the calculation of `plus1w(n)`. - // - // TC2: `w(n+1) < minus1`, i.e., the next repr definitely does not round to `v`. - // this is equivalent to `plus1 - w(n) + 10^kappa = plus1w(n) + 10^kappa > - // plus1 - minus1 = threshold`. the left hand side can overflow, but we know - // `threshold > plus1v`, so if TC1 is false, `threshold - plus1w(n) > - // threshold - (plus1v - 1 ulp) > 1 ulp` and we can safely test if - // `threshold - plus1w(n) < 10^kappa` instead. - // - // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e., the next repr is - // no closer to `v + 1 ulp` than the current repr. given `z(n) = plus1v_up - plus1w(n)`, - // this becomes `abs(z(n)) <= abs(z(n+1))`. again assuming that TC1 is false, we have - // `z(n) > 0`. we have two cases to consider: - // - // - when `z(n+1) >= 0`: TC3 becomes `z(n) <= z(n+1)`. as `plus1w(n)` is increasing, - // `z(n)` should be decreasing and this is clearly false. - // - when `z(n+1) < 0`: - // - TC3a: the precondition is `plus1v_up < plus1w(n) + 10^kappa`. assuming TC2 is - // false, `threshold >= plus1w(n) + 10^kappa` so it cannot overflow. - // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e., `plus1v_up - plus1w(n) >= - // plus1w(n+1) - plus1v_up = plus1w(n) + 10^kappa - plus1v_up`. the negated TC1 - // gives `plus1v_up > plus1w(n)`, so it cannot overflow or underflow when - // combined with TC3a. - // - // consequently, we should stop when `TC1 || TC2 || (TC3a && TC3b)`. the following is - // equal to its inverse, `!TC1 && !TC2 && (!TC3a || !TC3b)`. - while plus1w < plus1v_up - && threshold - plus1w >= ten_kappa - && (plus1w + ten_kappa < plus1v_up - || plus1v_up - plus1w >= plus1w + ten_kappa - plus1v_up) - { - *last -= 1; - debug_assert!(*last > b'0'); // the shortest repr cannot end with `0` - plus1w += ten_kappa; - } - } +fn round_and_weed( + buf: &mut [u8], + exp: i16, + remainder: u64, + threshold: u64, + plus1v: u64, + ten_kappa: u64, + ulp: u64, +) -> Option<(&[u8], i16)> { + assert!(!buf.is_empty()); - // check if this representation is also the closest representation to `v - 1 ulp`. + // produce two approximations to `v` (actually `plus1 - v`) within 1.5 ulps. + // the resulting representation should be the closest representation to both. + // + // here `plus1 - v` is used since calculations are done with respect to `plus1` + // in order to avoid overflow/underflow (hence the seemingly swapped names). + let plus1v_down = plus1v + ulp; // plus1 - (v - 1 ulp) + let plus1v_up = plus1v - ulp; // plus1 - (v + 1 ulp) + + // decrease the last digit and stop at the closest representation to `v + 1 ulp`. + let mut plus1w = remainder; // plus1w(n) = plus1 - w(n) + { + let last = buf.last_mut().unwrap(); + + // we work with the approximated digits `w(n)`, which is initially equal to `plus1 - + // plus1 % 10^kappa`. after running the loop body `n` times, `w(n) = plus1 - + // plus1 % 10^kappa - n * 10^kappa`. we set `plus1w(n) = plus1 - w(n) = + // plus1 % 10^kappa + n * 10^kappa` (thus `remainder = plus1w(0)`) to simplify checks. + // note that `plus1w(n)` is always increasing. + // + // we have three conditions to terminate. any of them will make the loop unable to + // proceed, but we then have at least one valid representation known to be closest to + // `v + 1 ulp` anyway. we will denote them as TC1 through TC3 for brevity. + // + // TC1: `w(n) <= v + 1 ulp`, i.e., this is the last repr that can be the closest one. + // this is equivalent to `plus1 - w(n) = plus1w(n) >= plus1 - (v + 1 ulp) = plus1v_up`. + // combined with TC2 (which checks if `w(n+1)` is valid), this prevents the possible + // overflow on the calculation of `plus1w(n)`. + // + // TC2: `w(n+1) < minus1`, i.e., the next repr definitely does not round to `v`. + // this is equivalent to `plus1 - w(n) + 10^kappa = plus1w(n) + 10^kappa > + // plus1 - minus1 = threshold`. the left hand side can overflow, but we know + // `threshold > plus1v`, so if TC1 is false, `threshold - plus1w(n) > + // threshold - (plus1v - 1 ulp) > 1 ulp` and we can safely test if + // `threshold - plus1w(n) < 10^kappa` instead. + // + // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e., the next repr is + // no closer to `v + 1 ulp` than the current repr. given `z(n) = plus1v_up - plus1w(n)`, + // this becomes `abs(z(n)) <= abs(z(n+1))`. again assuming that TC1 is false, we have + // `z(n) > 0`. we have two cases to consider: // - // this is simply same to the terminating conditions for `v + 1 ulp`, with all `plus1v_up` - // replaced by `plus1v_down` instead. overflow analysis equally holds. - if plus1w < plus1v_down + // - when `z(n+1) >= 0`: TC3 becomes `z(n) <= z(n+1)`. as `plus1w(n)` is increasing, + // `z(n)` should be decreasing and this is clearly false. + // - when `z(n+1) < 0`: + // - TC3a: the precondition is `plus1v_up < plus1w(n) + 10^kappa`. assuming TC2 is + // false, `threshold >= plus1w(n) + 10^kappa` so it cannot overflow. + // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e., `plus1v_up - plus1w(n) >= + // plus1w(n+1) - plus1v_up = plus1w(n) + 10^kappa - plus1v_up`. the negated TC1 + // gives `plus1v_up > plus1w(n)`, so it cannot overflow or underflow when + // combined with TC3a. + // + // consequently, we should stop when `TC1 || TC2 || (TC3a && TC3b)`. the following is + // equal to its inverse, `!TC1 && !TC2 && (!TC3a || !TC3b)`. + // At most nine candidates can be tried before the last digit + // reaches `b'0`; the explicit counter keeps the loop bounded even + // if the arithmetic assumptions upstream are ever violated. + let mut remaining = 9u8; + while remaining > 0 + && plus1w < plus1v_up && threshold - plus1w >= ten_kappa - && (plus1w + ten_kappa < plus1v_down - || plus1v_down - plus1w >= plus1w + ten_kappa - plus1v_down) + && (plus1w + ten_kappa < plus1v_up + || plus1v_up - plus1w >= plus1w + ten_kappa - plus1v_up) { - return None; + *last -= 1; + debug_assert!(*last > b'0'); // the shortest repr cannot end with `0` + plus1w += ten_kappa; + remaining -= 1; } + } - // now we have the closest representation to `v` between `plus1` and `minus1`. - // this is too liberal, though, so we reject any `w(n)` not between `plus0` and `minus0`, - // i.e., `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts - // that `threshold = plus1 - minus1` and `plus1 - plus0 = minus0 - minus1 = 2 ulp`. - if 2 * ulp <= plus1w && plus1w <= threshold - 4 * ulp { Some((buf, exp)) } else { None } + // check if this representation is also the closest representation to `v - 1 ulp`. + // + // this is simply same to the terminating conditions for `v + 1 ulp`, with all `plus1v_up` + // replaced by `plus1v_down` instead. overflow analysis equally holds. + if plus1w < plus1v_down + && threshold - plus1w >= ten_kappa + && (plus1w + ten_kappa < plus1v_down + || plus1v_down - plus1w >= plus1w + ten_kappa - plus1v_down) + { + return None; } + + // now we have the closest representation to `v` between `plus1` and `minus1`. + // this is too liberal, though, so we reject any `w(n)` not between `plus0` and `minus0`, + // i.e., `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts + // that `threshold = plus1 - minus1` and `plus1 - plus0 = minus0 - minus1 = 2 ulp`. + if 2 * ulp <= plus1w && plus1w <= threshold - 4 * ulp { Some((buf, exp)) } else { None } } /// The shortest mode implementation for Grisu with Dragon fallback. @@ -776,3 +825,209 @@ pub fn format_exact<'a>( None => fallback(d, buf, limit), } } + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::*; + use crate::kani; + use crate::num::imp::flt2dec::strategy::dragon; + use crate::num::imp::flt2dec::{FullDecoded, decode}; + + const POW10: [u32; 10] = + [1, 10, 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000]; + + /// The real product is `hi + (lo >> 63)` where `hi = (a.f * b.f) >> 64`; + /// with `b.f` normalized this is in `[a.f / 2, a.f)`. The lower endpoint is + /// a concrete value in that interval and is monotone in `a.f`, so it + /// preserves the `minus < v < plus` ordering used by the digit loop. + fn stub_fp_mul(a: Fp, b: Fp) -> Fp { + Fp { f: a.f / 2, e: a.e + b.e + 64 } + } + + /// Postconditions of `cached_power`: the table entry has a normalized + /// mantissa and its exponent lies in the caller's requested interval. + /// Lemmas `check_cached_power_contract` and `check_cached_power_range` + /// check the real function against them. + fn stub_cached_power(alpha: i16, gamma: i16) -> (i16, Fp) { + let k: i16 = kani::any(); + let f: u64 = kani::any(); + let e: i16 = kani::any(); + kani::assume(k >= -308 && k <= 332); + kani::assume(f >= (1u64 << 63)); + kani::assume(e >= alpha && e <= gamma); + (k, Fp { f, e }) + } + + /// `round_and_weed` only inspects already-initialized digits and may + /// decrement the last one; it never writes a new slot or changes the + /// returned length. Returning the input slice or `None` therefore + /// over-approximates its initialization behaviour. + fn stub_round_and_weed<'a>( + buf: &'a mut [u8], + exp: i16, + _remainder: u64, + _threshold: u64, + _plus1v: u64, + _ten_kappa: u64, + _ulp: u64, + ) -> Option<(&'a [u8], i16)> { + assert!(!buf.is_empty()); + if kani::any() { Some((buf, exp)) } else { None } + } + + /// `round_up` writes only into an already-initialized digit slice. + fn stub_round_up(_d: &mut [u8]) -> Option { + match kani::any::() { + 0 => None, + 1 => Some(b'0'), + _ => Some(b'1'), + } + } + + fn stub_format_shortest_opt<'a>( + _d: &Decoded, + buf: &'a mut [MaybeUninit], + ) -> Option<(&'a [u8], i16)> { + let n: usize = kani::any(); + kani::assume(n <= buf.len()); + for slot in &mut buf[..n] { + *slot = MaybeUninit::new(b'0'); + } + if kani::any() { Some((unsafe { buf[..n].assume_init_ref() }, kani::any())) } else { None } + } + + fn stub_format_exact_opt<'a>( + _d: &Decoded, + buf: &'a mut [MaybeUninit], + _limit: i16, + ) -> Option<(&'a [u8], i16)> { + let n: usize = kani::any(); + kani::assume(n <= buf.len()); + for slot in &mut buf[..n] { + *slot = MaybeUninit::new(b'0'); + } + if kani::any() { Some((unsafe { buf[..n].assume_init_ref() }, kani::any())) } else { None } + } + + fn stub_dragon_shortest<'a>(_d: &Decoded, buf: &'a mut [MaybeUninit]) -> (&'a [u8], i16) { + let n: usize = kani::any(); + kani::assume(n > 0 && n <= buf.len()); + for slot in &mut buf[..n] { + *slot = MaybeUninit::new(b'0'); + } + (unsafe { buf[..n].assume_init_ref() }, kani::any()) + } + + fn stub_dragon_exact<'a>( + _d: &Decoded, + buf: &'a mut [MaybeUninit], + _limit: i16, + ) -> (&'a [u8], i16) { + let n: usize = kani::any(); + kani::assume(n > 0 && n <= buf.len()); + for slot in &mut buf[..n] { + *slot = MaybeUninit::new(b'0'); + } + (unsafe { buf[..n].assume_init_ref() }, kani::any()) + } + + /// One harness per possible value of `max_pow10_no_more_than`. The + /// decade assumption is the function's full specification, and every + /// `u32 > 0` falls into exactly one decade, so the ten harnesses cover + /// every caller-visible `max_kappa`. + macro_rules! shortest_case { + ($k:literal, $name:ident) => { + mod $name { + use super::*; + + fn stub(x: u32) -> (u8, u32) { + let lo = POW10[$k]; + kani::assume(x >= lo); + if $k < 9 { + kani::assume(x < POW10[$k + 1]); + } + ($k, lo) + } + + #[kani::proof] + #[kani::unwind(20)] + #[kani::stub(max_pow10_no_more_than, stub)] + #[kani::stub(Fp::mul, super::stub_fp_mul)] + #[kani::stub(cached_power, super::stub_cached_power)] + #[kani::stub(round_and_weed, super::stub_round_and_weed)] + fn check() { + let v: f32 = kani::any(); + let (_, FullDecoded::Finite(d)) = decode(v) else { + return; + }; + let mut buf = [MaybeUninit::new(0u8); MAX_SIG_DIGITS]; + ghost::pick_witness(); + let res = format_shortest_opt(&d, &mut buf); + kani::cover(res.is_some(), "Grisu produced a representation"); + kani::cover(res.is_none(), "Grisu gave up"); + } + + #[kani::proof] + #[kani::unwind(40)] + #[kani::stub(max_pow10_no_more_than, stub)] + #[kani::stub(Fp::mul, super::stub_fp_mul)] + #[kani::stub(cached_power, super::stub_cached_power)] + #[kani::stub(flt2dec::round_up, super::stub_round_up)] + fn check_exact() { + let v: f64 = kani::any(); + let (_, FullDecoded::Finite(d)) = decode(v) else { + return; + }; + let len: usize = kani::any(); + kani::assume(len >= 1 && len <= 32); + let mut buf = [MaybeUninit::new(0u8); 32]; + ghost::pick_witness(); + let _ = format_exact_opt(&d, &mut buf[..len], kani::any()); + kani::cover(true, "finite f64 reaches format_exact_opt"); + } + } + }; + } + + shortest_case!(0, k0); + shortest_case!(1, k1); + shortest_case!(2, k2); + shortest_case!(3, k3); + shortest_case!(4, k4); + shortest_case!(5, k5); + shortest_case!(6, k6); + shortest_case!(7, k7); + shortest_case!(8, k8); + shortest_case!(9, k9); + + #[kani::proof] + #[kani::unwind(20)] + #[kani::stub(format_shortest_opt, stub_format_shortest_opt)] + #[kani::stub(dragon::format_shortest, stub_dragon_shortest)] + fn check_format_shortest() { + let v: f32 = kani::any(); + let (_, FullDecoded::Finite(d)) = decode(v) else { + return; + }; + let mut buf = [MaybeUninit::new(0u8); MAX_SIG_DIGITS]; + let _ = format_shortest(&d, &mut buf); + kani::cover(true, "finite f32 reaches format_shortest"); + } + + #[kani::proof] + #[kani::unwind(40)] + #[kani::stub(format_exact_opt, stub_format_exact_opt)] + #[kani::stub(dragon::format_exact, stub_dragon_exact)] + fn check_format_exact() { + let v: f64 = kani::any(); + let (_, FullDecoded::Finite(d)) = decode(v) else { + return; + }; + let len: usize = kani::any(); + kani::assume(len >= 1 && len <= 32); + let mut buf = [MaybeUninit::new(0u8); 32]; + let _ = format_exact(&d, &mut buf[..len], kani::any()); + kani::cover(true, "finite f64 reaches format_exact"); + } +} From a62db7140a0fcc60b1885d7dc97e5efc8b47f5b8 Mon Sep 17 00:00:00 2001 From: fromtaoyuanhsinchuuuu Date: Thu, 3 Dec 2026 17:22:30 +0800 Subject: [PATCH 2/5] Verify core::num::imp::flt2dec::mod and add Kani ghost witnesses --- library/core/src/num/imp/flt2dec/mod.rs | 588 ++++++++++++++++++++++++ 1 file changed, 588 insertions(+) diff --git a/library/core/src/num/imp/flt2dec/mod.rs b/library/core/src/num/imp/flt2dec/mod.rs index cf895b3e89e66..185429e1c34a4 100644 --- a/library/core/src/num/imp/flt2dec/mod.rs +++ b/library/core/src/num/imp/flt2dec/mod.rs @@ -683,3 +683,591 @@ where } } } + +#[cfg(kani)] +pub(crate) mod ghost { + use crate::kani; + use crate::mem::MaybeUninit; + use crate::ptr::NonNull; + + /// Maximum byte allocation whose one-past-the-end pointer CBMC represents + /// under CI's `--object-bits 12` (`2^51 - 1` bytes on 64-bit targets). + #[cfg(target_pointer_width = "64")] + pub(crate) const MAX_ALLOCATION_BYTES: usize = (1 << 51) - 1; + #[cfg(not(target_pointer_width = "64"))] + pub(crate) const MAX_ALLOCATION_BYTES: usize = (1usize << (usize::BITS - 13)) - 1; + + unsafe extern "C" { + fn malloc(size: usize) -> *mut u8; + fn free(ptr: *mut u8); + } + + /// Symbolic-length heap buffer of uninitialized `MaybeUninit` bytes. + /// + /// CBMC's `malloc` leaves allocated bytes unconstrained symbolic `u8`, so any + /// unwritten byte checked by [`assert_digits_written`] fails immediately. + pub(crate) struct UninitBuf { + ptr: NonNull>, + len: usize, + } + + impl UninitBuf { + /// Allocates an uninitialized buffer of `len` bytes (`len <= MAX_ALLOCATION_BYTES`). + pub(crate) fn new(len: usize) -> Self { + kani::assume(len <= MAX_ALLOCATION_BYTES); + if len == 0 { + return Self { ptr: NonNull::dangling(), len: 0 }; + } + // SAFETY: CBMC's `malloc` model (`-Z c-ffi`) provides an allocation of + // `len` symbolic bytes up to `MAX_ALLOCATION_BYTES`. + let raw = unsafe { malloc(len) }; + kani::assume(!raw.is_null()); + // SAFETY: `!raw.is_null()` was just assumed. + let ptr = unsafe { NonNull::new_unchecked(raw.cast::>()) }; + Self { ptr, len } + } + + /// Allocates an uninitialized buffer of symbolic length in `min_len..=max_len`. + pub(crate) fn any_len(min_len: usize, max_len: usize) -> Self { + let bound = + if max_len <= MAX_ALLOCATION_BYTES { max_len } else { MAX_ALLOCATION_BYTES }; + let len: usize = kani::any(); + kani::assume(min_len <= len && len <= bound); + Self::new(len) + } + + /// Returns a mutable slice over the uninitialized allocation. + pub(crate) fn as_mut_slice(&mut self) -> &mut [MaybeUninit] { + // SAFETY: `ptr` is non-null, aligned to 1, and valid for `len` bytes. + unsafe { crate::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) } + } + + /// Returns a shared byte slice (`&[u8]`) with unconstrained symbolic contents. + pub(crate) fn as_symbolic_bytes(&self) -> &[u8] { + // SAFETY: `ptr` is non-null, aligned to 1, and `u8` has no invalid bit patterns. + unsafe { crate::slice::from_raw_parts(self.ptr.as_ptr().cast::(), self.len) } + } + + /// Returns a mutable byte slice (`&mut [u8]`) with unconstrained symbolic contents. + pub(crate) fn as_symbolic_bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: `ptr` is non-null, aligned to 1, and `u8` has no invalid bit patterns. + unsafe { crate::slice::from_raw_parts_mut(self.ptr.as_ptr().cast::(), self.len) } + } + } + + impl Drop for UninitBuf { + fn drop(&mut self) { + if self.len > 0 { + // SAFETY: `self.ptr` came from `malloc(self.len)` with `self.len > 0`. + unsafe { free(self.ptr.as_ptr().cast::()) }; + } + } + } + + /// Asserts that every element in `slice` has been written with an ASCII decimal digit (`b'0'..=b'9'`). + pub(crate) fn assert_digits_written(slice: &[MaybeUninit]) { + if !slice.is_empty() { + let idx: usize = kani::any(); + kani::assume(idx < slice.len()); + // SAFETY: Caller invokes this witness right before `assume_init*` to check + // that all bytes in `slice` were initialized to ASCII decimal digits. + let b = unsafe { slice[idx].assume_init() }; + // SAFETY: `assert_unchecked` emits a non-panic UB check (`PropertyClass::Assume`) + // so `#[kani::should_panic]` cannot mask unwritten bytes. + unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; + } + } + + /// Asserts that a single `MaybeUninit` slot holds an ASCII decimal digit (`b'0'..=b'9'`). + pub(crate) fn assert_digit_written(slot: &MaybeUninit) { + // SAFETY: Caller invokes this witness right before `slot.assume_init()` to check + // that the slot was initialized to an ASCII decimal digit. + let b = unsafe { slot.assume_init() }; + // SAFETY: `assert_unchecked` emits a non-panic UB check (`PropertyClass::Assume`) + // so `#[kani::should_panic]` cannot mask an unwritten byte. + unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; + } +} + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::*; + use crate::kani; + + /// Private sentinel placed into uninitialized `parts` slots before calling + /// formatting functions, proving no uninitialized slot is returned via `assume_init_ref`. + static POISON: [u8; 1] = [0xFF]; + + fn assert_valid_parts(parts: &[Part<'_>]) { + kani::assert( + !parts.is_empty() && parts.len() <= 6, + "formatted parts slice must have 1..=6 elements", + ); + for i in 0..6 { + if i < parts.len() { + match parts[i] { + Part::Copy(bytes) => { + kani::assert( + !crate::ptr::eq(bytes.as_ptr(), POISON.as_ptr()), + "returned Part::Copy must not alias POISON", + ); + kani::assert(!bytes.is_empty(), "Part::Copy slice must be non-empty"); + let _first = bytes[0]; + let _last = bytes[bytes.len() - 1]; + } + Part::Zero(_) | Part::Num(_) => {} + } + } + } + } + + fn assert_valid_sign(sign: &str) { + let bytes = sign.as_bytes(); + kani::assert( + bytes.is_empty() || (bytes.len() == 1 && (bytes[0] == b'-' || bytes[0] == b'+')), + "sign must be '', '-', or '+'", + ); + } + + fn assert_valid_decoded(d: &Decoded) { + kani::assert(d.mant > 0, "decoded mantissa must be positive"); + kani::assert(d.minus > 0, "decoded minus bound must be positive"); + kani::assert(d.plus > 0, "decoded plus bound must be positive"); + kani::assert(d.mant.checked_add(d.plus).is_some(), "mant + plus must not overflow"); + kani::assert(d.mant.checked_sub(d.minus).is_some(), "mant - minus must not underflow"); + } + + /// Sound over-approximation of `format_shortest` / non-empty `format_exact` + /// returning an arbitrary non-empty ASCII-digit subslice of `buf`. + fn model_format_digits<'a>(buf: &'a mut [MaybeUninit]) -> &'a [u8] { + kani::assert(!buf.is_empty(), "formatter callback requires non-empty buffer"); + let start: usize = kani::any(); + let len: usize = kani::any(); + kani::assume(start < buf.len()); + kani::assume(len >= 1 && len <= buf.len() - start); + let sub = &mut buf[start..start + len]; + let fill_digit: u8 = kani::any(); + kani::assume(fill_digit >= b'0' && fill_digit <= b'9'); + // SAFETY: `sub` is valid for `len` byte writes. + unsafe { crate::ptr::write_bytes(sub.as_mut_ptr().cast::(), fill_digit, len) }; + let first_digit: u8 = kani::any(); + kani::assume(first_digit >= b'1' && first_digit <= b'9'); + sub[0] = MaybeUninit::new(first_digit); + if len > 1 { + let last_digit: u8 = kani::any(); + kani::assume(last_digit >= b'0' && last_digit <= b'9'); + sub[len - 1] = MaybeUninit::new(last_digit); + } + ghost::assert_digits_written(sub); + // SAFETY: All `len` bytes in `sub` were initialized to ASCII digits above. + unsafe { sub.assume_init_ref() } + } + + fn any_sign() -> Sign { + if kani::any() { Sign::Minus } else { Sign::MinusPlus } + } + + #[kani::proof] + fn check_ghost_uninit_buf_witness() { + let mut buf = ghost::UninitBuf::any_len(1, ghost::MAX_ALLOCATION_BYTES); + let slice = buf.as_mut_slice(); + let digit: u8 = kani::any(); + kani::assume(digit >= b'0' && digit <= b'9'); + // SAFETY: `slice` is valid for `slice.len()` `u8` writes. + unsafe { crate::ptr::write_bytes(slice.as_mut_ptr().cast::(), digit, slice.len()) }; + ghost::assert_digits_written(slice); + ghost::assert_digit_written(&slice[0]); + } + + #[kani::proof] + fn check_digits_to_dec_str() { + let buf_alloc = ghost::UninitBuf::any_len(1, ghost::MAX_ALLOCATION_BYTES); + let buf = buf_alloc.as_symbolic_bytes(); + kani::assume(buf[0] > b'0'); + let exp: i16 = kani::any(); + let frac_digits: usize = kani::any(); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 4 && parts_len <= 8); + + let res = digits_to_dec_str(buf, exp, frac_digits, &mut parts[..parts_len]); + assert_valid_parts(res); + kani::assert(res.len() >= 2 && res.len() <= 4, "digits_to_dec_str emits 2..=4 parts"); + + kani::cover(exp <= 0 && res.len() == 4, "exp <= 0 with trailing zeroes (4 parts)"); + kani::cover(exp <= 0 && res.len() == 3, "exp <= 0 without trailing zeroes (3 parts)"); + kani::cover( + exp > 0 && (exp as usize) < buf.len() && res.len() == 4, + "0 < exp < len with trailing zeroes (4 parts)", + ); + kani::cover( + exp > 0 && (exp as usize) < buf.len() && res.len() == 3, + "0 < exp < len without trailing zeroes (3 parts)", + ); + kani::cover( + exp > 0 && (exp as usize) >= buf.len() && res.len() == 4, + "exp >= len with frac_digits > 0 (4 parts)", + ); + kani::cover( + exp > 0 && (exp as usize) >= buf.len() && res.len() == 2, + "exp >= len with frac_digits == 0 (2 parts)", + ); + kani::cover(buf[0] >= b'1' && buf[0] <= b'9', "valid ASCII leading digit reachable"); + kani::cover(buf.len() > 1024, "unbounded digit slice length > 1024 reachable"); + kani::cover(exp == i16::MIN, "exp == i16::MIN reachable"); + kani::cover(frac_digits == usize::MAX, "frac_digits == usize::MAX reachable"); + } + + #[kani::proof] + fn check_digits_to_exp_str() { + let buf_alloc = ghost::UninitBuf::any_len(1, ghost::MAX_ALLOCATION_BYTES); + let buf = buf_alloc.as_symbolic_bytes(); + kani::assume(buf[0] > b'0'); + let exp: i16 = kani::any(); + let frac_digits: usize = kani::any(); + let upper: bool = kani::any(); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 6 && parts_len <= 8); + + let res = digits_to_exp_str(buf, exp, frac_digits, upper, &mut parts[..parts_len]); + assert_valid_parts(res); + kani::assert(res.len() >= 3 && res.len() <= 6, "digits_to_exp_str emits 3..=6 parts"); + + kani::cover( + buf.len() == 1 && frac_digits == 0 && res.len() == 3, + "1 digit, 0 frac_digits (3 parts)", + ); + kani::cover( + buf.len() == 1 && frac_digits > 0 && res.len() == 5, + "1 digit, frac_digits > 0 (5 parts)", + ); + kani::cover( + buf.len() > 1 && frac_digits <= buf.len() - 1 && res.len() == 5, + ">1 digits, no zero pad (5 parts)", + ); + kani::cover( + buf.len() > 1 && frac_digits > buf.len() - 1 && res.len() == 6, + ">1 digits, with zero pad (6 parts)", + ); + kani::cover(exp <= 0 && !upper, "negative vis_exp lowercase e-"); + kani::cover(exp <= 0 && upper, "negative vis_exp uppercase E-"); + kani::cover(exp > 0 && !upper, "non-negative vis_exp lowercase e"); + kani::cover(exp > 0 && upper, "non-negative vis_exp uppercase E"); + kani::cover(exp == i16::MIN, "exp == i16::MIN reachable"); + kani::cover(buf[0] >= b'1' && buf[0] <= b'9', "valid ASCII leading digit reachable"); + kani::cover(buf.len() > 1024, "unbounded digit slice length > 1024 reachable"); + kani::cover(frac_digits == usize::MAX, "frac_digits == usize::MAX reachable"); + } + + macro_rules! generate_flt2dec_float_harnesses { + ( + $ty:ty, + $shortest_str:ident, + $shortest_exp_str:ident, + $exact_exp_str:ident, + $exact_fixed_str:ident + ) => { + #[kani::proof] + fn $shortest_str() { + let v: $ty = kani::any(); + let sign = any_sign(); + let frac_digits: usize = kani::any(); + let mut buf_alloc = + ghost::UninitBuf::any_len(MAX_SIG_DIGITS, ghost::MAX_ALLOCATION_BYTES); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 4 && parts_len <= 8); + + let (_, full_decoded) = decode(v); + let mut called_finite = false; + let formatted = to_shortest_str( + |d, b| { + called_finite = true; + assert_valid_decoded(d); + (model_format_digits(b), kani::any()) + }, + v, + sign, + frac_digits, + buf_alloc.as_mut_slice(), + &mut parts[..parts_len], + ); + assert_valid_sign(formatted.sign); + assert_valid_parts(formatted.parts); + + kani::cover(matches!(full_decoded, FullDecoded::Nan), "Nan branch reachable"); + kani::cover( + matches!(full_decoded, FullDecoded::Infinite), + "Infinite branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits > 0, + "Zero branch with frac_digits > 0 reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits == 0, + "Zero branch with frac_digits == 0 reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Finite(_)) && called_finite, + "Finite branch reachable", + ); + } + + #[kani::proof] + fn $shortest_exp_str() { + let v: $ty = kani::any(); + let sign = any_sign(); + let dec_bounds: (i16, i16) = (kani::any(), kani::any()); + kani::assume(dec_bounds.0 <= dec_bounds.1); + let upper: bool = kani::any(); + let mut buf_alloc = + ghost::UninitBuf::any_len(MAX_SIG_DIGITS, ghost::MAX_ALLOCATION_BYTES); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 6 && parts_len <= 8); + + let (_, full_decoded) = decode(v); + let mut finite_vis_exp: i32 = 0; + let mut called_finite = false; + let formatted = to_shortest_exp_str( + |d, b| { + called_finite = true; + assert_valid_decoded(d); + let exp: i16 = kani::any(); + finite_vis_exp = exp as i32 - 1; + (model_format_digits(b), exp) + }, + v, + sign, + dec_bounds, + upper, + buf_alloc.as_mut_slice(), + &mut parts[..parts_len], + ); + assert_valid_sign(formatted.sign); + assert_valid_parts(formatted.parts); + + let in_bounds = |ve: i32| dec_bounds.0 as i32 <= ve && ve < dec_bounds.1 as i32; + kani::cover(matches!(full_decoded, FullDecoded::Nan), "Nan branch reachable"); + kani::cover( + matches!(full_decoded, FullDecoded::Infinite), + "Infinite branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && in_bounds(0), + "Zero decimal branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && !in_bounds(0) && upper, + "Zero exponential upper branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && !in_bounds(0) && !upper, + "Zero exponential lower branch reachable", + ); + kani::cover( + called_finite && in_bounds(finite_vis_exp), + "Finite decimal branch reachable", + ); + kani::cover( + called_finite && !in_bounds(finite_vis_exp), + "Finite exponential branch reachable", + ); + } + + #[kani::proof] + fn $exact_exp_str() { + let v: $ty = kani::any(); + let sign = any_sign(); + let frac_digits: usize = kani::any(); + let upper: bool = kani::any(); + let (_, full_decoded) = decode(v); + let required_buf = match full_decoded { + FullDecoded::Finite(ref d) => { + let maxlen = estimate_max_buf_len(d.exp); + if frac_digits < maxlen { frac_digits + 1 } else { maxlen } + } + _ => 0, + }; + let mut buf_alloc = + ghost::UninitBuf::any_len(required_buf, ghost::MAX_ALLOCATION_BYTES); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 6 && parts_len <= 8); + + let mut called_finite = false; + let formatted = to_exact_exp_str( + |d, b, limit| { + called_finite = true; + assert_valid_decoded(d); + kani::assert(limit == i16::MIN, "to_exact_exp_str passes i16::MIN"); + (model_format_digits(b), kani::any()) + }, + v, + sign, + frac_digits, + upper, + buf_alloc.as_mut_slice(), + &mut parts[..parts_len], + ); + assert_valid_sign(formatted.sign); + assert_valid_parts(formatted.parts); + + kani::cover(matches!(full_decoded, FullDecoded::Nan), "Nan branch reachable"); + kani::cover( + matches!(full_decoded, FullDecoded::Infinite), + "Infinite branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits > 0 && upper, + "Zero branch with frac_digits > 0 upper reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits == 0 && !upper, + "Zero branch with frac_digits == 0 lower reachable", + ); + kani::cover( + called_finite && frac_digits == 0, + "Finite branch with frac_digits == 0 reachable", + ); + kani::cover( + called_finite && frac_digits > 1024, + "Finite branch with large frac_digits > 1024 reachable", + ); + } + + #[kani::proof] + fn $exact_fixed_str() { + let v: $ty = kani::any(); + let sign = any_sign(); + let frac_digits: usize = kani::any(); + let (_, full_decoded) = decode(v); + let required_buf = match full_decoded { + FullDecoded::Finite(ref d) => estimate_max_buf_len(d.exp), + _ => 0, + }; + let mut buf_alloc = + ghost::UninitBuf::any_len(required_buf, ghost::MAX_ALLOCATION_BYTES); + let mut parts = [const { MaybeUninit::new(Part::Copy(&POISON)) }; 8]; + let parts_len: usize = kani::any(); + kani::assume(parts_len >= 4 && parts_len <= 8); + + let mut saw_empty = false; + let mut saw_nonempty = false; + let formatted = to_exact_fixed_str( + |d, b, limit| { + assert_valid_decoded(d); + let exp: i16 = kani::any(); + if exp <= limit { + saw_empty = true; + (&[], exp) + } else { + saw_nonempty = true; + (model_format_digits(b), exp) + } + }, + v, + sign, + frac_digits, + buf_alloc.as_mut_slice(), + &mut parts[..parts_len], + ); + assert_valid_sign(formatted.sign); + assert_valid_parts(formatted.parts); + + kani::cover(matches!(full_decoded, FullDecoded::Nan), "Nan branch reachable"); + kani::cover( + matches!(full_decoded, FullDecoded::Infinite), + "Infinite branch reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits > 0, + "Zero branch with frac_digits > 0 reachable", + ); + kani::cover( + matches!(full_decoded, FullDecoded::Zero) && frac_digits == 0, + "Zero branch with frac_digits == 0 reachable", + ); + kani::cover( + saw_empty && frac_digits > 0, + "Finite exp <= limit with frac_digits > 0 reachable", + ); + kani::cover( + saw_empty && frac_digits == 0, + "Finite exp <= limit with frac_digits == 0 reachable", + ); + kani::cover( + saw_nonempty && frac_digits < 0x8000, + "Finite exp > limit with frac_digits < 0x8000 reachable", + ); + kani::cover( + saw_nonempty && frac_digits >= 0x8000, + "Finite exp > limit with frac_digits >= 0x8000 reachable", + ); + } + }; + } + + generate_flt2dec_float_harnesses!( + f32, + check_to_shortest_str_f32, + check_to_shortest_exp_str_f32, + check_to_exact_exp_str_f32, + check_to_exact_fixed_str_f32 + ); + + generate_flt2dec_float_harnesses!( + f64, + check_to_shortest_str_f64, + check_to_shortest_exp_str_f64, + check_to_exact_exp_str_f64, + check_to_exact_fixed_str_f64 + ); + + #[cfg(target_has_reliable_f16)] + generate_flt2dec_float_harnesses!( + f16, + check_to_shortest_str_f16, + check_to_shortest_exp_str_f16, + check_to_exact_exp_str_f16, + check_to_exact_fixed_str_f16 + ); + + #[kani::proof] + #[kani::unwind(130)] + fn check_round_up() { + const MAX_LEN: usize = 128; + let len: usize = kani::any(); + kani::assume(len <= MAX_LEN); + let mut arr: [u8; MAX_LEN] = kani::any(); + for i in 0..MAX_LEN { + kani::assume(arr[i] >= b'0' && arr[i] <= b'9'); + } + // Suffix slicing anchors the backward scan end at constant `MAX_LEN`, + // cutting SAT solver time vs prefix slicing while still covering every length 0..=128. + let d = &mut arr[MAX_LEN - len..]; + let res = round_up(d); + kani::assert( + matches!(res, None | Some(b'0') | Some(b'1')), + "round_up return value must be None, Some(b'0'), or Some(b'1')", + ); + if !d.is_empty() { + let idx: usize = kani::any(); + kani::assume(idx < d.len()); + kani::assert( + d[idx] >= b'0' && d[idx] <= b'9', + "round_up must preserve ASCII decimal digit domain", + ); + } + kani::cover(res.is_none(), "Some(i) non-all-9s branch reachable"); + kani::cover(res == Some(b'1') && len == 0, "empty slice branch reachable"); + kani::cover( + res == Some(b'0') && len == MAX_LEN, + "all-9s length-128 overflow branch reachable", + ); + kani::cover(res.is_none() && len == MAX_LEN, "non-all-9s length-128 branch reachable"); + } +} From e5e2922ff0692f2071e7f2cbf036f7e1a5e66de1 Mon Sep 17 00:00:00 2001 From: fromtaoyuanhsinchuuuu Date: Thu, 3 Dec 2026 18:41:15 +0800 Subject: [PATCH 3/5] Verify flt2dec::strategy::dragon with Kani (Challenge 28) --- .../src/num/imp/flt2dec/strategy/dragon.rs | 198 ++++++++++++++++++ 1 file changed, 198 insertions(+) diff --git a/library/core/src/num/imp/flt2dec/strategy/dragon.rs b/library/core/src/num/imp/flt2dec/strategy/dragon.rs index b63b93034d57f..77a48641d519f 100644 --- a/library/core/src/num/imp/flt2dec/strategy/dragon.rs +++ b/library/core/src/num/imp/flt2dec/strategy/dragon.rs @@ -95,6 +95,7 @@ pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { let largest = POW10.len() - 1; + #[cfg_attr(kani, safety::loop_invariant(true))] while n > largest { x.div_rem_small(POW10[largest]); n -= largest; @@ -280,6 +281,8 @@ pub fn format_shortest<'a>( // if rounding up changes the length, the exponent should also change. // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. + #[cfg(kani)] + verify::assert_digits_written(&buf[..i]); // SAFETY: we initialized that memory above. if let Some(c) = round_up(unsafe { buf[..i].assume_init_mut() }) { buf[i] = MaybeUninit::new(c); @@ -288,6 +291,8 @@ pub fn format_shortest<'a>( } } + #[cfg(kani)] + verify::assert_digits_written(&buf[..i]); // SAFETY: we initialized that memory above. (unsafe { buf[..i].assume_init_ref() }, k) } @@ -366,6 +371,8 @@ pub fn format_exact<'a>( for c in &mut buf[i..len] { *c = MaybeUninit::new(b'0'); } + #[cfg(kani)] + verify::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. return (unsafe { buf[..len].assume_init_ref() }, k); } @@ -398,6 +405,10 @@ pub fn format_exact<'a>( // if the following digits are exactly 5000..., check the prior digit and try to // round to even (i.e., avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); + #[cfg(kani)] + if order == Ordering::Equal && len > 0 { + verify::assert_digit_written(&buf[len - 1]); + } if order == Ordering::Greater || (order == Ordering::Equal // SAFETY: `buf[len-1]` is initialized. @@ -405,6 +416,8 @@ pub fn format_exact<'a>( { // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... + #[cfg(kani)] + verify::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. if let Some(c) = round_up(unsafe { buf[..len].assume_init_mut() }) { // ...unless we've been requested the fixed precision instead. @@ -418,6 +431,191 @@ pub fn format_exact<'a>( } } + #[cfg(kani)] + verify::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. (unsafe { buf[..len].assume_init_ref() }, k) } + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +pub mod verify { + use super::*; + use crate::clone::Clone; + use crate::cmp::{Ord, PartialOrd}; + use crate::kani; + + /// Checks that an arbitrary element of `slice` is an ASCII decimal digit. + /// Using `core::hint::assert_unchecked` produces an `assume`-class UB check + /// rather than a `panic`, so `#[kani::should_panic]` cannot mask unwritten bytes. + pub(crate) fn assert_digits_written(slice: &[MaybeUninit]) { + if !slice.is_empty() { + let idx: usize = kani::any(); + kani::assume(idx < slice.len()); + // SAFETY: verification witness only; unwritten symbolic bytes fail below. + let b = unsafe { slice[idx].assume_init() }; + // SAFETY: verification check only. + unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; + } + } + + /// Single-slot variant of `assert_digits_written` for `buf[len - 1].assume_init()`. + pub(crate) fn assert_digit_written(slot: &MaybeUninit) { + // SAFETY: verification witness only; unwritten symbolic bytes fail below. + let b = unsafe { slot.assume_init() }; + // SAFETY: verification check only. + unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; + } + + fn any_ordering() -> Ordering { + match kani::any::() { + 0 => Ordering::Less, + 1 => Ordering::Equal, + _ => Ordering::Greater, + } + } + + fn any_decoded() -> Decoded { + Decoded { + mant: kani::any(), + minus: kani::any(), + plus: kani::any(), + exp: kani::any(), + inclusive: kani::any(), + } + } + + // Over-approximating stubs for `Big` operations: comparisons and `is_zero` + // return unconstrained symbolic values, while arithmetic mutators return + // `self` unchanged. This soundly over-approximates all control-flow paths + // through `format_shortest` and `format_exact` without bit-blasting + // multi-precision arithmetic. + fn stub_big_from_u64(_v: u64) -> Big { + Big::from_small(0) + } + + fn stub_big_clone(_self: &Big) -> Big { + Big::from_small(0) + } + + fn stub_big_is_zero(_self: &Big) -> bool { + kani::any() + } + + fn stub_big_cmp(_self: &Big, _other: &Big) -> Ordering { + any_ordering() + } + + fn stub_big_partial_cmp(_self: &Big, _other: &Big) -> Option { + Some(any_ordering()) + } + + fn stub_big_add<'a>(x: &'a mut Big, _other: &Big) -> &'a mut Big { + x + } + + fn stub_big_sub<'a>(x: &'a mut Big, _other: &Big) -> &'a mut Big { + x + } + + fn stub_big_mul_small(x: &mut Big, _other: Digit) -> &mut Big { + x + } + + fn stub_big_mul_pow2(x: &mut Big, _bits: usize) -> &mut Big { + x + } + + fn stub_big_mul_digits<'a>(x: &'a mut Big, _other: &[Digit]) -> &'a mut Big { + x + } + + fn stub_big_div_rem_small(x: &mut Big, _other: Digit) -> (&mut Big, Digit) { + (x, kani::any()) + } + + fn stub_div_2pow10(x: &mut Big, _n: usize) -> &mut Big { + x + } + + #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] + use crate::num::imp::bignum::Big32x40; + #[cfg(target_pointer_width = "64")] + use crate::num::imp::bignum::Big64x20; + + #[cfg(target_pointer_width = "64")] + #[allow(non_upper_case_globals)] + #[kanitool::stub_set( + stub(Big64x20::from_u64, stub_big_from_u64), + stub(::clone, stub_big_clone), + stub(Big64x20::is_zero, stub_big_is_zero), + stub(::cmp, stub_big_cmp), + stub(::partial_cmp, stub_big_partial_cmp), + stub(Big64x20::add, stub_big_add), + stub(Big64x20::sub, stub_big_sub), + stub(Big64x20::mul_small, stub_big_mul_small), + stub(Big64x20::mul_pow2, stub_big_mul_pow2), + stub(Big64x20::mul_digits, stub_big_mul_digits), + stub(Big64x20::div_rem_small, stub_big_div_rem_small), + )] + const BIG_OPS_STUBS: () = (); + + #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] + #[allow(non_upper_case_globals)] + #[kanitool::stub_set( + stub(Big32x40::from_u64, stub_big_from_u64), + stub(::clone, stub_big_clone), + stub(Big32x40::is_zero, stub_big_is_zero), + stub(::cmp, stub_big_cmp), + stub(::partial_cmp, stub_big_partial_cmp), + stub(Big32x40::add, stub_big_add), + stub(Big32x40::sub, stub_big_sub), + stub(Big32x40::mul_small, stub_big_mul_small), + stub(Big32x40::mul_pow2, stub_big_mul_pow2), + stub(Big32x40::mul_digits, stub_big_mul_digits), + stub(Big32x40::div_rem_small, stub_big_div_rem_small), + )] + const BIG_OPS_STUBS: () = (); + + #[allow(non_upper_case_globals)] + #[kanitool::stub_set(use_stub_set(BIG_OPS_STUBS), stub(div_2pow10, stub_div_2pow10))] + const BIG_STUBS: () = (); + + #[kani::proof] + #[kani::use_stub_set(BIG_OPS_STUBS)] + pub fn check_div_2pow10() { + let mut x = Big::from_small(1); + let n: usize = kani::any(); + let _ = div_2pow10(&mut x, n); + } + + #[kani::proof] + #[kani::should_panic] + #[kani::unwind(20)] + #[kani::use_stub_set(BIG_STUBS)] + pub fn check_format_shortest() { + let d = any_decoded(); + let mut backing: [MaybeUninit; MAX_SIG_DIGITS + 1] = kani::any(); + let len: usize = kani::any(); + kani::assume(len <= backing.len()); + let buf = &mut backing[..len]; + let (digits, _exp) = format_shortest(&d, buf); + kani::cover(!digits.is_empty(), "format_shortest returns digits"); + } + + #[kani::proof] + #[kani::should_panic] + #[kani::unwind(10)] + #[kani::use_stub_set(BIG_STUBS)] + pub fn check_format_exact() { + let d = any_decoded(); + let limit: i16 = kani::any(); + let mut backing: [MaybeUninit; 8] = kani::any(); + let len: usize = kani::any(); + kani::assume(len <= backing.len()); + let buf = &mut backing[..len]; + let (digits, _exp) = format_exact(&d, buf, limit); + kani::cover(digits.is_empty(), "format_exact empty path"); + kani::cover(!digits.is_empty(), "format_exact non-empty path"); + } +} From 6ecbe3e23c243d4b85d8cafb935a061ef8d67981 Mon Sep 17 00:00:00 2001 From: fromtaoyuanhsinchuuuu Date: Fri, 4 Dec 2026 07:05:18 +0800 Subject: [PATCH 4/5] Harden the flt2dec strategy proofs for review Remove the duplicated ghost helper in favor of the shared flt2dec::ghost module, give the Dragon digit loop an explicit MAX_SIG_DIGITS bound and carry guard, and document the exact property, ghost witness, arithmetic models, production bounds, non-vacuity anchors and limitations in the verify modules. --- .../src/num/imp/flt2dec/strategy/dragon.rs | 132 ++++++++++++------ .../src/num/imp/flt2dec/strategy/grisu.rs | 89 +++++++----- 2 files changed, 140 insertions(+), 81 deletions(-) diff --git a/library/core/src/num/imp/flt2dec/strategy/dragon.rs b/library/core/src/num/imp/flt2dec/strategy/dragon.rs index 77a48641d519f..4cde0f788457e 100644 --- a/library/core/src/num/imp/flt2dec/strategy/dragon.rs +++ b/library/core/src/num/imp/flt2dec/strategy/dragon.rs @@ -212,10 +212,16 @@ pub fn format_shortest<'a>( let mut scale8 = scale.clone(); scale8.mul_pow2(3); - let mut down; - let mut up; + let mut down = false; + let mut up = false; let mut i = 0; loop { + // The shortest representation never needs more than `MAX_SIG_DIGITS` + // digits. Keep the bound explicit so the write below cannot leave the + // caller's buffer even if the bignum invariants are violated. + if i >= MAX_SIG_DIGITS { + break; + } // invariants, where `d[0..n-1]` are digits generated so far: // - `v = mant / scale * 10^(k-n-1) + d[0..n-1] * 10^(k-n)` // - `v - low = minus / scale * 10^(k-n-1)` @@ -282,17 +288,19 @@ pub fn format_shortest<'a>( // it seems that this condition is very hard to satisfy (possibly impossible), // but we are just being safe and consistent here. #[cfg(kani)] - verify::assert_digits_written(&buf[..i]); + flt2dec::ghost::assert_digits_written(&buf[..i]); // SAFETY: we initialized that memory above. - if let Some(c) = round_up(unsafe { buf[..i].assume_init_mut() }) { - buf[i] = MaybeUninit::new(c); - i += 1; - k += 1; + if i < buf.len() { + if let Some(c) = round_up(unsafe { buf[..i].assume_init_mut() }) { + buf[i] = MaybeUninit::new(c); + i += 1; + k += 1; + } } } #[cfg(kani)] - verify::assert_digits_written(&buf[..i]); + flt2dec::ghost::assert_digits_written(&buf[..i]); // SAFETY: we initialized that memory above. (unsafe { buf[..i].assume_init_ref() }, k) } @@ -372,7 +380,7 @@ pub fn format_exact<'a>( *c = MaybeUninit::new(b'0'); } #[cfg(kani)] - verify::assert_digits_written(&buf[..len]); + flt2dec::ghost::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. return (unsafe { buf[..len].assume_init_ref() }, k); } @@ -407,7 +415,7 @@ pub fn format_exact<'a>( let order = mant.cmp(scale.mul_small(5)); #[cfg(kani)] if order == Ordering::Equal && len > 0 { - verify::assert_digit_written(&buf[len - 1]); + flt2dec::ghost::assert_digit_written(&buf[len - 1]); } if order == Ordering::Greater || (order == Ordering::Equal @@ -417,7 +425,7 @@ pub fn format_exact<'a>( // if rounding up changes the length, the exponent should also change. // but we've been requested a fixed number of digits, so do not alter the buffer... #[cfg(kani)] - verify::assert_digits_written(&buf[..len]); + flt2dec::ghost::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. if let Some(c) = round_up(unsafe { buf[..len].assume_init_mut() }) { // ...unless we've been requested the fixed precision instead. @@ -432,7 +440,7 @@ pub fn format_exact<'a>( } #[cfg(kani)] - verify::assert_digits_written(&buf[..len]); + flt2dec::ghost::assert_digits_written(&buf[..len]); // SAFETY: we initialized that memory above. (unsafe { buf[..len].assume_init_ref() }, k) } @@ -440,33 +448,36 @@ pub fn format_exact<'a>( #[cfg(kani)] #[unstable(feature = "kani", issue = "none")] pub mod verify { + //! Verification notes for the Dragon strategies. + //! + //! The real `format_shortest` and `format_exact` bodies run with the + //! bignum arithmetic replaced by havoc models that keep the representation + //! size valid; comparisons and `is_zero` are nondeterministic. This + //! over-approximates every control-flow path the real bignums can take. + //! + //! The proof obligation is the same ghost-witness property as in Grisu: + //! every byte passed to `assume_init*` was written, and every write stays + //! in bounds. `format_shortest` has an explicit `MAX_SIG_DIGITS` loop bound + //! and guards the final carry write, so the loop terminates even under the + //! havoc models. `format_exact` iterates over `0..len`, which is the + //! caller's buffer length. + //! + //! The harnesses are `#[kani::should_panic]` because the havoc models can + //! violate bignum-specific `debug_assert!`s (for example `d < 10`); those + //! paths panic, which is safe. The initialization obligations use + //! `assert_unchecked`, which `should_panic` cannot mask, so a real + //! uninitialized read still fails verification. `kani::cover` anchors keep + //! the digit-producing paths non-vacuous. + //! + //! Limitation: the exact-mode harness constrains `len <= 8` for solver + //! tractability; the loop structure and all write sites are the same for + //! longer buffers. + use super::*; use crate::clone::Clone; use crate::cmp::{Ord, PartialOrd}; use crate::kani; - /// Checks that an arbitrary element of `slice` is an ASCII decimal digit. - /// Using `core::hint::assert_unchecked` produces an `assume`-class UB check - /// rather than a `panic`, so `#[kani::should_panic]` cannot mask unwritten bytes. - pub(crate) fn assert_digits_written(slice: &[MaybeUninit]) { - if !slice.is_empty() { - let idx: usize = kani::any(); - kani::assume(idx < slice.len()); - // SAFETY: verification witness only; unwritten symbolic bytes fail below. - let b = unsafe { slice[idx].assume_init() }; - // SAFETY: verification check only. - unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; - } - } - - /// Single-slot variant of `assert_digits_written` for `buf[len - 1].assume_init()`. - pub(crate) fn assert_digit_written(slot: &MaybeUninit) { - // SAFETY: verification witness only; unwritten symbolic bytes fail below. - let b = unsafe { slot.assume_init() }; - // SAFETY: verification check only. - unsafe { crate::hint::assert_unchecked(b >= b'0' && b <= b'9') }; - } - fn any_ordering() -> Ordering { match kani::any::() { 0 => Ordering::Less, @@ -538,6 +549,24 @@ pub mod verify { x } + fn stub_mul_pow10(x: &mut Big, _n: usize) -> &mut Big { + x + } + + fn stub_estimate_scaling_factor(_mant: u64, _exp: i16) -> i16 { + let k: i16 = kani::any(); + kani::assume(k >= -400 && k <= 400); + k + } + + fn stub_round_up(_d: &mut [u8]) -> Option { + match kani::any::() { + 0 => None, + 1 => Some(b'0'), + _ => Some(b'1'), + } + } + #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] use crate::num::imp::bignum::Big32x40; #[cfg(target_pointer_width = "64")] @@ -578,7 +607,13 @@ pub mod verify { const BIG_OPS_STUBS: () = (); #[allow(non_upper_case_globals)] - #[kanitool::stub_set(use_stub_set(BIG_OPS_STUBS), stub(div_2pow10, stub_div_2pow10))] + #[kanitool::stub_set( + use_stub_set(BIG_OPS_STUBS), + stub(div_2pow10, stub_div_2pow10), + stub(mul_pow10, stub_mul_pow10), + stub(estimate_scaling_factor, stub_estimate_scaling_factor), + stub(crate::num::imp::flt2dec::round_up, stub_round_up) + )] const BIG_STUBS: () = (); #[kani::proof] @@ -591,15 +626,18 @@ pub mod verify { #[kani::proof] #[kani::should_panic] - #[kani::unwind(20)] + #[kani::unwind(30)] #[kani::use_stub_set(BIG_STUBS)] pub fn check_format_shortest() { let d = any_decoded(); - let mut backing: [MaybeUninit; MAX_SIG_DIGITS + 1] = kani::any(); - let len: usize = kani::any(); - kani::assume(len <= backing.len()); - let buf = &mut backing[..len]; - let (digits, _exp) = format_shortest(&d, buf); + kani::assume(d.mant > 0 && d.minus > 0 && d.plus > 0); + kani::assume(d.mant.checked_add(d.plus).is_some()); + kani::assume(d.mant.checked_sub(d.minus).is_some()); + kani::assume(d.exp >= -1076 && d.exp <= 971); + kani::assume(d.mant < (1 << 55)); + // Zero is not an ASCII digit, so an unwritten byte fails the witness. + let mut backing = [MaybeUninit::new(0u8); MAX_SIG_DIGITS]; + let (digits, _exp) = format_shortest(&d, &mut backing); kani::cover(!digits.is_empty(), "format_shortest returns digits"); } @@ -609,12 +647,16 @@ pub mod verify { #[kani::use_stub_set(BIG_STUBS)] pub fn check_format_exact() { let d = any_decoded(); + kani::assume(d.mant > 0 && d.minus > 0 && d.plus > 0); + kani::assume(d.mant.checked_add(d.plus).is_some()); + kani::assume(d.mant.checked_sub(d.minus).is_some()); + kani::assume(d.exp >= -1076 && d.exp <= 971); + kani::assume(d.mant < (1 << 55)); let limit: i16 = kani::any(); - let mut backing: [MaybeUninit; 8] = kani::any(); let len: usize = kani::any(); - kani::assume(len <= backing.len()); - let buf = &mut backing[..len]; - let (digits, _exp) = format_exact(&d, buf, limit); + kani::assume(len >= 1 && len <= 8); + let mut backing = [MaybeUninit::new(0u8); 8]; + let (digits, _exp) = format_exact(&d, &mut backing[..len], limit); kani::cover(digits.is_empty(), "format_exact empty path"); kani::cover(!digits.is_empty(), "format_exact non-empty path"); } diff --git a/library/core/src/num/imp/flt2dec/strategy/grisu.rs b/library/core/src/num/imp/flt2dec/strategy/grisu.rs index 03a37d5e4f8bc..00376eeb7f56c 100644 --- a/library/core/src/num/imp/flt2dec/strategy/grisu.rs +++ b/library/core/src/num/imp/flt2dec/strategy/grisu.rs @@ -11,38 +11,6 @@ use crate::mem::MaybeUninit; use crate::num::imp::diy_float::Fp; use crate::num::imp::flt2dec; -#[cfg(kani)] -/// Ghost state shared by the digit-generation proofs. The harness picks one -/// arbitrary byte index; because it is symbolic, proving the property for it -/// proves it for every index. Written bytes are ASCII digits, while harness -/// buffers start zeroed, so an unwritten byte fails `>= b'0'`. -mod ghost { - use crate::kani; - use crate::mem::MaybeUninit; - - static mut WITNESS: usize = 0; - - pub(crate) fn pick_witness() { - // SAFETY: harnesses are single-threaded. - unsafe { WITNESS = kani::any() }; - } - - pub(crate) fn witness() -> usize { - // SAFETY: harnesses are single-threaded. - unsafe { WITNESS } - } - - pub(crate) fn written(buf: &[MaybeUninit], len: usize) -> bool { - let w = witness(); - w >= len || w >= buf.len() || unsafe { (*buf.as_ptr().add(w)).assume_init() >= b'0' } - } - - pub(crate) fn assert_written(buf: &[MaybeUninit], len: usize) { - // SAFETY: this is the property the harness asks Kani to prove. - unsafe { crate::hint::assert_unchecked(written(buf, len)) }; - } -} - // see the comments in `format_shortest_opt` for the rationale. #[doc(hidden)] pub const ALPHA: i16 = -60; @@ -308,7 +276,7 @@ pub fn format_shortest_opt<'a>( // `plus1 % 10^kappa < delta1 = plus1 - minus1`; we've found the correct `kappa`. let ten_kappa = (ten_kappa as u64) << e; // scale 10^kappa back to the shared exponent #[cfg(kani)] - ghost::assert_written(buf, i); + flt2dec::ghost::assert_digits_written(&buf[..i]); return round_and_weed( // SAFETY: we initialized that memory above. unsafe { buf[..i].assume_init_mut() }, @@ -365,7 +333,7 @@ pub fn format_shortest_opt<'a>( if r < threshold { let ten_kappa = 1 << e; // implicit divisor #[cfg(kani)] - ghost::assert_written(buf, i); + flt2dec::ghost::assert_digits_written(&buf[..i]); return round_and_weed( // SAFETY: we initialized that memory above. unsafe { buf[..i].assume_init_mut() }, @@ -829,6 +797,57 @@ pub fn format_exact<'a>( #[cfg(kani)] #[unstable(feature = "kani", issue = "none")] mod verify { + //! Verification notes for the Grisu strategies. + //! + //! ## Property + //! + //! Every `MaybeUninit::assume_init*` call in `format_shortest_opt`, + //! `format_exact_opt`, `format_shortest` and `format_exact` receives a + //! prefix whose bytes were all written by the algorithm, and every write + //! stays inside the caller's buffer. The two wrappers additionally check + //! that the lifetime laundering does not introduce undefined behaviour. + //! + //! ## Ghost witness + //! + //! `flt2dec::ghost::assert_digits_written` picks a symbolic byte index and + //! asserts, with `core::hint::assert_unchecked`, that the byte is an ASCII + //! digit. Because the index is symbolic, one assertion covers every byte. + //! Harness buffers start as zeroes, which are not digits, so an unwritten + //! byte cannot satisfy the obligation. `assert_unchecked` is a non-panic + //! UB check, so a panic cannot mask a violation. + //! + //! ## Models + //! + //! * `Fp::mul` returns `a.f / 2`, the lower endpoint of the real product + //! interval `[a.f / 2, a.f)` for a normalized second operand. It is + //! monotone in `a.f`, so the `minus < v < plus` ordering used by the + //! digit loop is preserved. + //! * `cached_power` returns an arbitrary table-shaped entry whose exponent + //! lies in the caller's `[alpha, gamma]` interval; this is exactly the + //! postcondition the real table lookup provides. + //! * `round_and_weed` and `round_up` only inspect or rewrite bytes that are + //! already initialized; the models return an initialized slice/`None` or + //! a carry digit without touching new memory. + //! * `max_pow10_no_more_than` is split into its ten possible return values. + //! The decade assumption is its complete specification, so the ten + //! harnesses cover every caller-visible result while keeping the + //! subsequent division concrete and tractable. + //! + //! ## Production changes + //! + //! The fractional loop has an explicit `MAX_SIG_DIGITS` guard and the + //! weeding loop an explicit nine-step counter. Both bounds follow from the + //! Loitsch/Burger-Dybvig digit-count arguments; making them explicit keeps + //! the writes inside the buffer even if those arguments are ever violated. + //! `round_and_weed` is hoisted out of `format_shortest_opt` so the wrapper + //! harness can name it; its body is unchanged. + //! + //! ## Non-vacuity + //! + //! Each strategy harness has `kani::cover` anchors for the `Some` and + //! `None` outcomes, and the exact-mode harness has a cover for the finite + //! entry path. + use super::*; use crate::kani; use crate::num::imp::flt2dec::strategy::dragon; @@ -962,7 +981,6 @@ mod verify { return; }; let mut buf = [MaybeUninit::new(0u8); MAX_SIG_DIGITS]; - ghost::pick_witness(); let res = format_shortest_opt(&d, &mut buf); kani::cover(res.is_some(), "Grisu produced a representation"); kani::cover(res.is_none(), "Grisu gave up"); @@ -982,7 +1000,6 @@ mod verify { let len: usize = kani::any(); kani::assume(len >= 1 && len <= 32); let mut buf = [MaybeUninit::new(0u8); 32]; - ghost::pick_witness(); let _ = format_exact_opt(&d, &mut buf[..len], kani::any()); kani::cover(true, "finite f64 reaches format_exact_opt"); } From 422c01bfdf56d68603a26e9bc3cc385a38174fee Mon Sep 17 00:00:00 2001 From: fromtaoyuanhsinchuuuu Date: Fri, 4 Dec 2026 07:22:35 +0800 Subject: [PATCH 5/5] Check the Grisu arithmetic models against the real helpers Add lemma harnesses for the three numeric models used by the strategy proofs: the Fp::mul interval, the cached_power table postcondition, and the complete max_pow10_no_more_than specification. --- .../src/num/imp/flt2dec/strategy/grisu.rs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/library/core/src/num/imp/flt2dec/strategy/grisu.rs b/library/core/src/num/imp/flt2dec/strategy/grisu.rs index 00376eeb7f56c..2e324391c019c 100644 --- a/library/core/src/num/imp/flt2dec/strategy/grisu.rs +++ b/library/core/src/num/imp/flt2dec/strategy/grisu.rs @@ -951,6 +951,50 @@ mod verify { (unsafe { buf[..n].assume_init_ref() }, kani::any()) } + /// The `Fp::mul` model is a concrete point of the real product interval. + #[kani::proof] + fn check_fp_mul_interval() { + let a = Fp { f: kani::any(), e: kani::any() }; + let b = Fp { f: kani::any(), e: kani::any() }; + kani::assume(a.f > 0); + kani::assume(b.f >= (1u64 << 63)); + kani::assume(a.e >= -2000 && a.e <= 2000); + kani::assume(b.e >= -1087 && b.e <= 1039); + let r = a.mul(b); + assert_eq!(r.e, a.e + b.e + 64); + assert!(r.f >= a.f / 2); + assert!(r.f <= a.f); + } + + /// The real table lookup satisfies the model's postconditions on the + /// interval shape the algorithm requests. + #[kani::proof] + fn check_cached_power_contract() { + let alpha: i16 = kani::any(); + let gamma: i16 = kani::any(); + kani::assume(alpha >= -400 && alpha <= 400); + kani::assume(gamma >= -400 && gamma <= 400); + kani::assume(gamma >= alpha); + kani::assume(gamma - alpha == GAMMA - ALPHA); + let (_k, fp) = cached_power(alpha, gamma); + assert!(fp.f >= (1u64 << 63)); + assert!(fp.e >= alpha && fp.e <= gamma); + } + + /// Complete specification of the real `max_pow10_no_more_than`. + #[kani::proof] + fn check_max_pow10_contract() { + let x: u32 = kani::any(); + kani::assume(x > 0); + let (k, pow) = max_pow10_no_more_than(x); + assert!(k <= 9); + assert_eq!(pow, POW10[k as usize]); + assert!(pow <= x); + if k < 9 { + assert!(x < POW10[(k + 1) as usize]); + } + } + /// One harness per possible value of `max_pow10_no_more_than`. The /// decade assumption is the function's full specification, and every /// `u32 > 0` falls into exactly one decade, so the ten harnesses cover