Skip to main content

bevy_expected_components/
lib.rs

1//! # `bevy_expected_components`
2//!
3//! Runtime validation for Bevy component dependencies. Like `#[require]` but validates
4//! instead of auto-inserting.
5//!
6//! ## Why Use This?
7//!
8//! Bevy's `#[require(T)]` automatically inserts missing components using `Default`.
9//! This doesn't work when:
10//!
11//! - Required components need world access to construct
12//! - You want bugs to surface immediately rather than silently using defaults
13//! - The required component has no sensible default
14//!
15//! `#[expects(T)]` solves this by panicking if expected components are missing at insert
16//! time, making bugs immediately visible during development.
17//!
18//! ## Performance Warning
19//!
20//! This crate adds runtime overhead: every time a component with `#[expects(...)]` is
21//! inserted, the plugin checks that all expected components exist on the entity.
22//!
23//! **Recommended usage:** Enable only in development and test builds.
24//!
25//! ```rust,ignore
26//! // Only add the plugin in debug builds
27//! #[cfg(debug_assertions)]
28//! app.add_plugins(ExpectedComponentsPlugin);
29//! ```
30//!
31//! ## Example
32//!
33//! ```rust,ignore
34//! use bevy::prelude::*;
35//! use bevy_expected_components::prelude::*;
36//!
37//! #[derive(Component, Default)]
38//! struct Transform;
39//!
40//! #[derive(Component, Default)]
41//! struct Velocity;
42//!
43//! // PhysicsBody expects Transform and Velocity to exist when it's inserted
44//! #[derive(Component, ExpectComponents)]
45//! #[expects(Transform, Velocity)]
46//! struct PhysicsBody;
47//!
48//! fn main() {
49//!     let mut app = App::new();
50//!
51//!     // Enable validation (only in debug builds recommended)
52//!     #[cfg(debug_assertions)]
53//!     app.add_plugins(ExpectedComponentsPlugin);
54//!
55//!     // This works - all expected components present
56//!     app.world_mut().spawn((PhysicsBody, Transform, Velocity));
57//!
58//!     // This panics - Velocity is missing!
59//!     // app.world_mut().spawn((PhysicsBody, Transform));
60//! }
61//! ```
62//!
63//! ## How It Works
64//!
65//! 1. `#[derive(ExpectComponents)]` generates an [`ExpectComponents`] trait implementation
66//! 2. The derive macro registers the type with [`inventory`] at compile time
67//! 3. [`ExpectedComponentsPlugin`] iterates all registered types and installs `on_add` hooks
68//! 4. When a component is inserted, the hook validates expected components exist
69//!
70//! ## Comparison with `#[require]`
71//!
72//! | Feature | `#[require]` | `#[expects]` |
73//! |---------|--------------|--------------|
74//! | Missing component | Auto-inserted with `Default` | Panics |
75//! | Requires `Default` | Yes | No |
76//! | Runtime cost | Archetype lookup | Component existence check |
77//! | Use case | Convenience bundles | Bug detection |
78//!
79//! ## Limitations
80//!
81//! **Validates insertion only, not removal.** If you later remove an expected component
82//! from an entity, no error occurs. This keeps the implementation simple and covers
83//! the main use case: catching mistakes at spawn time.
84//!
85//! ## Future of This Crate
86//!
87//! This crate may become unnecessary when Bevy adds native support for non-defaultable
88//! required components. Relevant discussions:
89//!
90//! - [Issue #16194: Require components that can't be defaulted](https://github.com/bevyengine/bevy/issues/16194)
91//! - [Issue #18717: Support required components which have no sensible default](https://github.com/bevyengine/bevy/issues/18717)
92//! - Archetype invariants (future Bevy feature)
93
94use std::any::TypeId;
95
96use bevy_app::{App, Plugin};
97use bevy_ecs::component::Component;
98use bevy_ecs::lifecycle::HookContext;
99use bevy_ecs::world::{DeferredWorld, World};
100
101// Re-export for macro use
102#[doc(hidden)]
103pub use inventory;
104
105// Re-export derive macro
106pub use bevy_expected_components_macros::ExpectComponents;
107
108/// Prelude module for convenient imports.
109///
110/// ```rust,ignore
111/// use bevy_expected_components::prelude::*;
112/// ```
113pub mod prelude {
114    pub use crate::ExpectComponents;
115    pub use crate::ExpectedComponentsPlugin;
116}
117
118/// Trait implemented by components that expect other components to be present.
119///
120/// This trait is automatically implemented by the `#[derive(ExpectComponents)]` macro.
121/// You should not need to implement it manually.
122///
123/// # Example
124///
125/// ```rust,ignore
126/// #[derive(Component, ExpectComponents)]
127/// #[expects(Transform, Velocity)]
128/// struct PhysicsBody;
129/// ```
130pub trait ExpectComponents: Component {
131    /// Returns the `TypeId`s of expected components.
132    fn expected_components() -> &'static [TypeId];
133
134    /// Returns human-readable names of expected components for error messages.
135    fn expected_component_names() -> &'static [&'static str];
136}
137
138/// Registration entry for a component with expectations.
139///
140/// Created by the `#[derive(ExpectComponents)]` macro and collected via `inventory`.
141/// You should not need to use this directly.
142pub struct ExpectRegistration {
143    register_hooks: fn(&mut World),
144}
145
146impl ExpectRegistration {
147    /// Creates a new registration with a hook registration function.
148    ///
149    /// Called by the derive macro. You should not need to use this directly.
150    #[must_use]
151    pub const fn new(register_hooks: fn(&mut World)) -> Self {
152        Self { register_hooks }
153    }
154
155    /// Registers the component hooks with the world.
156    pub fn register(&self, world: &mut World) {
157        (self.register_hooks)(world);
158    }
159}
160
161/// Registers component hooks for type T. Used by the derive macro.
162#[doc(hidden)]
163pub fn register_hooks_for<T: ExpectComponents>(world: &mut World) {
164    world
165        .register_component_hooks::<T>()
166        .on_add(validate_expected::<T>);
167}
168
169inventory::collect!(ExpectRegistration);
170
171/// Plugin that enables runtime validation of component expectations.
172///
173/// When added to your app, this plugin registers `on_add` hooks for all components
174/// that use `#[derive(ExpectComponents)]`. When those components are inserted,
175/// the hooks validate that all expected components exist on the entity.
176///
177/// # Performance Warning
178///
179/// This plugin adds runtime overhead. It is recommended to only enable it in
180/// development and test builds:
181///
182/// ```rust,ignore
183/// #[cfg(debug_assertions)]
184/// app.add_plugins(ExpectedComponentsPlugin);
185/// ```
186///
187/// # Panics
188///
189/// When a component is inserted and its expected components are missing, the
190/// plugin will panic with a message like:
191///
192/// ```text
193/// my_crate::RoadNode expects bevy::transform::components::Transform
194/// but it was not found on entity 42v3
195/// ```
196pub struct ExpectedComponentsPlugin;
197
198impl Plugin for ExpectedComponentsPlugin {
199    fn build(&self, app: &mut App) {
200        for registration in inventory::iter::<ExpectRegistration> {
201            registration.register(app.world_mut());
202        }
203    }
204}
205
206/// Validation hook called when a component with expectations is inserted.
207#[allow(clippy::needless_pass_by_value)] // Bevy hook signature requires owned DeferredWorld
208fn validate_expected<T: ExpectComponents>(world: DeferredWorld, ctx: HookContext) {
209    let expected = T::expected_components();
210    let names = T::expected_component_names();
211    let entity = ctx.entity;
212
213    for (type_id, name) in expected.iter().zip(names.iter()) {
214        let component_id = world.components().get_id(*type_id);
215        let has_component = component_id.is_some_and(|id| world.entity(entity).contains_id(id));
216
217        assert!(
218            has_component,
219            "{} expects {} but it was not found on entity {:?}",
220            std::any::type_name::<T>(),
221            name,
222            entity
223        );
224    }
225}