1use std::{
4 any::{TypeId, type_name},
5 collections::HashSet,
6 error::Error,
7 fmt,
8};
9
10use bevy_ecs::{
11 bundle::{Bundle, NoBundleEffect},
12 component::{Component, ComponentId},
13 lifecycle::{ComponentHook, HookContext},
14 prelude::Resource,
15 resource::IsResource,
16 world::{DeferredWorld, World},
17};
18
19use crate::identity::ManagedEntity;
20
21mod supported {
22 use bevy_ecs::component::Component;
23
24 use super::{ComponentApprovalError, ComponentRegistry};
25
26 #[allow(
27 private_interfaces,
28 reason = "this method seals tuple implementations around the private registry"
29 )]
30 pub trait Tuple {
31 fn approve(registry: &mut ComponentRegistry) -> Result<(), ComponentApprovalError>;
32 }
33
34 macro_rules! impl_component_tuple {
35 ($($component:ident),+) => {
36 #[allow(
37 private_interfaces,
38 reason = "this implementation is hidden with the sealed tuple trait"
39 )]
40 impl<$($component: Component),+> Tuple for ($($component,)+) {
41 fn approve(
42 registry: &mut ComponentRegistry,
43 ) -> Result<(), ComponentApprovalError> {
44 $(registry.approve::<$component>()?;)+
45 Ok(())
46 }
47 }
48 };
49 }
50
51 impl_component_tuple!(C0);
52 impl_component_tuple!(C0, C1);
53 impl_component_tuple!(C0, C1, C2);
54 impl_component_tuple!(C0, C1, C2, C3);
55 impl_component_tuple!(C0, C1, C2, C3, C4);
56 impl_component_tuple!(C0, C1, C2, C3, C4, C5);
57 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6);
58 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7);
59 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8);
60 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9);
61 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
62 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11);
63 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12);
64 impl_component_tuple!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13);
65 impl_component_tuple!(
66 C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14
67 );
68}
69
70pub trait ComponentTuple: supported::Tuple {}
77
78impl<T: supported::Tuple> ComponentTuple for T {}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum LifecycleHook {
83 Add,
85 Insert,
87 Discard,
89 Remove,
91 Despawn,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum ComponentApprovalError {
98 LifecycleHook {
101 component: &'static str,
103 hook: LifecycleHook,
105 },
106 UnapprovedRequiredComponent {
109 component: &'static str,
111 required: String,
113 },
114 UnapprovedBundleComponent {
116 component: String,
119 },
120 RuntimeIdentityInBundle,
122}
123
124impl fmt::Display for ComponentApprovalError {
125 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 Self::LifecycleHook { component, hook } => {
128 write!(
129 formatter,
130 "component `{component}` uses the {hook:?} lifecycle hook"
131 )
132 }
133 Self::UnapprovedRequiredComponent {
134 component,
135 required,
136 } => write!(
137 formatter,
138 "component `{component}` requires unapproved component `{required}`"
139 ),
140 Self::UnapprovedBundleComponent { component } => {
141 write!(
142 formatter,
143 "bundle contains unapproved component `{component}`"
144 )
145 }
146 Self::RuntimeIdentityInBundle => formatter.write_str(
147 "bundle contains LogicEntity, which is attached only by the Sim;Logic runtime",
148 ),
149 }
150 }
151}
152
153impl Error for ComponentApprovalError {}
154
155struct ComponentRegistration {
156 type_id: TypeId,
157 name: &'static str,
158 register: fn(&mut World) -> ComponentId,
159}
160
161#[derive(Default)]
162pub(crate) struct ComponentRegistry {
163 registrations: Vec<ComponentRegistration>,
164}
165
166impl ComponentRegistry {
167 pub(crate) fn approve<T: Component>(&mut self) -> Result<(), ComponentApprovalError> {
168 if let Some(hook) = first_hook::<T>() {
169 return Err(ComponentApprovalError::LifecycleHook {
170 component: type_name::<T>(),
171 hook,
172 });
173 }
174
175 if self
176 .registrations
177 .iter()
178 .any(|registration| registration.type_id == TypeId::of::<T>())
179 {
180 return Ok(());
181 }
182
183 self.registrations.push(ComponentRegistration {
184 type_id: TypeId::of::<T>(),
185 name: type_name::<T>(),
186 register: World::register_component::<T>,
187 });
188 Ok(())
189 }
190
191 pub(crate) fn approve_tuple<T: ComponentTuple>(
192 &mut self,
193 ) -> Result<(), ComponentApprovalError> {
194 let checkpoint = self.registrations.len();
195 if let Err(error) = <T as supported::Tuple>::approve(self) {
196 self.registrations.truncate(checkpoint);
197 return Err(error);
198 }
199 Ok(())
200 }
201
202 pub(crate) fn install(
203 &self,
204 world: &mut World,
205 ) -> Result<ApprovedComponents, ComponentApprovalError> {
206 let registered: Vec<_> = self
207 .registrations
208 .iter()
209 .map(|registration| (registration, (registration.register)(world)))
210 .collect();
211 let approved: HashSet<_> = registered.iter().map(|(_, id)| *id).collect();
212
213 for (registration, component_id) in ®istered {
214 if let Some(hook) = first_registered_hook(world, *component_id) {
215 return Err(ComponentApprovalError::LifecycleHook {
216 component: registration.name,
217 hook,
218 });
219 }
220 let Some(required) = world.get_required_components_by_id(*component_id) else {
221 continue;
222 };
223 for required_id in required.iter_ids() {
224 if !approved.contains(&required_id) {
225 let required_name = world
226 .components()
227 .get_info(required_id)
228 .map(|info| info.name().to_string())
229 .unwrap_or_else(|| format!("{required_id:?}"));
230 return Err(ComponentApprovalError::UnapprovedRequiredComponent {
231 component: registration.name,
232 required: required_name,
233 });
234 }
235 }
236 }
237
238 let identity = world.register_component::<ManagedEntity>();
239 Ok(ApprovedComponents {
240 approved,
241 identity,
242 validated_bundles: Vec::new(),
243 last_validated_bundle: None,
244 })
245 }
246}
247
248fn first_hook<T: Component>() -> Option<LifecycleHook> {
249 if T::on_add().is_some() {
250 Some(LifecycleHook::Add)
251 } else if T::on_insert().is_some() {
252 Some(LifecycleHook::Insert)
253 } else if T::on_discard().is_some() {
254 Some(LifecycleHook::Discard)
255 } else if T::on_remove().is_some() {
256 Some(LifecycleHook::Remove)
257 } else if T::on_despawn().is_some() {
258 Some(LifecycleHook::Despawn)
259 } else {
260 None
261 }
262}
263
264fn no_op_component_hook(_world: DeferredWorld<'_>, _context: HookContext) {}
265
266fn first_registered_hook(world: &World, component: ComponentId) -> Option<LifecycleHook> {
267 let mut hooks = world.components().get_info(component)?.hooks().clone();
268 let hook: ComponentHook = no_op_component_hook;
269 if hooks.try_on_add(hook).is_none() {
270 Some(LifecycleHook::Add)
271 } else if hooks.try_on_insert(hook).is_none() {
272 Some(LifecycleHook::Insert)
273 } else if hooks.try_on_discard(hook).is_none() {
274 Some(LifecycleHook::Discard)
275 } else if hooks.try_on_remove(hook).is_none() {
276 Some(LifecycleHook::Remove)
277 } else if hooks.try_on_despawn(hook).is_none() {
278 Some(LifecycleHook::Despawn)
279 } else {
280 None
281 }
282}
283
284pub(crate) fn validate_resource<R: Resource>(
285 world: &mut World,
286) -> Result<(), ComponentApprovalError> {
287 if let Some(hook) = first_hook::<R>() {
288 return Err(ComponentApprovalError::LifecycleHook {
289 component: type_name::<R>(),
290 hook,
291 });
292 }
293
294 let resource_id = world.register_component::<R>();
295 if let Some(hook) = first_registered_hook(world, resource_id) {
296 return Err(ComponentApprovalError::LifecycleHook {
297 component: type_name::<R>(),
298 hook,
299 });
300 }
301 let is_resource_id = world.register_component::<IsResource>();
302 if let Some(required) = world.get_required_components_by_id(resource_id) {
303 for required_id in required.iter_ids() {
304 if required_id == is_resource_id {
307 continue;
308 }
309 return Err(ComponentApprovalError::UnapprovedRequiredComponent {
310 component: type_name::<R>(),
311 required: component_name(world, required_id),
312 });
313 }
314 }
315 Ok(())
316}
317
318pub(crate) struct ApprovedComponents {
319 approved: HashSet<ComponentId>,
320 identity: ComponentId,
321 validated_bundles: Vec<TypeId>,
322 last_validated_bundle: Option<TypeId>,
323}
324
325impl ApprovedComponents {
326 pub(crate) fn validate_bundle<B>(
327 &mut self,
328 world: &mut World,
329 ) -> Result<(), ComponentApprovalError>
330 where
331 B: Bundle<Effect: NoBundleEffect>,
332 {
333 let bundle = TypeId::of::<B>();
334 if self.last_validated_bundle == Some(bundle) {
335 return Ok(());
336 }
337 if self.validated_bundles.contains(&bundle) {
338 self.last_validated_bundle = Some(bundle);
339 return Ok(());
340 }
341
342 let invalid_explicit = B::get_component_ids(world.components()).find(|component_id| {
343 component_id.is_none_or(|component_id| {
344 component_id == self.identity || !self.approved.contains(&component_id)
345 })
346 });
347 if let Some(component_id) = invalid_explicit {
348 let Some(component_id) = component_id else {
349 return Err(ComponentApprovalError::UnapprovedBundleComponent {
350 component: "unregistered Rust component type".to_owned(),
351 });
352 };
353 if component_id == self.identity {
354 return Err(ComponentApprovalError::RuntimeIdentityInBundle);
355 }
356 return Err(ComponentApprovalError::UnapprovedBundleComponent {
357 component: component_name(world, component_id),
358 });
359 }
360
361 let invalid_contributed = world
362 .register_bundle::<B>()
363 .iter_contributed_components()
364 .find(|component_id| {
365 *component_id == self.identity || !self.approved.contains(component_id)
366 });
367 if let Some(component_id) = invalid_contributed {
368 if component_id == self.identity {
369 return Err(ComponentApprovalError::RuntimeIdentityInBundle);
370 }
371 return Err(ComponentApprovalError::UnapprovedBundleComponent {
372 component: component_name(world, component_id),
373 });
374 }
375
376 self.last_validated_bundle = Some(bundle);
377 if self.validated_bundles.try_reserve(1).is_ok() {
378 self.validated_bundles.push(bundle);
379 }
380 Ok(())
381 }
382}
383
384fn component_name(world: &World, component_id: ComponentId) -> String {
385 world
386 .components()
387 .get_info(component_id)
388 .map(|info| info.name().to_string())
389 .unwrap_or_else(|| format!("{component_id:?}"))
390}
391
392#[cfg(test)]
393mod tests {
394 use std::sync::atomic::{AtomicUsize, Ordering};
395
396 use bevy_ecs::{
397 component::{Component, Mutable, StorageType},
398 lifecycle::ComponentHook,
399 world::{DeferredWorld, World},
400 };
401
402 use super::*;
403
404 #[derive(Component)]
405 struct Plain;
406
407 fn on_add(_world: DeferredWorld<'_>, _context: bevy_ecs::lifecycle::HookContext) {}
408
409 #[derive(Component)]
410 #[component(on_add = on_add)]
411 struct Hooked;
412
413 #[derive(Component)]
414 #[require(Required)]
415 struct Requires;
416
417 #[derive(Component, Default)]
418 struct Required;
419
420 macro_rules! define_tuple_components {
421 ($($component:ident),+) => {
422 $(
423 #[derive(Component)]
424 struct $component;
425 )+
426 };
427 }
428
429 define_tuple_components!(
430 Tuple0, Tuple1, Tuple2, Tuple3, Tuple4, Tuple5, Tuple6, Tuple7, Tuple8, Tuple9, Tuple10,
431 Tuple11, Tuple12, Tuple13, Tuple14
432 );
433
434 static STATEFUL_HOOK_QUERIES: AtomicUsize = AtomicUsize::new(0);
435 static STATEFUL_HOOK_RUNS: AtomicUsize = AtomicUsize::new(0);
436
437 struct StatefulHook;
438
439 impl Component for StatefulHook {
440 const STORAGE_TYPE: StorageType = StorageType::Table;
441 type Mutability = Mutable;
442
443 fn on_add() -> Option<ComponentHook> {
444 if STATEFUL_HOOK_QUERIES.fetch_add(1, Ordering::SeqCst) == 0 {
445 None
446 } else {
447 Some(stateful_on_add)
448 }
449 }
450 }
451
452 fn stateful_on_add(_world: DeferredWorld<'_>, _context: bevy_ecs::lifecycle::HookContext) {
453 STATEFUL_HOOK_RUNS.fetch_add(1, Ordering::SeqCst);
454 }
455
456 #[test]
457 fn rejects_lifecycle_hooks_before_world_creation() {
458 let mut registry = ComponentRegistry::default();
459 let result = registry.approve::<Hooked>();
460
461 assert!(matches!(
462 result,
463 Err(ComponentApprovalError::LifecycleHook {
464 hook: LifecycleHook::Add,
465 ..
466 })
467 ));
468 }
469
470 #[test]
471 fn component_tuple_approves_all_supported_members() {
472 let mut registry = ComponentRegistry::default();
473 assert!(
474 registry
475 .approve_tuple::<(
476 Tuple0,
477 Tuple1,
478 Tuple2,
479 Tuple3,
480 Tuple4,
481 Tuple5,
482 Tuple6,
483 Tuple7,
484 Tuple8,
485 Tuple9,
486 Tuple10,
487 Tuple11,
488 Tuple12,
489 Tuple13,
490 Tuple14,
491 )>()
492 .is_ok()
493 );
494
495 let mut world = World::new();
496 let mut approved = registry
497 .install(&mut world)
498 .expect("flat tuple members should install");
499 assert!(
500 approved
501 .validate_bundle::<(
502 Tuple0,
503 Tuple1,
504 Tuple2,
505 Tuple3,
506 Tuple4,
507 Tuple5,
508 Tuple6,
509 Tuple7,
510 Tuple8,
511 Tuple9,
512 Tuple10,
513 Tuple11,
514 Tuple12,
515 Tuple13,
516 Tuple14,
517 )>(&mut world)
518 .is_ok()
519 );
520 }
521
522 #[test]
523 fn component_tuple_failure_rolls_back_only_new_approvals() {
524 let mut registry = ComponentRegistry::default();
525 assert!(registry.approve::<Required>().is_ok());
526
527 let result = registry.approve_tuple::<(Plain, Hooked)>();
528
529 assert!(matches!(
530 result,
531 Err(ComponentApprovalError::LifecycleHook { .. })
532 ));
533 assert_eq!(registry.registrations.len(), 1);
534 assert_eq!(registry.registrations[0].type_id, TypeId::of::<Required>());
535 }
536
537 #[test]
538 fn component_tuple_is_idempotent_and_closes_required_components() {
539 let mut registry = ComponentRegistry::default();
540 assert!(registry.approve_tuple::<(Requires, Required)>().is_ok());
541 assert!(registry.approve_tuple::<(Required, Requires)>().is_ok());
542 assert_eq!(registry.registrations.len(), 2);
543 assert!(registry.install(&mut World::new()).is_ok());
544 }
545
546 #[test]
547 fn required_closure_must_be_explicitly_approved() {
548 let mut registry = ComponentRegistry::default();
549 assert!(registry.approve::<Requires>().is_ok());
550
551 let result = registry.install(&mut World::new());
552 assert!(matches!(
553 result,
554 Err(ComponentApprovalError::UnapprovedRequiredComponent { .. })
555 ));
556 }
557
558 #[test]
559 fn approved_plain_bundle_passes_without_runtime_identity() {
560 let mut registry = ComponentRegistry::default();
561 assert!(registry.approve::<Plain>().is_ok());
562 let mut world = World::new();
563 let mut approved = match registry.install(&mut world) {
564 Ok(approved) => approved,
565 Err(error) => panic!("unexpected component approval failure: {error}"),
566 };
567
568 assert!(approved.validate_bundle::<Plain>(&mut world).is_ok());
569 assert!(matches!(
570 approved.validate_bundle::<ManagedEntity>(&mut world),
571 Err(ComponentApprovalError::RuntimeIdentityInBundle)
572 ));
573 }
574
575 #[test]
576 fn successful_bundle_validation_is_cached_once_across_alternating_types() {
577 let mut registry = ComponentRegistry::default();
578 assert!(registry.approve::<Plain>().is_ok());
579 assert!(registry.approve::<Required>().is_ok());
580 let mut world = World::new();
581 let mut approved = registry
582 .install(&mut world)
583 .expect("plain components should install");
584
585 assert!(approved.validated_bundles.is_empty());
586 assert!(approved.validate_bundle::<Plain>(&mut world).is_ok());
587 assert_eq!(approved.validated_bundles, [TypeId::of::<Plain>()]);
588 assert_eq!(approved.last_validated_bundle, Some(TypeId::of::<Plain>()));
589
590 assert!(approved.validate_bundle::<Plain>(&mut world).is_ok());
591 assert_eq!(approved.validated_bundles.len(), 1);
592
593 assert!(approved.validate_bundle::<Required>(&mut world).is_ok());
594 assert_eq!(approved.validated_bundles.len(), 2);
595 assert_eq!(
596 approved.last_validated_bundle,
597 Some(TypeId::of::<Required>())
598 );
599
600 assert!(approved.validate_bundle::<Plain>(&mut world).is_ok());
601 assert_eq!(approved.validated_bundles.len(), 2);
602 assert_eq!(approved.last_validated_bundle, Some(TypeId::of::<Plain>()));
603 }
604
605 #[test]
606 fn rejected_bundle_validation_is_never_cached() {
607 let mut registry = ComponentRegistry::default();
608 assert!(registry.approve::<Plain>().is_ok());
609 let mut world = World::new();
610 let mut approved = registry
611 .install(&mut world)
612 .expect("plain component should install");
613
614 for _ in 0..2 {
615 assert!(matches!(
616 approved.validate_bundle::<Required>(&mut world),
617 Err(ComponentApprovalError::UnapprovedBundleComponent { .. })
618 ));
619 assert!(approved.validated_bundles.is_empty());
620 assert_eq!(approved.last_validated_bundle, None);
621 }
622 }
623
624 #[test]
625 fn installed_worlds_do_not_share_bundle_validation_caches() {
626 let mut registry = ComponentRegistry::default();
627 assert!(registry.approve::<Plain>().is_ok());
628 let mut first_world = World::new();
629 let mut second_world = World::new();
630 let mut first = registry
631 .install(&mut first_world)
632 .expect("first component set should install");
633 let second = registry
634 .install(&mut second_world)
635 .expect("second component set should install");
636
637 assert!(first.validate_bundle::<Plain>(&mut first_world).is_ok());
638 assert_eq!(first.validated_bundles.len(), 1);
639 assert!(second.validated_bundles.is_empty());
640 assert_eq!(second.last_validated_bundle, None);
641 }
642
643 #[test]
644 fn install_rechecks_the_hooks_actually_registered_by_bevy() {
645 STATEFUL_HOOK_QUERIES.store(0, Ordering::SeqCst);
646 STATEFUL_HOOK_RUNS.store(0, Ordering::SeqCst);
647 let mut registry = ComponentRegistry::default();
648
649 assert!(registry.approve::<StatefulHook>().is_ok());
650 let result = registry.install(&mut World::new());
651
652 assert!(matches!(
653 result,
654 Err(ComponentApprovalError::LifecycleHook {
655 component,
656 hook: LifecycleHook::Add,
657 }) if component == std::any::type_name::<StatefulHook>()
658 ));
659 assert_eq!(STATEFUL_HOOK_RUNS.load(Ordering::SeqCst), 0);
660 }
661
662 #[test]
663 fn hook_function_has_expected_bevy_signature() {
664 let _: ComponentHook = on_add;
665 }
666}