Skip to content

Commit bb01a9f

Browse files
Raise compile error when using non-static lifetimes in #[derive(Resource)] (#21385)
# Objective Fixes #20413 Adding non-static lifetimes to `#[derive(Resource)]` should not compile. ## Solution Added a check in the derive macro of `Resource` to ensure all lifetime generics are bound to 'static, if not it raises an error. ## Testing Added a ui-test for compile error. --------- Co-authored-by: Chris Russell <[email protected]>
1 parent 4e44fcc commit bb01a9f

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use bevy_ecs::prelude::*;
2+
3+
#[derive(Resource)]
4+
//~v ERROR: Lifetimes must be 'static
5+
struct A<'a> {
6+
foo: &'a str,
7+
}
8+
9+
#[derive(Resource)]
10+
struct B<'a: 'static> {
11+
foo: &'a str,
12+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: Lifetimes must be 'static
2+
--> tests/ui/resource_derive.rs:5:10
3+
|
4+
5 | struct A<'a> {
5+
| ^^
6+
7+
error: aborting due to 1 previous error
8+

crates/bevy_ecs/macros/src/component.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,21 @@ pub fn derive_resource(input: TokenStream) -> TokenStream {
1717
let mut ast = parse_macro_input!(input as DeriveInput);
1818
let bevy_ecs_path: Path = crate::bevy_ecs_path();
1919

20+
// We want to raise a compile time error when the generic lifetimes
21+
// are not bound to 'static lifetime
22+
let non_static_lifetime_error = ast
23+
.generics
24+
.lifetimes()
25+
.filter(|lifetime| !lifetime.bounds.iter().any(|bound| bound.ident == "static"))
26+
.map(|param| syn::Error::new(param.span(), "Lifetimes must be 'static"))
27+
.reduce(|mut err_acc, err| {
28+
err_acc.combine(err);
29+
err_acc
30+
});
31+
if let Some(err) = non_static_lifetime_error {
32+
return err.into_compile_error().into();
33+
}
34+
2035
ast.generics
2136
.make_where_clause()
2237
.predicates
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
title: Derive on Resource will fail when using non-static lifetimes
3+
pull_requests: [21385]
4+
---
5+
6+
Any type with `#[derive(Resource)]` that uses non-static lifetime will no longer compile.
7+
8+
```rust
9+
// Will no longer compile in 0.18,
10+
// 'a should be 'static
11+
#[derive(Resource)]
12+
struct Foo<'a> {
13+
bar: &'a str
14+
}
15+
```

0 commit comments

Comments
 (0)