use crate::function::IntoHostFunction;
use crate::{
Error, GuestSurface, HostSchema, OpCapability, Profile, Result, Rustia, Settings, VmError,
VmErrorKind,
};
use rustia_compiler::{compile_with_options, CompileOptions};
use rustia_vm::{
ClockProvider, EntropyProvider, HostFunctionOp, ModuleResolver, Program, ResolvedModule,
StdoutSink, VmSettings,
};
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use std::time::{Instant, SystemTime, UNIX_EPOCH};
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn web_console_log(text: &str);
}
pub struct RustiaBuilder {
profile: Profile,
settings: VmSettings,
extensions: Vec<RustiaExtension>,
live_requested: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RustiaExecutionProfile {
profile: Profile,
guest_surface: GuestSurface,
}
impl RustiaExecutionProfile {
pub const DETERMINISTIC_STANDARD: Self =
Self::new(Profile::DeterministicSim, GuestSurface::Standard);
pub const DETERMINISTIC_HARDENED_LEAF: Self =
Self::new(Profile::DeterministicSim, GuestSurface::HardenedLeaf);
pub(crate) const fn new(profile: Profile, guest_surface: GuestSurface) -> Self {
Self {
profile,
guest_surface,
}
}
pub(crate) const fn from_vm(
profile: rustia_vm::Profile,
guest_surface: rustia_vm::GuestSurface,
) -> Self {
Self::new(
Profile::from_core(profile),
GuestSurface::from_core(guest_surface),
)
}
pub fn builder(self) -> RustiaBuilder {
RustiaBuilder::from_execution_profile(self)
}
pub const fn compatibility_id(self) -> u32 {
match (self.profile, self.guest_surface) {
(Profile::DeterministicSim, GuestSurface::HardenedLeaf) => 1,
(Profile::LuauCompat, GuestSurface::Standard) => 2,
(Profile::ReproducibleStandard, GuestSurface::Standard) => 3,
(Profile::DeterministicSim, GuestSurface::Standard) => 4,
(Profile::LuauCompat, GuestSurface::HardenedLeaf) => 5,
(Profile::ReproducibleStandard, GuestSurface::HardenedLeaf) => 6,
(Profile::Puc51Compat, GuestSurface::Standard) => 7,
(Profile::Puc51Compat, GuestSurface::HardenedLeaf) => 8,
}
}
pub const fn identity_bytes(self) -> [u8; 12] {
let encoding = 1u32.to_le_bytes();
let profile = match self.profile {
Profile::LuauCompat => 1u32,
Profile::ReproducibleStandard => 2,
Profile::DeterministicSim => 3,
Profile::Puc51Compat => 4,
}
.to_le_bytes();
let surface = match self.guest_surface {
GuestSurface::Standard => 1u32,
GuestSurface::HardenedLeaf => 2,
}
.to_le_bytes();
[
encoding[0],
encoding[1],
encoding[2],
encoding[3],
profile[0],
profile[1],
profile[2],
profile[3],
surface[0],
surface[1],
surface[2],
surface[3],
]
}
}
impl RustiaBuilder {
pub(crate) fn new() -> Self {
Self {
profile: Profile::ReproducibleStandard,
settings: VmSettings::default(),
extensions: Vec::new(),
live_requested: false,
}
}
fn from_execution_profile(execution_profile: RustiaExecutionProfile) -> Self {
let mut builder = Self::new();
builder.profile = execution_profile.profile;
builder.settings.guest_surface = execution_profile.guest_surface.to_core();
builder
}
pub const fn execution_profile(&self) -> RustiaExecutionProfile {
RustiaExecutionProfile::new(
self.profile,
GuestSurface::from_core(self.settings.guest_surface),
)
}
pub fn settings(&self) -> Settings {
Settings::from_core(self.profile, &self.settings)
}
#[cfg(test)]
pub(crate) const fn vm_settings(&self) -> &VmSettings {
&self.settings
}
pub fn standard() -> Self {
let builder = Self::new();
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
let builder = builder.stdout(|text| print!("{text}"));
builder
}
pub fn deterministic() -> Self {
RustiaExecutionProfile::DETERMINISTIC_STANDARD.builder()
}
pub fn deterministic_leaf() -> Self {
RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF.builder()
}
pub fn live() -> Self {
let builder = Self::standard();
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
let builder = builder
.wall_clock(ServiceClock::system())
.monotonic_clock(ServiceClock::monotonic())
.entropy(ServiceEntropy::system());
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
let builder = builder
.stdout(web_console_log)
.wall_clock(ServiceClock::system())
.monotonic_clock(ServiceClock::monotonic())
.entropy(ServiceEntropy::system());
let mut builder = builder;
builder.live_requested = true;
builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
builder
}
pub fn puc51_compat() -> Self {
let mut builder = Self::standard().profile(Profile::Puc51Compat);
builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
builder
}
pub fn profile(mut self, profile: Profile) -> Self {
self.profile = profile;
self
}
#[cfg(test)]
pub(crate) fn raw_settings(mut self, settings: VmSettings) -> Self {
self.settings = settings;
self
}
pub fn diagnostic_limits(mut self, limits: crate::DiagnosticLimits) -> Self {
self.settings.diagnostic_limits = limits.to_core();
self
}
pub fn fuel(mut self, fuel: u64) -> Self {
self.settings.initial_fuel = Some(fuel);
self
}
pub fn recursion_limit(mut self, limit: usize) -> Self {
self.settings.recursion_limit = limit.min(rustia_vm::MAX_RECURSION_LIMIT);
self
}
pub fn memory_limit_bytes(mut self, bytes: usize) -> Self {
self.settings.memory_limit_bytes = Some(bytes);
self
}
pub fn memory_tracking(mut self, enabled: bool) -> Self {
self.settings.enable_memory_tracking = enabled;
self
}
pub fn extension(mut self, extension: RustiaExtension) -> Self {
self.extensions.push(extension);
self
}
#[cfg(not(feature = "send"))]
pub fn stdout(mut self, sink: impl FnMut(&str) + 'static) -> Self {
self.settings.services.stdout = Some(StdoutSink::new(sink));
self
}
#[cfg(feature = "send")]
pub fn stdout(mut self, sink: impl FnMut(&str) + Send + 'static) -> Self {
self.settings.services.stdout = Some(StdoutSink::new(sink));
self
}
pub fn without_stdout(mut self) -> Self {
self.settings.services.stdout = None;
self
}
pub fn module_resolver(mut self, resolver: ServiceModuleResolver) -> Self {
self.settings.module_resolver = Some(resolver.into_provider());
self
}
pub fn wall_clock(mut self, clock: ServiceClock) -> Self {
self.settings.services.wall_clock = Some(clock.into_provider());
self
}
pub fn monotonic_clock(mut self, clock: ServiceClock) -> Self {
self.settings.services.monotonic_clock = Some(clock.into_provider());
self
}
pub fn entropy(mut self, entropy: ServiceEntropy) -> Self {
self.settings.services.entropy = Some(entropy.into_provider());
self
}
pub fn build(self) -> Result<Rustia> {
self.validate()?;
if self.settings.guest_surface.is_hardened_leaf() {
return Err(Error::from(VmError::new(
VmErrorKind::HardenedLeafViolation {
feature: "context-free facade",
},
)));
}
let mut rustia = Rustia::from_settings(self.profile, self.settings);
for extension in self.extensions {
rustia.install_extension(extension)?;
}
Ok(rustia)
}
pub fn build_for_host<H>(self) -> Result<Rustia<H>>
where
H: HostSchema,
{
self.validate()?;
if !self.extensions.is_empty() {
return Err(Error::embed(
"legacy RustiaExtension values cannot be installed into a typed VM; \
use HostModule instead"
.to_owned(),
));
}
Ok(Rustia::<H>::from_settings(self.profile, self.settings))
}
fn validate(&self) -> Result<()> {
if self.live_requested
&& (self.settings.services.wall_clock.is_none()
|| self.settings.services.monotonic_clock.is_none()
|| self.settings.services.entropy.is_none())
{
return Err(Error::from(VmError::new(VmErrorKind::Unsupported {
feature: "live() without a complete platform adapter (plug \
.wall_clock/.monotonic_clock/.entropy providers, or enable the \
default platform-adapters feature for browser/JavaScript wasm hosts)",
})));
}
if self.profile.is_deterministic_sim() {
for (feature, clock) in [
(
"non-deterministic wall clock provider",
&self.settings.services.wall_clock,
),
(
"non-deterministic monotonic clock provider",
&self.settings.services.monotonic_clock,
),
] {
if clock.as_ref().is_some_and(|clock| !clock.deterministic()) {
return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
feature,
operation: None,
profile: self.profile,
})));
}
}
if self
.settings
.services
.entropy
.as_ref()
.is_some_and(|entropy| !entropy.deterministic())
{
return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
feature: "non-deterministic entropy provider",
operation: None,
profile: self.profile,
})));
}
if self
.settings
.module_resolver
.as_ref()
.is_some_and(|resolver| !resolver.deterministic())
{
return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
feature: "non-deterministic module resolver",
operation: Some("require".to_owned()),
profile: self.profile,
})));
}
}
if self.settings.guest_surface.is_hardened_leaf() {
if !self.profile.is_deterministic_sim() {
return Err(Error::from(VmError::new(
VmErrorKind::HardenedLeafViolation {
feature: "non-DeterministicSim profile",
},
)));
}
if self.settings.memory_limit_bytes.is_none() {
return Err(Error::from(VmError::new(
VmErrorKind::HardenedLeafViolation {
feature: "missing logical-live memory limit",
},
)));
}
if self.settings.services.stdout.is_some()
|| self.settings.services.wall_clock.is_some()
|| self.settings.services.monotonic_clock.is_some()
|| self.settings.services.entropy.is_some()
{
return Err(Error::from(VmError::new(
VmErrorKind::HardenedLeafViolation {
feature: "host output, clock, or entropy services",
},
)));
}
if self.settings.loadstring_compiler.is_some()
|| self.settings.module_resolver.is_some()
|| self.settings.enable_conformance_coverage
|| self.settings.enable_opcode_census
|| self.settings.enable_conformance_top_level_yield
|| self.settings.enable_conformance_int64_userdata
|| self.settings.enable_conformance_native_userdata
|| self.settings.enable_conformance_native_type_checks
|| self.settings.enable_conformance_pcall_helpers
{
return Err(Error::from(VmError::new(
VmErrorKind::HardenedLeafViolation {
feature: "dynamic-code or conformance-only facilities",
},
)));
}
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ModuleSource {
identity: String,
source_name: String,
source: Vec<u8>,
}
impl ModuleSource {
pub fn new(identity: impl Into<String>, source: impl AsRef<[u8]>) -> Self {
let identity = identity.into();
Self {
source_name: identity.clone(),
identity,
source: source.as_ref().to_vec(),
}
}
pub fn with_source_name(
identity: impl Into<String>,
source_name: impl Into<String>,
source: impl AsRef<[u8]>,
) -> Self {
Self {
identity: identity.into(),
source_name: source_name.into(),
source: source.as_ref().to_vec(),
}
}
pub fn identity(&self) -> &str {
&self.identity
}
pub fn source_name(&self) -> &str {
&self.source_name
}
pub fn source(&self) -> &[u8] {
&self.source
}
}
#[derive(Clone, Debug)]
pub struct ServiceModuleResolver {
provider: ModuleResolver,
}
impl ServiceModuleResolver {
#[cfg(not(feature = "send"))]
pub fn from_fn(
resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
) -> Self {
Self::from_fn_with_determinism(resolver, true)
}
#[cfg(feature = "send")]
pub fn from_fn(
resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
) -> Self {
Self::from_fn_with_determinism(resolver, true)
}
#[cfg(not(feature = "send"))]
pub fn from_nondeterministic_fn(
resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
) -> Self {
Self::from_fn_with_determinism(resolver, false)
}
#[cfg(feature = "send")]
pub fn from_nondeterministic_fn(
resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
) -> Self {
Self::from_fn_with_determinism(resolver, false)
}
#[cfg(not(feature = "send"))]
fn from_fn_with_determinism(
mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
deterministic: bool,
) -> Self {
let provider = ModuleResolver::new_with_profile(
move |requested, referrer, profile| {
let module =
resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
compile_module_source(module, profile)
},
deterministic,
);
Self { provider }
}
#[cfg(feature = "send")]
fn from_fn_with_determinism(
mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
deterministic: bool,
) -> Self {
let provider = ModuleResolver::new_with_profile(
move |requested, referrer, profile| {
let module =
resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
compile_module_source(module, profile)
},
deterministic,
);
Self { provider }
}
fn into_provider(self) -> ModuleResolver {
self.provider
}
}
fn compile_module_source(
module: ModuleSource,
profile: rustia_vm::Profile,
) -> rustia_vm::Result<ResolvedModule> {
if module.identity.is_empty() {
return Err(crate::value::embed_to_vm_error(Error::embed(
"module identity must not be empty",
)));
}
let chunk = rustia_parser::parse_source_bytes(&module.source).map_err(|error| {
module_compile_error(
Error::from_engine(error),
&module.source_name,
&module.source,
)
})?;
let options = CompileOptions {
puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
..CompileOptions::default()
}
.with_source_bytes(module.source_name.clone(), &module.source);
let mut program = compile_with_options(&chunk, options).map_err(|error| {
module_compile_error(
Error::from_engine(error),
&module.source_name,
&module.source,
)
})?;
program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
&module.source,
crate::DiagnosticLimits::default().source_bytes,
);
Ok(ResolvedModule::new(module.identity, program))
}
fn module_compile_error(error: Error, name: &str, source: &[u8]) -> rustia_vm::Error {
let message = format!("{name}:1: {error}");
let mut error = error.with_source(name, source, crate::DiagnosticLimits::default());
let mut diagnostic = error.diagnostic.take();
let mut error = crate::value::embed_to_vm_error(error);
if let Some(diagnostic) = &mut diagnostic {
std::sync::Arc::make_mut(diagnostic).host_cause = error
.diagnostic
.as_ref()
.and_then(|diagnostic| diagnostic.host_cause.clone());
}
error.diagnostic = diagnostic.map(|diagnostic| std::sync::Arc::new(diagnostic.to_core()));
if let rustia_vm::ErrorKind::RuntimeError { message: raw } = &mut error.kind {
*raw = message;
}
error
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ServiceClock {
provider: ClockProvider,
}
impl ServiceClock {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn system() -> Self {
let epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |duration| duration.as_secs_f64());
let start = Instant::now();
Self {
provider: ClockProvider::new(move || epoch + start.elapsed().as_secs_f64(), false),
}
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn monotonic() -> Self {
let start = Instant::now();
Self {
provider: ClockProvider::new(move || start.elapsed().as_secs_f64(), false),
}
}
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
pub fn system() -> Self {
Self {
provider: ClockProvider::new(|| js_sys::Date::now() / 1_000.0, false),
}
}
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
pub fn monotonic() -> Self {
Self {
provider: ClockProvider::new(web_monotonic_seconds, false),
}
}
pub fn fixed(t: f64) -> Self {
Self {
provider: ClockProvider::new(move || t, true),
}
}
#[cfg(not(feature = "send"))]
pub fn from_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
Self {
provider: ClockProvider::new(clock, true),
}
}
#[cfg(feature = "send")]
pub fn from_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
Self {
provider: ClockProvider::new(clock, true),
}
}
#[cfg(not(feature = "send"))]
pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
Self {
provider: ClockProvider::new(clock, false),
}
}
#[cfg(feature = "send")]
pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
Self {
provider: ClockProvider::new(clock, false),
}
}
pub(crate) fn into_provider(self) -> ClockProvider {
self.provider
}
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct ServiceEntropy {
provider: EntropyProvider,
}
impl ServiceEntropy {
#[cfg(any(
not(all(target_arch = "wasm32", target_os = "unknown")),
all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
)
))]
pub fn system() -> Self {
let fallback_counter = std::sync::atomic::AtomicU64::new(0);
Self {
provider: EntropyProvider::new(
move || {
system_entropy().unwrap_or_else(|| {
let counter = fallback_counter
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
.wrapping_add(1);
fallback_entropy(counter)
})
},
false,
),
}
}
pub fn fixed(seed: u64) -> Self {
Self {
provider: EntropyProvider::new(move || seed, true),
}
}
#[cfg(not(feature = "send"))]
pub fn from_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
Self {
provider: EntropyProvider::new(entropy, true),
}
}
#[cfg(feature = "send")]
pub fn from_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
Self {
provider: EntropyProvider::new(entropy, true),
}
}
#[cfg(not(feature = "send"))]
pub fn from_nondeterministic_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
Self {
provider: EntropyProvider::new(entropy, false),
}
}
#[cfg(feature = "send")]
pub fn from_nondeterministic_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
Self {
provider: EntropyProvider::new(entropy, false),
}
}
pub(crate) fn into_provider(self) -> EntropyProvider {
self.provider
}
}
#[cfg(feature = "platform-adapters")]
fn system_entropy() -> Option<u64> {
getrandom::u64().ok()
}
#[cfg(all(
not(feature = "platform-adapters"),
not(all(target_arch = "wasm32", target_os = "unknown"))
))]
fn system_entropy() -> Option<u64> {
None
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn fallback_entropy(counter: u64) -> u64 {
let wall = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0_u128, |duration| duration.as_nanos());
(wall as u64) ^ ((wall >> 64) as u64) ^ counter.rotate_left(29)
}
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
fn fallback_entropy(counter: u64) -> u64 {
js_sys::Date::now().to_bits() ^ web_monotonic_seconds().to_bits() ^ counter.rotate_left(29)
}
#[cfg(all(
target_arch = "wasm32",
target_os = "unknown",
feature = "platform-adapters"
))]
fn web_monotonic_seconds() -> f64 {
let global = js_sys::global();
let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance"));
let Ok(performance) = performance else {
return js_sys::Date::now() / 1_000.0;
};
let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now"))
.ok()
.and_then(|value| value.dyn_into::<js_sys::Function>().ok())
.and_then(|now| now.call0(&performance).ok())
.and_then(|value| value.as_f64());
now.unwrap_or_else(js_sys::Date::now) / 1_000.0
}
fn stock_loadstring_compiler(
source: &[u8],
source_name: Option<&[u8]>,
profile: rustia_vm::Profile,
) -> std::result::Result<Program, String> {
let source_name = source_name.map_or_else(
|| loadstring_chunk_name(source),
|name| String::from_utf8_lossy(name).into_owned(),
);
let chunk = rustia_parser::parse_source_bytes(source)
.map_err(|error| format!("{source_name}:1: {error}"))?;
let options = CompileOptions {
puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
..CompileOptions::default()
}
.with_source_bytes(source_name.clone(), source);
let mut program = compile_with_options(&chunk, options)
.map_err(|error| format!("{source_name}:1: {error}"))?;
program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
source,
crate::DiagnosticLimits::default().source_bytes,
);
Ok(program)
}
fn loadstring_chunk_name(source: &[u8]) -> String {
let mut preview = String::new();
for byte in source.iter().copied().take(60) {
match byte {
b'\\' => preview.push_str("\\\\"),
b'"' => preview.push_str("\\\""),
b'\n' => break,
0x20..=0x7e => preview.push(byte as char),
_ => preview.push('?'),
}
}
if source.len() > 60 {
preview.push_str("...");
}
format!("[string \"{preview}\"]")
}
#[derive(Clone, Debug)]
pub struct RustiaExtension {
namespace: Option<String>,
functions: Vec<HostFunctionOp>,
}
pub const RUSTIA_HOST_FUEL_ABI_VERSION: u32 = 1;
pub const RUSTIA_DEFAULT_HOST_FUNCTION_FUEL: u32 = 1;
pub const RUSTIA_MIN_HOST_FUNCTION_FUEL: u32 = 1;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RustiaHostFuelPolicy {
pub abi_version: u32,
pub default_function_fuel: u32,
pub minimum_function_fuel: u32,
}
pub const RUSTIA_HOST_FUEL_POLICY: RustiaHostFuelPolicy = RustiaHostFuelPolicy {
abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
default_function_fuel: RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
minimum_function_fuel: RUSTIA_MIN_HOST_FUNCTION_FUEL,
};
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RustiaHostFunctionInfo<'a> {
pub name: &'a str,
pub fuel_abi_version: u32,
pub fuel_cost: u32,
pub capability: OpCapability,
pub parameter_count: u8,
pub parameter_types: &'a [&'static str],
pub return_types: &'a [&'static str],
pub fallible: bool,
}
impl RustiaExtension {
pub fn new(namespace: impl Into<String>) -> Self {
let namespace = namespace.into();
Self {
namespace: (!namespace.is_empty()).then_some(namespace),
functions: Vec::new(),
}
}
pub fn global() -> Self {
Self {
namespace: None,
functions: Vec::new(),
}
}
pub fn namespace(&self) -> Option<&str> {
self.namespace.as_deref()
}
pub fn fuel_policy(&self) -> RustiaHostFuelPolicy {
RUSTIA_HOST_FUEL_POLICY
}
pub fn functions(&self) -> impl Iterator<Item = RustiaHostFunctionInfo<'_>> + '_ {
self.functions
.iter()
.map(|function| RustiaHostFunctionInfo {
name: &function.name,
fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
fuel_cost: function.fuel_cost,
capability: OpCapability::from_core(function.capability),
parameter_count: function.parameter_count,
parameter_types: &function.parameter_types,
return_types: &function.return_types,
fallible: function.fallible,
})
}
pub fn fn_pure<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::Pure,
function,
)
}
pub fn fn_input<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::ReadsDeterministicInput,
function,
)
}
pub fn fn_slot_read<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::ReadsSlotState,
function,
)
}
pub fn fn_slot_write<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::WritesSlotEffect,
function,
)
}
pub fn fn_effect<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::EmitsDeterministicEffect,
function,
)
}
pub fn fn_external_state<Func, Args, Return>(
self,
name: impl Into<String>,
function: Func,
) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::ReadsExternalMutableState,
function,
)
}
pub fn fn_nondeterministic<Func, Args, Return>(
self,
name: impl Into<String>,
function: Func,
) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.fn_with(
name,
RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
OpCapability::NondeterministicEffect,
function,
)
}
pub fn fn_with<Func, Args, Return>(
mut self,
name: impl Into<String>,
fuel_cost: u32,
capability: OpCapability,
function: Func,
) -> Self
where
Func: IntoHostFunction<Args, Return>,
{
self.functions.push(
crate::HostFunction::<()>::with_capability(capability, function)
.fuel_cost(fuel_cost)
.into_op(name.into()),
);
self
}
pub(crate) fn install(self, rustia: &mut Rustia) -> Result<()> {
let Some(namespace) = self.namespace else {
return rustia
.vm_mut()
.install_host_functions(self.functions)
.map_err(Error::from_engine);
};
rustia
.vm_mut()
.install_host_module(namespace, self.functions)
.map_err(Error::from_engine)
}
}