This commit is contained in:
2025-06-22 15:11:37 +10:00
parent 5be3f2970c
commit 0667f79ff5
14 changed files with 508 additions and 319 deletions

View File

@@ -9,4 +9,3 @@ luaffi_impl = { version = "0.1.0", path = "../luaffi_impl" }
luaify = { version = "0.1.0", path = "../luaify" }
rustc-hash = "2.1.1"
simdutf8 = "0.1.5"
static_assertions = "1.1.0"

View File

@@ -1,6 +1,6 @@
use crate::{
__internal::{display, type_id},
CDef, CDefBuilder, Metatype, MetatypeBuilder, ToFfi, Type, TypeBuilder,
CDef, CDefBuilder, FfiReturnConvention, Metatype, MetatypeBuilder, ToFfi, Type, TypeBuilder,
};
use luaify::luaify;
use std::{
@@ -94,12 +94,9 @@ impl<F: Future<Output: ToFfi>> lua_future<F> {
}
unsafe extern "C" fn take(&mut self) -> <F::Output as ToFfi>::To {
// `fut:__take()` returns the fulfilled value by-value because it is the lowest common
// denominator for supported return conventions (all `ToFfi` impls support return by-value;
// primitives e.g. don't support return by out-param because they get boxed in cdata).
//
// Plus, if we preallocate a cdata for out-param and the thread for some reason gets dropped
// and never resumed, GC could call the destructor on an uninitialised cdata.
// `fut:__take()` returns the fulfilled value by-value (not by out-param) because if we
// preallocate a cdata for the out-param and the thread for some reason gets dropped and
// never resumed, the GC could call the destructor on an uninitialised cdata.
match self.state {
State::Fulfilled(_) => match mem::replace(&mut self.state, State::Complete) {
State::Fulfilled(value) => value.convert(),
@@ -170,7 +167,7 @@ unsafe impl<F: Future<Output: ToFfi> + 'static> ToFfi for lua_future<F> {
self
}
fn postlude(ret: &str) -> impl Display {
fn postlude(ret: &str, _conv: FfiReturnConvention) -> impl Display {
// When returning a future from Rust to Lua, yield it immediately to the runtime which will
// poll it to completion in the background, then take the fulfilled value once the thread
// gets resumed. Lua user code should never to worry about awaiting futures.
@@ -181,7 +178,7 @@ unsafe impl<F: Future<Output: ToFfi> + 'static> ToFfi for lua_future<F> {
// `coroutine.yield` is cached as `yield` and `ffi.gc` as `gc` in locals (see lib.rs)
display!(
"yield({ret}); {ret} = gc({ret}, nil):__take(); {}",
<F::Output as ToFfi>::postlude(ret)
<F::Output as ToFfi>::postlude(ret, FfiReturnConvention::ByValue)
)
}
}

View File

@@ -1,6 +1,5 @@
pub use luaify::*;
use rustc_hash::FxHasher;
pub use static_assertions::*;
use std::{
any::TypeId,
fmt::{self, Display, Formatter},

View File

@@ -19,8 +19,8 @@ const KEEP_FN: &str = "luaffi_keep";
const IS_UTF8_FN: &str = "luaffi_is_utf8";
// Dummy function to ensure that strings passed to Rust via wrapper objects will not be
// garbage-collected until the end of the function.
// This shall exist until LuaJIT one day implements something like `ffi.keep(obj)`.
// garbage-collected until the end of the function. This shall exist until LuaJIT one day implements
// something like `ffi.keep(obj)`.
//
// https://github.com/LuaJIT/LuaJIT/issues/1167
#[unsafe(export_name = "luaffi_keep")]
@@ -32,7 +32,6 @@ unsafe extern "C" fn __is_utf8(ptr: *const u8, len: usize) -> bool {
}
const CACHE_LIBS: &[(&str, &str)] = &[
// libs in global
("table", "table"),
("string", "string"),
("math", "math"),
@@ -43,8 +42,8 @@ const CACHE_LIBS: &[(&str, &str)] = &[
// require
("bit", r#"require("bit")"#),
("ffi", r#"require("ffi")"#),
("new", r#"require("table.new")"#),
("clear", r#"require("table.clear")"#),
("__tnew", r#"require("table.new")"#),
("__tclear", r#"require("table.clear")"#),
];
// https://www.lua.org/manual/5.1/manual.html#5.1
@@ -71,44 +70,48 @@ const CACHE_GLOBALS: &[(&str, &str)] = &[
("tostring", "tostring"),
("require", "require"),
// table
("concat", "table.concat"),
("insert", "table.insert"),
("maxn", "table.maxn"),
("remove", "table.remove"),
("sort", "table.sort"),
("__tconcat", "table.concat"),
("__tinsert", "table.insert"),
("__tmaxn", "table.maxn"),
("__tremove", "table.remove"),
("__tsort", "table.sort"),
// string
("strlen", "string.len"),
("format", "string.format"),
("strsub", "string.sub"),
("gsub", "string.gsub"),
("gmatch", "string.gmatch"),
("dump", "string.dump"),
("__slen", "string.len"),
("__sformat", "string.format"),
("__ssub", "string.sub"),
("__sgsub", "string.gsub"),
("__sgmatch", "string.gmatch"),
("__sdump", "string.dump"),
// math
("random", "math.random"),
("__fmod", "math.fmod"),
// coroutine
("yield", "coroutine.yield"),
("__yield", "coroutine.yield"),
// debug
("traceback", "debug.traceback"),
("__traceback", "debug.traceback"),
// ffi
("C", "ffi.C"),
("cdef", "ffi.cdef"),
("typeof", "ffi.typeof"),
("metatype", "ffi.metatype"),
("cast", "ffi.cast"),
("gc", "ffi.gc"),
("__C", "ffi.C"),
("__cdef", "ffi.cdef"),
("__cnew", "ffi.new"),
("__ctype", "ffi.typeof"),
("__ctypes", "{}"),
("__istype", "ffi.istype"),
("__metatype", "ffi.metatype"),
("__cast", "ffi.cast"),
("__gc", "ffi.gc"),
("__sizeof", "ffi.sizeof"),
("__alignof", "ffi.alignof"),
("__intern", "ffi.string"),
// bit
("tobit", "bit.tobit"),
("tohex", "bit.tohex"),
("bnot", "bit.bnot"),
("band", "bit.band"),
("bor", "bit.bor"),
("bxor", "bit.bxor"),
("lshift", "bit.lshift"),
("rshift", "bit.rshift"),
("arshift", "bit.arshift"),
("rol", "bit.rol"),
("ror", "bit.ror"),
("bswap", "bit.bswap"),
("__bnot", "bit.bnot"),
("__band", "bit.band"),
("__bor", "bit.bor"),
("__bxor", "bit.bxor"),
("__blshift", "bit.lshift"),
("__brshift", "bit.rshift"),
("__barshift", "bit.arshift"),
("__brol", "bit.rol"),
("__bror", "bit.ror"),
("__bswap", "bit.bswap"),
];
fn cache_local(f: &mut Formatter, list: &[(&str, &str)]) -> fmt::Result {
@@ -135,11 +138,6 @@ impl Registry {
s
}
pub fn preload<T: Type>(&mut self, _name: impl Display) -> &mut Self {
self.include::<T>();
self
}
pub fn include<T: Type>(&mut self) -> &mut Self {
self.types
.insert(T::name().to_string())
@@ -164,10 +162,10 @@ impl Display for Registry {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let name = env!("CARGO_PKG_NAME");
let version = env!("CARGO_PKG_VERSION");
writeln!(f, "-- automatically generated by {name} {version}")?;
writeln!(f, "--- automatically generated by {name} {version}")?;
cache_local(f, CACHE_LIBS)?;
cache_local(f, CACHE_GLOBALS)?;
writeln!(f, "cdef [[{}]];", self.cdef)?;
writeln!(f, "__cdef [[{}]];", self.cdef)?;
write!(f, "{}", self.lua)
}
}
@@ -222,14 +220,6 @@ pub struct CDefBuilder<'r> {
impl<'r> CDefBuilder<'r> {
fn new<T: CDef>(registry: &'r mut Registry) -> Self {
writeln!(
registry.lua,
r#"local {} = typeof("{}");"#,
T::name(),
T::cdecl("")
)
.unwrap();
Self {
registry,
cdef: format!("{} {{ ", T::cdecl("")),
@@ -293,6 +283,7 @@ pub unsafe trait Metatype {
pub struct MetatypeBuilder<'r> {
registry: &'r mut Registry,
name: String,
cdecl: String,
cdef: String,
lua: String,
}
@@ -302,8 +293,9 @@ impl<'r> MetatypeBuilder<'r> {
Self {
registry,
name: T::Target::name().to_string(),
cdecl: T::Target::cdecl("").to_string(),
cdef: String::new(),
lua: format!(r#"do local __mt, __idx = {{}}, {{}}; __mt.__index = __idx; "#),
lua: r#"do local __mt, __idx = {}, {}; __mt.__index = __idx; "#.into(),
}
}
@@ -333,7 +325,7 @@ impl<'r> MetatypeBuilder<'r> {
name: impl Display,
f: impl FnOnce(&mut MetatypeMethodBuilder),
) -> &mut Self {
write!(self.lua, "__idx.{name} = ").unwrap();
write!(self.lua, "__mt.{name} = ").unwrap();
f(&mut MetatypeMethodBuilder::new(self));
write!(self.lua, "; ").unwrap();
self
@@ -350,6 +342,7 @@ impl<'r> Drop for MetatypeBuilder<'r> {
let Self {
registry,
name,
cdecl,
cdef,
lua,
..
@@ -357,37 +350,45 @@ impl<'r> Drop for MetatypeBuilder<'r> {
registry.cdef.push_str(cdef);
registry.lua.push_str(lua);
writeln!(registry.lua, "metatype({name}, __mt); end;").unwrap();
writeln!(
registry.lua,
r#"__ctypes.{name} = __metatype("{cdecl}", __mt); end;"#
)
.unwrap();
}
}
pub unsafe trait FromFfi: Sized {
type From: Type + Sized;
type FromValue: Type + Sized;
type FromArg: Type + Sized;
const ARG_KEEPALIVE: bool = false;
fn require_keepalive() -> bool {
false
}
fn prelude(_arg: &str) -> impl Display {
""
}
fn convert(from: Self::From) -> Self;
fn convert_value(from: Self::FromValue) -> Self;
fn convert_arg(from: Self::FromArg) -> Self;
}
pub unsafe trait ToFfi: Sized {
type To: Type + Sized;
fn postlude(_ret: &str) -> impl Display {
fn postlude(_ret: &str, _conv: FfiReturnConvention) -> impl Display {
""
}
fn convert(self) -> Self::To;
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FfiReturnConvention {
Void,
#[default]
ByValue,
ByOutParam,
}
@@ -420,9 +421,9 @@ impl<'r, 'm> MetatypeMethodBuilder<'r, 'm> {
write!(self.params, "{name}").unwrap();
write!(self.args, "{name}").unwrap();
if T::ARG_KEEPALIVE {
if T::require_keepalive() {
write!(self.prelude, "local __keep_{name} = {name}; ").unwrap();
write!(self.postlude, "C.{KEEP_FN}(__keep_{name}); ").unwrap();
write!(self.postlude, "__C.{KEEP_FN}(__keep_{name}); ").unwrap();
}
let name = name.to_string();
@@ -432,6 +433,10 @@ impl<'r, 'm> MetatypeMethodBuilder<'r, 'm> {
pub fn param_str(&mut self, name: impl Display) -> &mut Self {
// fast-path for &str and &[u8]-like parameters
//
// this passes one lua `string` argument as two C `const uint8_t *ptr` and `uintptr_t len`
// arguments, bypassing the slower generic `&[u8]: FromFfi` path which constructs a
// temporary cdata to pass the string and its length in one argument
(!self.params.is_empty()).then(|| self.params.push_str(", "));
(!self.args.is_empty()).then(|| self.args.push_str(", "));
write!(self.params, "{name}").unwrap();
@@ -445,7 +450,7 @@ impl<'r, 'm> MetatypeMethodBuilder<'r, 'm> {
self
}
pub fn call<T: ToFfi>(&mut self, func: impl Display, conv: FfiReturnConvention) {
pub fn call<T: ToFfi>(&mut self, func: impl Display, ret: FfiReturnConvention) {
let Self {
metatype,
params,
@@ -459,22 +464,22 @@ impl<'r, 'm> MetatypeMethodBuilder<'r, 'm> {
let lua = &mut metatype.lua;
write!(lua, "function({params}) {prelude}").unwrap();
match conv {
match ret {
FfiReturnConvention::Void => {
write!(lua, "C.{func}({args}); {postlude}return nil; end").unwrap();
write!(lua, "__C.{func}({args}); {postlude}end").unwrap();
}
FfiReturnConvention::ByValue => {
let check = T::postlude("res");
let check = T::postlude("res", ret);
write!(
lua,
"local res = C.{func}({args}); {check}{postlude}return res; end"
"local res = __C.{func}({args}); {check}{postlude}return res; end"
)
.unwrap();
}
FfiReturnConvention::ByOutParam => {
let ct = T::To::name();
let check = T::postlude("res");
write!(lua, "local res = {ct}(); C.{func}(res").unwrap();
let check = T::postlude("res", ret);
write!(lua, "local res = __cnew(__ctypes.{ct}); __C.{func}(res").unwrap();
if !args.is_empty() {
write!(lua, ", {args}").unwrap();
}
@@ -505,16 +510,25 @@ impl_primitive!(c_void, "void");
unsafe impl ToFfi for () {
//
// SAFETY: Unit type return maps to a C void return, which is a nil return in lua.
// There is no equivalent to passing a unit type as an argument in C.
// `c_void` cannot be returned from rust so it should return the unit type instead.
// SAFETY: Unit type return maps to a C void return, which is a nil return in lua. There is no
// equivalent to passing a unit type as an argument in C. `c_void` cannot be returned from rust
// so it should return the unit type instead.
//
type To = ();
fn convert(self) -> Self::To {}
fn postlude(_ret: &str, conv: FfiReturnConvention) -> impl Display {
assert!(
conv == FfiReturnConvention::Void,
"void type cannot be instantiated"
);
""
}
}
macro_rules! impl_copy_primitive {
($rtype:ty, $ctype:expr, $ltype:expr) => {
($rtype:ty, $ctype:expr, $ltype:expr $(, $unwrap:expr)?) => {
impl_primitive!($rtype, $ctype);
//
@@ -522,7 +536,7 @@ macro_rules! impl_copy_primitive {
//
unsafe impl FromFfi for $rtype {
type From = $rtype;
type FromValue = $rtype;
type FromArg = $rtype;
fn prelude(arg: &str) -> impl Display {
display!(r#"assert(type({arg}) == "{0}", "{0} expected in argument '{arg}', got " .. type({arg})); "#, $ltype)
@@ -532,7 +546,7 @@ macro_rules! impl_copy_primitive {
from
}
fn convert_value(from: Self::FromValue) -> Self {
fn convert_arg(from: Self::FromArg) -> Self {
from
}
}
@@ -543,23 +557,38 @@ macro_rules! impl_copy_primitive {
fn convert(self) -> Self::To {
self
}
#[allow(unused)]
fn postlude(ret: &str, conv: FfiReturnConvention) -> impl Display {
disp(move |f| {
match conv {
FfiReturnConvention::Void => unreachable!(),
FfiReturnConvention::ByValue => {},
// if a primitive type for some reason gets returned by out-param, unwrap
// the cdata containing the value and convert it to the equivalent lua value
FfiReturnConvention::ByOutParam => { $(write!(f, "{ret} = {}; ", $unwrap(ret))?;)? },
}
Ok(())
})
}
}
};
}
impl_copy_primitive!(bool, "bool", "boolean");
impl_copy_primitive!(u8, "uint8_t", "number");
impl_copy_primitive!(u16, "uint16_t", "number");
impl_copy_primitive!(u32, "uint32_t", "number");
impl_copy_primitive!(bool, "bool", "boolean", |n| display!("{n} ~= 0"));
impl_copy_primitive!(u8, "uint8_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(u16, "uint16_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(u32, "uint32_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(u64, "uint64_t", "number");
impl_copy_primitive!(usize, "uintptr_t", "number");
impl_copy_primitive!(i8, "int8_t", "number");
impl_copy_primitive!(i16, "int16_t", "number");
impl_copy_primitive!(i32, "int32_t", "number");
impl_copy_primitive!(i8, "int8_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(i16, "int16_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(i32, "int32_t", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(i64, "int64_t", "number");
impl_copy_primitive!(isize, "intptr_t", "number");
impl_copy_primitive!(c_float, "float", "number");
impl_copy_primitive!(c_double, "double", "number");
impl_copy_primitive!(c_float, "float", "number", |n| display!("tonumber({n})"));
impl_copy_primitive!(c_double, "double", "number", |n| display!("tonumber({n})"));
unsafe impl<T: Type> Type for *const T {
fn name() -> impl Display {
@@ -596,34 +625,34 @@ unsafe impl<T: Type> Type for *mut T {
//
unsafe impl<T: Type> FromFfi for *const T {
type From = *const T;
type FromValue = *const T;
type FromArg = *const T;
fn convert(from: Self::From) -> Self {
from
}
fn convert_value(from: Self::FromValue) -> Self {
fn convert_arg(from: Self::FromArg) -> Self {
from
}
}
unsafe impl<T: Type> FromFfi for *mut T {
type From = *mut T;
type FromValue = *mut T;
type FromArg = *mut T;
fn convert(from: Self::From) -> Self {
from
}
fn convert_value(from: Self::FromValue) -> Self {
fn convert_arg(from: Self::FromArg) -> Self {
from
}
}
//
// SAFETY: Return by value for pointers, which maps to a `cdata` return in lua containing the pointer (`T *`).
// We also map null pointers to `nil` for convenience (otherwise it's still a cdata value containing
// a null pointer)
// SAFETY: Return by value for pointers, which maps to a `cdata` return in lua containing the
// pointer (`T *`). We also map null pointers to `nil` for convenience (otherwise it's still a cdata
// value containing a null pointer)
//
unsafe impl<T: Type> ToFfi for *const T {
type To = *const T;
@@ -632,7 +661,7 @@ unsafe impl<T: Type> ToFfi for *const T {
self
}
fn postlude(ret: &str) -> impl Display {
fn postlude(ret: &str, _conv: FfiReturnConvention) -> impl Display {
display!("if {ret} == nil then {ret} = nil; end; ")
}
}
@@ -644,14 +673,14 @@ unsafe impl<T: Type> ToFfi for *mut T {
self
}
fn postlude(ret: &str) -> impl Display {
fn postlude(ret: &str, _conv: FfiReturnConvention) -> impl Display {
display!("if {ret} == nil then {ret} = nil; end; ")
}
}
//
// SAFETY: No `ToFfi` for references because we can't guarantee that the returned reference converted
// to a pointer will not outlive the pointee.
// SAFETY: No `ToFfi` for references because we can't guarantee that the returned reference
// converted to a pointer will not outlive the pointee.
//
unsafe impl<T: Type> Type for &T {
fn name() -> impl Display {
@@ -682,22 +711,18 @@ unsafe impl<T: Type> Type for &mut T {
}
//
// SAFETY: Pass by value for references, which have the same semantics as pointers (see above).
// Must ensure that the pointer is not nil before being converted to a reference.
// SAFETY: Pass by value for references, which have the same semantics as pointers (see above). Must
// ensure that the pointer is not nil before being converted to a reference.
//
unsafe impl<T: Type> FromFfi for &T {
type From = *const T;
type FromValue = *const T;
type FromArg = *const T;
fn prelude(arg: &str) -> impl Display {
display!(r#"assert({arg} ~= nil, "argument '{arg}' cannot be nil"); "#)
}
fn convert(from: Self::From) -> Self {
Self::convert_value(from)
}
fn convert_value(from: Self::FromValue) -> Self {
debug_assert!(
!from.is_null(),
"<&T>::convert() called on a null pointer when it was checked to be non-null"
@@ -705,36 +730,37 @@ unsafe impl<T: Type> FromFfi for &T {
unsafe { &*from }
}
fn convert_arg(from: Self::FromArg) -> Self {
Self::convert(from)
}
}
unsafe impl<T: Type> FromFfi for &mut T {
//
// SAFETY: `FromFfi` for *mutable* references is safe because it is guaranteed that no two Rust
// code called via FFI can be running at the same time on the same OS thread (no Lua reentrancy).
// code called via FFI can be running at the same time on the same OS thread (no Lua
// reentrancy).
//
// i.e. The call stack will always look something like this:
//
// * Runtime (LuaJIT/Rust) -> Lua (via C) -> Rust (via FFI):
// This is SAFE and the only use case we support. All references (mutable or not) to Rust
// user objects will be dropped before returning to Lua.
// * Runtime (LuaJIT/Rust) -> Lua (via C) -> Rust (via FFI): This is SAFE and the only use case
// we support. All references (mutable or not) to Rust user objects will be dropped before
// returning to Lua.
//
// * Runtime (LuaJIT/Rust) -> Lua (via C) -> Rust (via FFI) -> Lua (via callback):
// This is UNSAFE because we cannot prevent the Lua callback from calling back into Rust code
// via FFI which could violate exclusive borrow semantics. This is prevented by not
// implementing `FromFfi` for function pointers (see below).
// * Runtime (LuaJIT/Rust) -> Lua (via C) -> Rust (via FFI) -> Lua (via callback): This is
// UNSAFE because we cannot prevent the Lua callback from calling back into Rust code via
// FFI which could violate exclusive borrow semantics. This is prevented by not implementing
// `FromFfi` for function pointers (see below).
//
type From = *mut T;
type FromValue = *mut T;
type FromArg = *mut T;
fn prelude(arg: &str) -> impl Display {
display!(r#"assert({arg} ~= nil, "argument '{arg}' cannot be nil"); "#)
}
fn convert(from: Self::From) -> Self {
Self::convert_value(from)
}
fn convert_value(from: Self::FromValue) -> Self {
debug_assert!(
!from.is_null(),
"<&mut T>::convert() called on a null pointer when it was checked to be non-null"
@@ -742,11 +768,15 @@ unsafe impl<T: Type> FromFfi for &mut T {
unsafe { &mut *from }
}
fn convert_arg(from: Self::FromArg) -> Self {
Self::convert(from)
}
}
//
// SAFETY: No `FromFfi` and `ToFfi` for arrays because passing or returning them by value is not
// a thing in C (they are just pointers).
// SAFETY: No `FromFfi` and `ToFfi` for arrays because passing or returning them by value is not a
// thing in C (they are just pointers).
//
// TODO: we could automatically convert them to tables and vice-versa
//
@@ -786,7 +816,8 @@ macro_rules! impl_function {
(($($type:tt)+), fn($($arg:tt),*) -> $ret:tt) => {
//
// SAFETY: No `FromFfi` for function pointers because of borrow safety invariants (see above in `&mut T`).
// SAFETY: No `FromFfi` for function pointers because of borrow safety invariants (see above
// in `&mut T`).
//
// We also can't implement `ToFfi` because we can't call `FromFfi` and `ToFfi` for the
// function's respective argument and return values.

View File

@@ -1,4 +1,4 @@
use crate::{CDef, CDefBuilder, FromFfi, ToFfi, Type, TypeBuilder, display};
use crate::{CDef, CDefBuilder, FfiReturnConvention, FromFfi, ToFfi, Type, TypeBuilder, display};
use std::{ffi::c_int, fmt::Display, ptr};
#[repr(C)]
@@ -29,34 +29,32 @@ unsafe impl<T: Type> CDef for lua_option<T> {
}
unsafe impl<T: FromFfi> FromFfi for Option<T> {
type From = *mut Self::FromValue; // pass by-ref
type FromValue = lua_option<T::FromValue>;
type From = lua_option<T::From>;
type FromArg = *mut Self::From; // pass by-ref
const ARG_KEEPALIVE: bool = T::ARG_KEEPALIVE;
fn require_keepalive() -> bool {
T::require_keepalive()
}
fn prelude(arg: &str) -> impl Display {
let ct = Self::FromValue::name();
let ct = Self::From::name();
display!(
"if {arg} == nil then {arg} = {ct}(); else {}{arg} = {ct}(1, {arg}); end; ",
"if {arg} == nil then {arg} = __cnew(__ctypes.{ct}); else {}{arg} = __cnew(__ctypes.{ct}, 1, {arg}); end; ",
T::prelude(arg)
)
}
fn convert(from: Self::From) -> Self {
debug_assert!(
!from.is_null(),
"Option<T>::convert() called on a null lua_option<T>"
);
Self::convert_value(unsafe { ptr::replace(from, lua_option::None) })
}
fn convert_value(from: Self::FromValue) -> Self {
match from {
lua_option::Some(value) => Some(T::convert_value(value)),
lua_option::Some(value) => Some(T::convert(value)),
lua_option::None => None,
}
}
fn convert_arg(from: Self::FromArg) -> Self {
debug_assert!(!from.is_null());
Self::convert(unsafe { ptr::replace(from, lua_option::None) })
}
}
unsafe impl<T: ToFfi> ToFfi for Option<T> {
@@ -69,12 +67,12 @@ unsafe impl<T: ToFfi> ToFfi for Option<T> {
}
}
fn postlude(ret: &str) -> impl Display {
fn postlude(ret: &str, _conv: FfiReturnConvention) -> impl Display {
// if we don't have a value, return nil. otherwise copy out the inner value immediately,
// forget the option cdata, then call postlude on the inner value.
display!(
"if {ret}.__tag == 0 then {ret} = nil; else {ret} = {ret}.__value; {}end; ",
T::postlude(ret)
T::postlude(ret, FfiReturnConvention::ByValue)
)
}
}

View File

@@ -2,80 +2,80 @@ use crate::{__internal::disp, FromFfi, IS_UTF8_FN, Type};
use luaffi_impl::{cdef, metatype};
use std::{fmt, ptr, slice};
#[cdef]
#[derive(Debug, Clone, Copy)]
#[cdef]
pub struct lua_buf {
__ptr: *mut u8,
__len: usize,
}
#[metatype]
impl lua_buf {}
impl lua_buf {
#[new]
extern "Lua-C" fn new() -> u32 {
todo!()
}
}
unsafe impl FromFfi for *const [u8] {
type From = *const Self::FromValue; // pass by-ref
type FromValue = lua_buf;
type From = lua_buf;
type FromArg = *const Self::From;
const ARG_KEEPALIVE: bool = true;
fn require_keepalive() -> bool {
true
}
fn prelude(arg: &str) -> impl fmt::Display {
// this converts string arguments to a `lua_buf` with a pointer to the string and its length
disp(move |f| {
let ct = lua_buf::name();
let ct = Self::From::name();
write!(
f,
r#"if {arg} ~= nil then assert(type({arg}) == "string", "string expected in argument '{arg}', got " .. type({arg})); "#
)?;
write!(f, "{arg} = {ct}({arg}, #{arg}); end; ")
write!(f, "{arg} = __cnew(__ctypes.{ct}, {arg}, #{arg}); end; ")
})
}
fn convert(from: Self::From) -> Self {
ptr::slice_from_raw_parts(from.__ptr, from.__len)
}
fn convert_arg(from: Self::FromArg) -> Self {
if from.is_null() {
ptr::slice_from_raw_parts(ptr::null(), 0)
} else {
// SAFETY: this is safe because lua_buf is copyable
unsafe { Self::convert_value(*from) }
Self::convert(unsafe { *from })
}
}
fn convert_value(from: Self::FromValue) -> Self {
ptr::slice_from_raw_parts(from.__ptr, from.__len)
}
}
unsafe impl FromFfi for &str {
type From = *const Self::FromValue; // pass by-ref
type FromValue = lua_buf;
type From = lua_buf;
type FromArg = *const Self::From;
const ARG_KEEPALIVE: bool = true;
fn require_keepalive() -> bool {
true
}
fn prelude(arg: &str) -> impl fmt::Display {
disp(move |f| {
let ct = lua_buf::name();
let ct = Self::From::name();
write!(
f,
r#"assert(type({arg}) == "string", "string expected in argument '{arg}', got " .. type({arg})); "#
)?;
write!(
f,
r#"assert(C.{IS_UTF8_FN}({arg}, #{arg}), "argument '{arg}' must be a valid utf8 string"); "#
r#"assert(__C.{IS_UTF8_FN}({arg}, #{arg}), "argument '{arg}' must be a valid utf-8 string"); "#
)?;
write!(f, "{arg} = {ct}({arg}, #{arg}); ")
write!(f, "{arg} = __cnew(__ctypes.{ct}, {arg}, #{arg}); ")
})
}
fn convert(from: Self::From) -> Self {
debug_assert!(
!from.is_null(),
"<&str>::convert() called on a null lua_buf"
);
// SAFETY: this is safe because lua_buf is copyable
unsafe { Self::convert_value(*from) }
}
fn convert_value(from: Self::FromValue) -> Self {
// SAFETY: we already checked that the string is nonnull and valid utf8 from the lua side
debug_assert!(!from.__ptr.is_null());
let s = unsafe { slice::from_raw_parts(from.__ptr, from.__len) };
debug_assert!(
@@ -83,7 +83,11 @@ unsafe impl FromFfi for &str {
"<&str>::convert() called on an invalid utf8 string when it was checked to be valid"
);
// SAFETY: we already checked that the string is valid utf8 from the lua side
unsafe { std::str::from_utf8_unchecked(s) }
}
fn convert_arg(from: Self::FromArg) -> Self {
debug_assert!(!from.is_null());
unsafe { Self::convert(*from) }
}
}