Skip to content

Commit

Permalink
Make Query::single (and friends) return a Result (#18082)
Browse files Browse the repository at this point in the history
# Objective

As discussed in #14275, Bevy is currently too prone to panic, and makes
the easy / beginner-friendly way to do a large number of operations just
to panic on failure.

This is seriously frustrating in library code, but also slows down
development, as many of the `Query::single` panics can actually safely
be an early return (these panics are often due to a small ordering issue
or a change in game state.

More critically, in most "finished" products, panics are unacceptable:
any unexpected failures should be handled elsewhere. That's where the
new

With the advent of good system error handling, we can now remove this.

Note: I was instrumental in a) introducing this idea in the first place
and b) pushing to make the panicking variant the default. The
introduction of both `let else` statements in Rust and the fancy system
error handling work in 0.16 have changed my mind on the right balance
here.

## Solution

1. Make `Query::single` and `Query::single_mut` (and other random
related methods) return a `Result`.
2. Handle all of Bevy's internal usage of these APIs.
3. Deprecate `Query::get_single` and friends, since we've moved their
functionality to the nice names.
4. Add detailed advice on how to best handle these errors.

Generally I like the diff here, although `get_single().unwrap()` in
tests is a bit of a downgrade.

## Testing

I've done a global search for `.single` to track down any missed
deprecated usages.

As to whether or not all the migrations were successful, that's what CI
is for :)

## Future work

~~Rename `Query::get_single` and friends to `Query::single`!~~

~~I've opted not to do this in this PR, and smear it across two releases
in order to ease the migration. Successive deprecations are much easier
to manage than the semantics and types shifting under your feet.~~

Cart has convinced me to change my mind on this; see
#18082 (comment).

## Migration guide

`Query::single`, `Query::single_mut` and their `QueryState` equivalents
now return a `Result`. Generally, you'll want to:

1. Use Bevy 0.16's system error handling to return a `Result` using the
`?` operator.
2. Use a `let else Ok(data)` block to early return if it's an expected
failure.
3. Use `unwrap()` or `Ok` destructuring inside of tests.

The old `Query::get_single` (etc) methods which did this have been
deprecated.
  • Loading branch information
alice-i-cecile authored Mar 2, 2025
1 parent ff1ae62 commit 2ad5908
Show file tree
Hide file tree
Showing 50 changed files with 261 additions and 268 deletions.
2 changes: 1 addition & 1 deletion crates/bevy_core_pipeline/src/oit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ fn configure_depth_texture_usages(
}

