Skip to content

Compile Time Query checking and System Parameters #17837

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/bevy_core_pipeline/src/oit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ impl Default for OrderIndependentTransparencySettings {
// we can hook on_add to issue a warning in case `layer_count` is seemingly too high.
impl Component for OrderIndependentTransparencySettings {
const STORAGE_TYPE: StorageType = StorageType::SparseSet;
const UNSTABLE_TYPE_ID: u128 = 28539417283523;
type Mutability = Mutable;

fn on_add() -> Option<ComponentHook> {
Expand Down
8 changes: 7 additions & 1 deletion crates/bevy_ecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ categories = ["game-engines", "data-structures"]
rust-version = "1.83.0"

[features]
default = ["std", "bevy_reflect", "async_executor"]
default = ["std", "bevy_reflect", "async_executor", "diagnostic_component_names"]

# Functionality

Expand Down Expand Up @@ -53,6 +53,11 @@ bevy_debug_stepping = []
## This will often provide more detailed error messages.
track_location = []

## Provides name information in Component traits for use in System conflict diagnostics
diagnostic_component_names = [
"bevy_ecs_macros/diagnostic_component_names"
]

# Executor Backend

## Uses `async-executor` as a task execution backend.
Expand Down Expand Up @@ -138,6 +143,7 @@ variadics_please = { version = "1.1", default-features = false }
tracing = { version = "0.1", default-features = false, optional = true }
log = { version = "0.4", default-features = false }
bumpalo = "3"
const_panic = { version = "0.2.12" , features = ["rust_latest_stable"] }

[dev-dependencies]
rand = "0.8"
Expand Down
4 changes: 4 additions & 0 deletions crates/bevy_ecs/compile_fail/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ compile_fail_utils = { path = "../../../tools/compile_fail_utils" }
[[test]]
name = "ui"
harness = false

[[test]]
name = "system_params"
harness = false
3 changes: 3 additions & 0 deletions crates/bevy_ecs/compile_fail/tests/system_params.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() -> compile_fail_utils::ui_test::Result<()> {
compile_fail_utils::test("ecs_system_params", "tests/system_params")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, bevy_ecs::query::AnyOf<(&mut A, &mut A)>>))), {closure@tests/system_params/any_of_with_conflicting.rs:8:37: 8:72}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

fn main() {
Schedule::default().add_systems(|_: Query<AnyOf<(&mut A, &mut A)>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, bevy_ecs::query::AnyOf<(&mut A, std::option::Option<&A>)>>))), {closure@tests/system_params/any_of_with_mut_and_option.rs:8:37: 8:76}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

fn main() {
Schedule::default().add_systems(|_: Query<AnyOf<(&mut A, Option<&A>)>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, bevy_ecs::query::AnyOf<(&mut A, &A)>>))), {closure@tests/system_params/any_of_with_mut_and_ref.rs:8:37: 8:68}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

fn main() {
Schedule::default().add_systems(|_: Query<AnyOf<(&mut A, &A)>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, bevy_ecs::query::AnyOf<(&A, &mut A)>>))), {closure@tests/system_params/any_of_with_ref_and_mut.rs:8:37: 8:68}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

