Skip to main content

bevy_ecs/component/
required.rs

1use alloc::{format, vec::Vec};
2use bevy_platform::{hash::FixedHasher, sync::Arc};
3use bevy_ptr::OwningPtr;
4use core::fmt::Debug;
5use indexmap::{IndexMap, IndexSet};
6use thiserror::Error;
7
8use crate::{
9    bundle::BundleInfo,
10    change_detection::{MaybeLocation, Tick},
11    component::{Component, ComponentId, Components, ComponentsRegistrator},
12    entity::Entity,
13    query::DebugCheckedUnwrap as _,
14    storage::{SparseSets, Table, TableRow},
15};
16
17/// Metadata associated with a required component. See [`Component`] for details.
18#[derive(Clone)]
19pub struct RequiredComponent {
20    /// The constructor used for the required component.
21    pub constructor: RequiredComponentConstructor,
22}
23
24/// A Required Component constructor. See [`Component`] for details.
25#[derive(Clone)]
26pub struct RequiredComponentConstructor(
27    // Note: this function makes `unsafe` assumptions, so it cannot be public.
28    Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
29);
30
31impl RequiredComponentConstructor {
32    /// Creates a new instance of `RequiredComponentConstructor` for the given type
33    ///
34    /// # Safety
35    ///
36    /// - `component_id` must be a valid component for type `C`.
37    pub unsafe fn new<C: Component>(
38        component_id: ComponentId,
39        constructor: impl Fn() -> C + 'static,
40    ) -> Self {
41        RequiredComponentConstructor({
42            // `portable-atomic-util` `Arc` is not able to coerce an unsized
43            // type like `std::sync::Arc` can. Creating a `Box` first does the
44            // coercion.
45            //
46            // This would be resolved by https://github.com/rust-lang/rust/issues/123430
47
48            #[cfg(not(target_has_atomic = "ptr"))]
49            use alloc::boxed::Box;
50
51            type Constructor = dyn for<'a, 'b> Fn(
52                &'a mut Table,
53                &'b mut SparseSets,
54                Tick,
55                TableRow,
56                Entity,
57                MaybeLocation,
58            );
59
60            #[cfg(not(target_has_atomic = "ptr"))]
61            type Intermediate<T> = Box<T>;
62
63            #[cfg(target_has_atomic = "ptr")]
64            type Intermediate<T> = Arc<T>;
65
66            let boxed: Intermediate<Constructor> = Intermediate::new(
67                move |table, sparse_sets, change_tick, table_row, entity, caller| {
68                    OwningPtr::make(constructor(), |ptr| {
69                        // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
70                        // pass in a valid table_row and entity requiring a C constructor
71                        // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
72                        // `ptr` points to valid `C` data, which matches the type associated with `component_id`
73                        unsafe {
74                            BundleInfo::initialize_required_component(
75                                table,
76                                sparse_sets,
77                                change_tick,
78                                table_row,
79                                entity,
80                                component_id,
81                                C::STORAGE_TYPE,
82                                ptr,
83                                caller,
84                            );
85                        }
86                    });
87                },
88            );
89
90            Arc::from(boxed)
91        })
92    }
93
94    /// # Safety
95    /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
96    /// Calling it _anywhere else_ should be considered unsafe.
97    ///
98    /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
99    /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
100    /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
101    ///
102    /// Again, don't call this anywhere but [`BundleInfo::write_components`].
103    pub(crate) unsafe fn initialize(
104        &self,
105        table: &mut Table,
106        sparse_sets: &mut SparseSets,
107        change_tick: Tick,
108        table_row: TableRow,
109        entity: Entity,
110        caller: MaybeLocation,
111    ) {
112        (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
113    }
114}
115
116/// The collection of metadata for components that are required for a given component.
117///
118/// For more information, see the "Required Components" section of [`Component`].
119#[derive(Default, Clone)]
120pub struct RequiredComponents {
121    /// The components that are directly required (i.e. excluding inherited ones), in the order of their precedence.
122    ///
123    /// # Safety
124    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
125    pub(crate) direct: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
126    /// All the components that are required (i.e. including inherited ones), in depth-first order. Most importantly,
127    /// components in this list always appear after all the components that they require.
128    ///
129    /// Note that the direct components are not necessarily at the end of this list, for example if A and C are directly
130    /// requires, and A requires B requires C, then `all` will hold [C, B, A].
131    ///
132    /// # Safety
133    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
134    pub(crate) all: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
135}
136
137impl Debug for RequiredComponents {
138    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139        f.debug_struct("RequiredComponents")
140            .field("direct", &self.direct.keys())
141            .field("all", &self.all.keys())
142            .finish()
143    }
144}
145
146impl RequiredComponents {
147    /// Registers the [`Component`] `C` as an explicitly required component.
148    ///
149    /// If the component was not already registered as an explicit required component then it is added
150    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
151    ///
152    /// # Safety
153    ///
154    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
155    unsafe fn register<C: Component>(
156        &mut self,
157        components: &mut ComponentsRegistrator<'_>,
158        constructor: impl Fn() -> C + 'static,
159    ) {
160        let id = components.register_component::<C>();
161        // SAFETY:
162        // - `id` was just registered in `components`;
163        // - the caller guarantees all other components were registered in `components`.
164        unsafe { self.register_by_id::<C>(id, components, constructor) };
165    }
166
167    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
168    ///
169    /// If the component was not already registered as an explicit required component then it is added
170    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
171    ///
172    /// # Safety
173    ///
174    /// - `component_id` must be a valid component in `components` for the type `C`;
175    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
176    unsafe fn register_by_id<C: Component>(
177        &mut self,
178        component_id: ComponentId,
179        components: &Components,
180        constructor: impl Fn() -> C + 'static,
181    ) {
182        // SAFETY: the caller guarantees that `component_id` is valid for the type `C`.
183        let constructor =
184            || unsafe { RequiredComponentConstructor::new(component_id, constructor) };
185
186        // SAFETY:
187        // - the caller guarantees that `component_id` is valid in `components`
188        // - the caller guarantees all other components were registered in `components`;
189        // - constructor is guaranteed to create a valid constructor for the component with id `component_id`.
190        unsafe { self.register_dynamic_with(component_id, components, constructor) };
191    }
192
193    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
194    ///
195    /// If the component was not already registered as an explicit required component then it is added
196    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
197    ///
198    /// # Safety
199    ///
200    /// - `component_id` must be a valid component in `components`;
201    /// - all other components in `self` must have been registered in `components`;
202    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
203    ///   component with ID `component_id`.
204    unsafe fn register_dynamic_with(
205        &mut self,
206        component_id: ComponentId,
207        components: &Components,
208        constructor: impl FnOnce() -> RequiredComponentConstructor,
209    ) {
210        // If already registered as a direct required component then bail.
211        let entry = match self.direct.entry(component_id) {
212            indexmap::map::Entry::Vacant(entry) => entry,
213            indexmap::map::Entry::Occupied(_) =>
214                panic!("Error while registering required component {component_id:?}: already directly required"),
215        };
216
217        // Insert into `direct`.
218        let constructor = constructor();
219        let required_component = RequiredComponent { constructor };
220        entry.insert(required_component.clone());
221
222        // Register inherited required components.
223        // SAFETY:
224        // - the caller guarantees all components that were in `self` have been registered in `components`;
225        // - `component_id` has just been added, but is also guaranteed by the called to be valid in `components`.
226        unsafe {
227            Self::register_inherited_required_components_unchecked(
228                &mut self.all,
229                component_id,
230                required_component,
231                components,
232            );
233        }
234    }
235
236    /// Rebuild the `all` list
237    ///
238    /// # Safety
239    ///
240    /// - all components in `self` must have been registered in `components`.
241    unsafe fn rebuild_inherited_required_components(&mut self, components: &Components) {
242        // Clear `all`, we are re-initializing it.
243        self.all.clear();
244
245        // Register all inherited components as if we just registered all components in `direct` one-by-one.
246        for (&required_id, required_component) in &self.direct {
247            // SAFETY:
248            // - the caller guarantees that all components in this instance have been registered in `components`,
249            //   meaning both `all` and `required_id` have been registered in `components`;
250            // - `required_component` was associated to `required_id`, so it must hold a constructor valid for it.
251            unsafe {
252                Self::register_inherited_required_components_unchecked(
253                    &mut self.all,
254                    required_id,
255                    required_component.clone(),
256                    components,
257                );
258            }
259        }
260    }
261
262    /// Registers all the inherited required components from `required_id`.
263    ///
264    /// # Safety
265    ///
266    /// - all components in `all` must have been registered in `components`;
267    /// - `required_id` must have been registered in `components`;
268    /// - `required_component` must hold a valid constructor for the component with id `required_id`.
269    unsafe fn register_inherited_required_components_unchecked(
270        all: &mut IndexMap<ComponentId, RequiredComponent, FixedHasher>,
271        required_id: ComponentId,
272        required_component: RequiredComponent,
273        components: &Components,
274    ) {
275        // SAFETY: the caller guarantees that `required_id` is valid in `components`.
276        let info = unsafe { components.get_info(required_id).debug_checked_unwrap() };
277
278        // Now we need to "recursively" register the
279        // Small optimization: if the current required component was already required recursively
280        // by an earlier direct required component then all its inherited components have all already
281        // been inserted, so let's not try to reinsert them.
282        if !all.contains_key(&required_id) {
283            for (&inherited_id, inherited_required) in &info.required_components().all {
284                // This is an inherited required component: insert it only if not already present.
285                // By the invariants of `RequiredComponents`, `info.required_components().all` holds the required
286                // components in a depth-first order, and this makes us store the components in `self.all` also
287                // in depth-first order, as long as we don't overwrite existing ones.
288                //
289                // SAFETY:
290                // `inherited_required` was associated to `inherited_id`, so it must have been valid for its component.
291                all.entry(inherited_id)
292                    .or_insert_with(|| inherited_required.clone());
293            }
294        }
295
296        // For direct required components:
297        // - insert them after inherited components to follow the depth-first order;
298        // - insert them unconditionally in order to make their constructor the one that's used.
299        // Note that `insert` does not change the order of components, meaning `component_id` will still appear
300        // before any other component that requires it.
301        //
302        // SAFETY: the caller guarantees that `required_component` is valid for the component with ID `required_id`.
303        all.insert(required_id, required_component);
304    }
305
306    /// Iterates the ids of all required components. This includes recursive required components.
307    pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
308        self.all.keys().copied()
309    }
310
311    /// Iterates the ids of all required components. This is only directly required components.
312    pub fn iter_direct_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
313        self.direct.keys().copied()
314    }
315}
316
317impl Components {
318    /// Registers the components in `required_components` as required by `requiree`.
319    ///
320    /// # Safety
321    ///
322    /// - `requiree` must have been registered in `self`
323    /// - all components in `required_components` must have been registered in `self`;
324    /// - this is called with `requiree` before being called on any component requiring `requiree`.
325    pub(crate) unsafe fn register_required_by(
326        &mut self,
327        requiree: ComponentId,
328        required_components: &RequiredComponents,
329    ) {
330        for &required in required_components.all.keys() {
331            // SAFETY: the caller guarantees that all components in `required_components` have been registered in `self`.
332            let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
333            // This preserves the invariant of `required_by` because:
334            // - components requiring `required` and required by `requiree` are already initialized at this point
335            //   and hence registered in `required_by` before `requiree`;
336            // - components requiring `requiree` cannot exist yet, as this is called on `requiree` before them.
337            required_by.insert(requiree);
338        }
339    }
340
341    /// Registers the given component `R` and [required components] inherited from it as required by `T`.
342    ///
343    /// When `T` is added to an entity, `R` will also be added if it was not already provided.
344    /// The given `constructor` will be used for the creation of `R`.
345    ///
346    /// [required components]: Component#required-components
347    ///
348    /// # Safety
349    ///
350    /// - the given component IDs `required` and `requiree` must be valid in `self`;
351    /// - the given component ID `required` must be valid for the component type `R`.
352    ///
353    ///
354    /// # Errors
355    ///
356    /// Returns a [`RequiredComponentsError`] if either of these are true:
357    /// - the `required` component is already a *directly* required component for the `requiree`; indirect
358    ///   requirements through other components are allowed. In those cases, the more specific
359    ///   registration will be used.
360    /// - the `requiree` component is already a (possibly indirect) required component for the `required` component.
361    pub(crate) unsafe fn register_required_components<R: Component>(
362        &mut self,
363        requiree: ComponentId,
364        required: ComponentId,
365        constructor: impl Fn() -> R + 'static,
366    ) -> Result<(), RequiredComponentsError> {
367        // First step: validate inputs and return errors.
368
369        // SAFETY: The caller ensures that the `required` is valid.
370        let required_required_components = unsafe {
371            self.get_required_components(required)
372                .debug_checked_unwrap()
373        };
374
375        // Cannot create cyclic requirements.
376        if required_required_components.all.contains_key(&requiree) {
377            return Err(RequiredComponentsError::CyclicRequirement(
378                requiree, required,
379            ));
380        }
381
382        // SAFETY: The caller ensures that the `requiree` is valid.
383        let required_components = unsafe {
384            self.get_required_components_mut(requiree)
385                .debug_checked_unwrap()
386        };
387
388        // Cannot directly require the same component twice.
389        if required_components.direct.contains_key(&required) {
390            return Err(RequiredComponentsError::DuplicateRegistration(
391                requiree, required,
392            ));
393        }
394
395        // Second step: register the single requirement requiree->required
396
397        // Store the old count of (all) required components. This will help determine which ones are new.
398        let old_required_count = required_components.all.len();
399
400        // SAFETY: the caller guarantees that `requiree` is valid in `self`.
401        unsafe {
402            self.required_components_scope(requiree, |this, required_components| {
403                // SAFETY: the caller guarantees that `required` is valid for type `R` in `self`
404                required_components.register_by_id(required, this, constructor);
405            });
406        }
407        // Third step: update the required components and required_by of all the indirect requirements/requirees.
408
409        // Borrow again otherwise it conflicts with the `self.required_components_scope` call.
410        // SAFETY: The caller ensures that the `requiree` is valid.
411        let required_components = unsafe {
412            self.get_required_components_mut(requiree)
413                .debug_checked_unwrap()
414        };
415
416        // Optimization: get all the new required components, i.e. those that were appended.
417        // Other components that might be inherited when requiring `required` can be safely ignored because
418        // any component requiring `requiree` will already transitively require them.
419        // Note: the only small exception is for `required` itself, for which we cannot ignore the value of the
420        // constructor. But for simplicity we will rebuild any `RequiredComponents`
421        let new_required_components = required_components.all[old_required_count..]
422            .keys()
423            .copied()
424            .collect::<Vec<_>>();
425
426        // Get all the new requiree components, i.e. `requiree` and all the components that `requiree` is required by.
427        // SAFETY: The caller ensures that the `requiree` is valid.
428        let requiree_required_by = unsafe { self.get_required_by(requiree).debug_checked_unwrap() };
429        let new_requiree_components = [requiree]
430            .into_iter()
431            .chain(requiree_required_by.iter().copied())
432            .collect::<IndexSet<_, FixedHasher>>();
433
434        // We now need to update the required and required_by components of all the components
435        // directly or indirectly involved.
436        // Important: we need to be careful about the order we do these operations in.
437        // Since computing the required components of some component depends on the required components of
438        // other components, and while we do this operations not all required components are up-to-date, we need
439        // to ensure we update components in such a way that we update a component after the components it depends on.
440        // Luckily, `new_requiree_components` comes from `ComponentInfo::required_by`, which guarantees an order
441        // with that property.
442
443        // Update the inherited required components of all requiree components (directly or indirectly).
444        // Skip the first one (requiree) because we already updates it.
445        for &indirect_requiree in &new_requiree_components[1..] {
446            // SAFETY: `indirect_requiree` comes from `self` so it must be valid.
447            unsafe {
448                self.required_components_scope(indirect_requiree, |this, required_components| {
449                    // Rebuild the inherited required components.
450                    // SAFETY: `required_components` comes from `self`, so all its components must have be valid in `self`.
451                    required_components.rebuild_inherited_required_components(this);
452                });
453            }
454        }
455
456        // Update the `required_by` of all the components that were newly required (directly or indirectly).
457        for &indirect_required in &new_required_components {
458            // SAFETY: `indirect_required` comes from `self`, so it must be valid.
459            let required_by = unsafe {
460                self.get_required_by_mut(indirect_required)
461                    .debug_checked_unwrap()
462            };
463
464            // Remove and re-add all the components in `new_requiree_components`
465            // This preserves the invariant of `required_by` because `new_requiree_components`
466            // satisfies its invariant, due to being `requiree` followed by its `required_by` components,
467            // and because any component not in `new_requiree_components` cannot require a component in it,
468            // since if that was the case it would appear in the `required_by` for `requiree`.
469            required_by.retain(|id| !new_requiree_components.contains(id));
470            required_by.extend(&new_requiree_components);
471        }
472
473        Ok(())
474    }
475
476    /// Temporarily take out the [`RequiredComponents`] of the component with id `component_id`
477    /// and runs the given closure with mutable access to `self` and the given [`RequiredComponents`].
478    ///
479    /// SAFETY:
480    ///
481    /// `component_id` is valid in `self.components`
482    unsafe fn required_components_scope<R>(
483        &mut self,
484        component_id: ComponentId,
485        f: impl FnOnce(&mut Self, &mut RequiredComponents) -> R,
486    ) -> R {
487        struct DropGuard<'a> {
488            components: &'a mut Components,
489            component_id: ComponentId,
490            required_components: RequiredComponents,
491        }
492
493        impl Drop for DropGuard<'_> {
494            fn drop(&mut self) {
495                // SAFETY: The caller ensures that the `component_id` is valid.
496                let required_components = unsafe {
497                    self.components
498                        .get_required_components_mut(self.component_id)
499                        .debug_checked_unwrap()
500                };
501
502                debug_assert!(required_components.direct.is_empty());
503                debug_assert!(required_components.all.is_empty());
504
505                *required_components = core::mem::take(&mut self.required_components);
506            }
507        }
508
509        let mut guard = DropGuard {
510            component_id,
511            // SAFETY: The caller ensures that the `component_id` is valid.
512            required_components: core::mem::take(unsafe {
513                self.get_required_components_mut(component_id)
514                    .debug_checked_unwrap()
515            }),
516            components: self,
517        };
518
519        f(guard.components, &mut guard.required_components)
520    }
521}
522
523/// An error returned when the registration of a required component fails.
524#[derive(Error, Debug)]
525#[non_exhaustive]
526pub enum RequiredComponentsError {
527    /// The component is already a directly required component for the requiree.
528    #[error("Component {0:?} already directly requires component {1:?}")]
529    DuplicateRegistration(ComponentId, ComponentId),
530    /// Adding the given requirement would create a cycle.
531    #[error("Cyclic requirement found: the requiree component {0:?} is required by the required component {1:?}")]
532    CyclicRequirement(ComponentId, ComponentId),
533    /// An archetype with the component that requires other components already exists
534    #[error("An archetype with the component {0:?} that requires other components already exists")]
535    ArchetypeExists(ComponentId),
536}
537
538pub(super) fn enforce_no_required_components_recursion(
539    components: &Components,
540    recursion_check_stack: &[ComponentId],
541    required: ComponentId,
542) {
543    if let Some(direct_recursion) = recursion_check_stack
544        .iter()
545        .position(|&id| id == required)
546        .map(|index| index == recursion_check_stack.len() - 1)
547    {
548        panic!(
549            "Recursive required components detected: {}\nhelp: {}",
550            recursion_check_stack
551                .iter()
552                .map(|id| format!("{}", components.get_name(*id).unwrap().shortname()))
553                .collect::<Vec<_>>()
554                .join(" → "),
555            if direct_recursion {
556                format!(
557                    "Remove require({}).",
558                    components.get_name(required).unwrap().shortname()
559                )
560            } else {
561                "If this is intentional, consider merging the components.".into()
562            }
563        );
564    }
565}
566
567/// This is a safe handle around `ComponentsRegistrator` and `RequiredComponents` to register required components.
568pub struct RequiredComponentsRegistrator<'a, 'w> {
569    components: &'a mut ComponentsRegistrator<'w>,
570    required_components: &'a mut RequiredComponents,
571}
572
573impl<'a, 'w> RequiredComponentsRegistrator<'a, 'w> {
574    /// # Safety
575    ///
576    /// All components in `required_components` must have been registered in `components`
577    pub(super) unsafe fn new(
578        components: &'a mut ComponentsRegistrator<'w>,
579        required_components: &'a mut RequiredComponents,
580    ) -> Self {
581        Self {
582            components,
583            required_components,
584        }
585    }
586
587    /// Provides access to the current [`World`](crate::world::World)'s [`ComponentsRegistrator`]
588    pub fn components_registrator(&mut self) -> &mut ComponentsRegistrator<'w> {
589        self.components
590    }
591
592    /// Registers the [`Component`] `C` as an explicitly required component.
593    ///
594    /// If the component was not already registered as an explicit required component then it is added
595    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
596    pub fn register_required<C: Component>(&mut self, constructor: impl Fn() -> C + 'static) {
597        // SAFETY: we internally guarantee that all components in `required_components`
598        // are registered in `components`
599        unsafe {
600            self.required_components
601                .register(self.components, constructor);
602        }
603    }
604
605    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
606    ///
607    /// If the component was not already registered as an explicit required component then it is added
608    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
609    ///
610    /// # Safety
611    ///
612    /// `component_id` must be a valid [`ComponentId`] for `C` in the [`Components`] instance of `self`.
613    pub unsafe fn register_required_by_id<C: Component>(
614        &mut self,
615        component_id: ComponentId,
616        constructor: impl Fn() -> C + 'static,
617    ) {
618        // SAFETY:
619        // - the caller guarantees `component_id` is a valid component in `components` for `C`;
620        // - we internally guarantee all other components in `required_components` are registered in `components`.
621        unsafe {
622            self.required_components.register_by_id::<C>(
623                component_id,
624                self.components,
625                constructor,
626            );
627        }
628    }
629
630    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
631    ///
632    /// If the component was not already registered as an explicit required component then it is added
633    /// as one, potentially overriding the constructor of an inherited required component, otherwise panics.
634    ///
635    /// # Safety
636    ///
637    /// - `component_id` must be valid in the [`Components`] instance of `self`;
638    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
639    ///   component with ID `component_id`.
640    pub unsafe fn register_required_dynamic_with(
641        &mut self,
642        component_id: ComponentId,
643        constructor: impl FnOnce() -> RequiredComponentConstructor,
644    ) {
645        // SAFETY:
646        // - the caller guarantees `component_id` is valid in `components`;
647        // - the caller guarantees `constructor` returns a valid constructor for `component_id`;
648        // - we internally guarantee all other components in `required_components` are registered in `components`.
649        unsafe {
650            self.required_components.register_dynamic_with(
651                component_id,
652                self.components,
653                constructor,
654            );
655        }
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use alloc::string::{String, ToString};
662
663    use crate::{
664        bundle::Bundle,
665        component::{Component, RequiredComponentsError},
666        prelude::Resource,
667        world::World,
668    };
669
670    #[test]
671    fn required_components() {
672        #[derive(Component)]
673        #[require(Y)]
674        struct X;
675
676        #[derive(Component)]
677        #[require(Z = new_z())]
678        struct Y {
679            value: String,
680        }
681
682        #[derive(Component)]
683        struct Z(u32);
684
685        impl Default for Y {
686            fn default() -> Self {
687                Self {
688                    value: "hello".to_string(),
689                }
690            }
691        }
692
693        fn new_z() -> Z {
694            Z(7)
695        }
696
697        let mut world = World::new();
698        let id = world.spawn(X).id();
699        assert_eq!(
700            "hello",
701            world.entity(id).get::<Y>().unwrap().value,
702            "Y should have the default value"
703        );
704        assert_eq!(
705            7,
706            world.entity(id).get::<Z>().unwrap().0,
707            "Z should have the value provided by the constructor defined in Y"
708        );
709
710        let id = world
711            .spawn((
712                X,
713                Y {
714                    value: "foo".to_string(),
715                },
716            ))
717            .id();
718        assert_eq!(
719            "foo",
720            world.entity(id).get::<Y>().unwrap().value,
721            "Y should have the manually provided value"
722        );
723        assert_eq!(
724            7,
725            world.entity(id).get::<Z>().unwrap().0,
726            "Z should have the value provided by the constructor defined in Y"
727        );
728
729        let id = world.spawn((X, Z(8))).id();
730        assert_eq!(
731            "hello",
732            world.entity(id).get::<Y>().unwrap().value,
733            "Y should have the default value"
734        );
735        assert_eq!(
736            8,
737            world.entity(id).get::<Z>().unwrap().0,
738            "Z should have the manually provided value"
739        );
740    }
741
742    #[test]
743    fn generic_required_components() {
744        #[derive(Component)]
745        #[require(Y<usize>)]
746        struct X;
747
748        #[derive(Component, Default)]
749        struct Y<T> {
750            value: T,
751        }
752
753        let mut world = World::new();
754        let id = world.spawn(X).id();
755        assert_eq!(
756            0,
757            world.entity(id).get::<Y<usize>>().unwrap().value,
758            "Y should have the default value"
759        );
760    }
761
762    #[test]
763    fn required_components_spawn_nonexistent_hooks() {
764        #[derive(Component)]
765        #[require(Y)]
766        struct X;
767
768        #[derive(Component, Default)]
769        struct Y;
770
771        #[derive(Resource)]
772        struct A(usize);
773
774        #[derive(Resource)]
775        struct I(usize);
776
777        let mut world = World::new();
778        world.insert_resource(A(0));
779        world.insert_resource(I(0));
780        world
781            .register_component_hooks::<Y>()
782            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
783            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
784
785        // Spawn entity and ensure Y was added
786        assert!(world.spawn(X).contains::<Y>());
787
788        assert_eq!(world.resource::<A>().0, 1);
789        assert_eq!(world.resource::<I>().0, 1);
790    }
791
792    #[test]
793    fn required_components_insert_existing_hooks() {
794        #[derive(Component)]
795        #[require(Y)]
796        struct X;
797
798        #[derive(Component, Default)]
799        struct Y;
800
801        #[derive(Resource)]
802        struct A(usize);
803
804        #[derive(Resource)]
805        struct I(usize);
806
807        let mut world = World::new();
808        world.insert_resource(A(0));
809        world.insert_resource(I(0));
810        world
811            .register_component_hooks::<Y>()
812            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
813            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
814
815        // Spawn entity and ensure Y was added
816        assert!(world.spawn_empty().insert(X).contains::<Y>());
817
818        assert_eq!(world.resource::<A>().0, 1);
819        assert_eq!(world.resource::<I>().0, 1);
820    }
821
822    #[test]
823    fn required_components_take_leaves_required() {
824        #[derive(Component)]
825        #[require(Y)]
826        struct X;
827
828        #[derive(Component, Default)]
829        struct Y;
830
831        let mut world = World::new();
832        let e = world.spawn(X).id();
833        let _ = world.entity_mut(e).take::<X>().unwrap();
834        assert!(world.entity_mut(e).contains::<Y>());
835    }
836
837    #[test]
838    fn required_components_retain_keeps_required() {
839        #[derive(Component)]
840        #[require(Y)]
841        struct X;
842
843        #[derive(Component, Default)]
844        struct Y;
845
846        #[derive(Component, Default)]
847        struct Z;
848
849        let mut world = World::new();
850        let e = world.spawn((X, Z)).id();
851        world.entity_mut(e).retain::<X>();
852        assert!(world.entity_mut(e).contains::<X>());
853        assert!(world.entity_mut(e).contains::<Y>());
854        assert!(!world.entity_mut(e).contains::<Z>());
855    }
856
857    #[test]
858    fn required_components_spawn_then_insert_no_overwrite() {
859        #[derive(Component)]
860        #[require(Y)]
861        struct X;
862
863        #[derive(Component, Default)]
864        struct Y(usize);
865
866        let mut world = World::new();
867        let id = world.spawn((X, Y(10))).id();
868        world.entity_mut(id).insert(X);
869
870        assert_eq!(
871            10,
872            world.entity(id).get::<Y>().unwrap().0,
873            "Y should still have the manually provided value"
874        );
875    }
876
877    #[test]
878    fn dynamic_required_components() {
879        #[derive(Component)]
880        #[require(Y)]
881        struct X;
882
883        #[derive(Component, Default)]
884        struct Y;
885
886        let mut world = World::new();
887        let x_id = world.register_component::<X>();
888
889        let mut e = world.spawn_empty();
890
891        // SAFETY: x_id is a valid component id
892        bevy_ptr::OwningPtr::make(X, |ptr| unsafe {
893            e.insert_by_id(x_id, ptr);
894        });
895
896        assert!(e.contains::<Y>());
897    }
898
899    #[test]
900    fn remove_component_and_its_runtime_required_components() {
901        #[derive(Component)]
902        struct X;
903
904        #[derive(Component, Default)]
905        struct Y;
906
907        #[derive(Component, Default)]
908        struct Z;
909
910        #[derive(Component)]
911        struct V;
912
913        let mut world = World::new();
914        world.register_required_components::<X, Y>();
915        world.register_required_components::<Y, Z>();
916
917        let e = world.spawn((X, V)).id();
918        assert!(world.entity(e).contains::<X>());
919        assert!(world.entity(e).contains::<Y>());
920        assert!(world.entity(e).contains::<Z>());
921        assert!(world.entity(e).contains::<V>());
922
923        //check that `remove` works as expected
924        world.entity_mut(e).remove::<X>();
925        assert!(!world.entity(e).contains::<X>());
926        assert!(world.entity(e).contains::<Y>());
927        assert!(world.entity(e).contains::<Z>());
928        assert!(world.entity(e).contains::<V>());
929
930        world.entity_mut(e).insert(X);
931        assert!(world.entity(e).contains::<X>());
932        assert!(world.entity(e).contains::<Y>());
933        assert!(world.entity(e).contains::<Z>());
934        assert!(world.entity(e).contains::<V>());
935
936        //remove `X` again and ensure that `Y` and `Z` was removed too
937        world.entity_mut(e).remove_with_requires::<X>();
938        assert!(!world.entity(e).contains::<X>());
939        assert!(!world.entity(e).contains::<Y>());
940        assert!(!world.entity(e).contains::<Z>());
941        assert!(world.entity(e).contains::<V>());
942    }
943
944    #[test]
945    fn remove_component_and_its_required_components() {
946        #[derive(Component)]
947        #[require(Y)]
948        struct X;
949
950        #[derive(Component, Default)]
951        #[require(Z)]
952        struct Y;
953
954        #[derive(Component, Default)]
955        struct Z;
956
957        #[derive(Component)]
958        struct V;
959
960        let mut world = World::new();
961
962        let e = world.spawn((X, V)).id();
963        assert!(world.entity(e).contains::<X>());
964        assert!(world.entity(e).contains::<Y>());
965        assert!(world.entity(e).contains::<Z>());
966        assert!(world.entity(e).contains::<V>());
967
968        //check that `remove` works as expected
969        world.entity_mut(e).remove::<X>();
970        assert!(!world.entity(e).contains::<X>());
971        assert!(world.entity(e).contains::<Y>());
972        assert!(world.entity(e).contains::<Z>());
973        assert!(world.entity(e).contains::<V>());
974
975        world.entity_mut(e).insert(X);
976        assert!(world.entity(e).contains::<X>());
977        assert!(world.entity(e).contains::<Y>());
978        assert!(world.entity(e).contains::<Z>());
979        assert!(world.entity(e).contains::<V>());
980
981        //remove `X` again and ensure that `Y` and `Z` was removed too
982        world.entity_mut(e).remove_with_requires::<X>();
983        assert!(!world.entity(e).contains::<X>());
984        assert!(!world.entity(e).contains::<Y>());
985        assert!(!world.entity(e).contains::<Z>());
986        assert!(world.entity(e).contains::<V>());
987    }
988
989    #[test]
990    fn remove_bundle_and_his_required_components() {
991        #[derive(Component, Default)]
992        #[require(Y)]
993        struct X;
994
995        #[derive(Component, Default)]
996        struct Y;
997
998        #[derive(Component, Default)]
999        #[require(W)]
1000        struct Z;
1001
1002        #[derive(Component, Default)]
1003        struct W;
1004
1005        #[derive(Component)]
1006        struct V;
1007
1008        #[derive(Bundle, Default)]
1009        struct TestBundle {
1010            x: X,
1011            z: Z,
1012        }
1013
1014        let mut world = World::new();
1015        let e = world.spawn((TestBundle::default(), V)).id();
1016
1017        assert!(world.entity(e).contains::<X>());
1018        assert!(world.entity(e).contains::<Y>());
1019        assert!(world.entity(e).contains::<Z>());
1020        assert!(world.entity(e).contains::<W>());
1021        assert!(world.entity(e).contains::<V>());
1022
1023        world.entity_mut(e).remove_with_requires::<TestBundle>();
1024        assert!(!world.entity(e).contains::<X>());
1025        assert!(!world.entity(e).contains::<Y>());
1026        assert!(!world.entity(e).contains::<Z>());
1027        assert!(!world.entity(e).contains::<W>());
1028        assert!(world.entity(e).contains::<V>());
1029    }
1030
1031    #[test]
1032    fn runtime_required_components() {
1033        // Same as `required_components` test but with runtime registration
1034
1035        #[derive(Component)]
1036        struct X;
1037
1038        #[derive(Component)]
1039        struct Y {
1040            value: String,
1041        }
1042
1043        #[derive(Component)]
1044        struct Z(u32);
1045
1046        impl Default for Y {
1047            fn default() -> Self {
1048                Self {
1049                    value: "hello".to_string(),
1050                }
1051            }
1052        }
1053
1054        let mut world = World::new();
1055
1056        world.register_required_components::<X, Y>();
1057        world.register_required_components_with::<Y, Z>(|| Z(7));
1058
1059        let id = world.spawn(X).id();
1060
1061        assert_eq!(
1062            "hello",
1063            world.entity(id).get::<Y>().unwrap().value,
1064            "Y should have the default value"
1065        );
1066        assert_eq!(
1067            7,
1068            world.entity(id).get::<Z>().unwrap().0,
1069            "Z should have the value provided by the constructor defined in Y"
1070        );
1071
1072        let id = world
1073            .spawn((
1074                X,
1075                Y {
1076                    value: "foo".to_string(),
1077                },
1078            ))
1079            .id();
1080        assert_eq!(
1081            "foo",
1082            world.entity(id).get::<Y>().unwrap().value,
1083            "Y should have the manually provided value"
1084        );
1085        assert_eq!(
1086            7,
1087            world.entity(id).get::<Z>().unwrap().0,
1088            "Z should have the value provided by the constructor defined in Y"
1089        );
1090
1091        let id = world.spawn((X, Z(8))).id();
1092        assert_eq!(
1093            "hello",
1094            world.entity(id).get::<Y>().unwrap().value,
1095            "Y should have the default value"
1096        );
1097        assert_eq!(
1098            8,
1099            world.entity(id).get::<Z>().unwrap().0,
1100            "Z should have the manually provided value"
1101        );
1102    }
1103
1104    #[test]
1105    fn runtime_required_components_override_1() {
1106        #[derive(Component)]
1107        struct X;
1108
1109        #[derive(Component, Default)]
1110        struct Y;
1111
1112        #[derive(Component)]
1113        struct Z(u32);
1114
1115        let mut world = World::new();
1116
1117        // - X requires Y with default constructor
1118        // - Y requires Z with custom constructor
1119        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1120        world.register_required_components::<X, Y>();
1121        world.register_required_components_with::<Y, Z>(|| Z(5));
1122        world.register_required_components_with::<X, Z>(|| Z(7));
1123
1124        let id = world.spawn(X).id();
1125
1126        assert_eq!(
1127            7,
1128            world.entity(id).get::<Z>().unwrap().0,
1129            "Z should have the value provided by the constructor defined in X"
1130        );
1131    }
1132
1133    #[test]
1134    fn runtime_required_components_override_2() {
1135        // Same as `runtime_required_components_override_1` test but with different registration order
1136
1137        #[derive(Component)]
1138        struct X;
1139
1140        #[derive(Component, Default)]
1141        struct Y;
1142
1143        #[derive(Component)]
1144        struct Z(u32);
1145
1146        let mut world = World::new();
1147
1148        // - X requires Y with default constructor
1149        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1150        // - Y requires Z with custom constructor
1151        world.register_required_components::<X, Y>();
1152        world.register_required_components_with::<X, Z>(|| Z(7));
1153        world.register_required_components_with::<Y, Z>(|| Z(5));
1154
1155        let id = world.spawn(X).id();
1156
1157        assert_eq!(
1158            7,
1159            world.entity(id).get::<Z>().unwrap().0,
1160            "Z should have the value provided by the constructor defined in X"
1161        );
1162    }
1163
1164    #[test]
1165    fn runtime_required_components_propagate_up() {
1166        // `A` requires `B` directly.
1167        #[derive(Component)]
1168        #[require(B)]
1169        struct A;
1170
1171        #[derive(Component, Default)]
1172        struct B;
1173
1174        #[derive(Component, Default)]
1175        struct C;
1176
1177        let mut world = World::new();
1178
1179        // `B` requires `C` with a runtime registration.
1180        // `A` should also require `C` because it requires `B`.
1181        world.register_required_components::<B, C>();
1182
1183        let id = world.spawn(A).id();
1184
1185        assert!(world.entity(id).get::<C>().is_some());
1186    }
1187
1188    #[test]
1189    fn runtime_required_components_propagate_up_even_more() {
1190        #[derive(Component)]
1191        struct A;
1192
1193        #[derive(Component, Default)]
1194        struct B;
1195
1196        #[derive(Component, Default)]
1197        struct C;
1198
1199        #[derive(Component, Default)]
1200        struct D;
1201
1202        let mut world = World::new();
1203
1204        world.register_required_components::<A, B>();
1205        world.register_required_components::<B, C>();
1206        world.register_required_components::<C, D>();
1207
1208        let id = world.spawn(A).id();
1209
1210        assert!(world.entity(id).get::<D>().is_some());
1211    }
1212
1213    #[test]
1214    fn runtime_required_components_deep_require_does_not_override_shallow_require() {
1215        #[derive(Component)]
1216        struct A;
1217        #[derive(Component, Default)]
1218        struct B;
1219        #[derive(Component, Default)]
1220        struct C;
1221        #[derive(Component)]
1222        struct Counter(i32);
1223        #[derive(Component, Default)]
1224        struct D;
1225
1226        let mut world = World::new();
1227
1228        world.register_required_components::<A, B>();
1229        world.register_required_components::<B, C>();
1230        world.register_required_components::<C, D>();
1231        world.register_required_components_with::<D, Counter>(|| Counter(2));
1232        // This should replace the require constructor in A since it is
1233        // shallower.
1234        world.register_required_components_with::<C, Counter>(|| Counter(1));
1235
1236        let id = world.spawn(A).id();
1237
1238        // The "shallower" of the two components is used.
1239        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1240    }
1241
1242    #[test]
1243    fn runtime_required_components_deep_require_does_not_override_shallow_require_deep_subtree_after_shallow(
1244    ) {
1245        #[derive(Component)]
1246        struct A;
1247        #[derive(Component, Default)]
1248        struct B;
1249        #[derive(Component, Default)]
1250        struct C;
1251        #[derive(Component, Default)]
1252        struct D;
1253        #[derive(Component, Default)]
1254        struct E;
1255        #[derive(Component)]
1256        struct Counter(i32);
1257        #[derive(Component, Default)]
1258        struct F;
1259
1260        let mut world = World::new();
1261
1262        world.register_required_components::<A, B>();
1263        world.register_required_components::<B, C>();
1264        world.register_required_components::<C, D>();
1265        world.register_required_components::<D, E>();
1266        world.register_required_components_with::<E, Counter>(|| Counter(1));
1267        world.register_required_components_with::<F, Counter>(|| Counter(2));
1268        world.register_required_components::<E, F>();
1269
1270        let id = world.spawn(A).id();
1271
1272        // The "shallower" of the two components is used.
1273        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1274    }
1275
1276    #[test]
1277    fn runtime_required_components_existing_archetype() {
1278        #[derive(Component)]
1279        struct X;
1280
1281        #[derive(Component, Default)]
1282        struct Y;
1283
1284        let mut world = World::new();
1285
1286        // Registering required components after the archetype has already been created should panic.
1287        // This may change in the future.
1288        world.spawn(X);
1289        assert!(matches!(
1290            world.try_register_required_components::<X, Y>(),
1291            Err(RequiredComponentsError::ArchetypeExists(_))
1292        ));
1293    }
1294
1295    #[test]
1296    fn runtime_required_components_fail_with_duplicate() {
1297        #[derive(Component)]
1298        #[require(Y)]
1299        struct X;
1300
1301        #[derive(Component, Default)]
1302        struct Y;
1303
1304        let mut world = World::new();
1305
1306        // This should fail: Tried to register Y as a requirement for X, but the requirement already exists.
1307        assert!(matches!(
1308            world.try_register_required_components::<X, Y>(),
1309            Err(RequiredComponentsError::DuplicateRegistration(_, _))
1310        ));
1311    }
1312
1313    #[test]
1314    fn required_components_bundle_priority() {
1315        #[derive(Component, PartialEq, Eq, Clone, Copy, Debug)]
1316        struct MyRequired(bool);
1317
1318        #[derive(Component, Default)]
1319        #[require(MyRequired(false))]
1320        struct MiddleMan;
1321
1322        #[derive(Component, Default)]
1323        #[require(MiddleMan)]
1324        struct ConflictingRequire;
1325
1326        #[derive(Component, Default)]
1327        #[require(MyRequired(true))]
1328        struct MyComponent;
1329
1330        let mut world = World::new();
1331        let order_a = world
1332            .spawn((ConflictingRequire, MyComponent))
1333            .get::<MyRequired>()
1334            .cloned();
1335        let order_b = world
1336            .spawn((MyComponent, ConflictingRequire))
1337            .get::<MyRequired>()
1338            .cloned();
1339
1340        assert_eq!(order_a, Some(MyRequired(false)));
1341        assert_eq!(order_b, Some(MyRequired(true)));
1342    }
1343
1344    #[test]
1345    #[should_panic]
1346    fn required_components_recursion_errors() {
1347        #[derive(Component, Default)]
1348        #[require(B)]
1349        struct A;
1350
1351        #[derive(Component, Default)]
1352        #[require(C)]
1353        struct B;
1354
1355        #[derive(Component, Default)]
1356        #[require(B)]
1357        struct C;
1358
1359        World::new().register_component::<A>();
1360    }
1361
1362    #[test]
1363    #[should_panic]
1364    fn required_components_self_errors() {
1365        #[derive(Component, Default)]
1366        #[require(A)]
1367        struct A;
1368
1369        World::new().register_component::<A>();
1370    }
1371
1372    #[test]
1373    fn regression_19333() {
1374        #[derive(Component)]
1375        struct X(usize);
1376
1377        #[derive(Default, Component)]
1378        #[require(X(0))]
1379        struct Base;
1380
1381        #[derive(Default, Component)]
1382        #[require(X(1), Base)]
1383        struct A;
1384
1385        #[derive(Default, Component)]
1386        #[require(A, Base)]
1387        struct B;
1388
1389        #[derive(Default, Component)]
1390        #[require(B, Base)]
1391        struct C;
1392
1393        let mut w = World::new();
1394
1395        assert_eq!(w.spawn(B).get::<X>().unwrap().0, 1);
1396        assert_eq!(w.spawn(C).get::<X>().unwrap().0, 1);
1397    }
1398
1399    #[test]
1400    fn required_components_depth_first_2v1() {
1401        #[derive(Component)]
1402        struct X(usize);
1403
1404        #[derive(Component)]
1405        #[require(Left, Right)]
1406        struct Root;
1407
1408        #[derive(Component, Default)]
1409        #[require(LeftLeft)]
1410        struct Left;
1411
1412        #[derive(Component, Default)]
1413        #[require(X(0))] // This is at depth 2 but is more on the left of the tree
1414        struct LeftLeft;
1415
1416        #[derive(Component, Default)]
1417        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1418        struct Right;
1419
1420        let mut world = World::new();
1421
1422        // LeftLeft should have priority over Right
1423        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1424    }
1425
1426    #[test]
1427    fn required_components_depth_first_3v1() {
1428        #[derive(Component)]
1429        struct X(usize);
1430
1431        #[derive(Component)]
1432        #[require(Left, Right)]
1433        struct Root;
1434
1435        #[derive(Component, Default)]
1436        #[require(LeftLeft)]
1437        struct Left;
1438
1439        #[derive(Component, Default)]
1440        #[require(LeftLeftLeft)]
1441        struct LeftLeft;
1442
1443        #[derive(Component, Default)]
1444        #[require(X(0))] // This is at depth 3 but is more on the left of the tree
1445        struct LeftLeftLeft;
1446
1447        #[derive(Component, Default)]
1448        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1449        struct Right;
1450
1451        let mut world = World::new();
1452
1453        // LeftLeftLeft should have priority over Right
1454        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1455    }
1456
1457    #[test]
1458    fn runtime_required_components_depth_first_2v1() {
1459        #[derive(Component)]
1460        struct X(usize);
1461
1462        #[derive(Component)]
1463        struct Root;
1464
1465        #[derive(Component, Default)]
1466        struct Left;
1467
1468        #[derive(Component, Default)]
1469        struct LeftLeft;
1470
1471        #[derive(Component, Default)]
1472        struct Right;
1473
1474        // Register bottom up: registering higher level components should pick up lower level ones.
1475        let mut world = World::new();
1476        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1477        world.register_required_components_with::<Right, X>(|| X(1));
1478        world.register_required_components::<Left, LeftLeft>();
1479        world.register_required_components::<Root, Left>();
1480        world.register_required_components::<Root, Right>();
1481        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1482
1483        // Register top down: registering lower components should propagate to higher ones
1484        let mut world = World::new();
1485        world.register_required_components::<Root, Left>(); // Note: still register Left before Right
1486        world.register_required_components::<Root, Right>();
1487        world.register_required_components::<Left, LeftLeft>();
1488        world.register_required_components_with::<Right, X>(|| X(1));
1489        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1490        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1491
1492        // Register top down again, but this time LeftLeft before Right
1493        let mut world = World::new();
1494        world.register_required_components::<Root, Left>();
1495        world.register_required_components::<Root, Right>();
1496        world.register_required_components::<Left, LeftLeft>();
1497        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1498        world.register_required_components_with::<Right, X>(|| X(1));
1499        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1500    }
1501
1502    #[test]
1503    fn runtime_required_components_propagate_metadata_alternate() {
1504        #[derive(Component, Default)]
1505        #[require(L1)]
1506        struct L0;
1507
1508        #[derive(Component, Default)]
1509        struct L1;
1510
1511        #[derive(Component, Default)]
1512        #[require(L3)]
1513        struct L2;
1514
1515        #[derive(Component, Default)]
1516        struct L3;
1517
1518        #[derive(Component, Default)]
1519        #[require(L5)]
1520        struct L4;
1521
1522        #[derive(Component, Default)]
1523        struct L5;
1524
1525        // Try to piece the 3 requirements together
1526        let mut world = World::new();
1527        world.register_required_components::<L1, L2>();
1528        world.register_required_components::<L3, L4>();
1529        let e = world.spawn(L0).id();
1530        assert!(world
1531            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1532            .get(&world, e)
1533            .is_ok());
1534
1535        // Repeat but in the opposite order
1536        let mut world = World::new();
1537        world.register_required_components::<L3, L4>();
1538        world.register_required_components::<L1, L2>();
1539        let e = world.spawn(L0).id();
1540        assert!(world
1541            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1542            .get(&world, e)
1543            .is_ok());
1544    }
1545
1546    #[test]
1547    fn runtime_required_components_propagate_metadata_chain() {
1548        #[derive(Component, Default)]
1549        #[require(L1)]
1550        struct L0;
1551
1552        #[derive(Component, Default)]
1553        struct L1;
1554
1555        #[derive(Component, Default)]
1556        struct L2;
1557
1558        #[derive(Component, Default)]
1559        #[require(L4)]
1560        struct L3;
1561
1562        #[derive(Component, Default)]
1563        struct L4;
1564
1565        // Try to piece the 3 requirements together
1566        let mut world = World::new();
1567        world.register_required_components::<L1, L2>();
1568        world.register_required_components::<L2, L3>();
1569        let e = world.spawn(L0).id();
1570        assert!(world
1571            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1572            .get(&world, e)
1573            .is_ok());
1574
1575        // Repeat but in the opposite order
1576        let mut world = World::new();
1577        world.register_required_components::<L2, L3>();
1578        world.register_required_components::<L1, L2>();
1579        let e = world.spawn(L0).id();
1580        assert!(world
1581            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1582            .get(&world, e)
1583            .is_ok());
1584    }
1585
1586    #[test]
1587    fn runtime_required_components_cyclic() {
1588        #[derive(Component, Default)]
1589        #[require(B)]
1590        struct A;
1591
1592        #[derive(Component, Default)]
1593        struct B;
1594
1595        #[derive(Component, Default)]
1596        struct C;
1597
1598        let mut world = World::new();
1599
1600        assert!(world.try_register_required_components::<B, C>().is_ok());
1601        assert!(matches!(
1602            world.try_register_required_components::<C, A>(),
1603            Err(RequiredComponentsError::CyclicRequirement(_, _))
1604        ));
1605    }
1606}