Skip to content

Commit 994e5e0

Browse files
committed
Allow a closure to be used as a required component default
1 parent 20dbf79 commit 994e5e0

File tree

1 file changed

+44
-22
lines changed

1 file changed

+44
-22
lines changed

crates/bevy_ecs/macros/src/component.rs

Lines changed: 44 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use syn::{
99
punctuated::Punctuated,
1010
spanned::Spanned,
1111
token::{Comma, Paren},
12-
DeriveInput, ExprPath, Ident, LitStr, Path, Result,
12+
DeriveInput, ExprClosure, ExprPath, Ident, LitStr, Path, Result,
1313
};
1414

1515
pub fn derive_event(input: TokenStream) -> TokenStream {
@@ -90,24 +90,37 @@ pub fn derive_component(input: TokenStream) -> TokenStream {
9090
inheritance_depth + 1
9191
);
9292
});
93-
if let Some(func) = &require.func {
94-
register_required.push(quote! {
95-
components.register_required_components_manual::<Self, #ident>(
96-
storages,
97-
required_components,
98-
|| { let x: #ident = #func().into(); x },
99-
inheritance_depth
100-
);
101-
});
102-
} else {
103-
register_required.push(quote! {
104-
components.register_required_components_manual::<Self, #ident>(
105-
storages,
106-
required_components,
107-
<#ident as Default>::default,
108-
inheritance_depth
109-
);
110-
});
93+
match &require.func {
94+
Some(RequireFunc::Path(func)) => {
95+
register_required.push(quote! {
96+
components.register_required_components_manual::<Self, #ident>(
97+
storages,
98+
required_components,
99+
|| { let x: #ident = #func().into(); x },
100+
inheritance_depth
101+
);
102+
});
103+
}
104+
Some(RequireFunc::Closure(func)) => {
105+
register_required.push(quote! {
106+
components.register_required_components_manual::<Self, #ident>(
107+
storages,
108+
required_components,
109+
|| { let x: #ident = (#func)().into(); x },
110+
inheritance_depth
111+
);
112+
});
113+
}
114+
None => {
115+
register_required.push(quote! {
116+
components.register_required_components_manual::<Self, #ident>(
117+
storages,
118+
required_components,
119+
<#ident as Default>::default,
120+
inheritance_depth
121+
);
122+
});
123+
}
111124
}
112125
}
113126
}
@@ -180,7 +193,12 @@ enum StorageTy {
180193

181194
struct Require {
182195
path: Path,
183-
func: Option<Path>,
196+
func: Option<RequireFunc>,
197+
}
198+
199+
enum RequireFunc {
200+
Path(Path),
201+
Closure(ExprClosure),
184202
}
185203

186204
// values for `storage` attribute
@@ -256,8 +274,12 @@ impl Parse for Require {
256274
let func = if input.peek(Paren) {
257275
let content;
258276
parenthesized!(content in input);
259-
let func = content.parse::<Path>()?;
260-
Some(func)
277+
if let Ok(func) = content.parse::<ExprClosure>() {
278+
Some(RequireFunc::Closure(func))
279+
} else {
280+
let func = content.parse::<Path>()?;
281+
Some(RequireFunc::Path(func))
282+
}
261283
} else {
262284
None
263285
};

0 commit comments

Comments
 (0)