use crate::heap::Heap;
use crate::id::WaitKey;
use crate::value::Value;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct EffectId {
pub domain: u64,
pub sequence: u64,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct EffectRecord {
pub id: EffectId,
pub arg: i64,
pub outcome: i64,
pub bytes: Option<Vec<u8>>,
pub request: Option<Vec<u8>>,
pub module: Option<Vec<u8>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JournalError;
impl std::fmt::Display for JournalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("journal payload mismatch")
}
}
impl std::error::Error for JournalError {}
mod journal_payload {
pub trait Sealed {}
impl Sealed for i64 {}
impl Sealed for Vec<u8> {}
}
pub trait JournalPayload: journal_payload::Sealed + Sized {
#[doc(hidden)]
fn record(self, id: EffectId, arg: i64) -> EffectRecord;
#[doc(hidden)]
fn replay(record: &EffectRecord) -> Result<Self, JournalError>;
}
impl JournalPayload for i64 {
fn record(self, id: EffectId, arg: i64) -> EffectRecord {
EffectRecord {
id,
arg,
outcome: self,
bytes: None,
module: None,
request: None,
}
}
fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
if record.bytes.is_none() {
Ok(record.outcome)
} else {
Err(JournalError)
}
}
}
impl JournalPayload for Vec<u8> {
fn record(self, id: EffectId, arg: i64) -> EffectRecord {
EffectRecord {
id,
arg,
outcome: 0,
bytes: Some(self),
module: None,
request: None,
}
}
fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
record.bytes.clone().ok_or(JournalError)
}
}
#[derive(Clone, Debug, Default)]
pub struct Journal {
entries: Vec<EffectRecord>,
index: std::collections::HashMap<EffectId, usize>,
}
impl PartialEq for Journal {
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
}
}
impl Eq for Journal {}
impl Journal {
pub fn new() -> Self {
Self::default()
}
pub fn entries(&self) -> &[EffectRecord] {
&self.entries
}
pub fn commit<P: JournalPayload>(
&mut self,
id: EffectId,
arg: i64,
fresh: impl FnOnce() -> P,
) -> Result<P, JournalError> {
if let Some(&position) = self.index.get(&id) {
if self.entries[position].request.is_some() {
return Err(JournalError);
}
return P::replay(&self.entries[position]);
}
let record = fresh().record(id, arg);
let outcome = P::replay(&record);
self.index.insert(id, self.entries.len());
self.entries.push(record);
outcome
}
pub fn seed(&mut self, id: EffectId, arg: i64, outcome: i64) {
let _ = self.seed_record(outcome.record(id, arg));
}
pub fn seed_record(&mut self, record: EffectRecord) -> Result<(), JournalError> {
if record.bytes.is_some() && record.outcome != 0
|| record.module.is_some() && record.bytes.is_none()
|| record.module.is_some() && record.request.is_some()
{
return Err(JournalError);
}
if !self.index.contains_key(&record.id) {
self.index.insert(record.id, self.entries.len());
self.entries.push(record);
}
Ok(())
}
pub fn replay_request<P: JournalPayload>(
&self,
id: EffectId,
arg: i64,
request: &[u8],
) -> Result<Option<P>, JournalError> {
let Some(&position) = self.index.get(&id) else {
return Ok(None);
};
let record = &self.entries[position];
if record.arg != arg
|| record.module.is_some()
|| record.request.as_deref() != Some(request)
{
return Err(JournalError);
}
P::replay(record).map(Some)
}
pub fn commit_request<P: JournalPayload>(
&mut self,
id: EffectId,
arg: i64,
request: &[u8],
fresh: impl FnOnce() -> P,
) -> Result<P, JournalError> {
if let Some(outcome) = self.replay_request(id, arg, request)? {
return Ok(outcome);
}
let mut record = fresh().record(id, arg);
record.request = Some(request.to_vec());
let outcome = P::replay(&record);
self.index.insert(id, self.entries.len());
self.entries.push(record);
outcome
}
pub(crate) fn module_result(&self, domain: u64, name: &[u8]) -> Option<(EffectId, &[u8])> {
self.entries.iter().find_map(|record| {
(record.id.domain == domain && record.module.as_deref() == Some(name))
.then(|| record.bytes.as_deref().map(|bytes| (record.id, bytes)))?
})
}
pub(crate) fn commit_module(
&mut self,
id: EffectId,
name: &[u8],
fresh: impl FnOnce() -> Vec<u8>,
) -> Result<Vec<u8>, JournalError> {
if let Some(&position) = self.index.get(&id)
&& (self.entries[position].module.as_deref() != Some(name)
|| self.entries[position].request.is_some())
{
return Err(JournalError);
}
let outcome = self.commit(id, 0, fresh)?;
let position = self.index[&id];
let record = &mut self.entries[position];
record.module = Some(name.to_vec());
Ok(outcome)
}
}
pub struct HostCtx<'a> {
pub journal: &'a mut Journal,
pub effect: EffectId,
}
pub enum HostResult {
Ready(i64),
Pending(WaitKey),
Fault,
}
#[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
pub type HostFn = fn(&mut HostCtx<'_>, i64) -> HostResult;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NativePolicy {
VmLocal,
External,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NativeOutcome {
Ready,
Pending(WaitKey),
Fault,
}
pub type NativeFn = fn(&mut NativeCall<'_>) -> NativeOutcome;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum LuaType {
Nil,
Boolean,
Number,
String,
Table,
Function,
Thread,
Userdata,
}
#[derive(Clone, Copy)]
pub struct NativeValue<'a> {
pub(crate) value: Value,
_call: std::marker::PhantomData<&'a ()>,
}
impl std::fmt::Debug for NativeValue<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let ty = match self.value {
Value::Nil => LuaType::Nil,
Value::Bool(_) => LuaType::Boolean,
Value::Integer(_) | Value::Float(_) => LuaType::Number,
Value::String(_) => LuaType::String,
Value::Table(_) => LuaType::Table,
Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
Value::Thread(_) => LuaType::Thread,
Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
};
f.debug_tuple("NativeValue").field(&ty).finish()
}
}
impl NativeValue<'_> {
pub(crate) fn wrap(value: Value) -> Self {
Self {
value,
_call: std::marker::PhantomData,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RawSetError {
NotATable,
InvalidKey,
Memory,
}
#[derive(Clone, Debug, PartialEq)]
#[deprecated(note = "use Value and IntoLua/FromLua with rooted object values")]
pub enum HostValue {
Nil,
Boolean(bool),
Integer(i64),
Number(f64),
String(Vec<u8>),
Object(crate::id::ObjectId),
Native(String),
LightUserdata(crate::userdata::LightUserdata),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum UserdataError {
NotUserdata,
Unregistered,
Memory,
}
#[derive(Clone, Debug, PartialEq)]
#[deprecated(note = "use Completion with rooted Value objects")]
pub enum LegacyCompletion {
Return(Vec<HostValue>),
Error(HostValue),
}
#[deprecated(note = "use NativeContext with HostRegistry::function or typed")]
pub type NativeCall<'a> = LegacyNativeCall<'a>;
pub(crate) enum NativeError {
Argument(usize, Vec<u8>),
Message(Vec<u8>, bool),
}
#[doc(hidden)]
pub struct LegacyNativeCall<'a> {
pub(crate) heap: &'a mut Heap,
pub(crate) args: &'a [Value],
pub(crate) results: &'a mut Vec<Value>,
pub(crate) effect: Option<EffectId>,
pub(crate) journal: Option<&'a mut Journal>,
pub(crate) out_of_memory: bool,
pub(crate) registry: &'a HostRegistry,
pub(crate) max_objects: u32,
pub(crate) error: Option<NativeError>,
}
impl<'a> LegacyNativeCall<'a> {
pub fn arg_count(&self) -> usize {
self.args.len()
}
pub fn arg(&self, index: usize) -> NativeValue<'a> {
NativeValue::wrap(self.args.get(index).copied().unwrap_or(Value::Nil))
}
pub fn type_of(&self, value: NativeValue<'a>) -> LuaType {
match value.value {
Value::Nil => LuaType::Nil,
Value::Bool(_) => LuaType::Boolean,
Value::Integer(_) | Value::Float(_) => LuaType::Number,
Value::String(_) => LuaType::String,
Value::Table(_) => LuaType::Table,
Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
Value::Thread(_) => LuaType::Thread,
Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
}
}
pub fn string_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
match value.value {
Value::String(handle) => self.heap.string_bytes(handle),
_ => None,
}
}
pub fn raw_get(&self, table: NativeValue<'a>, key: NativeValue<'a>) -> Option<NativeValue<'a>> {
let Value::Table(handle) = table.value else {
return None;
};
let value = match self.heap.key_view(key.value) {
Ok(key) => self.heap.table_get_view(handle, key)?,
Err(_) => Value::Nil,
};
Some(NativeValue::wrap(value))
}
pub fn raw_set(
&mut self,
table: NativeValue<'a>,
key: NativeValue<'a>,
value: NativeValue<'a>,
) -> Result<(), RawSetError> {
let Value::Table(handle) = table.value else {
return Err(RawSetError::NotATable);
};
if self.heap.update_string_key(handle, key.value, value.value) {
return Ok(());
}
let normalized = self
.heap
.normalize_value(key.value)
.map_err(|_| RawSetError::InvalidKey)?;
match self
.heap
.table_insert(handle, normalized, key.value, value.value)
{
Ok(()) => Ok(()),
Err(crate::heap::InsertError::NoTable) => Err(RawSetError::NotATable),
Err(crate::heap::InsertError::Memory) => {
self.out_of_memory = true;
Err(RawSetError::Memory)
}
}
}
pub fn raw_equal(&self, a: NativeValue<'a>, b: NativeValue<'a>) -> bool {
crate::compare::equal(self.heap, a.value, b.value)
}
pub fn raw_len(&self, value: NativeValue<'a>) -> Option<i64> {
match value.value {
Value::String(handle) => i64::try_from(self.heap.string_bytes(handle)?.len()).ok(),
Value::Table(handle) => Some(self.heap.tables.get(handle)?.table.raw_border()),
_ => None,
}
}
pub fn metatable(&self, value: NativeValue<'a>) -> Option<NativeValue<'a>> {
let metatable = self.heap.metatable_of(value.value)?;
Some(NativeValue::wrap(Value::Table(metatable)))
}
pub fn set_metatable(
&mut self,
object: NativeValue<'a>,
metatable: Option<NativeValue<'a>>,
) -> bool {
let metatable = match metatable.map(|value| value.value) {
None => None,
Some(Value::Table(metatable)) => Some(metatable),
Some(_) => return false,
};
self.heap.set_metatable(object.value, metatable)
}
pub fn new_userdata(
&mut self,
len: usize,
user_values: usize,
) -> Result<NativeValue<'a>, UserdataError> {
if len > crate::userdata::MAX_USERDATA_BYTES {
self.out_of_memory = true;
return Err(UserdataError::Memory);
}
let made = self
.heap
.alloc_userdata(self.max_objects, user_values, len as u64, || {
crate::userdata::Payload::Bytes(vec![0; len].into_boxed_slice())
});
self.made(made)
}
pub fn new_host_userdata<T: crate::userdata::HostUserdata>(
&mut self,
value: T,
user_values: usize,
) -> Result<NativeValue<'a>, UserdataError> {
if !self.registry.has_userdata_type::<T>() {
return Err(UserdataError::Unregistered);
}
let charge = value.logical_size();
let made = self
.heap
.alloc_userdata(self.max_objects, user_values, charge, || {
crate::userdata::Payload::Host {
symbol: T::SYMBOL,
value: Box::new(value),
}
});
self.made(made)
}
fn made(
&mut self,
made: Result<crate::id::Handle<crate::heap::UserdataObj>, crate::id::TerminationReason>,
) -> Result<NativeValue<'a>, UserdataError> {
match made {
Ok(handle) => Ok(NativeValue::wrap(Value::Userdata(handle))),
Err(_) => {
self.out_of_memory = true;
Err(UserdataError::Memory)
}
}
}
pub fn light_userdata(&self, key: crate::userdata::HostLightKey) -> NativeValue<'a> {
NativeValue::wrap(Value::LightUserdata(crate::value::LightDomain::Host, key.0))
}
pub fn light(&self, value: NativeValue<'a>) -> Option<crate::userdata::LightUserdata> {
match value.value {
Value::LightUserdata(domain, bits) => {
Some(crate::userdata::LightUserdata { domain, bits })
}
_ => None,
}
}
pub fn is_full_userdata(&self, value: NativeValue<'a>) -> bool {
matches!(value.value, Value::Userdata(_))
}
fn userdata_object(&self, value: NativeValue<'a>) -> Option<&crate::heap::UserdataObj> {
match value.value {
Value::Userdata(handle) => self.heap.userdata.get(handle),
_ => None,
}
}
fn userdata_object_mut(
&mut self,
value: NativeValue<'a>,
) -> Option<&mut crate::heap::UserdataObj> {
match value.value {
Value::Userdata(handle) => self.heap.userdata.get_mut(handle),
_ => None,
}
}
pub fn userdata_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
self.userdata_object(value)?.payload.bytes()
}
pub fn userdata_bytes_mut(&mut self, value: NativeValue<'a>) -> Option<&mut [u8]> {
self.userdata_object_mut(value)?.payload.bytes_mut()
}
pub fn userdata_ref<T: crate::userdata::HostUserdata>(
&self,
value: NativeValue<'a>,
) -> Option<&T> {
self.userdata_object(value)?.payload.host::<T>()
}
pub fn userdata_mut<T: crate::userdata::HostUserdata>(
&mut self,
value: NativeValue<'a>,
) -> Option<&mut T> {
self.userdata_object_mut(value)?.payload.host_mut::<T>()
}
pub fn user_value(&self, value: NativeValue<'a>, n: usize) -> Option<NativeValue<'a>> {
let object = self.userdata_object(value)?;
let held = *object.user_values.get(n.checked_sub(1)?)?;
Some(NativeValue::wrap(held))
}
pub fn set_user_value(
&mut self,
value: NativeValue<'a>,
n: usize,
held: NativeValue<'a>,
) -> bool {
let Some(slot) = n
.checked_sub(1)
.and_then(|index| self.userdata_object_mut(value)?.user_values.get_mut(index))
else {
return false;
};
*slot = held.value;
true
}
pub fn set_userdata_charge(
&mut self,
value: NativeValue<'a>,
bytes: u64,
) -> Result<(), UserdataError> {
let Value::Userdata(handle) = value.value else {
return Err(UserdataError::NotUserdata);
};
let object = self
.heap
.userdata
.get(handle)
.ok_or(UserdataError::NotUserdata)?;
if object.payload.symbol().is_none() {
return Err(UserdataError::NotUserdata);
}
let old = object.charge;
if bytes > old && !self.heap.gc.fits(bytes - old) {
self.out_of_memory = true;
return Err(UserdataError::Memory);
}
if bytes > old {
self.heap.gc.charge(bytes - old);
} else {
self.heap.give_back(old - bytes);
}
if let Some(object) = self.heap.userdata.get_mut(handle) {
object.charge = bytes;
}
Ok(())
}
pub fn arg_error(&mut self, index: usize, message: &str) -> NativeOutcome {
self.error = Some(NativeError::Argument(index, message.as_bytes().to_vec()));
NativeOutcome::Fault
}
pub fn error(&mut self, message: &str) -> NativeOutcome {
self.error = Some(NativeError::Message(message.as_bytes().to_vec(), true));
NativeOutcome::Fault
}
pub fn raw_error(&mut self, message: &str) -> NativeOutcome {
self.error = Some(NativeError::Message(message.as_bytes().to_vec(), false));
NativeOutcome::Fault
}
pub fn type_error(&mut self, index: usize, expected: &str) -> NativeOutcome {
let got: Vec<u8> = if index >= self.args.len() {
b"no value".to_vec()
} else {
let value = self.args[index];
match crate::index::metamethod(self.heap, value, b"__name") {
Some(Value::String(name)) => {
self.heap.string_bytes(name).unwrap_or_default().to_vec()
}
_ if matches!(value, Value::LightUserdata(..)) => b"light userdata".to_vec(),
_ => crate::heap::type_name(value).as_bytes().to_vec(),
}
};
let mut message = format!("{expected} expected, got ").into_bytes();
message.extend(got);
self.error = Some(NativeError::Argument(index, message));
NativeOutcome::Fault
}
pub fn push(&mut self, value: NativeValue<'a>) {
self.results.push(value.value);
}
pub fn integer(&self, index: usize) -> Option<i64> {
match self.args.get(index)? {
Value::Integer(integer) => Some(*integer),
_ => None,
}
}
pub fn number(&self, index: usize) -> Option<f64> {
match self.args.get(index)? {
Value::Integer(integer) => Some(*integer as f64),
Value::Float(float) => Some(*float),
_ => None,
}
}
pub fn boolean(&self, index: usize) -> Option<bool> {
match self.args.get(index)? {
Value::Bool(bit) => Some(*bit),
_ => None,
}
}
pub fn is_nil(&self, index: usize) -> bool {
matches!(self.args.get(index), None | Some(Value::Nil))
}
pub fn push_integer(&mut self, value: i64) {
self.results.push(Value::Integer(value));
}
pub fn push_number(&mut self, value: f64) {
self.results.push(Value::Float(value));
}
pub fn push_boolean(&mut self, value: bool) {
self.results.push(Value::Bool(value));
}
pub fn push_nil(&mut self) {
self.results.push(Value::Nil);
}
pub fn push_arg(&mut self, index: usize) {
self.results
.push(self.args.get(index).copied().unwrap_or(Value::Nil));
}
pub fn effect(&self) -> Option<EffectId> {
self.effect
}
pub fn journal(&mut self) -> Option<&mut Journal> {
self.journal.as_deref_mut()
}
}
#[derive(Clone)]
pub(crate) struct NativeEntry {
pub(crate) policy: NativePolicy,
pub(crate) function: NativeFn,
pub(crate) callback: Option<std::rc::Rc<crate::api::native::Callback>>,
pub(crate) typed: Option<std::rc::Rc<crate::api::native::TypedCallback>>,
pub(crate) builtin: Option<Builtin>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Builtin {
#[allow(dead_code)] Exit,
Os(crate::oslib::OsFn),
Io(crate::iolib::IoFn),
#[cfg(test)]
CapabilitySmoke,
Pcall,
Xpcall,
Error,
Assert,
Type,
ToString,
ToNumber,
Print,
Next,
Pairs,
Ipairs,
IpairsNext,
CollectGarbage,
Load,
LoadFile,
DoFile,
Math(crate::library::MathFn),
Table(crate::library::TableFn),
String(crate::strlib::StrFn),
Utf8(crate::utf8lib::Utf8Fn),
Package(crate::package::PkgFn),
Debug(crate::debuglib::DbgFn),
Coroutine(crate::corolib::CoFn),
Warn,
}
pub type Output = Box<dyn FnMut(&[u8])>;
pub type Warnings = Box<dyn FnMut(&[u8], bool)>;
pub type Entropy = Box<dyn FnMut() -> i64>;
fn builtin_placeholder(_call: &mut NativeCall<'_>) -> NativeOutcome {
NativeOutcome::Fault
}
type HookEntries = Vec<(String, std::rc::Rc<crate::api::hooks::HookCallback>)>;
#[derive(Clone)]
pub struct HostRegistry {
entries: Vec<(String, HostFn)>,
natives: Vec<(String, NativeEntry)>,
userdata_types: Vec<crate::userdata::HostType>,
hooks: Option<Box<HookEntries>>,
}
impl HostRegistry {
pub fn new() -> Self {
Self {
entries: Vec::new(),
natives: Vec::new(),
userdata_types: Vec::new(),
hooks: None,
}
}
pub fn register_hook<F>(&mut self, symbol: impl Into<String>, callback: F)
where
F: Fn(&mut crate::HookContext<'_>) -> crate::Result<crate::HookAction> + 'static,
{
let symbol = symbol.into();
let hooks = self.hooks.get_or_insert_with(Box::default);
let entry = (
symbol.clone(),
std::rc::Rc::new(callback) as std::rc::Rc<crate::api::hooks::HookCallback>,
);
if let Some(slot) = hooks.iter().position(|(name, _)| name == &symbol) {
hooks[slot] = entry;
} else {
hooks.push(entry);
}
}
pub(crate) fn hook_slot(&self, symbol: &str) -> Option<u32> {
self.hooks
.as_ref()?
.iter()
.position(|(name, _)| name == symbol)
.and_then(|i| i.try_into().ok())
}
pub(crate) fn hook(
&self,
slot: u32,
) -> Option<(&str, &std::rc::Rc<crate::api::hooks::HookCallback>)> {
self.hooks
.as_ref()?
.get(slot as usize)
.map(|(name, callback)| (name.as_str(), callback))
}
pub fn register_userdata<T: crate::userdata::HostUserdata>(&mut self) {
self.insert_userdata_type(crate::userdata::HostType::of::<T>());
}
pub fn register_portable_userdata<T: crate::userdata::PortableUserdata>(&mut self) {
self.insert_userdata_type(crate::userdata::HostType::portable::<T>());
}
pub fn register_rebind_userdata<T: crate::userdata::RebindUserdata>(&mut self) {
self.insert_userdata_type(crate::userdata::HostType::rebind::<T>());
}
pub fn userdata_policy(&self, symbol: &str) -> Option<crate::UserdataPolicy> {
self.userdata_type(symbol).map(|entry| entry.policy.kind())
}
fn insert_userdata_type(&mut self, entry: crate::userdata::HostType) {
self.userdata_types
.retain(|held| held.symbol != entry.symbol && held.type_id != entry.type_id);
self.userdata_types.push(entry);
}
pub(crate) fn has_userdata_type<T: 'static>(&self) -> bool {
let type_id = std::any::TypeId::of::<T>();
self.userdata_types
.iter()
.any(|entry| entry.type_id == type_id)
}
pub(crate) fn userdata_type(&self, symbol: &str) -> Option<crate::userdata::HostType> {
self.userdata_types
.iter()
.find(|entry| entry.symbol == symbol)
.copied()
}
pub fn register_native(
&mut self,
symbol: impl Into<String>,
policy: NativePolicy,
function: NativeFn,
) {
self.insert_native(
symbol.into(),
NativeEntry {
policy,
function,
callback: None,
typed: None,
builtin: None,
},
);
}
pub fn function<F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
where
F: Fn(&mut crate::NativeContext<'_>) -> crate::Result<crate::NativeReturn> + 'static,
{
self.insert_native(
symbol.into(),
NativeEntry {
policy,
function: builtin_placeholder,
callback: Some(std::rc::Rc::new(f)),
typed: None,
builtin: None,
},
);
}
pub fn typed<A, R, F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
where
A: crate::FromLuaMulti,
R: crate::IntoLuaMulti,
F: Fn(&mut crate::NativeContext<'_>, A) -> crate::Result<R> + 'static,
{
let fast: std::rc::Rc<crate::api::native::TypedCallback> = std::rc::Rc::new(move |cx| {
let args = cx
.arguments::<A>()
.map_err(|error| cx.argument_error(error))?;
let result = f(cx, args)?;
cx.write_results(result)
});
let callback = fast.clone();
self.insert_native(
symbol.into(),
NativeEntry {
policy,
function: builtin_placeholder,
builtin: None,
typed: Some(fast),
callback: Some(std::rc::Rc::new(move |cx| {
callback(cx)?;
Ok(crate::NativeReturn::Return(cx.take_results()?))
})),
},
);
}
pub(crate) fn register_builtin(&mut self, symbol: &str, builtin: Builtin) {
self.insert_native(
symbol.to_string(),
NativeEntry {
policy: NativePolicy::VmLocal,
function: builtin_placeholder,
callback: None,
typed: None,
builtin: Some(builtin),
},
);
}
fn insert_native(&mut self, symbol: String, entry: NativeEntry) {
if let Some(slot) = self.natives.iter().position(|(name, _)| name == &symbol) {
self.natives[slot] = (symbol, entry);
} else {
self.natives.push((symbol, entry));
}
}
pub(crate) fn fill_missing_natives(&mut self, source: &Self) {
for (symbol, entry) in &source.natives {
if self.native_slot(symbol).is_none() {
self.insert_native(symbol.clone(), entry.clone());
}
}
}
pub(crate) fn native_slot(&self, symbol: &str) -> Option<usize> {
self.natives.iter().position(|(name, _)| name == symbol)
}
pub(crate) fn native(&self, slot: usize) -> Option<&NativeEntry> {
self.natives.get(slot).map(|(_, entry)| entry)
}
#[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
pub(crate) fn register(&mut self, symbol: impl Into<String>, function: HostFn) {
let symbol = symbol.into();
if let Some(slot) = self.entries.iter().position(|(name, _)| name == &symbol) {
self.entries[slot] = (symbol, function);
} else {
self.entries.push((symbol, function));
}
}
#[doc(hidden)] pub fn proof() -> Self {
let mut registry = Self::new();
registry.register("mark", mark);
registry.register("park", park);
registry.register_native("add", NativePolicy::VmLocal, native_add);
registry.register_native("sub", NativePolicy::VmLocal, native_sub);
registry.register_native("many", NativePolicy::VmLocal, native_many);
registry.register_native("none", NativePolicy::VmLocal, native_none);
registry.register_native("mark", NativePolicy::External, native_mark);
registry.register_native("park", NativePolicy::VmLocal, native_park);
registry.register_native("second", NativePolicy::VmLocal, native_second);
registry.register_native("upto", NativePolicy::VmLocal, native_upto);
register_userdata_proof(&mut registry);
crate::library::register_standard(&mut registry);
crate::debuglib::register_debug(&mut registry);
registry
}
pub(crate) fn contains(&self, symbol: &str) -> bool {
self.entries.iter().any(|(name, _)| name == symbol)
}
pub(crate) fn call(&self, symbol: &str, ctx: &mut HostCtx<'_>, arg: i64) -> Option<HostResult> {
let function = self.entries.iter().find(|(name, _)| name == symbol)?.1;
Some(function(ctx, arg))
}
}
impl Default for HostRegistry {
fn default() -> Self {
Self::new()
}
}
pub fn mark(ctx: &mut HostCtx<'_>, arg: i64) -> HostResult {
let effect = ctx.effect;
let outcome = ctx.journal.commit(effect, arg, || effect.sequence as i64);
match outcome {
Ok(outcome) => HostResult::Ready(outcome),
Err(_) => HostResult::Fault,
}
}
pub fn park(_ctx: &mut HostCtx<'_>, _arg: i64) -> HostResult {
HostResult::Pending(WaitKey(1))
}
pub fn native_add(call: &mut NativeCall<'_>) -> NativeOutcome {
match (call.integer(0), call.integer(1)) {
(Some(a), Some(b)) => {
call.push_integer(a.wrapping_add(b));
NativeOutcome::Ready
}
_ => NativeOutcome::Fault,
}
}
pub fn native_sub(call: &mut NativeCall<'_>) -> NativeOutcome {
match (call.integer(0), call.integer(1)) {
(Some(a), Some(b)) => {
call.push_integer(a.wrapping_sub(b));
NativeOutcome::Ready
}
_ => NativeOutcome::Fault,
}
}
pub fn native_many(call: &mut NativeCall<'_>) -> NativeOutcome {
call.push_integer(10);
call.push_nil();
call.push_integer(30);
NativeOutcome::Ready
}
pub fn native_none(_call: &mut NativeCall<'_>) -> NativeOutcome {
NativeOutcome::Ready
}
pub fn native_mark(call: &mut NativeCall<'_>) -> NativeOutcome {
let (Some(effect), Some(arg)) = (call.effect(), call.integer(0)) else {
return NativeOutcome::Fault;
};
let Some(journal) = call.journal() else {
return NativeOutcome::Fault;
};
let Ok(outcome) = journal.commit(effect, arg, || effect.sequence as i64) else {
return NativeOutcome::Fault;
};
call.push_integer(outcome);
NativeOutcome::Ready
}
pub fn native_park(_call: &mut NativeCall<'_>) -> NativeOutcome {
NativeOutcome::Pending(WaitKey(1))
}
pub fn native_second(call: &mut NativeCall<'_>) -> NativeOutcome {
call.push_arg(1);
NativeOutcome::Ready
}
pub fn native_upto(call: &mut NativeCall<'_>) -> NativeOutcome {
let last = if call.is_nil(1) {
Some(0)
} else {
call.integer(1)
};
match (call.integer(0), last.and_then(|last| last.checked_add(1))) {
(Some(n), Some(next)) => {
if next <= n {
call.push_integer(next);
}
NativeOutcome::Ready
}
_ => NativeOutcome::Fault,
}
}
#[doc(hidden)] pub const USERDATA_NATIVES: [(&str, NativeFn); 10] = [
("newud", native_newud),
("light", native_light),
("udpeek", native_udpeek),
("udpoke", native_udpoke),
("counter_new", native_counter_new),
("counter_get", native_counter_get),
("counter_add", native_counter_add),
("counter_grow", native_counter_grow),
("handle_new", native_handle_new),
("handle_get", native_handle_get),
];
#[doc(hidden)] pub fn register_userdata_proof(registry: &mut HostRegistry) {
for (symbol, function) in USERDATA_NATIVES {
registry.register_native(symbol, NativePolicy::VmLocal, function);
}
registry.register_portable_userdata::<ProofCounter>();
registry.register_userdata::<ProofHandle>();
}
#[derive(Debug, PartialEq)]
#[doc(hidden)] pub struct ProofCounter {
pub count: i64,
pub size: u64,
}
impl crate::userdata::HostUserdata for ProofCounter {
const SYMBOL: &'static str = "moonseed.Counter";
fn logical_size(&self) -> u64 {
self.size
}
}
impl crate::userdata::PortableUserdata for ProofCounter {
fn encode(&self) -> Vec<u8> {
let mut bytes = self.count.to_le_bytes().to_vec();
bytes.extend(self.size.to_le_bytes());
bytes
}
fn decode(bytes: &[u8]) -> Option<Self> {
let (count, size) = bytes.split_at_checked(8)?;
Some(Self {
count: i64::from_le_bytes(count.try_into().ok()?),
size: u64::from_le_bytes(size.try_into().ok()?),
})
}
}
#[derive(Debug)]
#[doc(hidden)] pub struct ProofHandle(pub i64);
impl crate::userdata::HostUserdata for ProofHandle {
const SYMBOL: &'static str = "moonseed.Handle";
fn logical_size(&self) -> u64 {
8
}
}
fn native_newud(call: &mut NativeCall<'_>) -> NativeOutcome {
let size = call.integer(0).and_then(|size| usize::try_from(size).ok());
let user_values = if call.is_nil(1) {
Some(0)
} else {
call.integer(1).and_then(|n| usize::try_from(n).ok())
};
let (Some(size), Some(user_values)) = (size, user_values) else {
return NativeOutcome::Fault;
};
match call.new_userdata(size, user_values) {
Ok(userdata) => {
call.push(userdata);
NativeOutcome::Ready
}
Err(_) => NativeOutcome::Fault,
}
}
fn native_light(call: &mut NativeCall<'_>) -> NativeOutcome {
let Some(key) = call.integer(0) else {
return NativeOutcome::Fault;
};
let light = call.light_userdata(crate::userdata::HostLightKey(key as u64));
call.push(light);
NativeOutcome::Ready
}
fn native_udpeek(call: &mut NativeCall<'_>) -> NativeOutcome {
let userdata = call.arg(0);
let byte = call
.integer(1)
.and_then(|index| usize::try_from(index).ok())
.and_then(|index| call.userdata_bytes(userdata)?.get(index).copied());
match byte {
Some(byte) => {
call.push_integer(i64::from(byte));
NativeOutcome::Ready
}
None => NativeOutcome::Fault,
}
}
fn native_udpoke(call: &mut NativeCall<'_>) -> NativeOutcome {
let userdata = call.arg(0);
let (Some(index), Some(byte)) = (call.integer(1), call.integer(2)) else {
return NativeOutcome::Fault;
};
let slot = usize::try_from(index)
.ok()
.and_then(|index| call.userdata_bytes_mut(userdata)?.get_mut(index));
match slot {
Some(slot) => {
*slot = byte as u8;
NativeOutcome::Ready
}
None => NativeOutcome::Fault,
}
}
fn native_counter_new(call: &mut NativeCall<'_>) -> NativeOutcome {
let Some(count) = call.integer(0) else {
return call.type_error(0, "number");
};
let size = call.integer(2).map_or(16, |size| size.max(0) as u64);
let metatable = call.arg(1);
let counter = match call.new_host_userdata(ProofCounter { count, size }, 1) {
Ok(counter) => counter,
Err(_) => return NativeOutcome::Fault,
};
if !call.is_nil(1) && !call.set_metatable(counter, Some(metatable)) {
return call.type_error(1, "table");
}
call.push(counter);
NativeOutcome::Ready
}
fn native_counter_get(call: &mut NativeCall<'_>) -> NativeOutcome {
let this = call.arg(0);
let Some(counter) = call.userdata_ref::<ProofCounter>(this) else {
return call.type_error(0, ProofCounter::SYMBOL_NAME);
};
let count = counter.count;
call.push_integer(count);
NativeOutcome::Ready
}
fn native_counter_add(call: &mut NativeCall<'_>) -> NativeOutcome {
let this = call.arg(0);
let Some(by) = call.integer(1) else {
return call.type_error(1, "number");
};
let Some(counter) = call.userdata_mut::<ProofCounter>(this) else {
return call.type_error(0, ProofCounter::SYMBOL_NAME);
};
counter.count = counter.count.wrapping_add(by);
call.push_arg(0);
NativeOutcome::Ready
}
fn native_counter_grow(call: &mut NativeCall<'_>) -> NativeOutcome {
let this = call.arg(0);
let Some(size) = call.integer(1).and_then(|size| u64::try_from(size).ok()) else {
return call.type_error(1, "number");
};
if call.userdata_ref::<ProofCounter>(this).is_none() {
return call.type_error(0, ProofCounter::SYMBOL_NAME);
}
if call.set_userdata_charge(this, size).is_err() {
return NativeOutcome::Fault;
}
if let Some(counter) = call.userdata_mut::<ProofCounter>(this) {
counter.size = size;
}
NativeOutcome::Ready
}
fn native_handle_new(call: &mut NativeCall<'_>) -> NativeOutcome {
let Some(n) = call.integer(0) else {
return call.type_error(0, "number");
};
match call.new_host_userdata(ProofHandle(n), 0) {
Ok(handle) => {
call.push(handle);
NativeOutcome::Ready
}
Err(_) => NativeOutcome::Fault,
}
}
fn native_handle_get(call: &mut NativeCall<'_>) -> NativeOutcome {
let this = call.arg(0);
let Some(handle) = call.userdata_ref::<ProofHandle>(this) else {
return call.type_error(0, ProofHandle::SYMBOL_NAME);
};
let n = handle.0;
call.push_integer(n);
NativeOutcome::Ready
}
impl ProofCounter {
const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
}
impl ProofHandle {
const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
}