fn main() {
Schedule::default().add_systems(|_: Query<AnyOf<(&A, &mut A)>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &A>, bevy_ecs::system::Query<'_, '_, &mut A>))), {closure@tests/system_params/conflicting_query_immut_system.rs:20:37: 20:69}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|_: Query<&mut A>, _: Query<(), Or<(Changed<A>,)>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &A>, bevy_ecs::system::Query<'_, '_, &mut A>))), {closure@tests/system_params/conflicting_query_immut_system.rs:20:37: 20:69}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|_: Query<&A>, _: Query<&mut A>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut A>, bevy_ecs::system::Query<'_, '_, &mut A>))), {closure@tests/system_params/conflicting_query_mut_system.rs:20:37: 20:73}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|_: Query<&mut A>, _: Query<&mut A>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Or<(bevy_ecs::query::Or<(bevy_ecs::query::With<A>, bevy_ecs::query::With<B>)>, bevy_ecs::query::Or<(bevy_ecs::query::With<A>, bevy_ecs::query::With<C>)>)>>, bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Without<A>>))), {closure@tests/system_params/or_expanded_nested_or_with_and_disjoint_without.rs:20:37: 23:6}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|
_: Query<&mut D, Or<(Or<(With<A>, With<B>)>, Or<(With<A>, With<C>)>)>>,
_: Query<&mut D, Without<A>>,
| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Or<((bevy_ecs::query::With<A>, bevy_ecs::query::With<B>), (bevy_ecs::query::With<B>, bevy_ecs::query::With<C>))>>, bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Or<(bevy_ecs::query::Without<A>, bevy_ecs::query::Without<B>)>>))), {closure@tests/system_params/or_expanded_nested_with_and_disjoint_nested_without.rs:20:37: 23:6}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|
_: Query<&mut D, Or<((With<A>, With<B>), (With<B>, With<C>))>>,
_: Query<&mut D, Or<(Without<A>, Without<B>)>>,
| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut E, (bevy_ecs::query::Or<((bevy_ecs::query::With<B>, bevy_ecs::query::With<C>), (bevy_ecs::query::With<C>, bevy_ecs::query::With<D>))>, bevy_ecs::query::With<A>)>, bevy_ecs::system::Query<'_, '_, &mut E, bevy_ecs::query::Without<D>>))), {closure@tests/system_params/or_expanded_nested_with_and_disjoint_without.rs:20:37: 22:38}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|
_: Query<&mut E, (Or<((With<B>, With<C>), (With<C>, With<D>))>, With<A>)>,
_: Query<&mut E, Without<D>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Or<(bevy_ecs::query::With<A>, bevy_ecs::query::With<B>)>>, bevy_ecs::system::Query<'_, '_, &mut D, bevy_ecs::query::Or<(bevy_ecs::query::Without<A>, bevy_ecs::query::Without<B>)>>))), {closure@tests/system_params/or_expanded_with_and_disjoint_nested_without.rs:20:37: 23:6}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|
_: Query<&mut D, Or<(With<A>, With<B>)>>,
_: Query<&mut D, Or<(Without<A>, Without<B>)>>,
| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut B, bevy_ecs::query::Or<(bevy_ecs::query::With<A>, bevy_ecs::query::With<B>)>>, bevy_ecs::system::Query<'_, '_, &mut B, bevy_ecs::query::Without<A>>))), {closure@tests/system_params/or_has_no_filter_with.rs:11:37: 11:109}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

