lean-rs 0.1.0

Safe Rust bindings for hosting Lean 4 capabilities: runtime initialization, owned and borrowed object handles, typed first-order ABI conversions, compiled module loading, exported function calls, semantic handles, bounded meta services, batching, and session pooling.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! RAII handle over a Lake-built Lean shared object.
//!
//! [`LeanLibrary`] owns a [`libloading::Library`] for the duration of its
//! scope and exposes a single safe operation that callers actually want:
//! initialize a named Lean module out of it. The dlopen step, the Lake
//! symbol-mangling convention, the `IO Unit` decoding, and the
//! `builtin` flag policy are hidden inside the implementation; the
//! interface mentions only the human-readable package and module names.
//!
//! Construction requires a `&'lean LeanRuntime` borrow. Use-before-init
//! is therefore structurally impossible: a caller cannot build a
//! [`LeanLibrary`] without holding the proof that
//! [`crate::LeanRuntime::init`] has succeeded.
//!
//! ## Symbol-table walk at `open`
//!
//! Lean compiles `def x : T := constant` — a nullary export whose body
//! reduces to a constant — to a persistent `lean_object*` global variable
//! (`lean_mark_persistent` at module init), not a callable function.
//! Calling such a symbol as a function pointer SIGBUSes. To make the
//! distinction invisible to callers, [`LeanLibrary::open`] reads the
//! dylib's bytes once, walks the export table with the [`object`] crate,
//! and records the names of data-section exports as `globals`.
//! [`LeanModule::exported`](super::loaded::LeanModule::exported) consults
//! the set to dispatch function-vs-global at call time.

// SAFETY DOC: every `unsafe { ... }` block in this file carries its own
// `// SAFETY:` comment. The blanket allow exists because this is the
// single `pub` doorway into the dlopen/dlsym path; per
// `docs/architecture/01-safety-model.md` the opt-out lives at the
// smallest scope that compiles.
#![allow(unsafe_code)]

use std::collections::HashSet;
use std::ffi::c_void;
use std::path::{Path, PathBuf};

use lean_rs_sys::lean_object;
use object::{Object, ObjectSection, ObjectSymbol, SectionKind, SymbolSection};

use super::initializer::{InitializerName, RawInitializer, call_initializer};
use super::loaded::LeanModule;
#[cfg(doc)]
use crate::error::HostStage;
use crate::error::{LeanError, LeanResult};
use crate::runtime::LeanRuntime;

/// A loaded native Lean shared object.
///
/// Wraps a [`libloading::Library`] and hands out initialized module
/// handles via [`LeanLibrary::initialize_module`]. The `'lean` lifetime
/// parameter ties the library to the witnessing
/// [`crate::LeanRuntime`] borrow; the resulting [`LeanModule`] handles
/// borrow from `self`, so they cannot outlive the library that hosts
/// them.
///
/// Neither [`Send`] nor [`Sync`]: the `&'lean LeanRuntime` field
/// inherits the runtime's per-thread restriction (`LeanRuntime: !Sync`
/// implies `&LeanRuntime: !Send`, and `&LeanRuntime: Sync` iff
/// `LeanRuntime: Sync`). A negative-bound compile-time assertion in
/// the test module fails if either auto-trait is ever implemented.
pub struct LeanLibrary<'lean> {
    library: libloading::Library,
    path: PathBuf,
    runtime: &'lean LeanRuntime,
    /// Names of data-section exports (Lean nullary-constant globals),
    /// normalised to what [`libloading::Library::get`] resolves with
    /// (Mach-O leading underscore stripped). Computed once at [`open`]
    /// and consulted by
    /// [`LeanModule::exported`](super::loaded::LeanModule::exported) to
    /// dispatch function-vs-global at call time.
    ///
    /// [`open`]: Self::open
    globals: HashSet<String>,
}

