lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use std::{collections::BTreeMap, sync::Arc};

use crate::{
    runtime::{
        AbiCallError, ErrorChannel, ExecutionMode, Function, LeasedJitCompilationUnit,
        RuntimeAllocator, RuntimeErrorSink, ScriptWorkspace, WorkspaceError,
    },
    rust_lib::RustLib,
    semantic::CanonicalSymbolPath,
};

/// Supplies dependency source requested while compiling a module graph.
///
/// Return `Ok(None)` when the canonical path is unavailable. Provider failures
/// become workspace compilation failures and do not partially commit the graph.
pub trait ModuleSourceProvider {
    /// Loads one requested canonical module path.
    fn load(&mut self, path: &str) -> Result<Option<String>, WorkspaceError>;
}

impl<F> ModuleSourceProvider for F
where
    F: for<'a> FnMut(&'a str) -> Result<Option<String>, WorkspaceError>,
{
    fn load(&mut self, path: &str) -> Result<Option<String>, WorkspaceError> {
        self(path)
    }
}

/// Configures and creates a high-level [`LehitRuntime`].
///
/// The default uses [`ExecutionMode::Direct`] and the global Rust allocator.
/// Host-facing code should usually select [`ExecutionMode::Checked`].
#[derive(Default)]
pub struct RuntimeBuilder {
    rust_libraries: Vec<RustLib>,
    allocator: RuntimeAllocator,
    execution_mode: ExecutionMode,
    error_channel: Option<Arc<dyn ErrorChannel>>,
}

impl RuntimeBuilder {
    /// Creates a builder with the core library, direct execution, and default
    /// allocator configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a trusted Rust-provided library and returns the builder.
    pub fn with_rust_lib(mut self, library: RustLib) -> Self {
        self.rust_libraries.push(library);
        self
    }

    /// Adds a trusted Rust-provided library through a mutable builder reference.
    pub fn add_rust_lib(&mut self, library: RustLib) -> &mut Self {
        self.rust_libraries.push(library);
        self
    }

    /// Installs a custom allocator created under its documented unsafe contract.
    pub fn with_allocator(mut self, allocator: RuntimeAllocator) -> Self {
        self.allocator = allocator;
        self
    }

    pub fn allocator(&mut self, allocator: RuntimeAllocator) -> &mut Self {
        self.allocator = allocator;
        self
    }

    /// Selects direct or checked semantics and returns the builder.
    pub fn with_execution_mode(mut self, execution_mode: ExecutionMode) -> Self {
        self.execution_mode = execution_mode;
        self
    }

    pub fn execution_mode(&mut self, execution_mode: ExecutionMode) -> &mut Self {
        self.execution_mode = execution_mode;
        self
    }

    /// Installs a channel for detailed checked-execution diagnostics.
    pub fn with_error_channel<C>(mut self, channel: C) -> Self
    where
        C: ErrorChannel,
    {
        self.error_channel = Some(Arc::new(channel));
        self
    }

    /// Installs a shared channel for detailed checked-execution diagnostics.
    pub fn with_shared_error_channel(mut self, channel: Arc<dyn ErrorChannel>) -> Self {
        self.error_channel = Some(channel);
        self
    }

    /// Builds the core workspace and compiles every registered Rust library.
    ///
    /// # Errors
    ///
    /// Returns an error when core initialization, source parsing, native
    /// registration validation, semantic analysis, or JIT compilation fails.
    pub fn build(self) -> Result<LehitRuntime, WorkspaceError> {
        let error_sink = self.error_channel.map(RuntimeErrorSink::new);
        let mut workspace = ScriptWorkspace::with_core_configuration(
            self.allocator,
            self.execution_mode,
            error_sink,
        )?;
        let rust_lib_unit = if self.rust_libraries.is_empty() {
            None
        } else {
            let libraries = self.rust_libraries.iter().collect::<Vec<_>>();
            Some(workspace.compile_rust_libs_unit(&libraries)?)
        };
        Ok(LehitRuntime {
            workspace,
            rust_lib_unit,
        })
    }
}

/// Mutable host runtime containing semantic workspace state and leased JIT units.
///
/// Load and reload operations are transactional. Returned functions retain the
/// unit they came from, so an old handle can outlive a registry reload/unload.
pub struct LehitRuntime {
    workspace: ScriptWorkspace,
    rust_lib_unit: Option<Arc<LeasedJitCompilationUnit>>,
}