fn main() {
Schedule::default().add_systems(|_: Query<&mut B, Or<(With<A>, With<B>)>>, _: Query<&mut B, Without<A>>| {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@error-in-other-file: evaluation of `bevy_ecs::schedule::Schedule::add_systems::<(bevy_ecs::schedule::Infallible, (bevy_ecs::system::IsFunctionSystem, fn(bevy_ecs::system::Query<'_, '_, &mut B, bevy_ecs::query::With<A>>, bevy_ecs::system::Query<'_, '_, &mut B, bevy_ecs::query::Or<((), bevy_ecs::query::Without<A>)>>))), {closure@tests/system_params/with_and_disjoint_or_empty_without.rs:20:37: 20:104}>::{constant#0}` failed
use bevy_ecs::prelude::*;

#[derive(Component)]
pub struct A;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct C;

#[derive(Component)]
pub struct D;

#[derive(Component)]
pub struct E;

fn main() {
Schedule::default().add_systems(|_: Query<&mut B, With<A>>, _: Query<&mut B, Or<((), Without<A>)>>| {});
}
7 changes: 7 additions & 0 deletions crates/bevy_ecs/examples/change_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ use bevy_ecs::prelude::*;
use rand::Rng;
use std::ops::Deref;

#[derive(Component)]
pub struct B;

#[derive(Component)]
pub struct A;

fn main() {
// Create a new empty World to hold our Entities, Components and Resources
let mut world = World::new();
Expand All @@ -28,6 +34,7 @@ fn main() {
// Add systems to the Schedule to execute our app logic
// We can label our systems to force a specific run-order between some of them
schedule.add_systems((
|_: Query<&mut A>, _: Query<(), Or<(Changed<A>,)>>|{},
spawn_entities.in_set(SimulationSet::Spawn),
print_counter_when_changed.after(SimulationSet::Spawn),
age_all_entities.in_set(SimulationSet::Age),
Expand Down
4 changes: 4 additions & 0 deletions crates/bevy_ecs/macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@ license = "MIT OR Apache-2.0"
[lib]
proc-macro = true

[features]
diagnostic_component_names = []

[dependencies]
bevy_macro_utils = { path = "../../bevy_macro_utils", version = "0.16.0-dev" }

syn = { version = "2.0", features = ["full"] }
quote = "1.0"
proc-macro2 = "1.0"
rand = "0.9.0"
[lints]
workspace = true

Expand Down
13 changes: 13 additions & 0 deletions crates/bevy_ecs/macros/src/component.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use proc_macro::{TokenStream, TokenTree};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, ToTokens};
use rand::Rng;
use std::collections::HashSet;
use syn::{
parenthesized,
Expand Down Expand Up @@ -214,12 +215,24 @@ pub fn derive_component(input: TokenStream) -> TokenStream {
(&&&#bevy_ecs_path::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
)
};
let mut rng = rand::rng();
let unstable_type_id: u128 = rng.random();
let struct_name_2 = struct_name.to_string();
let struct_name_code = if cfg!(feature = "diagnostic_component_names") {
quote! {
const STRUCT_NAME: &'static str = #struct_name_2;
}
} else {
quote! {}
};

// This puts `register_required` before `register_recursive_requires` to ensure that the constructors of _all_ top
// level components are initialized first, giving them precedence over recursively defined constructors for the same component type
TokenStream::from(quote! {
impl #impl_generics #bevy_ecs_path::component::Component for #struct_name #type_generics #where_clause {
const STORAGE_TYPE: #bevy_ecs_path::component::StorageType = #storage;
const UNSTABLE_TYPE_ID: u128 = #unstable_type_id;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to make this value deterministic? I think that's preferable from it randomly changing whenever cargo clean && cargo build is ran.

Copy link

@MarcGuiselin MarcGuiselin Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think so. Using something like type_id::<Self>() would be ideal, but you'd need a nightly feature flag to make it const.

I guess you could do some sort of hashing that takes for input the component's ast, but that still probably isn't enough to avoid collisions with other components. It would also drastically increase the complexity of this pr.

I agree it'd be preferable, but what benefits are there to making it deterministic?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah using type_id:: would be ideal, but we don't want to use any sort of deterministic count because I've heard from the grape vine that rustc might mess with things so we could end up with UB. Unless I have a guarantee that IDs are never going to repeat I would rather safely stick with a random u128.

#struct_name_code
type Mutability = #mutable_type;
fn register_required_components(
requiree: #bevy_ecs_path::component::ComponentId,
Expand Down
12 changes: 12 additions & 0 deletions crates/bevy_ecs/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,18 @@ pub trait Component: Send + Sync + 'static {
/// A constant indicating the storage type used for this component.
const STORAGE_TYPE: StorageType;

/// A randomly generated u128 that is consistent per component type, used to uniquely identify
/// components in const contexts.
/// This enables compile-time validation of component access patterns
/// for both inter-query and intra-query correctness.
const UNSTABLE_TYPE_ID: u128;

/// The name of the component's struct, if available.
/// This is used to provide more helpful error messages when component access conflicts
/// are detected at compile-time. Will be None if the component isn't derived automatically
/// or if the name isn't available.
#[cfg(feature = "diagnostic_component_names")]
const STRUCT_NAME: &'static str = "";
/// A marker type to assist Bevy with determining if this component is
/// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],
/// while immutable components will instead have [`Component<Mutability = Immutable>`].
Expand Down
Loading
Loading