Skip to content

Commit

Permalink
Allow #[cfg] to be used in #[godot_api] virtual impls
Browse files Browse the repository at this point in the history
  • Loading branch information
PgBiel committed Oct 12, 2023
1 parent 3491d7b commit c0dac5f
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 7 deletions.
56 changes: 49 additions & 7 deletions godot-macros/src/class/godot_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
let mut on_notification_fn = quote! { None };

let mut virtual_methods = vec![];
let mut virtual_method_cfg_attrs = vec![];
let mut virtual_method_names = vec![];

let prv = quote! { ::godot::private };
Expand All @@ -409,52 +410,85 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
continue;
};

// Transport #[cfg] attributes to the virtual method's FFI glue, to ensure it won't be
// registered in Godot if conditionally removed from compilation.
let cfg_attrs = util::extract_cfg_attrs(&method.attributes)
.into_iter()
.collect::<Vec<_>>();
let method_name = method.name.to_string();
match method_name.as_str() {
"register_class" => {
register_class_impl = quote! {
#(#cfg_attrs)*
impl ::godot::obj::cap::GodotRegisterClass for #class_name {
fn __godot_register_class(builder: &mut ::godot::builder::GodotBuilder<Self>) {
<Self as #trait_name>::register_class(builder)
}
}
};

// Use 'match' as a way to only return 'Some(...)' if the given cfg attrs allow.
// Needs '#[allow(unreachable_patterns)]' to avoid warnings about the last arm.
register_fn = quote! {
Some(#prv::ErasedRegisterFn {
raw: #prv::callbacks::register_class_by_builder::<#class_name>
})
match () {
#(#cfg_attrs)*
() => Some(#prv::ErasedRegisterFn {
raw: #prv::callbacks::register_class_by_builder::<#class_name>
}),
_ => None,
}
};
}

"init" => {
godot_init_impl = quote! {
#(#cfg_attrs)*
impl ::godot::obj::cap::GodotInit for #class_name {
fn __godot_init(base: ::godot::obj::Base<Self::Base>) -> Self {
<Self as #trait_name>::init(base)
}
}
};
create_fn = quote! { Some(#prv::callbacks::create::<#class_name>) };
create_fn = quote! {
match () {
#(#cfg_attrs)*
() => Some(#prv::callbacks::create::<#class_name>),
_ => None,
}
};
if cfg!(since_api = "4.2") {
recreate_fn = quote! { Some(#prv::callbacks::recreate::<#class_name>) };
recreate_fn = quote! {
match () {
#(#cfg_attrs)*
() => Some(#prv::callbacks::recreate::<#class_name>),
_ => None,
}
};
}
}

"to_string" => {
to_string_impl = quote! {
#(#cfg_attrs)*
impl ::godot::obj::cap::GodotToString for #class_name {
fn __godot_to_string(&self) -> ::godot::builtin::GodotString {
<Self as #trait_name>::to_string(self)
}
}
};

to_string_fn = quote! { Some(#prv::callbacks::to_string::<#class_name>) };
to_string_fn = quote! {
match () {
#(#cfg_attrs)*
() => Some(#prv::callbacks::to_string::<#class_name>),
_ => None,
}
};
}

"on_notification" => {
on_notification_impl = quote! {
#(#cfg_attrs)*
impl ::godot::obj::cap::GodotNotification for #class_name {
fn __godot_notification(&mut self, what: i32) {
if ::godot::private::is_class_inactive(Self::__config().is_tool) {
Expand All @@ -467,7 +501,11 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
};

on_notification_fn = quote! {
Some(#prv::callbacks::on_notification::<#class_name>)
match () {
#(#cfg_attrs)*
() => Some(#prv::callbacks::on_notification::<#class_name>),
_ => None,
}
};
}

Expand All @@ -487,6 +525,7 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
} else {
format!("_{method_name}")
};
virtual_method_cfg_attrs.push(cfg_attrs);
virtual_method_names.push(virtual_method_name);
virtual_methods.push(method);
}
Expand Down Expand Up @@ -517,6 +556,7 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {

match name {
#(
#(#virtual_method_cfg_attrs)*
#virtual_method_names => #virtual_method_callbacks,
)*
_ => None,
Expand All @@ -526,6 +566,8 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {

::godot::sys::plugin_add!(__GODOT_PLUGIN_REGISTRY in #prv; #prv::ClassPlugin {
class_name: #class_name_obj,
#[allow(unreachable_patterns)] // due to the cfg-based match statements
#[allow(clippy::match_single_binding)] // avoid warning on single-arm matches
component: #prv::PluginComponent::UserVirtuals {
user_register_fn: #register_fn,
user_create_fn: #create_fn,
Expand Down
9 changes: 9 additions & 0 deletions godot-macros/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,15 @@ pub(crate) fn path_ends_with(path: &[TokenTree], expected: &str) -> bool {
.unwrap_or(false)
}

pub(crate) fn extract_cfg_attrs(
attrs: &[venial::Attribute],
) -> impl IntoIterator<Item = &venial::Attribute> {
attrs.iter().filter(|attr| {
attr.get_single_path_segment()
.map_or(false, |name| name == "cfg")
})
}

pub(crate) struct DeclInfo {
pub where_: Option<WhereClause>,
pub generic_params: Option<GenericParamList>,
Expand Down
5 changes: 5 additions & 0 deletions itest/rust/src/object_tests/virtual_methods_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ impl Node2DVirtual for ReadyVirtualTest {
fn ready(&mut self) {
self.implementation_value += 1;
}

#[cfg(any())]
fn to_string(&self) -> GodotString {
compile_error!("Removed by #[cfg]")
}
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
Expand Down
30 changes: 30 additions & 0 deletions itest/rust/src/register_tests/func_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,34 @@ impl RefCountedVirtual for GdSelfReference {
base,
}
}

#[cfg(any())]
fn init(base: Base<Self::Base>) -> Self {
compile_error!("Removed by #[cfg]")
}

#[cfg(all())]
fn to_string(&self) -> GodotString {
GodotString::new()
}

#[cfg(any())]
fn register_class() {
compile_error!("Removed by #[cfg]");
}

#[cfg(all())]
fn on_notification(&mut self, _: godot::engine::notify::ObjectNotification) {
godot_print!("Hello!");
}

#[cfg(any())]
fn on_notification(&mut self, _: godot::engine::notify::ObjectNotification) {
compile_error!("Removed by #[cfg]");
}

#[cfg(any())]
fn cfg_removes_this() {
compile_error!("Removed by #[cfg]");
}
}

0 comments on commit c0dac5f

Please sign in to comment.