Work with Nat in rust
This commit is contained in:
1 parent
ba8bdf146a
commit
2f5925a1c7
2 files changed
+116
-3
No files matched your search
@@ -12,6 +12,16 @@ def myCustomNat : Nat := 69420
|
||||
@[export mycustomintfunction]
|
||||
def myCustomIntFunction (input: UInt32): UInt32 := input + 42069
|
||||
|
||||
-- Grows fast enough that small inputs (>= 21) overflow Lean's inline/tagged
|
||||
-- Nat representation and force the runtime to allocate a real bignum object.
|
||||
def natFactorial : Nat → Nat
|
||||
| 0 => 1
|
||||
| n + 1 => (n + 1) * natFactorial n
|
||||
|
||||
@[export mycustomnatfunction]
|
||||
def myCustomNatFunction (input : UInt32) : Nat :=
|
||||
natFactorial input.toNat
|
||||
|
||||
structure AST where
|
||||
name: String
|
||||
count: Nat
|
||||
|
||||
@@ -1,16 +1,106 @@
|
||||
use std::ffi::c_void;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct LeanObject {
|
||||
_private: [u8; 0],
|
||||
}
|
||||
|
||||
// Mirrors `lean_object` from lean.h. `m_rc` doubles as an atomic refcount;
|
||||
// the three fields after it are declared in the header as bitfields
|
||||
// (m_cs_sz:16, m_other:8, m_tag:8) which - on this platform's C ABI - pack
|
||||
// least-significant-field-first into the 4 bytes following `m_rc`, so plain
|
||||
// fields in the same order reproduce the same layout.
|
||||
#[repr(C)]
|
||||
struct LeanObjectHeader {
|
||||
m_rc: i32,
|
||||
m_cs_sz: u16,
|
||||
m_other: u8,
|
||||
m_tag: u8,
|
||||
}
|
||||
|
||||
// Object tag used by the Lean runtime for boxed Nat/Int values (lean.h: `LeanMPZ`).
|
||||
const LEAN_MPZ_TAG: u8 = 250;
|
||||
|
||||
// Mirrors the (internal, not part of the public C API) `lean_mpz_object`:
|
||||
// a `lean_object` header directly followed by a GMP `mpz_t`. `mpz_t` is
|
||||
// GMP's `__mpz_struct { int _mp_alloc; int _mp_size; mp_limb_t *_mp_d; }` -
|
||||
// on x86_64 `mp_limb_t` is a 64-bit `unsigned long`, so limbs are `u64`s in
|
||||
// little-limb order (least-significant limb first).
|
||||
#[repr(C)]
|
||||
struct LeanMpzObject {
|
||||
header: LeanObjectHeader,
|
||||
mp_alloc: i32,
|
||||
mp_size: i32,
|
||||
mp_d: *const u64,
|
||||
}
|
||||
|
||||
/// Interprets the raw bytes of an owned `lean_object *` known to represent a
|
||||
/// `Nat`, without calling any Lean Nat-inspection API.
|
||||
///
|
||||
/// A Lean `Nat` is represented one of two ways:
|
||||
/// - small values are "boxed" as a tagged pointer: the value is shifted left
|
||||
/// one bit and the low bit is set to 1, so the "pointer" never points at
|
||||
/// real memory at all (see `lean_box`/`lean_unbox`/`lean_is_scalar`).
|
||||
/// - values above `LEAN_MAX_SMALL_NAT` (`SIZE_MAX >> 1`, i.e. 2^63 - 1 on a
|
||||
/// 64-bit machine) are real pointers to a heap-allocated GMP `mpz_t`.
|
||||
unsafe fn describe_lean_nat(label: &str, obj: *mut LeanObject) {
|
||||
let raw = obj as usize;
|
||||
|
||||
if raw & 1 == 1 {
|
||||
let value = raw >> 1;
|
||||
println!("{label}: tagged scalar Nat (no heap allocation), value = {value}");
|
||||
return;
|
||||
}
|
||||
|
||||
let mpz = obj as *const LeanMpzObject;
|
||||
let tag = unsafe { (*mpz).header.m_tag };
|
||||
assert_eq!(
|
||||
tag, LEAN_MPZ_TAG,
|
||||
"expected a boxed Nat (GMP mpz object, tag {LEAN_MPZ_TAG}), got tag {tag}"
|
||||
);
|
||||
|
||||
// Nat is never negative, so `_mp_size` (which would be negative for a
|
||||
// negative Int) is directly the number of limbs in use.
|
||||
let mp_size = unsafe { (*mpz).mp_size };
|
||||
let mp_d = unsafe { (*mpz).mp_d };
|
||||
let limb_count = mp_size as usize;
|
||||
let limbs = unsafe { std::slice::from_raw_parts(mp_d, limb_count) };
|
||||
|
||||
print!("{label}: boxed Nat (GMP mpz object), {limb_count} limb(s), raw limbs (little-limb order) = [");
|
||||
for (i, limb) in limbs.iter().enumerate() {
|
||||
if i > 0 {
|
||||
print!(", ");
|
||||
}
|
||||
print!("{limb:#018x}");
|
||||
}
|
||||
println!("]");
|
||||
|
||||
print!("{label}: hex value = 0x");
|
||||
for &limb in limbs.iter().rev() {
|
||||
print!("{limb:016x}");
|
||||
}
|
||||
println!();
|
||||
|
||||
if limb_count <= 2 {
|
||||
let mut value: u128 = 0;
|
||||
for (i, &limb) in limbs.iter().enumerate() {
|
||||
value |= (limb as u128) << (64 * i);
|
||||
}
|
||||
println!("{label}: decimal value = {value}");
|
||||
} else {
|
||||
println!("{label}: too large to fit a u128, see hex value above");
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
unsafe extern "C" {
|
||||
fn mycustomintfunction(x: u32) -> u32;
|
||||
//fn mycustomint() -> u32;
|
||||
//static mycustomint : u32;
|
||||
|
||||
// Returns an owned `lean_object *` representing a `Nat`. Depending on the
|
||||
// magnitude of the result this is either a tagged scalar (no allocation)
|
||||
// or a pointer to a boxed GMP `mpz_t` object - see `describe_lean_nat`.
|
||||
fn mycustomnatfunction(x: u32) -> *mut LeanObject;
|
||||
|
||||
// Initializers - names from objdump
|
||||
#[link_name = "initialize_lean_x2dffi_x2dexperiment_LeanFfiExperiment"]
|
||||
fn initialize_LeanFfiExperiment(builtin: u8) -> *mut LeanObject;
|
||||
@@ -32,7 +122,7 @@ unsafe extern "C" {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("Going to invoke Lean FFI");
|
||||
println!("A series of invocations of Lean FFI code");
|
||||
|
||||
unsafe {
|
||||
lean_initialize_runtime_module();
|
||||
@@ -49,8 +139,21 @@ fn main() {
|
||||
let input = 20;
|
||||
let output = unsafe { mycustomintfunction(input) };
|
||||
|
||||
println!("Calling `myCustomIntFunction : UInt32 -> UInt32`");
|
||||
println!("Input: {input} output: {output}");
|
||||
|
||||
// Small enough that `n!` stays within Lean's tagged-scalar Nat range.
|
||||
let small_factorial_input = 5u32;
|
||||
let small_nat = unsafe { mycustomnatfunction(small_factorial_input) };
|
||||
println!("\n{small_factorial_input}! as a Lean Nat:");
|
||||
unsafe { describe_lean_nat(" result", small_nat) };
|
||||
|
||||
// Big enough that `n!` overflows into a boxed GMP bignum.
|
||||
let big_factorial_input = 25u32;
|
||||
let big_nat = unsafe { mycustomnatfunction(big_factorial_input) };
|
||||
println!("\n{big_factorial_input}! as a Lean Nat:");
|
||||
unsafe { describe_lean_nat(" result", big_nat) };
|
||||
|
||||
/* this segfaults because mycustomint is a zero-argument Lean function
|
||||
* that gets placed into the .bss section of the shared library
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user