use std::cell::RefCell;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use crate::heap::Heap;
use crate::id::{ObjectId, OwnerToken};
use crate::{HostUserdata, LightUserdata, LuaType, Runtime};
use super::roots::{RootTable, Rooted};
use super::{ConversionError, FromLua, IntoLua, Result};
#[derive(Clone, Debug)]
pub enum Value {
Nil,
Boolean(bool),
Integer(i64),
Number(f64),
LightUserdata(LightUserdata),
String(LuaString),
Table(Table),
Function(Function),
Thread(Thread),
UserData(AnyUserData),
}
macro_rules! object_type {
($name:ident, $doc:literal) => {
#[doc = $doc]
#[derive(Clone)]
pub struct $name(pub(crate) Rooted);
impl $name {
pub fn id(&self) -> ObjectId {
self.0.id.expect("collectable object identity")
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple(stringify!($name)).field(&self.0.id).finish()
}
}
};
}
object_type!(LuaString, "A rooted Lua byte string.");
object_type!(Table, "A rooted Lua table. Raw operations never call Lua.");
object_type!(Thread, "A rooted Lua thread.");
object_type!(
AnyUserData,
"A rooted full userdata, with checked Rust payload borrows."
);
#[derive(Clone)]
pub struct Function(pub(crate) Rooted);
impl fmt::Debug for Function {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Function").field(&self.0.id).finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FunctionKind {
Lua,
Native,
NativeClosure,
Builtin,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ThreadStatus {
Ready,
Suspended,
Waiting,
Completed,
Failed,
}
impl Value {
pub fn id(&self) -> Option<ObjectId> {
match self {
Self::String(value) => Some(value.id()),
Self::Table(value) => Some(value.id()),
Self::Function(value) => value.id(),
Self::Thread(value) => Some(value.id()),
Self::UserData(value) => Some(value.id()),
_ => None,
}
}
pub fn lua_type(&self) -> LuaType {
match self {
Self::Nil => LuaType::Nil,
Self::Boolean(_) => LuaType::Boolean,
Self::Integer(_) | Self::Number(_) => LuaType::Number,
Self::LightUserdata(_) | Self::UserData(_) => LuaType::Userdata,
Self::String(_) => LuaType::String,
Self::Table(_) => LuaType::Table,
Self::Function(_) => LuaType::Function,
Self::Thread(_) => LuaType::Thread,
}
}
pub fn as_ref<'a>(&self, runtime: &'a Runtime) -> Result<ValueRef<'a>> {
let value = self.raw(runtime)?;
Ok(ValueRef::new(runtime, value))
}
pub(crate) fn check(&self, runtime: &Runtime) -> Result<()> {
self.raw(runtime).map(|_| ())
}
#[inline]
pub(crate) fn raw(&self, runtime: &Runtime) -> Result<crate::value::Value> {
use crate::value::Value as Raw;
Ok(match self {
Self::Nil => Raw::Nil,
Self::Boolean(value) => Raw::Bool(*value),
Self::Integer(value) => Raw::Integer(*value),
Self::Number(value) => Raw::Float(*value),
Self::LightUserdata(value) => Raw::LightUserdata(value.domain, value.bits),
Self::String(value) => value.0.value(runtime.owner())?,
Self::Table(value) => value.0.value(runtime.owner())?,
Self::Function(value) => value.0.value(runtime.owner())?,
Self::Thread(value) => value.0.value(runtime.owner())?,
Self::UserData(value) => value.0.value(runtime.owner())?,
})
}
#[inline]
pub(crate) fn wrap(
value: crate::value::Value,
heap: &Heap,
owner: OwnerToken,
roots: Option<&Rc<RefCell<RootTable>>>,
) -> Result<Self> {
use crate::value::Value as Raw;
let root = || -> Result<Rooted> {
let roots = roots.ok_or(super::ApiError::Released)?;
let id = heap.object_id_of_value(value);
if !matches!(value, Raw::Native(_)) && id.is_none() {
return Err(super::ApiError::Released.into());
}
Ok(Rooted::new(roots, owner, id, value))
};
Ok(match value {
Raw::Nil => Self::Nil,
Raw::Bool(value) => Self::Boolean(value),
Raw::Integer(value) => Self::Integer(value),
Raw::Float(value) => Self::Number(value),
Raw::LightUserdata(domain, bits) => Self::LightUserdata(LightUserdata { domain, bits }),
Raw::String(_) => Self::String(LuaString(root()?)),
Raw::Table(_) => Self::Table(Table(root()?)),
Raw::Closure(_) | Raw::Native(_) | Raw::NativeClosure(_) => {
Self::Function(Function(root()?))
}
Raw::Thread(_) => Self::Thread(Thread(root()?)),
Raw::Userdata(_) => Self::UserData(AnyUserData(root()?)),
})
}
}
#[derive(Clone, Copy)]
pub struct ValueRef<'a> {
pub(crate) value: crate::value::Value,
heap: &'a Heap,
owner: OwnerToken,
roots: Option<&'a Rc<RefCell<RootTable>>>,
}
impl<'a> ValueRef<'a> {
pub(crate) fn new(runtime: &'a Runtime, value: crate::value::Value) -> Self {
Self {
value,
heap: runtime.heap(),
owner: runtime.owner(),
roots: runtime.heap().api_roots.as_ref(),
}
}
pub fn lua_type(&self) -> LuaType {
use crate::value::Value as Raw;
match self.value {
Raw::Nil => LuaType::Nil,
Raw::Bool(_) => LuaType::Boolean,
Raw::Integer(_) | Raw::Float(_) => LuaType::Number,
Raw::String(_) => LuaType::String,
Raw::Table(_) => LuaType::Table,
Raw::Closure(_) | Raw::Native(_) | Raw::NativeClosure(_) => LuaType::Function,
Raw::Thread(_) => LuaType::Thread,
Raw::Userdata(_) | Raw::LightUserdata(..) => LuaType::Userdata,
}
}
pub fn id(&self) -> Option<ObjectId> {
self.heap.object_id_of_value(self.value)
}
pub fn to_owned_value(&self) -> Result<Value> {
Value::wrap(self.value, self.heap, self.owner, self.roots)
}
pub fn is_nil(&self) -> bool {
matches!(self.value, crate::value::Value::Nil)
}
pub fn as_light_userdata(&self) -> Option<LightUserdata> {
if let crate::value::Value::LightUserdata(domain, bits) = self.value {
Some(LightUserdata { domain, bits })
} else {
None
}
}
pub fn as_integer(&self) -> Option<i64> {
if let crate::value::Value::Integer(value) = self.value {
Some(value)
} else {
None
}
}
pub fn as_number(&self) -> Option<f64> {
match self.value {
crate::value::Value::Integer(value) => Some(value as f64),
crate::value::Value::Float(value) => Some(value),
_ => None,
}
}
pub fn as_boolean(&self) -> Option<bool> {
if let crate::value::Value::Bool(value) = self.value {
Some(value)
} else {
None
}
}
pub fn as_string(&self) -> Option<StrRef<'a>> {
if let crate::value::Value::String(handle) = self.value {
self.heap.string_bytes(handle).map(StrRef)
} else {
None
}
}
}
impl fmt::Debug for ValueRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ValueRef")
.field("type", &self.lua_type())
.field("id", &self.id())
.finish()
}
}
#[derive(Clone, Copy)]
pub struct StrRef<'a>(&'a [u8]);
impl<'a> StrRef<'a> {
pub fn as_bytes(&self) -> &'a [u8] {
self.0
}
pub fn to_str(&self) -> Result<&'a str> {
std::str::from_utf8(self.0).map_err(|_| {
ConversionError {
expected: "UTF-8 string",
actual: LuaType::String,
position: None,
}
.into()
})
}
}
impl fmt::Debug for StrRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("StrRef").field(&self.0).finish()
}
}
impl LuaString {
pub fn as_bytes<'a>(&self, runtime: &'a Runtime) -> Result<&'a [u8]> {
runtime.api_string(self)
}
pub fn to_str<'a>(&self, runtime: &'a Runtime) -> Result<&'a str> {
StrRef(self.as_bytes(runtime)?).to_str()
}
}
impl Table {
pub fn get<K: IntoLua, R: super::FromLuaMulti>(
&self,
runtime: &mut Runtime,
key: K,
journal: &mut crate::Journal,
fuel: u64,
) -> Result<super::CallOutcome<R>> {
self.0.value(runtime.owner())?;
let key = key.into_lua(runtime)?;
runtime.api_table_get(self, key, journal, fuel)
}
pub fn set<K: IntoLua, V: IntoLua>(
&self,
runtime: &mut Runtime,
key: K,
value: V,
journal: &mut crate::Journal,
fuel: u64,
) -> Result<super::CallOutcome<()>> {
self.0.value(runtime.owner())?;
let key = key.into_lua(runtime)?;
let value = value.into_lua(runtime)?;
runtime.api_table_set(self, key, value, journal, fuel)
}
pub fn raw_get<K: IntoLua, V: FromLua>(&self, runtime: &mut Runtime, key: K) -> Result<V> {
self.0.value(runtime.owner())?;
let key = key.into_lua(runtime)?;
let value = runtime.api_raw_get(self, &key)?;
V::from_lua(value, runtime)
}
pub fn raw_set<K: IntoLua, V: IntoLua>(
&self,
runtime: &mut Runtime,
key: K,
value: V,
) -> Result<()> {
self.0.value(runtime.owner())?;
let key = key.into_lua(runtime)?;
let value = value.into_lua(runtime)?;
runtime.api_raw_set(self, &key, &value)
}
pub fn raw_len(&self, runtime: &Runtime) -> Result<i64> {
runtime.api_raw_len(self)
}
pub fn next(
&self,
runtime: &mut Runtime,
key: Option<&Value>,
) -> Result<Option<(Value, Value)>> {
runtime.api_next(self, key)
}
pub fn metatable(&self, runtime: &mut Runtime) -> Result<Option<Table>> {
runtime.api_metatable(self)
}
pub fn set_metatable(&self, runtime: &mut Runtime, table: Option<&Table>) -> Result<()> {
runtime.api_set_metatable(self, table)
}
}
impl Function {
pub fn id(&self) -> Option<ObjectId> {
self.0.id
}
pub fn kind(&self, runtime: &Runtime) -> Result<FunctionKind> {
runtime.api_function_kind(self)
}
}
impl Thread {
pub fn status(&self, runtime: &Runtime) -> Result<ThreadStatus> {
runtime.api_thread_status(self)
}
}
impl AnyUserData {
pub fn borrow<'a, T: HostUserdata>(&self, runtime: &'a Runtime) -> Result<&'a T> {
runtime.api_userdata(self)
}
pub fn borrow_mut<'a, T: HostUserdata>(
&self,
runtime: &'a mut Runtime,
) -> Result<UserDataRefMut<'a, T>> {
runtime.api_userdata_mut(self)
}
}
pub struct UserDataRefMut<'a, T: HostUserdata> {
pub(crate) runtime: &'a mut Runtime,
pub(crate) handle: crate::id::Handle<crate::heap::UserdataObj>,
pub(crate) marker: std::marker::PhantomData<T>,
}
impl<T: HostUserdata> Deref for UserDataRefMut<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.runtime
.api_userdata_at(self.handle)
.expect("borrowed userdata type")
}
}
impl<T: HostUserdata> DerefMut for UserDataRefMut<'_, T> {
fn deref_mut(&mut self) -> &mut T {
self.runtime
.api_userdata_at_mut(self.handle)
.expect("borrowed userdata type")
}
}
impl<T: HostUserdata> Drop for UserDataRefMut<'_, T> {
fn drop(&mut self) {
self.runtime.api_userdata_recharge::<T>(self.handle);
}
}