inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Runtime support for Rust code generated from Lean by `inlean`.
//!
//! Generated code calls into this crate for every primitive that Lean implements in its C
//! runtime. Each function here is a port of the C function of the same name in Lean's
//! `lean.h`, minus the `lean_` prefix and split into one module per type:
//! `lean_uint32_shift_left` is [`scalar::uint32::shift_left`].
//!
//! This crate is an implementation detail of `inlean`. Its API follows Lean's runtime, not
//! Rust conventions, and changes with the pinned Lean release.
//!
//! The ported functions derive from Lean 4's `lean.h`, Copyright (c) 2019 Microsoft
//! Corporation, under the Apache License 2.0; the crate's `NOTICE` file has the details.

pub mod array;
mod bignum;
pub mod codec;
pub mod collections;
pub mod int;
pub mod math;
pub mod misc;
pub mod nat;
mod object;
pub mod sarray;
pub mod scalar;
pub mod string;
mod types;

pub use object::*;
pub use codec::{Codec, Pass, Primitive, Repr, Value};
pub use types::{Generic, Int, Nat, ParseIntError, ParseNatError, TooLarge};

/// Resolves the name of a function of Lean's C runtime, such as `lean_nat_add`, to the Rust
/// path of its port relative to this crate, such as `nat::nat_add`.
///
/// Returns `None` for a function this crate does not provide.
pub fn resolve(c_symbol: &str) -> Option<String> {
    if let Some(path) = scalar::resolve(c_symbol) {
        return Some(path);
    }
    if math::has(c_symbol) {
        return Some(format!("math::{c_symbol}"));
    }
    let name = c_symbol.strip_prefix("lean_")?;
    [("nat", nat::OPS), ("string", string::OPS), ("array", array::OPS), ("misc", misc::OPS), ("int", int::OPS), ("sarray", sarray::OPS)]
        .into_iter()
        .find(|(_, ops)| ops.contains(&name))
        .map(|(module, _)| format!("{module}::{name}"))
}

/// Lean's `unreachable` instruction: a point the Lean compiler proved cannot be reached.
#[cold]
#[inline(never)]
pub fn unreachable() -> ! {
    panic!("inlean: reached code Lean marked unreachable")
}

/// A Lean `Char` as a Rust `char`. Lean's `Char` carries a proof that it is a Unicode
/// scalar value, so a failure here is a bug in the translation, not in the caller.
#[inline]
pub fn char_of_u32(value: u32) -> char {
    match char::from_u32(value) {
        Some(c) => c,
        None => panic!("inlean: Lean returned an invalid Char: {value:#x}"),
    }
}