impl<'lean> LeanLibrary<'lean> {
    /// Load a Lake-built Lean shared object from `path`.
    ///
    /// Reads the file's symbol table once to classify each exported
    /// symbol as a function (text/code section) or a Lean
    /// nullary-constant global (data/rodata/bss section). The
    /// classification is consulted by
    /// [`LeanModule::exported`](super::loaded::LeanModule::exported) so
    /// callers never write the function-vs-global distinction at the
    /// call site. The walk is cheap (a single `std::fs::read` plus an
    /// in-memory parse) and amortised across every later lookup.
    ///
    /// The `runtime` borrow is the type-level proof that the Lean runtime
    /// is up; it is retained for the symbol-initialization step but
    /// otherwise unused. Module initialization happens later through
    /// [`LeanLibrary::initialize_module`].
    ///
    /// # Errors
    ///
    /// Returns [`LeanError::Host`] with stage [`HostStage::Load`] if:
    ///
    /// - the file cannot be read (missing, permission denied),
    /// - the bytes do not parse as a recognised object format (Mach-O,
    ///   ELF, PE),
    /// - the dynamic linker fails to open the file (missing transitive
    ///   dependency, architecture mismatch, …).
    ///
    /// The diagnostic embeds the path and the underlying error message.
    pub fn open(runtime: &'lean LeanRuntime, path: impl AsRef<Path>) -> LeanResult<Self> {
        let path = path.as_ref();
        let _span = tracing::debug_span!(
            target: "lean_rs",
            "lean_rs.module.library.open",
            path = %crate::error::redact::short_path(path),
        )
        .entered();
        let globals = classify_globals(path)?;
        // SAFETY: `Library::new` runs the platform dynamic loader. Lake
        // does not emit constructor-style initializers for Lean
        // libraries (the per-module `initialize_*` functions are
        // explicit, not C constructors), so the load is side-effect-free
        // from Rust's perspective; the resulting handle releases the
        // library on drop.
        let library = unsafe { libloading::Library::new(path) }.map_err(|err| {
            LeanError::module_init(format!("failed to open Lean library '{}': {err}", path.display()))
        })?;
        Ok(Self {
            library,
            path: path.to_path_buf(),
            runtime,
            globals,
        })
    }

    /// Open a Lake-built Lean shared object with **globally visible
    /// symbols** (POSIX `RTLD_GLOBAL` on Unix; the Windows side stays
    /// on the default loader since DLL symbols are already global).
    ///
    /// The same contract as [`LeanLibrary::open`], plus: symbols
    /// defined by this dylib become visible to the dynamic linker's
    /// global namespace, so any subsequently `dlopen`ed dylib whose
    /// initializer chain references them resolves correctly.
    ///
    /// The motivating case is the `lean-rs-host` two-dylib load: a
    /// downstream capability dylib's `initialize_<ConsumerLib>`
    /// transitively calls `initialize_<RequiredShim>`, which is
    /// defined in a sibling dylib (the `lean-rs-host-shims` Lake
    /// package). With the default `RTLD_LOCAL`, the consumer's
    /// initializer chain SIGSEGVs jumping to the unresolved symbol;
    /// opening the shim dylib globally first lets the consumer's
    /// chain resolve through the global namespace.
    ///
    /// # Errors
    ///
    /// Same as [`LeanLibrary::open`].
    pub fn open_globally(runtime: &'lean LeanRuntime, path: impl AsRef<Path>) -> LeanResult<Self> {
        let path = path.as_ref();
        let _span = tracing::debug_span!(
            target: "lean_rs",
            "lean_rs.module.library.open_globally",
            path = %crate::error::redact::short_path(path),
        )
        .entered();
        let globals = classify_globals(path)?;
        let library = open_with_global_visibility(path)?;
        Ok(Self {
            library,
            path: path.to_path_buf(),
            runtime,
            globals,
        })
    }

