inlean_runtime/lib.rs
1//! Runtime support for Rust code generated from Lean by `inlean`.
2//!
3//! Generated code calls into this crate for every primitive that Lean implements in its C
4//! runtime. Each function here is a port of the C function of the same name in Lean's
5//! `lean.h`, minus the `lean_` prefix and split into one module per type:
6//! `lean_uint32_shift_left` is [`scalar::uint32::shift_left`].
7//!
8//! This crate is an implementation detail of `inlean`. Its API follows Lean's runtime, not
9//! Rust conventions, and changes with the pinned Lean release.
10//!
11//! The ported functions derive from Lean 4's `lean.h`, Copyright (c) 2019 Microsoft
12//! Corporation, under the Apache License 2.0; the crate's `NOTICE` file has the details.
13
14pub mod array;
15mod bignum;
16pub mod codec;
17pub mod collections;
18pub mod int;
19pub mod math;
20pub mod misc;
21pub mod nat;
22mod object;
23pub mod sarray;
24pub mod scalar;
25pub mod string;
26mod types;
27
28pub use object::*;
29pub use codec::{Codec, Pass, Primitive, Repr, Value};
30pub use types::{Generic, Int, Nat, ParseIntError, ParseNatError, TooLarge};
31
32/// Resolves the name of a function of Lean's C runtime, such as `lean_nat_add`, to the Rust
33/// path of its port relative to this crate, such as `nat::nat_add`.
34///
35/// Returns `None` for a function this crate does not provide.
36pub fn resolve(c_symbol: &str) -> Option<String> {
37 if let Some(path) = scalar::resolve(c_symbol) {
38 return Some(path);
39 }
40 if math::has(c_symbol) {
41 return Some(format!("math::{c_symbol}"));
42 }
43 let name = c_symbol.strip_prefix("lean_")?;
44 [("nat", nat::OPS), ("string", string::OPS), ("array", array::OPS), ("misc", misc::OPS), ("int", int::OPS), ("sarray", sarray::OPS)]
45 .into_iter()
46 .find(|(_, ops)| ops.contains(&name))
47 .map(|(module, _)| format!("{module}::{name}"))
48}
49
50/// Lean's `unreachable` instruction: a point the Lean compiler proved cannot be reached.
51#[cold]
52#[inline(never)]
53pub fn unreachable() -> ! {
54 panic!("inlean: reached code Lean marked unreachable")
55}
56
57/// A Lean `Char` as a Rust `char`. Lean's `Char` carries a proof that it is a Unicode
58/// scalar value, so a failure here is a bug in the translation, not in the caller.
59#[inline]
60pub fn char_of_u32(value: u32) -> char {
61 match char::from_u32(value) {
62 Some(c) => c,
63 None => panic!("inlean: Lean returned an invalid Char: {value:#x}"),
64 }
65}