/// Function lookup result tied to the lifetime of its owning JIT unit.
///
/// Convert it to an ABI function before calling; construction validates the
/// function signature and execution mode.
pub struct RuntimeFunction {
    unit: Arc<LeasedJitCompilationUnit>,
    path: CanonicalSymbolPath,
}

impl RuntimeFunction {
    /// Creates a universal Lehit ABI descriptor in this unit's execution mode.
    pub fn abi_function(&self) -> Result<Function, AbiCallError> {
        Function::new(Arc::clone(&self.unit), &self.path)
    }

    /// Returns the canonical module/local function identity.
    pub fn path(&self) -> &CanonicalSymbolPath {
        &self.path
    }

    /// Exposes the low-level compilation lease for compiler/runtime tooling.
    #[doc(hidden)]
    pub fn unit(&self) -> &Arc<LeasedJitCompilationUnit> {
        &self.unit
    }
}

impl LehitRuntime {
    /// Builds a runtime from borrowed Rust-library descriptions.
    pub fn new(rust_libs: &[&RustLib]) -> Result<Self, WorkspaceError> {
        let mut builder = RuntimeBuilder::new();
        for library in rust_libs {
            builder.add_rust_lib((*library).clone());
        }
        builder.build()
    }

    /// Builds a runtime from owned Rust-library descriptions.
    pub fn with_rust_libs(
        rust_libs: impl IntoIterator<Item = RustLib>,
    ) -> Result<Self, WorkspaceError> {
        let mut builder = RuntimeBuilder::new();
        for library in rust_libs {
            builder.add_rust_lib(library);
        }
        builder.build()
    }