    /// Initialize the Lean module identified by `(package, module)`.
    ///
    /// Resolves the Lake-mangled initializer symbol against this
    /// library, invokes it under a panic boundary with the runtime
    /// `builtin` flag, and decodes the resulting `IO Unit`. Idempotent:
    /// the Lean-emitted initializer body short-circuits to `IO.ok(())`
    /// on its second and later calls, so repeated invocations are safe
    /// and cheap.
    ///
    /// # Errors
    ///
    /// Returns [`LeanError::Host`] with:
    ///
    /// - [`HostStage::Link`] if `package` or `module` is not a valid
    ///   Lake identifier, or the mangled initializer symbol is not
    ///   exported by this library.
    /// - [`HostStage::Load`] if the initializer panics or returns
    ///   `IO.error`.
    pub fn initialize_module<'lib>(&'lib self, package: &str, module: &str) -> LeanResult<LeanModule<'lean, 'lib>> {
        let _span = tracing::debug_span!(
            target: "lean_rs",
            "lean_rs.module.library.initialize",
            package = package,
            module = module,
        )
        .entered();
        let name = InitializerName::from_lake_names(package, module)?;
        let init = self.lookup_initializer(&name)?;
        call_initializer(self.runtime, init, &name)?;
        Ok(LeanModule::new(self, name))
    }

    /// Names of data-section exports for this library, normalised to the
    /// form [`libloading::Library::get`] resolves with.
    pub(crate) fn globals(&self) -> &HashSet<String> {
        &self.globals
    }

    /// The runtime borrow this library was opened with.
    pub(crate) fn runtime(&self) -> &'lean LeanRuntime {
        self.runtime
    }

    /// On-disk path the library was opened from. Used only for
    /// diagnostics.
    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    /// Resolve `name` as a function-pointer symbol (text section).
    ///
    /// Returns the raw symbol address. The caller is responsible for
    /// casting to the right `unsafe extern "C" fn(...) -> ...`
    /// signature, typically by handing the address to
    /// [`LeanExported::from_function_address`].
    ///
    /// # Errors
    ///
    /// Returns [`LeanError::Host`] with stage [`HostStage::Link`] if
    /// the symbol is not exported by this library. The diagnostic
    /// embeds the symbol name and the library path.
    ///
    /// [`LeanExported::from_function_address`]: crate::module::LeanExported::from_function_address
    pub fn resolve_function_symbol(&self, name: &str) -> LeanResult<*mut c_void> {
        // SAFETY: `libloading::Library::get::<*mut c_void>` is the raw
        // address lookup; the returned `Symbol<'_, *mut c_void>` borrows
        // from `self.library`, so dereferencing it inside this scope is
        // valid. We copy the address out via `*symbol` — the same idiom
        // `lookup_initializer` uses.
        let symbol: libloading::Symbol<'_, *mut c_void> =
            unsafe { self.library.get(name.as_bytes()) }.map_err(|err| {
                LeanError::symbol_lookup(format!(
                    "unknown exported symbol '{}' in '{}': {err}",
                    name,
                    self.path.display()
                ))
            })?;
        Ok(*symbol)
    }

    /// Resolve `name` as a function-pointer symbol, tolerating a missing
    /// symbol.
    ///
    /// Returns `Some(address)` when the symbol resolves, `None` when it
    /// is absent from this library. The opinionated `lean-rs-host` stack
    /// uses this to pre-resolve *optional* capability symbols at
    /// `LeanCapabilities::new` time without failing capability load when
    /// a fixture omits a service.
    ///
    /// Symbol resolution at the dlsym level only fails with "symbol not
    /// present" — the dynamic linker has already accepted the library at
    /// [`Self::open`], so a per-symbol lookup error is either "missing"
    /// or a `\0` in the name (which a sane caller never passes). Both
    /// are collapsed into the `None` branch by design.
    pub fn resolve_optional_function_symbol(&self, name: &str) -> Option<*mut c_void> {
        // SAFETY: identical to `resolve_function_symbol`; the symbol
        // borrow does not escape this scope.
        match unsafe { self.library.get::<*mut c_void>(name.as_bytes()) } {
            Ok(symbol) => Some(*symbol),
            Err(_) => None,
        }
    }

    /// Resolve `name` as a Lean nullary-constant global symbol
    /// (data section). The returned pointer addresses the storage
    /// holding the persistent `lean_object*` value; the caller reads
    /// `*returned` to get the Lean object pointer itself.
    ///
    /// # Errors
    ///
    /// Returns [`LeanError::Host`] with stage [`HostStage::Link`] if
    /// the symbol is not exported by this library.
    pub(crate) fn resolve_global_symbol(&self, name: &str) -> LeanResult<*mut *mut lean_object> {
        // SAFETY: `libloading::Library::get::<T>` returns the symbol's
        // address typed as `T`. For data symbols the address is the
        // location of the variable, so the parameterised type spells a
        // pointer to the variable's value. The borrow lifetime ends
        // when this function returns; we copy the address out.
        let symbol: libloading::Symbol<'_, *mut *mut lean_object> = unsafe { self.library.get(name.as_bytes()) }
            .map_err(|err| {
                LeanError::symbol_lookup(format!(
                    "unknown global symbol '{}' in '{}': {err}",
                    name,
                    self.path.display()
                ))
            })?;
        Ok(*symbol)
    }

    /// Resolve the module initializer by `dlsym`, trying both the modern
    /// (Lean ≥ 4.27) and legacy (Lean ≤ 4.26) Lake symbol shapes. The
    /// diagnostic on failure names both candidates so the operator can
    /// see what was searched.
    fn lookup_initializer(&self, name: &InitializerName) -> LeanResult<RawInitializer> {
        // SAFETY: the type parameter spells the canonical Lake
        // initializer signature (`(u8) -> *mut lean_object`), verified
        // against the Lake-emitted C in `fixtures/lean/.lake/build/ir/`
        // for every supported Lean version. `libloading::Library::get`
        // returns a borrowed `Symbol<'_, T>`; copying the raw function
        // pointer out of it via deref is the standard pattern when the
        // caller does not need to retain the borrow.
        let modern: Result<libloading::Symbol<'_, RawInitializer>, _> =
            unsafe { self.library.get(name.symbol_bytes()) };
        if let Ok(symbol) = modern {
            return Ok(*symbol);
        }
        // SAFETY: same as above; the legacy symbol shape is the only
        // exported form for Lean ≤ 4.26 dylibs.
        let legacy: Result<libloading::Symbol<'_, RawInitializer>, _> =
            unsafe { self.library.get(name.legacy_symbol_bytes()) };
        match legacy {
            Ok(symbol) => Ok(*symbol),
            Err(err) => Err(LeanError::linking(format!(
                "missing initializer symbol in '{}': tried '{}' and '{}': {err}",
                self.path.display(),
                name.symbol_str(),
                name.legacy_symbol_str(),
            ))),
        }
    }
}