// Find all the render target that potentially uses OIT
let primary_window = p.get_single().ok();
let primary_window = p.single().ok();
let mut render_target_has_oit = <HashSet<_>>::default();
for (camera, has_oit) in &cameras {
if has_oit {
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_dev_tools/src/picking_debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ pub fn debug_draw(
.map(|(entity, camera)| {
(
entity,
camera.target.normalize(primary_window.get_single().ok()),
camera.target.normalize(primary_window.single().ok()),
)
})
.filter_map(|(entity, target)| Some(entity).zip(target))
Expand Down
16 changes: 8 additions & 8 deletions crates/bevy_ecs/compile_fail/tests/ui/query_lifetime_safety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,29 @@ fn main() {
}

{
let data: &Foo = query.single();
let mut data2: Mut<Foo> = query.single_mut();
let data: &Foo = query.single().unwrap();
let mut data2: Mut<Foo> = query.single_mut().unwrap();
//~^ E0502
assert_eq!(data, &mut *data2); // oops UB
}

{
let mut data2: Mut<Foo> = query.single_mut();
let data: &Foo = query.single();
let mut data2: Mut<Foo> = query.single_mut().unwrap();
let data: &Foo = query.single().unwrap();
//~^ E0502
assert_eq!(data, &mut *data2); // oops UB
}

{
let data: &Foo = query.get_single().unwrap();
let mut data2: Mut<Foo> = query.get_single_mut().unwrap();
let data: &Foo = query.single().unwrap();
let mut data2: Mut<Foo> = query.single_mut().unwrap();
//~^ E0502
assert_eq!(data, &mut *data2); // oops UB
}

{
let mut data2: Mut<Foo> = query.get_single_mut().unwrap();
let data: &Foo = query.get_single().unwrap();
let mut data2: Mut<Foo> = query.single_mut().unwrap();
let data: &Foo = query.single().unwrap();
//~^ E0502
assert_eq!(data, &mut *data2); // oops UB
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ error[E0502]: cannot borrow `query` as immutable because it is also borrowed as
error[E0502]: cannot borrow `query` as mutable because it is also borrowed as immutable
--> tests/ui/query_lifetime_safety.rs:45:39
|
44 | let data: &Foo = query.get_single().unwrap();
44 | let data: &Foo = query.single().unwrap();
| ----- immutable borrow occurs here
45 | let mut data2: Mut<Foo> = query.get_single_mut().unwrap();
45 | let mut data2: Mut<Foo> = query.single_mut().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
46 |
47 | assert_eq!(data, &mut *data2); // oops UB
Expand All @@ -56,9 +56,9 @@ error[E0502]: cannot borrow `query` as mutable because it is also borrowed as im
error[E0502]: cannot borrow `query` as immutable because it is also borrowed as mutable
--> tests/ui/query_lifetime_safety.rs:52:30
|
51 | let mut data2: Mut<Foo> = query.get_single_mut().unwrap();
51 | let mut data2: Mut<Foo> = query.single_mut().unwrap();
| ----- mutable borrow occurs here
52 | let data: &Foo = query.get_single().unwrap();
52 | let data: &Foo = query.single().unwrap();
| ^^^^^ immutable borrow occurs here
53 |
54 | assert_eq!(data, &mut *data2); // oops UB
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_ecs/compile_fail/tests/ui/query_to_readonly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ fn for_loops(mut query: Query<&mut Foo>) {
fn single_mut_query(mut query: Query<&mut Foo>) {
// this should fail to compile
{
let mut mut_foo = query.single_mut();
let mut mut_foo = query.single_mut().unwrap();

// This solves "temporary value dropped while borrowed"
let readonly_query = query.as_readonly();
//~^ E0502

let ref_foo = readonly_query.single();
let ref_foo = readonly_query.single().unwrap();

*mut_foo = Foo;

Expand All @@ -55,7 +55,7 @@ fn single_mut_query(mut query: Query<&mut Foo>) {

let ref_foo = readonly_query.single();

let mut mut_foo = query.single_mut();
let mut mut_foo = query.single_mut().unwrap();
//~^ E0502

println!("{ref_foo:?}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ fn main() {
let mut query_a = lens_a.query();
let mut query_b = lens_b.query();

let a = query_a.single_mut();
let b = query_b.single_mut(); // oops 2 mutable references to same Foo
let a = query_a.single_mut().unwrap();
let b = query_b.single_mut().unwrap(); // oops 2 mutable references to same Foo
assert_eq!(*a, *b);
}

Expand All @@ -34,8 +34,8 @@ fn main() {
let mut query_b = lens.query();
//~^ E0499

let a = query_a.single_mut();
let b = query_b.single_mut(); // oops 2 mutable references to same Foo
let a = query_a.single_mut().unwrap();
let b = query_b.single_mut().unwrap(); // oops 2 mutable references to same Foo
assert_eq!(*a, *b);
}
}
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/change_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1557,7 +1557,7 @@ mod tests {
// Since the world is always ahead, as long as changes can't get older than `u32::MAX` (which we ensure),
// the wrapping difference will always be positive, so wraparound doesn't matter.
let mut query = world.query::<Ref<C>>();
assert!(query.single(&world).is_changed());
assert!(query.single(&world).unwrap().is_changed());
}

#[test]
Expand Down
14 changes: 7 additions & 7 deletions crates/bevy_ecs/src/query/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use super::{FilteredAccess, QueryData, QueryFilter};
/// .build();
///
/// // Consume the QueryState
/// let (entity, b) = query.single(&world);
/// let (entity, b) = query.single(&world).unwrap();
/// ```
pub struct QueryBuilder<'w, D: QueryData = (), F: QueryFilter = ()> {
access: FilteredAccess<ComponentId>,
Expand Down Expand Up @@ -297,13 +297,13 @@ mod tests {
.with::<A>()
.without::<C>()
.build();
assert_eq!(entity_a, query_a.single(&world));
assert_eq!(entity_a, query_a.single(&world).unwrap());

let mut query_b = QueryBuilder::<Entity>::new(&mut world)
.with::<A>()
.without::<B>()
.build();
assert_eq!(entity_b, query_b.single(&world));
assert_eq!(entity_b, query_b.single(&world).unwrap());
}

#[test]
Expand All @@ -319,13 +319,13 @@ mod tests {
.with_id(component_id_a)
.without_id(component_id_c)
.build();
assert_eq!(entity_a, query_a.single(&world));
assert_eq!(entity_a, query_a.single(&world).unwrap());

let mut query_b = QueryBuilder::<Entity>::new(&mut world)
.with_id(component_id_a)
.without_id(component_id_b)
.build();
assert_eq!(entity_b, query_b.single(&world));
assert_eq!(entity_b, query_b.single(&world).unwrap());
}

#[test]
Expand Down Expand Up @@ -385,7 +385,7 @@ mod tests {
.data::<&B>()
.build();

let entity_ref = query.single(&world);
let entity_ref = query.single(&world).unwrap();

assert_eq!(entity, entity_ref.id());

Expand All @@ -408,7 +408,7 @@ mod tests {
.ref_id(component_id_b)
.build();

let entity_ref = query.single(&world);
let entity_ref = query.single(&world).unwrap();

assert_eq!(entity, entity_ref.id());

Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/query/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl<'w> PartialEq for QueryEntityError<'w> {
impl<'w> Eq for QueryEntityError<'w> {}

/// An error that occurs when evaluating a [`Query`](crate::system::Query) or [`QueryState`](crate::query::QueryState) as a single expected result via
/// [`get_single`](crate::system::Query::get_single) or [`get_single_mut`](crate::system::Query::get_single_mut).
/// [`single`](crate::system::Query::single) or [`single_mut`](crate::system::Query::single_mut).
#[derive(Debug, Error)]
pub enum QuerySingleError {
/// No entity fits the query.
Expand Down
8 changes: 4 additions & 4 deletions crates/bevy_ecs/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,8 +763,8 @@ mod tests {
let _: Option<&Foo> = q.get(&world, e).ok();
let _: Option<&Foo> = q.get_manual(&world, e).ok();
let _: Option<[&Foo; 1]> = q.get_many(&world, [e]).ok();
let _: Option<&Foo> = q.get_single(&world).ok();
let _: &Foo = q.single(&world);
let _: Option<&Foo> = q.single(&world).ok();
let _: &Foo = q.single(&world).unwrap();

// system param
let mut q = SystemState::<Query<&mut Foo>>::new(&mut world);
Expand All @@ -776,9 +776,9 @@ mod tests {

let _: Option<&Foo> = q.get(e).ok();
let _: Option<[&Foo; 1]> = q.get_many([e]).ok();
let _: Option<&Foo> = q.get_single().ok();
let _: Option<&Foo> = q.single().ok();
let _: [&Foo; 1] = q.many([e]);
let _: &Foo = q.single();
let _: &Foo = q.single().unwrap();
}

// regression test for https://github.com/bevyengine/bevy/pull/8029
Expand Down
Loading

0 comments on commit 2ad5908

Please sign in to comment.