Skip to content

wip: allow custom derive to work on generics #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions godot-macros/src/derive_godot_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{util, ParseResult};
use proc_macro2::{Ident, Punct, Span, TokenStream};
use quote::spanned::Spanned;
use quote::{format_ident, quote};
use venial::{Attribute, NamedField, Struct, StructFields, TyExpr};
use venial::{Attribute, GenericParamList, NamedField, Struct, StructFields, TyExpr, WhereClause};

pub fn transform(input: TokenStream) -> ParseResult<TokenStream> {
let decl = venial::parse_declaration(input)?;
Expand All @@ -25,22 +25,24 @@ pub fn transform(input: TokenStream) -> ParseResult<TokenStream> {
let base_ty_str = struct_cfg.base_ty.to_string();
let class_name = &class.name;
let class_name_str = class.name.to_string();
let generics = &class.generic_params;
let where_clause = &class.where_clause;
let inherits_macro = format_ident!("inherits_transitive_{}", &base_ty_str);

let prv = quote! { ::godot::private };
let deref_impl = make_deref_impl(class_name, &fields);
let deref_impl = make_deref_impl(class_name, generics, where_clause, &fields);

let (godot_init_impl, create_fn);
if struct_cfg.has_generated_init {
godot_init_impl = make_godot_init_impl(class_name, fields);
godot_init_impl = make_godot_init_impl(class_name, generics, where_clause, fields);
create_fn = quote! { Some(#prv::callbacks::create::<#class_name>) };
} else {
godot_init_impl = TokenStream::new();
create_fn = quote! { None };
};

Ok(quote! {
impl ::godot::obj::GodotClass for #class_name {
impl #generics ::godot::obj::GodotClass for #class_name #generics #where_clause {
type Base = ::godot::engine::#base_ty;
type Declarer = ::godot::obj::dom::UserDomain;
type Mem = <Self::Base as ::godot::obj::GodotClass>::Mem;
Expand Down Expand Up @@ -208,7 +210,7 @@ impl ExportedField {
}
}

fn make_godot_init_impl(class_name: &Ident, fields: Fields) -> TokenStream {
fn make_godot_init_impl(class_name: &Ident, generics: &Option<GenericParamList>, where_clause: &Option<WhereClause>, fields: Fields) -> TokenStream {
let base_init = if let Some(ExportedField { name, .. }) = fields.base_field {
quote! { #name: base, }
} else {
Expand All @@ -220,7 +222,7 @@ fn make_godot_init_impl(class_name: &Ident, fields: Fields) -> TokenStream {
});

quote! {
impl ::godot::obj::cap::GodotInit for #class_name {
impl #generics ::godot::obj::cap::GodotInit for #class_name #generics #where_clause {
fn __godot_init(base: ::godot::obj::Base<Self::Base>) -> Self {
Self {
#( #rest_init )*
Expand All @@ -231,22 +233,22 @@ fn make_godot_init_impl(class_name: &Ident, fields: Fields) -> TokenStream {
}
}

fn make_deref_impl(class_name: &Ident, fields: &Fields) -> TokenStream {
fn make_deref_impl(class_name: &Ident, generics: &Option<GenericParamList>, where_clause: &Option<WhereClause>, fields: &Fields) -> TokenStream {
let base_field = if let Some(ExportedField { name, .. }) = &fields.base_field {
name
} else {
return TokenStream::new();
};

quote! {
impl std::ops::Deref for #class_name {
impl #generics std::ops::Deref for #class_name #generics #where_clause {
type Target = <Self as ::godot::obj::GodotClass>::Base;

fn deref(&self) -> &Self::Target {
&*self.#base_field
}
}
impl std::ops::DerefMut for #class_name {
impl #generics std::ops::DerefMut for #class_name #generics #where_clause {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *self.#base_field
}
Expand Down
19 changes: 8 additions & 11 deletions godot-macros/src/godot_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,6 @@ pub fn transform(input: TokenStream) -> Result<TokenStream, Error> {
)?,
};

if decl.impl_generic_params.is_some() {
bail(
"#[godot_api] currently does not support generic parameters",
&decl,
)?;
}

if decl.self_ty.as_path().is_none() {
return bail("invalid Self type for #[godot_api] impl", decl);
};
Expand Down Expand Up @@ -71,13 +64,15 @@ fn transform_inherent_impl(mut decl: Impl) -> Result<TokenStream, Error> {

let (funcs, signals) = process_godot_fns(&mut decl)?;
let signal_name_strs = signals.into_iter().map(|ident| ident.to_string());
let generics = &decl.impl_generic_params;
let where_clause = &decl.where_clause;

let prv = quote! { ::godot::private };

let result = quote! {
#decl

impl ::godot::obj::cap::ImplementsGodotApi for #class_name {
impl #generics ::godot::obj::cap::ImplementsGodotApi for #class_name #generics #where_clause {
//fn __register_methods(_builder: &mut ::godot::builder::ClassBuilder<Self>) {
fn __register_methods() {
#(
Expand Down Expand Up @@ -218,6 +213,8 @@ fn extract_attributes(method: &Function) -> Result<Option<BoundAttr>, Error> {
fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
let class_name = util::validate_impl(&original_impl, Some("GodotExt"), "godot_api")?;
let class_name_str = class_name.to_string();
let generics = &original_impl.impl_generic_params;
let where_clause = &original_impl.where_clause;

let mut godot_init_impl = TokenStream::new();
let mut register_fn = quote! { None };
Expand Down Expand Up @@ -245,7 +242,7 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {

"init" => {
godot_init_impl = quote! {
impl ::godot::obj::cap::GodotInit for #class_name {
impl #generics ::godot::obj::cap::GodotInit for #class_name #generics #where_clause {
fn __godot_init(base: ::godot::obj::Base<Self::Base>) -> Self {
<Self as ::godot::bind::GodotExt>::init(base)
}
Expand Down Expand Up @@ -281,9 +278,9 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
#original_impl
#godot_init_impl

impl ::godot::private::You_forgot_the_attribute__godot_api for #class_name {}
impl #generics ::godot::private::You_forgot_the_attribute__godot_api for #class_name #generics #where_clause {}

impl ::godot::obj::cap::ImplementsGodotExt for #class_name {
impl #generics ::godot::obj::cap::ImplementsGodotExt for #class_name #generics #where_clause {
fn __virtual_call(name: &str) -> ::godot::sys::GDNativeExtensionClassCallVirtual {
//println!("virtual_call: {}.{}", std::any::type_name::<Self>(), name);

Expand Down
9 changes: 1 addition & 8 deletions godot-macros/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,7 @@ pub(crate) fn validate_impl(

// impl Trait for Self -- validate Self
if let Some(segment) = extract_typename(&original_impl.self_ty) {
if segment.generic_args.is_none() {
Ok(segment.ident)
} else {
bail(
format!("#[{attr}] for does currently not support generic arguments"),
&original_impl,
)
}
Ok(segment.ident)
} else {
bail(
format!("#[{attr}] requires Self type to be a simple path"),
Expand Down
1 change: 1 addition & 0 deletions itest/godot/itest.gdextension
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ entry_symbol = "itest_init"
[libraries]
linux.64 = "res://../../target/debug/libitest.so"
windows.64 = "res://../../target/debug/itest.dll"
macos.x86_64 = "res://../../target/debug/libitest.dylib"
63 changes: 63 additions & 0 deletions itest/rust/src/generic_struct_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

#![allow(dead_code)]

use std::fmt::Debug;
use godot::bind::{godot_api, GodotClass, GodotExt};
use godot::engine::Node;
use godot::obj::{Base, Gd};
use godot::test::itest;
use std::marker::PhantomData;

/// A simple abstractio to see if we can derive GodotClass for Generic Structs
trait Abstraction {}
#[derive(Debug)]
struct A {}
#[derive(Debug)]
struct B {}
impl Abstraction for A {}
impl Abstraction for B {}


#[derive(GodotClass, Debug)]
#[class(init, base=Node)]
struct GenericStructTest<T> where T: Abstraction + Debug {
#[base]
some_base: Base<Node>,
// Use phantom data so we're _only_ testing the generic aspect
phantom_data: PhantomData<T>
}

#[godot_api]
impl<T> GenericStructTest<T> where T: Abstraction + Debug {
fn get_phantom_data(&self) -> String {
format!("{:?}", self.phantom_data)
}
}

#[godot_api]
impl<T> GodotExt for GenericStructTest<T> where T: Abstraction + Debug {}

pub(crate) fn run() -> bool {
let mut ok = true;
ok &= test_to_string();
ok
}

// pub(crate) fn register() {
// godot::register_class::<VirtualMethodTest>();
// }

// ----------------------------------------------------------------------------------------------------------------------------------------------

#[itest]
fn test_to_string() {
let _obj1 = Gd::<GenericStructTest<A>>::new_default();
dbg!(_obj1);
let _obj2 = Gd::<GenericStructTest<B>>::new_default();
dbg!(_obj2);
}
2 changes: 2 additions & 0 deletions itest/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::panic::UnwindSafe;
mod base_test;
mod enum_test;
mod gdscript_ffi_test;
mod generic_struct_test;
mod node_test;
mod object_test;
mod singleton_test;
Expand All @@ -24,6 +25,7 @@ fn run_tests() -> bool {
let mut ok = true;
ok &= base_test::run();
ok &= gdscript_ffi_test::run();
ok &= generic_struct_test::run();
ok &= node_test::run();
ok &= enum_test::run();
ok &= object_test::run();
Expand Down