LuaDevice macro now uses LuaDeviceCreate trait to create devices from configs

This commit is contained in:
2024-04-29 02:53:21 +02:00
parent 9f636a2572
commit 44a40d4dfa
16 changed files with 116 additions and 84 deletions

View File

@@ -1,30 +1,9 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DataStruct, DeriveInput, Fields, FieldsNamed};
use syn::DeriveInput;
pub fn impl_lua_device_macro(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
// TODO: Handle errors properly
// This includes making sure one, and only one config is specified
let config = if let Data::Struct(DataStruct {
fields: Fields::Named(FieldsNamed { ref named, .. }),
..
}) = ast.data
{
named
.iter()
.find(|&field| {
field
.attrs
.iter()
.any(|attr| attr.path().is_ident("config"))
})
.map(|field| field.ty.clone())
.unwrap()
} else {
unimplemented!()
};
let gen = quote! {
impl #name {
pub fn register_with_lua(lua: &mlua::Lua) -> mlua::Result<()> {
@@ -34,8 +13,10 @@ pub fn impl_lua_device_macro(ast: &DeriveInput) -> TokenStream {
impl mlua::UserData for #name {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_function("new", |lua, config: mlua::Value| async {
let config: #config = mlua::FromLua::from_lua(config, lua)?;
let device = #name::create(config).await.map_err(mlua::ExternalError::into_lua_err)?;
let config = mlua::FromLua::from_lua(config, lua)?;
// TODO: Using crate:: could cause issues
let device: #name = crate::devices::LuaDeviceCreate::create(config).await.map_err(mlua::ExternalError::into_lua_err)?;
Ok(crate::device_manager::WrappedDevice::new(Box::new(device)))
});