use super::{
AnyUserData, ApiError, FromLua, FromLuaMulti, Function, IntoLua, IntoLuaMulti, LuaError,
LuaString, MultiValue, Result, Table, UserDataRefMut, Value, ValueRef,
};
use crate::value::Value as Raw;
use crate::{EffectId, HostUserdata, Journal, Runtime, WaitKey};
pub(crate) type TypedCallback = dyn Fn(&mut NativeContext<'_>) -> Result<()>;
pub(crate) type Callback = dyn Fn(&mut NativeContext<'_>) -> Result<NativeReturn>;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum NativeReturn {
Return(MultiValue),
Error(Value),
Wait(WaitRequest),
CallLua {
function: Value,
args: MultiValue,
tag: u32,
keep: MultiValue,
},
CallLuaNoYield {
function: Value,
args: MultiValue,
tag: u32,
keep: MultiValue,
},
}
impl From<MultiValue> for NativeReturn {
fn from(values: MultiValue) -> Self {
Self::Return(values)
}
}
#[derive(Clone, Debug)]
pub struct WaitRequest {
pub operation: String,
pub payload: MultiValue,
}
pub type WaitInfo = WaitRequest;
#[derive(Clone, Debug)]
pub enum ResumeOutcome {
Returned(MultiValue),
Errored(LuaError),
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Resume {
pub tag: u32,
pub outcome: ResumeOutcome,
pub kept: MultiValue,
}
#[derive(Clone, Debug)]
pub enum Completion {
Return(Vec<Value>),
Error(Value),
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CallOutcome<R> {
Done(R),
Waiting(WaitKey),
ExitRequested {
status: crate::ExitStatus,
close: bool,
},
OutOfFuel,
}
pub struct NativeContext<'cx> {
pub(crate) runtime: &'cx mut Runtime,
pub(crate) args: &'cx [Raw],
pub(crate) callee: Raw,
pub(crate) effect: Option<EffectId>,
pub(crate) journal: Option<&'cx mut Journal>,
pub(crate) resume: Option<&'cx Resume>,
}
impl NativeContext<'_> {
pub fn charge_fuel(&mut self, units: u64) -> Result<()> {
self.runtime.api_charge_fuel(units)
}
pub fn arg_count(&self) -> usize {
self.args.len()
}
#[inline]
pub fn arg(&self, index: usize) -> ValueRef<'_> {
ValueRef::new(
self.runtime,
self.args.get(index).copied().unwrap_or(Raw::Nil),
)
}
pub fn string_bytes(&self, index: usize) -> Option<&[u8]> {
self.arg(index).as_string().map(|string| string.as_bytes())
}
#[inline]
pub fn argument<T: FromLua>(&mut self, index: usize) -> Result<T> {
<T as FromLua>::from_context(self, index)
.map_err(|error| positioned(error, index.checked_add(1)))
}
#[inline]
pub fn arguments<A: FromLuaMulti>(&mut self) -> Result<A> {
<A as FromLuaMulti>::from_context(self)
}
pub fn argument_error(&mut self, error: super::Error) -> super::Error {
self.runtime.api_argument_error(self.callee, error)
}
pub fn bad_argument(&mut self, index: usize, detail: &str) -> Result<super::LuaError> {
self.runtime.api_bad_argument(index, detail.as_bytes())
}
#[inline]
pub(crate) fn write_results<R: IntoLuaMulti>(&mut self, values: R) -> Result<()> {
values.write_native(self)
}
#[inline]
pub(crate) fn push_result(&mut self, value: Value) -> Result<()> {
let raw = value.raw(self.runtime)?;
self.runtime.native_results.push(raw);
Ok(())
}
pub(crate) fn take_results(&mut self) -> Result<MultiValue> {
let raw = std::mem::take(&mut self.runtime.native_results);
raw.iter()
.map(|value| self.runtime.api_owned(*value))
.collect::<Result<Vec<_>>>()
.map(MultiValue)
}
pub fn captures(&self) -> Vec<ValueRef<'_>> {
self.runtime
.api_captures(self.callee)
.iter()
.map(|raw| ValueRef::new(self.runtime, *raw))
.collect()
}
pub fn set_capture<V: IntoLua>(&mut self, index: usize, value: V) -> Result<()> {
let value = value.into_lua(self.runtime)?;
self.runtime.api_set_capture(self.callee, index, &value)
}
pub fn resumed(&self) -> Option<Resume> {
self.resume.cloned()
}
pub fn resumed_ref(&self) -> Option<&Resume> {
self.resume
}
pub fn call_lua(
&mut self,
function: impl IntoLua,
args: impl IntoLuaMulti,
tag: u32,
keep: impl IntoLuaMulti,
) -> Result<NativeReturn> {
Ok(NativeReturn::CallLua {
function: function.into_lua(self.runtime)?,
args: args.into_lua_multi(self.runtime)?,
tag,
keep: keep.into_lua_multi(self.runtime)?,
})
}
#[inline]
pub fn return_values<R: IntoLuaMulti>(&mut self, values: R) -> Result<NativeReturn> {
values
.into_lua_multi(self.runtime)
.map(NativeReturn::Return)
}
pub fn create_string(&mut self, bytes: impl AsRef<[u8]>) -> Result<LuaString> {
self.runtime.create_string(bytes)
}
pub fn create_table(&mut self) -> Result<Table> {
self.runtime.create_table()
}
pub fn create_userdata<T: HostUserdata>(
&mut self,
value: T,
user_values: usize,
) -> Result<AnyUserData> {
self.runtime.create_host_userdata(value, user_values)
}
pub fn make_closure(&mut self, symbol: &str, captures: impl IntoLuaMulti) -> Result<Function> {
self.runtime.make_closure(symbol, captures)
}
pub fn borrow_userdata<'a, T: HostUserdata>(&'a self, value: &AnyUserData) -> Result<&'a T> {
value.borrow(self.runtime)
}
pub fn borrow_userdata_mut<'a, T: HostUserdata>(
&'a mut self,
value: &AnyUserData,
) -> Result<UserDataRefMut<'a, T>> {
value.borrow_mut(self.runtime)
}
pub fn raw_get<K: IntoLua, V: FromLua>(&mut self, table: &Table, key: K) -> Result<V> {
table.raw_get(self.runtime, key)
}
pub fn value_ref(&self, value: &Value) -> Result<ValueRef<'_>> {
value.as_ref(self.runtime)
}
pub fn raw_pairs(&mut self, table: &Table, depth: usize) -> Result<super::TableTraversal> {
self.runtime.api_traversal(table, depth)
}
pub fn raw_set<K: IntoLua, V: IntoLua>(
&mut self,
table: &Table,
key: K,
value: V,
) -> Result<()> {
table.raw_set(self.runtime, key, value)
}
pub fn raw_len(&self, table: &Table) -> Result<i64> {
table.raw_len(self.runtime)
}
pub fn metatable<V: IntoLua>(&mut self, object: V) -> Result<Option<Table>> {
let object = object.into_lua(self.runtime)?;
self.runtime.api_value_metatable(&object)
}
pub fn set_metatable<V: IntoLua>(&mut self, object: V, meta: Option<&Table>) -> Result<()> {
let object = object.into_lua(self.runtime)?;
self.runtime.api_value_set_metatable(&object, meta)
}
pub fn effect(&self) -> Option<EffectId> {
self.effect
}
pub fn journal(&mut self) -> Option<&mut Journal> {
self.journal.as_deref_mut()
}
}
fn positioned(error: super::Error, index: Option<usize>) -> super::Error {
if let super::Error::Api(ApiError::Conversion(mut error)) = error {
error.position = index;
error.into()
} else {
error
}
}
impl NativeContext<'_> {
pub fn current_thread(&mut self) -> Result<Value> {
let thread = self.runtime.heap().active.ok_or(crate::VmError::Corrupt)?;
self.runtime.api_owned(Raw::Thread(thread))
}
pub fn globals(&mut self) -> Table {
self.runtime.globals()
}
pub fn set_hook(
&mut self,
thread: Option<&Value>,
symbol: &str,
mask: super::HookMask,
count: i32,
) -> Result<()> {
let current = self.current_thread()?;
self.runtime
.set_hook(Some(thread.unwrap_or(¤t)), symbol, mask, count)
}
pub fn clear_hook(&mut self, thread: Option<&Value>) -> Result<()> {
let current = self.current_thread()?;
self.runtime.clear_hook(Some(thread.unwrap_or(¤t)))
}
pub fn get_hook(&mut self, thread: Option<&Value>) -> Result<Option<super::HookSettings>> {
let current = self.current_thread()?;
self.runtime.get_hook(Some(thread.unwrap_or(¤t)))
}
}