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 int;
18pub mod map;
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;
30pub use types::{FromLean, Int, Nat, ParseIntError, ParseNatError, ToLean, 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 if let Some(name) = c_symbol.strip_prefix("inlean_map_") {
44 return map::OPS.contains(&name).then(|| format!("map::{name}"));
45 }
46 let name = c_symbol.strip_prefix("lean_")?;
47 [("nat", nat::OPS), ("string", string::OPS), ("array", array::OPS), ("misc", misc::OPS), ("int", int::OPS), ("sarray", sarray::OPS)]
48 .into_iter()
49 .find(|(_, ops)| ops.contains(&name))
50 .map(|(module, _)| format!("{module}::{name}"))
51}
52
53/// Lean's `unreachable` instruction: a point the Lean compiler proved cannot be reached.
54#[cold]
55#[inline(never)]
56pub fn unreachable() -> ! {
57 panic!("inlean: reached code Lean marked unreachable")
58}
59
60/// A Lean `Char` as a Rust `char`. Lean's `Char` carries a proof that it is a Unicode
61/// scalar value, so a failure here is a bug in the translation, not in the caller.
62#[inline]
63pub fn char_of_u32(value: u32) -> char {
64 match char::from_u32(value) {
65 Some(c) => c,
66 None => panic!("inlean: Lean returned an invalid Char: {value:#x}"),
67 }
68}