    /// Compiles and registers one source module.
    ///
    /// Existing registry state is unchanged when compilation fails.
    pub fn load_script(
        &mut self,
        path: impl Into<String>,
        source: impl Into<String>,
    ) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
        self.compile_unit(BTreeMap::from([(path.into(), source.into())]))
    }

    /// Transactionally recompiles an already loaded root module.
    ///
    /// Existing leased handles continue to refer to their old unit.
    pub fn reload_script(
        &mut self,
        path: &str,
        source: &str,
    ) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
        self.reload_graph(path, source, |_requested: &str| Ok(None))
    }

    /// Looks up a compiled function by canonical module and local path.
    pub fn function(&self, module: &str, local: &str) -> Result<RuntimeFunction, AbiCallError> {
        let path = CanonicalSymbolPath {
            module: module.to_owned(),
            local: local.to_owned(),
        };
        let unit = self
            .unit_for_module(module)
            .ok_or_else(|| AbiCallError::UnknownFunction(path.clone()))?;
        if unit.signature(&path).is_none() {
            return Err(AbiCallError::UnknownFunction(path));
        }
        Ok(RuntimeFunction { unit, path })
    }

    /// Returns the leased unit containing functions registered through
    /// [`RuntimeBuilder::with_rust_lib`].
    ///
    /// Native library modules are compiled into this shared unit rather than the
    /// per-script module registry used by [`LehitRuntime::function`].
    pub fn rust_lib_unit(&self) -> Option<Arc<LeasedJitCompilationUnit>> {
        self.rust_lib_unit.clone()
    }

    pub fn compile_unit(
        &mut self,
        sources: BTreeMap<String, String>,
    ) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
        let id = self
            .workspace
            .compile_and_register_scripts_unit(sources, &[])?;
        self.workspace
            .loaded_unit(id)
            .ok_or(WorkspaceError::UnknownCompilationUnit(id))
    }

    /// Compiles a root and lazily requests dependency source from `provider`.
    pub fn compile_graph<P>(
        &mut self,
        root_path: &str,
        root_source: &str,
        mut provider: P,
    ) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError>
    where
        P: ModuleSourceProvider,
    {
        let unit = self
            .workspace
            .compile_graph(root_path, root_source, |path| provider.load(path))?;
        self.workspace
            .loaded_unit(unit)
            .ok_or(WorkspaceError::UnknownCompilationUnit(unit))
    }

    pub fn reload_graph<P>(
        &mut self,
        root_path: &str,
        root_source: &str,
        mut provider: P,
    ) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError>
    where
        P: ModuleSourceProvider,
    {
        let unit = self
            .workspace
            .reload_graph(root_path, root_source, |path| provider.load(path))?;
        self.workspace
            .loaded_unit(unit)
            .ok_or(WorkspaceError::UnknownCompilationUnit(unit))
    }

    pub fn unit_for_module(&self, module: &str) -> Option<Arc<LeasedJitCompilationUnit>> {
        let id = self.workspace.unit_for_module(module)?;
        self.workspace.loaded_unit(id)
    }

    /// Detaches the module's executable unit from the runtime registry.
    ///
    /// Existing leased handles/values may keep the old unit alive.
    pub fn unload_module(&mut self, module: &str) -> Result<(), WorkspaceError> {
        self.workspace.unload_module(module)
    }

    /// Returns the low-level compiler workspace.
    #[doc(hidden)]
    pub fn workspace(&self) -> &ScriptWorkspace {
        &self.workspace
    }

    /// Returns mutable access to low-level compiler workspace state.
    #[doc(hidden)]
    pub fn workspace_mut(&mut self) -> &mut ScriptWorkspace {
        &mut self.workspace
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, sync::Arc};

    use crate::runtime::{ExecutionMode, Function, Runtime, RuntimeBuilder, RuntimeFunction};

    fn call_i32(function: &Function, arguments: &[i32]) -> i32 {
        let mut call = function.abi_call_builder();
        for argument in arguments {
            call.push_rust_value_argument(*argument).unwrap();
        }
        call.call().unwrap().into_rust_value::<i32>().unwrap()
    }

    fn call_runtime_i32(function: &RuntimeFunction, arguments: &[i32]) -> i32 {
        call_i32(&function.abi_function().unwrap(), arguments)
    }

    #[test]
    fn public_runtime_loads_unloads_and_keeps_leased_units_alive() {
        let mut runtime = Runtime::new(&[]).unwrap();
        let unit = runtime
            .load_script(
                "app://lifecycle.lt",
                "pub acs answer: fn() -> i32 { return 42 }
                 pub acs increment: fn(value: i32) -> i32 { return value + 1 }
                 pub acs add: fn(left: i32, right: i32) -> i32 { return left + right }",
            )
            .unwrap();
        assert!(runtime.unit_for_module("app://lifecycle.lt").is_some());
        let old_function = runtime.function("app://lifecycle.lt", "answer").unwrap();
        let old_answer = old_function.abi_function().unwrap();
        assert_eq!(call_i32(&old_answer, &[]), 42);
        assert!(Arc::ptr_eq(old_function.unit(), &unit));
        let increment = runtime
            .function("app://lifecycle.lt", "increment")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(call_i32(&increment, &[41]), 42);
        let add = runtime
            .function("app://lifecycle.lt", "add")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(call_i32(&add, &[20, 22]), 42);

        assert!(
            runtime
                .reload_script("app://lifecycle.lt", "pub acs answer: fn() -> i32 {")
                .is_err()
        );
        let current_answer = runtime
            .function("app://lifecycle.lt", "answer")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(call_i32(&current_answer, &[]), 42);

        let new_unit = runtime
            .reload_script(
                "app://lifecycle.lt",
                "pub acs answer: fn() -> i32 { return 43 }",
            )
            .unwrap();
        let new_function = runtime.function("app://lifecycle.lt", "answer").unwrap();
        assert!(Arc::ptr_eq(new_function.unit(), &new_unit));
        let new_answer = new_function.abi_function().unwrap();
        assert_eq!(call_i32(&new_answer, &[]), 43);
        assert_eq!(call_i32(&old_answer, &[]), 42);

        runtime.unload_module("app://lifecycle.lt").unwrap();
        assert!(runtime.unit_for_module("app://lifecycle.lt").is_none());
        assert_eq!(call_i32(&old_answer, &[]), 42);
        assert_eq!(call_i32(&new_answer, &[]), 43);
    }

    #[test]
    fn universal_abi_validates_arity_void_results_and_mixed_layout() {
        let mut runtime = RuntimeBuilder::new()
            .with_execution_mode(ExecutionMode::Checked)
            .build()
            .unwrap();

        runtime
            .load_script("app://void.lt", "let value: i32 = 1")
            .unwrap();
        let void = runtime
            .function("app://void.lt", "")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(void.result_size_and_align(), (0, 1));
        void.abi_call_builder().call().unwrap().into_void().unwrap();

        runtime
            .load_script(
                "app://mixed.lt",
                "as fn(first: u8, second: u64, third: u16) -> u16 return third",
            )
            .unwrap();
        let mixed = runtime
            .function("app://mixed.lt", "")
            .unwrap()
            .abi_function()
            .unwrap();
        let arguments = mixed.get_arguments();
        assert_eq!(arguments.len(), 3);
        assert_eq!(
            (
                arguments[0].offset(),
                arguments[1].offset(),
                arguments[2].offset()
            ),
            (0, 8, 16)
        );
        let mut call = mixed.abi_call_builder();
        call.push_rust_value_argument(1_u8).unwrap();
        call.push_rust_value_argument(2_u64).unwrap();
        call.push_rust_value_argument(42_u16).unwrap();
        assert_eq!(call.call().unwrap().into_rust_value::<u16>().unwrap(), 42);
    }

    #[test]
    fn universal_checked_abi_reports_all_arithmetic_statuses() {
        let mut runtime = RuntimeBuilder::new()
            .with_execution_mode(ExecutionMode::Checked)
            .build()
            .unwrap();
        runtime
            .load_script(
                "app://divide.lt",
                "as fn(first: i32, second: i32) -> i32 return first / second",
            )
            .unwrap();
        let divide = runtime
            .function("app://divide.lt", "")
            .unwrap()
            .abi_function()
            .unwrap();
        let mut call = divide.abi_call_builder();
        call.push_rust_value_argument(1_i32).unwrap();
        call.push_rust_value_argument(0_i32).unwrap();
        assert!(matches!(
            call.call(),
            Err(crate::runtime::AbiCallError::Execution(status))
                if status == crate::runtime::AbiCallStatus::DIVISION_BY_ZERO
        ));
    }

    #[test]
    fn explicit_file_entry_reload_is_transactional_and_keeps_old_lease_alive() {
        let mut runtime = Runtime::new(&[]).unwrap();
        runtime
            .load_script("app://entry-reload.lt", "as fn() -> i32 return 42")
            .unwrap();
        let old = runtime
            .function("app://entry-reload.lt", "")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(call_i32(&old, &[]), 42);

        assert!(
            runtime
                .reload_script("app://entry-reload.lt", "as fn() -> i32 return")
                .is_err()
        );
        assert_eq!(
            call_runtime_i32(&runtime.function("app://entry-reload.lt", "").unwrap(), &[],),
            42
        );

        runtime
            .reload_script("app://entry-reload.lt", "as fn() -> i32 return 43")
            .unwrap();
        let new = runtime
            .function("app://entry-reload.lt", "")
            .unwrap()
            .abi_function()
            .unwrap();
        assert_eq!(call_i32(&new, &[]), 43);
        assert_eq!(call_i32(&old, &[]), 42);
    }

    #[test]
    fn explicit_void_file_contract_creates_an_entry_without_statements() {
        let mut runtime = Runtime::new(&[]).unwrap();
        runtime
            .load_script("app://empty-entry.lt", "as fn()")
            .unwrap();
        runtime
            .function("app://empty-entry.lt", "")
            .unwrap()
            .abi_function()
            .unwrap()
            .abi_call_builder()
            .call()
            .unwrap()
            .into_void()
            .unwrap();
    }

    #[test]
    fn multiple_file_function_contracts_are_rejected() {
        let mut runtime = Runtime::new(&[]).unwrap();
        assert!(matches!(
            runtime.load_script("app://duplicate-entry.lt", "as fn() as fn()"),
            Err(crate::runtime::WorkspaceError::MultipleFileFunctionContracts { path })
                if path == "app://duplicate-entry.lt"
        ));
        assert!(
            runtime
                .unit_for_module("app://duplicate-entry.lt")
                .is_none()
        );
    }

    #[test]
    fn file_entry_requires_a_contract_or_top_level_statement() {
        let mut runtime = Runtime::new(&[]).unwrap();
        runtime
            .load_script(
                "app://declarations.lt",
                "pub acs answer: fn() -> i32 { return 42 }",
            )
            .unwrap();
        assert!(runtime.function("app://declarations.lt", "").is_err());
        assert_eq!(
            call_runtime_i32(
                &runtime.function("app://declarations.lt", "answer").unwrap(),
                &[]
            ),
            42
        );
    }

    #[test]
    fn builder_preserves_the_checked_execution_mode_configuration() {
        let mut runtime = RuntimeBuilder::new()
            .with_execution_mode(ExecutionMode::Checked)
            .build()
            .unwrap();
        assert_eq!(runtime.workspace().execution_mode(), ExecutionMode::Checked);
        let unit = runtime
            .compile_unit(BTreeMap::from([(
                "app://checked-mode.lt".into(),
                "pub acs answer: fn() -> i32 { return 42 }".into(),
            )]))
            .unwrap();
        assert_eq!(unit.execution_mode(), ExecutionMode::Checked);
    }
}