Work with strings across the FFI

This commit is contained in:
Greg Shuflin committed 2026-07-28 01:03:51 -07:00
1 parent f3e9224f5b
commit e89e05fa14
3 files changed
+56 -9

No files matched your search

+5
View File
@@ -22,6 +22,11 @@ def natFactorial : Nat → Nat
def myCustomNatFunction (input : UInt32) : Nat :=
natFactorial input.toNat
@[export mycustomstringfunction]
def myCustomStringFunction (input: UInt32) : String :=
s!"You input the number {input}"
structure AST where
name: String
count: Nat
+12 -7
View File
@@ -1,7 +1,10 @@
use std::{env, path::PathBuf, process::Command};
fn main() {
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).parent().unwrap().to_owned();
let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.unwrap()
.to_owned();
// Lake output dir containing libYourLeanLib.so
let lake_lib_dir = root.join(".lake").join("build").join("lib");
@@ -23,7 +26,9 @@ fn main() {
// Re-run if the Lean shared library changes.
println!(
"cargo::rerun-if-changed={}",
lake_lib_dir.join(format!("lib{lean_lib_name}.so")).display()
lake_lib_dir
.join(format!("lib{lean_lib_name}.so"))
.display()
);
// Lean runtime shared libraries.
@@ -35,10 +40,7 @@ fn main() {
.output()
.expect("failed to run `lean --print-prefix`");
assert!(
lean_prefix.status.success(),
"`lean --print-prefix` failed"
);
assert!(lean_prefix.status.success(), "`lean --print-prefix` failed");
let lean_prefix = String::from_utf8(lean_prefix.stdout).unwrap();
let lean_prefix = lean_prefix.trim();
@@ -46,7 +48,10 @@ fn main() {
let lean_lib_dir = PathBuf::from(lean_prefix).join("lib").join("lean");
println!("cargo::rustc-link-search=native={}", lean_lib_dir.display());
println!("cargo::rustc-link-arg=-Wl,-rpath,{}", lean_lib_dir.display());
println!(
"cargo::rustc-link-arg=-Wl,-rpath,{}",
lean_lib_dir.display()
);
// Lean runtime/core shared libraries
println!("cargo::rustc-link-lib=dylib=Init_shared");
+39 -2
View File
@@ -113,6 +113,33 @@ unsafe fn describe_lean_nat(label: &str, obj: *mut LeanObject) {
}
}
// Mirrors `lean_string_object` from lean.h. Unlike the Nat/mpz case, this
// struct *is* documented directly in the public header:
// lean_object m_header;
// size_t m_size; // byte length, including the trailing '\0'
// size_t m_capacity;
// size_t m_length; // UTF-8 length, in codepoints
// char m_data[];
// so reading it doesn't require guessing at any third-party library's ABI.
#[repr(C)]
struct LeanStringObject {
header: LeanObjectHeader,
m_size: usize,
m_capacity: usize,
m_length: usize,
}
/// Reads a Lean `String` object's bytes out as a `&str`, mirroring
/// `lean_string_cstr`/`lean_string_size` (lean.h) - `static inline`, so not
/// linkable, but built on a struct layout the header documents directly.
unsafe fn lean_string_to_str<'a>(obj: *mut LeanObject) -> &'a str {
let size = unsafe { (*(obj as *const LeanStringObject)).m_size };
let data = unsafe { (obj as *const u8).add(std::mem::size_of::<LeanStringObject>()) };
// `m_size` includes the trailing '\0' that `m_data` is guaranteed to have.
let bytes = unsafe { std::slice::from_raw_parts(data, size - 1) };
std::str::from_utf8(bytes).expect("Lean strings are valid UTF-8")
}
#[allow(dead_code)]
unsafe extern "C" {
fn mycustomintfunction(x: u32) -> u32;
@@ -131,6 +158,10 @@ unsafe extern "C" {
fn lean_uint32_of_big_nat(obj: *mut LeanObject) -> u32;
fn lean_uint64_of_big_nat(obj: *mut LeanObject) -> u64;
// Returns an owned `lean_object *` representing a `String` - see
// `lean_string_to_str`.
fn mycustomstringfunction(x: u32) -> *mut LeanObject;
// Initializers - names from objdump
#[link_name = "initialize_lean_x2dffi_x2dexperiment_LeanFfiExperiment"]
fn initialize_LeanFfiExperiment(builtin: u8) -> *mut LeanObject;
@@ -173,17 +204,23 @@ fn main() {
println!("Input: {input} output: {output}");
// Small enough that `n!` stays within Lean's tagged-scalar Nat range.
let small_factorial_input = 5u32;
let small_factorial_input: u32 = 5;
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_factorial_input: u32 = 25;
let big_nat = unsafe { mycustomnatfunction(big_factorial_input) };
println!("\n{big_factorial_input}! as a Lean Nat:");
unsafe { describe_lean_nat(" result", big_nat) };
let string_input: u32 = 69;
let lean_string = unsafe { mycustomstringfunction(string_input) };
let text = unsafe { lean_string_to_str(lean_string) };
println!("\nCalling `myCustomStringFunction : UInt32 -> String` with input {string_input}:");
println!(" result: {text:?}");
/* this segfaults because mycustomint is a zero-argument Lean function
* that gets placed into the .bss section of the shared library
*/