lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
//! Registers and calls a scalar Rust function through Lehit's public native API.
//!
//! The Lehit source declaration is the authoritative contract. The native
//! registration supplies the Rust ABI details that the checked runtime validates
//! before installing the function pointer.

use lehit::{
    core_lib::PRIMITIVE_MODULE_FILE_PATH,
    runtime::{ExecutionMode, RuntimeBuilder},
    rust_lib::{NativeFunction, RustLib, RustTypeRef, Script},
    semantic::{AccessPath, CanonicalSymbolPath},
};

const MODULE: &str = "native://arithmetic.lt";

fn i32_type() -> RustTypeRef {
    RustTypeRef::Named(AccessPath {
        file_path: PRIMITIVE_MODULE_FILE_PATH.into(),
        local_access: "i32".into(),
        generics: Vec::new(),
    })
}

fn add(left: i32, right: i32) -> i32 {
    left.wrapping_add(right)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut script = Script {
        content: "pub acs add: fn(left: i32, right: i32) -> i32".into(),
        ..Script::default()
    };

    // SAFETY: `add` is a function item and therefore remains valid for the
    // process lifetime. Its `fn(i32, i32) -> i32` ABI exactly matches the typed
    // descriptor below, and `wrapping_add` cannot panic or unwind.
    let native = unsafe { NativeFunction::from_rust_fn2("native_add", add) };
    script
        .native_function("add", native)
        .public()
        .exported()
        .argument("left", i32_type())
        .argument("right", i32_type())
        .returns(i32_type())
        .finish();

    let mut library = RustLib::default();
    library.scripts.insert(MODULE.into(), script);

    let runtime = RuntimeBuilder::new()
        .with_execution_mode(ExecutionMode::Direct)
        .with_rust_lib(library)
        .build()?;
    let unit = runtime
        .rust_lib_unit()
        .expect("the configured native library has a compiled unit");
    let path = CanonicalSymbolPath {
        module: MODULE.into(),
        local: "add".into(),
    };
    let add = unit
        .function_ptr(&path)
        .expect("registered native function");
    // SAFETY: registration above establishes this exact Rust ABI and the
    // function item remains valid for the process lifetime.
    let add: fn(i32, i32) -> i32 = unsafe { std::mem::transmute(add) };

    assert_eq!(add(20, 22), 42);
    Ok(())
}