Skip to content

Commit 8c63cc0

Browse files
committed
Allow #[cfg] to be used in #[godot_api] virtual impls
1 parent 844f0f3 commit 8c63cc0

File tree

4 files changed

+150
-15
lines changed

4 files changed

+150
-15
lines changed

godot-macros/src/class/godot_api.rs

+106-15
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,30 @@ where
381381

382382
// ----------------------------------------------------------------------------------------------------------------------------------------------
383383

384+
/// Expects either Some(quote! { () => A, () => B, ... }) or None as the 'tokens' parameter.
385+
/// The idea is that the () => ... arms can be annotated by cfg attrs, so, if any of them compiles (and assuming the cfg
386+
/// attrs only allow one arm to 'survive' compilation), their return value (Some(...)) will be prioritized over the
387+
/// 'None' from the catch-all arm at the end. If, however, none of them compile, then None is returned from the last
388+
/// match arm.
389+
fn convert_to_match_expression_or_none(tokens: Option<TokenStream>) -> TokenStream {
390+
if let Some(tokens) = tokens {
391+
quote! {
392+
{
393+
// When one of the () => ... arms is present, the last arm intentionally won't ever match.
394+
#[allow(unreachable_patterns)]
395+
// Don't warn when only _ => None is present as all () => ... arms were removed from compilation.
396+
#[allow(clippy::match_single_binding)]
397+
match () {
398+
#tokens
399+
_ => None,
400+
}
401+
}
402+
}
403+
} else {
404+
quote! { None }
405+
}
406+
}
407+
384408
/// Codegen for `#[godot_api] impl GodotExt for MyType`
385409
fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
386410
let (class_name, trait_name) = util::validate_trait_impl_virtual(&original_impl, "godot_api")?;
@@ -391,13 +415,14 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
391415
let mut register_class_impl = TokenStream::new();
392416
let mut on_notification_impl = TokenStream::new();
393417

394-
let mut register_fn = quote! { None };
395-
let mut create_fn = quote! { None };
396-
let mut recreate_fn = quote! { None };
397-
let mut to_string_fn = quote! { None };
398-
let mut on_notification_fn = quote! { None };
418+
let mut register_fn = None;
419+
let mut create_fn = None;
420+
let mut recreate_fn = None;
421+
let mut to_string_fn = None;
422+
let mut on_notification_fn = None;
399423

400424
let mut virtual_methods = vec![];
425+
let mut virtual_method_cfg_attrs = vec![];
401426
let mut virtual_method_names = vec![];
402427

403428
let prv = quote! { ::godot::private };
@@ -409,52 +434,99 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
409434
continue;
410435
};
411436

437+
// Transport #[cfg] attributes to the virtual method's FFI glue, to ensure it won't be
438+
// registered in Godot if conditionally removed from compilation.
439+
let cfg_attrs = util::extract_cfg_attrs(&method.attributes)
440+
.into_iter()
441+
.collect::<Vec<_>>();
412442
let method_name = method.name.to_string();
413443
match method_name.as_str() {
414444
"register_class" => {
445+
// Implements the trait once for each implementation of this method, forwarding the cfg attrs of each
446+
// implementation to the generated trait impl. If the cfg attrs allow for multiple implementations of
447+
// this method to exist, then Rust will generate an error, so we don't have to worry about the multiple
448+
// trait implementations actually generating an error, since that can only happen if multiple
449+
// implementations of the same method are kept by #[cfg] (due to user error).
450+
// Thus, by implementing the trait once for each possible implementation of this method (depending on
451+
// what #[cfg] allows), forwarding the cfg attrs, we ensure this trait impl will remain in the code if
452+
// at least one of the method impls are kept.
415453
register_class_impl = quote! {
454+
#register_class_impl
455+
456+
#(#cfg_attrs)*
416457
impl ::godot::obj::cap::GodotRegisterClass for #class_name {
417458
fn __godot_register_class(builder: &mut ::godot::builder::GodotBuilder<Self>) {
418459
<Self as #trait_name>::register_class(builder)
419460
}
420461
}
421462
};
422463

423-
register_fn = quote! {
424-
Some(#prv::ErasedRegisterFn {
464+
// Adds a match arm for each implementation of this method, transferring its respective cfg attrs to
465+
// the corresponding match arm (see explanation for the match after this loop).
466+
// In principle, the cfg attrs will allow only either 0 or 1 of a function with this name to exist,
467+
// unless there are duplicate implementations for the same method, which should error anyway.
468+
// Thus, in any correct program, the match arms (which are, in principle, identical) will be reduced to
469+
// a single one at most, since we forward the cfg attrs. The idea here is precisely to keep this
470+
// specific match arm 'alive' if at least one implementation of the method is also kept (hence why all
471+
// the match arms are identical).
472+
register_fn = Some(quote! {
473+
#register_fn
474+
#(#cfg_attrs)*
475+
() => Some(#prv::ErasedRegisterFn {
425476
raw: #prv::callbacks::register_class_by_builder::<#class_name>
426-
})
427-
};
477+
}),
478+
});
428479
}
429480