impl std::fmt::Debug for LeanLibrary<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LeanLibrary")
            .field("path", &self.path)
            .field("globals_count", &self.globals.len())
            .finish()
    }
}

/// Read `path` and collect the names of its data-section exports
/// (Lean nullary-constant globals).
///
/// Mach-O export names carry a leading `_` that `libloading` strips at
/// lookup; we strip here so the set keys match what
/// [`LeanLibrary::resolve_global_symbol`] queries with. ELF and PE
/// symbol names are stored without leading `_`, so no normalisation is
/// needed on those platforms.
///
/// Symbols whose section can't be classified (undefined, absolute,
/// common) are skipped: they cannot be the Lean-compiled persistent
/// globals we care about.
fn classify_globals(path: &Path) -> LeanResult<HashSet<String>> {
    let bytes = std::fs::read(path)
        .map_err(|err| LeanError::module_init(format!("failed to read Lean library '{}': {err}", path.display())))?;
    let file = object::File::parse(&*bytes)
        .map_err(|err| LeanError::module_init(format!("failed to parse object file '{}': {err}", path.display())))?;

    let strip_underscore = matches!(file.format(), object::BinaryFormat::MachO | object::BinaryFormat::Wasm);

    let mut globals = HashSet::new();
    // `symbols()` covers both ELF `.symtab` (when present) and Mach-O
    // `LC_SYMTAB` external defs; `dynamic_symbols()` on Mach-O omits
    // data-section externals such as Lean nullary-constant globals,
    // which is exactly what we need to classify.
    for symbol in file.symbols() {
        if !symbol.is_global() || symbol.is_undefined() {
            continue;
        }
        let SymbolSection::Section(section_index) = symbol.section() else {
            continue;
        };
        let Ok(section) = file.section_by_index(section_index) else {
            continue;
        };
        if !is_data_section(section.kind()) {
            continue;
        }
        let Ok(name) = symbol.name() else {
            continue;
        };
        let normalised = if strip_underscore {
            name.strip_prefix('_').unwrap_or(name)
        } else {
            name
        };
        if normalised.is_empty() {
            continue;
        }
        globals.insert(normalised.to_owned());
    }
    Ok(globals)
}

/// Open `path` with the dynamic loader's *global* symbol-visibility
/// flag set so any subsequently loaded dylib can resolve symbols
/// defined here.
///
/// On Unix this means `RTLD_LAZY | RTLD_GLOBAL`. On Windows the
/// platform loader publishes module symbols globally by default, so
/// the standard [`libloading::Library::new`] path is sufficient.
fn open_with_global_visibility(path: &Path) -> LeanResult<libloading::Library> {
    #[cfg(unix)]
    {
        // SAFETY: identical contract to `Library::new` — runs the
        // platform dynamic loader against `path`. The added
        // `RTLD_GLOBAL` flag only affects symbol-table visibility for
        // later loads; it does not change initializer-execution
        // semantics (Lake-built Lean dylibs have no constructor-style
        // init).
        let unix_library = unsafe {
            libloading::os::unix::Library::open(
                Some(path),
                libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL,
            )
        }
        .map_err(|err| {
            LeanError::module_init(format!(
                "failed to open Lean library '{}' with RTLD_GLOBAL: {err}",
                path.display()
            ))
        })?;
        Ok(unix_library.into())
    }
    #[cfg(not(unix))]
    {
        // SAFETY: same as `Library::new`. See unix branch.
        let library = unsafe { libloading::Library::new(path) }.map_err(|err| {
            LeanError::module_init(format!("failed to open Lean library '{}': {err}", path.display()))
        })?;
        Ok(library)
    }
}

/// Section kinds that hold runtime data (Lean nullary-constant
/// `lean_object*` pointers live in `__data` on Mach-O, `.data` /
/// `.rodata` / `.bss` on ELF).
fn is_data_section(kind: SectionKind) -> bool {
    matches!(
        kind,
        SectionKind::Data
            | SectionKind::ReadOnlyData
            | SectionKind::ReadOnlyDataWithRel
            | SectionKind::UninitializedData
            | SectionKind::Common
            | SectionKind::Tls
            | SectionKind::UninitializedTls
    )
}