use std::{collections::BTreeMap, sync::Arc};
use crate::{
runtime::{
AbiCallError, ErrorChannel, ExecutionMode, Function, LeasedJitCompilationUnit,
RuntimeAllocator, RuntimeErrorSink, ScriptWorkspace, WorkspaceError,
},
rust_lib::RustLib,
semantic::CanonicalSymbolPath,
};
pub trait ModuleSourceProvider {
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)
}
}
#[derive(Default)]
pub struct RuntimeBuilder {
rust_libraries: Vec<RustLib>,
allocator: RuntimeAllocator,
execution_mode: ExecutionMode,
error_channel: Option<Arc<dyn ErrorChannel>>,
}
impl RuntimeBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn with_rust_lib(mut self, library: RustLib) -> Self {
self.rust_libraries.push(library);
self
}
pub fn add_rust_lib(&mut self, library: RustLib) -> &mut Self {
self.rust_libraries.push(library);
self
}
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
}
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
}
pub fn with_error_channel<C>(mut self, channel: C) -> Self
where
C: ErrorChannel,
{
self.error_channel = Some(Arc::new(channel));
self
}
pub fn with_shared_error_channel(mut self, channel: Arc<dyn ErrorChannel>) -> Self {
self.error_channel = Some(channel);
self
}
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,
})
}
}
pub struct LehitRuntime {
workspace: ScriptWorkspace,
rust_lib_unit: Option<Arc<LeasedJitCompilationUnit>>,
}
pub struct RuntimeFunction {
unit: Arc<LeasedJitCompilationUnit>,
path: CanonicalSymbolPath,
}
impl RuntimeFunction {
pub fn abi_function(&self) -> Result<Function, AbiCallError> {
Function::new(Arc::clone(&self.unit), &self.path)
}
pub fn path(&self) -> &CanonicalSymbolPath {
&self.path
}
#[doc(hidden)]
pub fn unit(&self) -> &Arc<LeasedJitCompilationUnit> {
&self.unit
}
}
impl LehitRuntime {
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()
}
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()
}
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())]))
}
pub fn reload_script(
&mut self,
path: &str,
source: &str,
) -> Result<Arc<LeasedJitCompilationUnit>, WorkspaceError> {
self.reload_graph(path, source, |_requested: &str| Ok(None))
}
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 })
}
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))
}
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)
}
pub fn unload_module(&mut self, module: &str) -> Result<(), WorkspaceError> {
self.workspace.unload_module(module)
}
#[doc(hidden)]
pub fn workspace(&self) -> &ScriptWorkspace {
&self.workspace
}
#[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(¤t_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);
}
}