430481
"init" => {
431482
godot_init_impl = quote! {
483+
#godot_init_impl
484+
485+
#(#cfg_attrs)*
432486
impl ::godot::obj::cap::GodotInit for #class_name {
433487
fn __godot_init(base: ::godot::obj::Base<Self::Base>) -> Self {
434488
<Self as #trait_name>::init(base)
435489
}
436490
}
437491
};
438-
create_fn = quote! { Some(#prv::callbacks::create::<#class_name>) };
492+
create_fn = Some(quote! {
493+
#create_fn
494+
#(#cfg_attrs)*
495+
() => Some(#prv::callbacks::create::<#class_name>),
496+
});
439497
if cfg!(since_api = "4.2") {
440-
recreate_fn = quote! { Some(#prv::callbacks::recreate::<#class_name>) };
498+
recreate_fn = Some(quote! {
499+
#recreate_fn
500+
#(#cfg_attrs)*
501+
() => Some(#prv::callbacks::recreate::<#class_name>),
502+
});
441503
}
442504
}
443505

444506
"to_string" => {
445507
to_string_impl = quote! {
508+
#to_string_impl
509+
510+
#(#cfg_attrs)*
446511
impl ::godot::obj::cap::GodotToString for #class_name {
447512
fn __godot_to_string(&self) -> ::godot::builtin::GodotString {
448513
<Self as #trait_name>::to_string(self)
449514
}
450515
}
451516
};
452517

453-
to_string_fn = quote! { Some(#prv::callbacks::to_string::<#class_name>) };
518+
to_string_fn = Some(quote! {
519+
#to_string_fn
520+
#(#cfg_attrs)*
521+
() => Some(#prv::callbacks::to_string::<#class_name>),
522+
});
454523
}
455524

456525
"on_notification" => {
457526
on_notification_impl = quote! {
527+
#on_notification_impl
528+
529+
#(#cfg_attrs)*
458530
impl ::godot::obj::cap::GodotNotification for #class_name {
459531
fn __godot_notification(&mut self, what: i32) {
460532
if ::godot::private::is_class_inactive(Self::__config().is_tool) {
@@ -466,9 +538,11 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
466538
}
467539
};
468540

469-
on_notification_fn = quote! {
470-
Some(#prv::callbacks::on_notification::<#class_name>)
471-
};
541+
on_notification_fn = Some(quote! {
542+
#on_notification_fn
543+
#(#cfg_attrs)*
544+
() => Some(#prv::callbacks::on_notification::<#class_name>),
545+
});
472546
}
473547

474548
// Other virtual methods, like ready, process etc.
@@ -487,6 +561,11 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
487561
} else {
488562
format!("_{method_name}")
489563
};
564+
// Note that, if the same method is implemented multiple times (with different cfg attr combinations),
565+
// then there will be multiple match arms annotated with the same cfg attr combinations, thus they will
566+
// be reduced to just one arm (at most, if the implementations aren't all removed from compilation) for
567+
// each distinct method.
568+
virtual_method_cfg_attrs.push(cfg_attrs);
490569
virtual_method_names.push(virtual_method_name);
491570
virtual_methods.push(method);
492571
}
@@ -498,6 +577,17 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
498577
.map(|method| make_virtual_method_callback(&class_name, method))
499578
.collect();
500579

580+
// Use 'match' as a way to only emit 'Some(...)' if the given cfg attrs allow.
581+
// This permits users to conditionally remove virtual method impls from compilation while also removing their FFI
582+
// glue which would otherwise make them visible to Godot even if not really implemented.
583+
// Needs '#[allow(unreachable_patterns)]' to avoid warnings about the last match arm.
584+
// Also requires '#[allow(clippy::match_single_binding)]' for similar reasons.
585+
let register_fn = convert_to_match_expression_or_none(register_fn);
586+
let create_fn = convert_to_match_expression_or_none(create_fn);
587+
let recreate_fn = convert_to_match_expression_or_none(recreate_fn);
588+
let to_string_fn = convert_to_match_expression_or_none(to_string_fn);
589+
let on_notification_fn = convert_to_match_expression_or_none(on_notification_fn);
590+
501591
let result = quote! {
502592
#original_impl
503593
#godot_init_impl
@@ -517,6 +607,7 @@ fn transform_trait_impl(original_impl: Impl) -> Result<TokenStream, Error> {
517607

518608
match name {
519609
#(
610+
#(#virtual_method_cfg_attrs)*
520611
#virtual_method_names => #virtual_method_callbacks,
521612
)*
522613
_ => None,

godot-macros/src/util/mod.rs

+9
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,15 @@ pub(crate) fn path_ends_with(path: &[TokenTree], expected: &str) -> bool {
227227
.unwrap_or(false)
228228
}
229229

230+
pub(crate) fn extract_cfg_attrs(
231+
attrs: &[venial::Attribute],
232+
) -> impl IntoIterator<Item = &venial::Attribute> {
233+
attrs.iter().filter(|attr| {
234+
attr.get_single_path_segment()
235+
.map_or(false, |name| name == "cfg")
236+
})
237+
}
238+
230239
pub(crate) struct DeclInfo {
231240
pub where_: Option<WhereClause>,
232241
pub generic_params: Option<GenericParamList>,

itest/rust/src/object_tests/virtual_methods_test.rs

+5
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,11 @@ impl Node2DVirtual for ReadyVirtualTest {
7676
fn ready(&mut self) {
7777
self.implementation_value += 1;
7878
}
79+
80+
#[cfg(any())]
81+
fn to_string(&self) -> GodotString {
82+
compile_error!("Removed by #[cfg]")
83+
}
7984
}
8085

8186
// ----------------------------------------------------------------------------------------------------------------------------------------------

itest/rust/src/register_tests/func_test.rs

+30
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,34 @@ impl RefCountedVirtual for GdSelfReference {
147147
base,
148148
}
149149
}
150+
151+
#[cfg(any())]
152+
fn init(base: Base<Self::Base>) -> Self {
153+
compile_error!("Removed by #[cfg]")
154+
}
155+
156+
#[cfg(all())]
157+
fn to_string(&self) -> GodotString {
158+
GodotString::new()
159+
}
160+
161+
#[cfg(any())]
162+
fn register_class() {
163+
compile_error!("Removed by #[cfg]");
164+
}
165+
166+
#[cfg(all())]
167+
fn on_notification(&mut self, _: godot::engine::notify::ObjectNotification) {
168+
godot_print!("Hello!");
169+
}
170+
171+
#[cfg(any())]
172+
fn on_notification(&mut self, _: godot::engine::notify::ObjectNotification) {
173+
compile_error!("Removed by #[cfg]");
174+
}
175+
176+
#[cfg(any())]
177+
fn cfg_removes_this() {
178+
compile_error!("Removed by #[cfg]");
179+
}
150180
}

0 commit comments

Comments
 (0)