inlean-runtime 0.1.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! The C math library functions Lean's `Float` and `Float32` call directly, under their C
//! names.

macro_rules! unary {
    ($($double:ident $single:ident $method:ident),*) => {
        $(
            #[inline(always)]
            pub fn $double(x: f64) -> f64 {
                x.$method()
            }

            #[inline(always)]
            pub fn $single(x: f32) -> f32 {
                x.$method()
            }
        )*
        const UNARY: &[&str] = &[$(stringify!($double), stringify!($single)),*];
    };
}

unary!(
    sin sinf sin, cos cosf cos, tan tanf tan, asin asinf asin, acos acosf acos, atan atanf atan,
    sinh sinhf sinh, cosh coshf cosh, tanh tanhf tanh, asinh asinhf asinh, acosh acoshf acosh,
    atanh atanhf atanh, exp expf exp, exp2 exp2f exp2, log logf ln, log2 log2f log2, log10 log10f log10,
    sqrt sqrtf sqrt, ceil ceilf ceil, floor floorf floor, round roundf round,
    fabs fabsf abs
);

#[inline(always)]
pub fn cbrt(x: f64) -> f64 {
    c::cbrt(x)
}

#[inline(always)]
pub fn cbrtf(x: f32) -> f32 {
    c::cbrtf(x)
}

/// The C library's cube roots, which Lean's `Float.cbrt` and `Float32.cbrt` call.
///
/// On Linux, Rust's `f64::cbrt` and `f32::cbrt` do not reach glibc's: Rust's compiler-builtins
/// defines `cbrt` and `cbrtf` itself (CORE-MATH's correctly rounded cube root and FreeBSD's),
/// and those definitions take the place of glibc's in the program. glibc's results differ in
/// the last bit or two. glibc also exports the functions as `cbrtf64` and `cbrtf32`, names
/// Rust does not define; those need glibc 2.27 or later.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod c {
    #[link(name = "m")]
    unsafe extern "C" {
        #[link_name = "cbrtf64"]
        pub safe fn cbrt(x: f64) -> f64;
        #[link_name = "cbrtf32"]
        pub safe fn cbrtf(x: f32) -> f32;
    }
}

/// Elsewhere, Rust's cube roots. They are the C library's on Apple platforms and Windows, where
/// compiler-builtins leaves them to the system; Lean publishes no release for the other
/// platforms, so there is nothing else to agree with.
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
mod c {
    #[inline(always)]
    pub fn cbrt(x: f64) -> f64 {
        x.cbrt()
    }

    #[inline(always)]
    pub fn cbrtf(x: f32) -> f32 {
        x.cbrt()
    }
}

#[inline(always)]
pub fn pow(x: f64, y: f64) -> f64 {
    x.powf(y)
}

#[inline(always)]
pub fn powf(x: f32, y: f32) -> f32 {
    x.powf(y)
}

#[inline(always)]
pub fn atan2(y: f64, x: f64) -> f64 {
    y.atan2(x)
}

#[inline(always)]
pub fn atan2f(y: f32, x: f32) -> f32 {
    y.atan2(x)
}

/// Whether this module has the C function `name`.
pub(crate) fn has(name: &str) -> bool {
    UNARY.contains(&name) || matches!(name, "cbrt" | "cbrtf" | "pow" | "powf" | "atan2" | "atan2f")
}