bevy_ecs 0.19.0

Bevy Engine's entity component system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//! This module provides functionality to link entities to each other using specialized components called "relationships". See the [`Relationship`] trait for more info.

mod related_methods;
mod relationship_query;
mod relationship_source_collection;

use alloc::boxed::Box;
use bevy_platform::sync::Arc;
use bevy_ptr::Ptr;
use core::{any::TypeId, marker::PhantomData};

use alloc::format;

use bevy_utils::prelude::DebugName;
pub use related_methods::*;
pub use relationship_query::*;
pub use relationship_source_collection::*;

use crate::{
    component::{Component, ComponentCloneBehavior, ComponentId, Components, Mutable},
    entity::{ComponentCloneCtx, Entity},
    lifecycle::HookContext,
    system::EntityCommand,
    world::{DeferredWorld, EntityWorldMut},
};
use log::warn;

/// A [`Component`] on a "source" [`Entity`] that references another target [`Entity`], creating a "relationship" between them. Every [`Relationship`]
/// has a corresponding [`RelationshipTarget`] type (and vice-versa), which exists on the "target" entity of a relationship and contains the list of all
/// "source" entities that relate to the given "target".
///
/// A [`Relationship`] may only be one-to-many (or one-to-one): an [`Entity`] may point to at most one [`Entity`] through the [`Relationship`] component.
///
/// The [`Relationship`] component is the "source of truth" and the [`RelationshipTarget`] component reflects that source of truth. When a [`Relationship`]
/// component is inserted on an [`Entity`], the corresponding [`RelationshipTarget`] component is immediately inserted on the target component if it does
/// not already exist, and the "source" entity is automatically added to the [`RelationshipTarget`] collection (this is done via "component hooks").
///
/// A common example of a [`Relationship`] is the parent / child relationship. Bevy ECS includes a canonical form of this via the [`ChildOf`](crate::hierarchy::ChildOf)
/// [`Relationship`] and the [`Children`](crate::hierarchy::Children) [`RelationshipTarget`].
///
/// [`Relationship`] and [`RelationshipTarget`] should always be derived via the [`Component`] trait to ensure the hooks are set up properly.
///
/// ## Derive
///
/// [`Relationship`] and [`RelationshipTarget`] can only be derived for structs with a single unnamed field, single named field
/// or for named structs where one field is annotated with `#[relationship]`.
/// If there are additional fields, they must all implement [`Default`].
///
/// [`RelationshipTarget`] also requires that the relationship field is private to prevent direct mutation,
/// ensuring the correctness of relationships.
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = Children)]
/// pub struct ChildOf {
///     #[relationship]
///     pub parent: Entity,
///     internal: u8,
/// };
///
/// #[derive(Component)]
/// #[relationship_target(relationship = ChildOf)]
/// pub struct Children(Vec<Entity>);
/// ```
///
/// A one-to-one relationship can be created by putting a single [`Entity`] in the [`RelationshipTarget`]'s field.
/// In that case, if another entity is added to the relationship, the original entity is removed.
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = View)]
/// pub struct ViewOf(pub Entity);
///
/// #[derive(Component)]
/// #[relationship_target(relationship = ViewOf)]
/// pub struct View(Entity);
/// ```
///
/// When deriving [`RelationshipTarget`] you can specify the `#[relationship_target(linked_spawn)]` attribute to
/// automatically despawn entities stored in an entity's [`RelationshipTarget`] when that entity is despawned:
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = Children)]
/// pub struct ChildOf(pub Entity);
///
/// #[derive(Component)]
/// #[relationship_target(relationship = ChildOf, linked_spawn)]
/// pub struct Children(Vec<Entity>);
/// ```
///
/// By default, relationships cannot point to their own entity. If you want to allow self-referential
/// relationships, you can use the `allow_self_referential` attribute:
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::entity::Entity;
/// #[derive(Component)]
/// #[relationship(relationship_target = PeopleILike, allow_self_referential)]
/// pub struct LikedBy(pub Entity);
///
/// #[derive(Component)]
/// #[relationship_target(relationship = LikedBy)]
/// pub struct PeopleILike(Vec<Entity>);
/// ```
pub trait Relationship: Component + Sized {
    /// The [`Component`] added to the "target" entities of this [`Relationship`], which contains the list of all "source"
    /// entities that relate to the "target".
    type RelationshipTarget: RelationshipTarget<Relationship = Self>;

    /// If `true`, a relationship is allowed to point to its own entity.
    ///
    /// Set this to `true` when self-relationships are semantically valid for your use case,
    /// such as `Likes(self)`, `EmployedBy(self)`, or a `ColliderOf` relationship where
    /// a collider can be attached to its own entity.
    ///
    /// # Warning
    ///
    /// When `ALLOW_SELF` is `true`, be careful when using recursive traversal methods
    /// like `iter_ancestors` or `root_ancestor`, as they will loop infinitely if an entity
    /// points to itself.
    const ALLOW_SELF_REFERENTIAL: bool = false;

    /// Gets the [`Entity`] ID of the related entity.
    fn get(&self) -> Entity;

    /// Creates this [`Relationship`] from the given `entity`.
    fn from(entity: Entity) -> Self;

    /// Changes the current [`Entity`] ID of the entity containing the [`RelationshipTarget`] to another one.
    ///
    /// This is useful for updating the relationship without overwriting other fields stored in `Self`.
    ///
    /// # Warning
    ///
    /// This should generally not be called by user code, as modifying the related entity could invalidate the
    /// relationship. If this method is used, then the hooks [`on_discard`](Relationship::on_discard) have to
    /// run before and [`on_insert`](Relationship::on_insert) after it.
    /// This happens automatically when this method is called with [`EntityWorldMut::modify_component`].
    ///
    /// Prefer to use regular means of insertions when possible.
    fn set_risky(&mut self, entity: Entity);

    /// The `on_insert` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
    fn on_insert(
        mut world: DeferredWorld,
        HookContext {
            entity,
            caller,
            relationship_hook_mode,
            ..
        }: HookContext,
    ) {
        match relationship_hook_mode {
            RelationshipHookMode::Run => {}
            RelationshipHookMode::Skip => return,
            RelationshipHookMode::RunIfNotLinked => {
                if <Self::RelationshipTarget as RelationshipTarget>::LINKED_SPAWN {
                    return;
                }
            }
        }
        let target_entity = world.entity(entity).get::<Self>().unwrap().get();
        if !Self::ALLOW_SELF_REFERENTIAL && target_entity == entity {
            warn!(
                "{}The {}({target_entity:?}) relationship on entity {entity:?} points to itself. The invalid {} relationship has been removed.\nIf this is intended behavior self-referential relations can be enabled with the allow_self_referential attribute: #[relationship(allow_self_referential)]",
                caller.map(|location|format!("{location}: ")).unwrap_or_default(),
                DebugName::type_name::<Self>(),
                DebugName::type_name::<Self>()
            );
            world.commands().entity(entity).remove::<Self>();
            return;
        }
        // For one-to-one relationships, remove existing relationship before adding new one
        let current_source_to_remove = world
            .get_entity(target_entity)
            .ok()
            .and_then(|target_entity_ref| target_entity_ref.get::<Self::RelationshipTarget>())
            .and_then(|relationship_target| {
                relationship_target
                    .collection()
                    .source_to_remove_before_add()
            });

        if let Some(current_source) = current_source_to_remove {
            world.commands().entity(current_source).try_remove::<Self>();
        }

        if let Ok(mut entity_commands) = world.commands().get_entity(target_entity) {
            // Deferring is necessary for batch mode
            entity_commands
                .entry::<Self::RelationshipTarget>()
                .and_modify(move |mut relationship_target| {
                    relationship_target.collection_mut_risky().add(entity);
                })
                .or_insert_with(move || {
                    let mut target = Self::RelationshipTarget::with_capacity(1);
                    target.collection_mut_risky().add(entity);
                    target
                });
        } else {
            warn!(
                "{}The {}({target_entity:?}) relationship on entity {entity:?} relates to an entity that does not exist. The invalid {} relationship has been removed.",
                caller.map(|location|format!("{location}: ")).unwrap_or_default(),
                DebugName::type_name::<Self>(),
                DebugName::type_name::<Self>()
            );
            world.commands().entity(entity).remove::<Self>();
        }
    }

    /// The `on_discard` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
    // note: think of this as "on_drop"
    fn on_discard(
        mut world: DeferredWorld,
        HookContext {
            entity,
            relationship_hook_mode,
            ..
        }: HookContext,
    ) {
        match relationship_hook_mode {
            RelationshipHookMode::Run => {}
            RelationshipHookMode::Skip => return,
            RelationshipHookMode::RunIfNotLinked => {
                if <Self::RelationshipTarget as RelationshipTarget>::LINKED_SPAWN {
                    return;
                }
            }
        }
        let target_entity = world.entity(entity).get::<Self>().unwrap().get();
        if let Ok(mut target_entity_mut) = world.get_entity_mut(target_entity)
            && let Some(mut relationship_target) =
                target_entity_mut.get_mut::<Self::RelationshipTarget>()
        {
            relationship_target.collection_mut_risky().remove(entity);
            if relationship_target.len() == 0 {
                let command = |mut entity: EntityWorldMut| {
                    // this "remove" operation must check emptiness because in the event that an identical
                    // relationship is inserted on top, this despawn would result in the removal of that identical
                    // relationship ... not what we want!
                    if entity
                        .get::<Self::RelationshipTarget>()
                        .is_some_and(RelationshipTarget::is_empty)
                    {
                        entity.remove::<Self::RelationshipTarget>();
                    }
                };

                world
                    .commands()
                    .queue_silenced(command.with_entity(target_entity));
            }
        }
    }
}

/// The iterator type for the source entities in a [`RelationshipTarget`] collection,
/// as defined in the [`RelationshipSourceCollection`] trait.
pub type SourceIter<'w, R> =
    <<R as RelationshipTarget>::Collection as RelationshipSourceCollection>::SourceIter<'w>;

/// A [`Component`] containing the collection of entities that relate to this [`Entity`] via the associated `Relationship` type.
/// See the [`Relationship`] documentation for more information.
pub trait RelationshipTarget: Component<Mutability = Mutable> + Sized {
    /// If this is true, when despawning or cloning (when [linked cloning is enabled](crate::entity::EntityClonerBuilder::linked_cloning)), the related entities targeting this entity will also be despawned or cloned.
    ///
    /// For example, this is set to `true` for Bevy's built-in parent-child relation, defined by [`ChildOf`](crate::prelude::ChildOf) and [`Children`](crate::prelude::Children).
    /// This means that when a parent is despawned, any children targeting that parent are also despawned (and the same applies to cloning).
    ///
    /// To get around this behavior, you can first break the relationship between entities, and *then* despawn or clone.
    /// This defaults to false when derived.
    const LINKED_SPAWN: bool;
    /// The [`Relationship`] that populates this [`RelationshipTarget`] collection.
    type Relationship: Relationship<RelationshipTarget = Self>;
    /// The collection type that stores the "source" entities for this [`RelationshipTarget`] component.
    ///
    /// Check the list of types which implement [`RelationshipSourceCollection`] for the data structures that can be used inside of your component.
    /// If you need a new collection type, you can implement the [`RelationshipSourceCollection`] trait
    /// for a type you own which wraps the collection you want to use (to avoid the orphan rule),
    /// or open an issue on the Bevy repository to request first-party support for your collection type.
    type Collection: RelationshipSourceCollection;

    /// Returns a reference to the stored [`RelationshipTarget::Collection`].
    fn collection(&self) -> &Self::Collection;
    /// Returns a mutable reference to the stored [`RelationshipTarget::Collection`].
    ///
    /// # Warning
    /// This should generally not be called by user code, as modifying the internal collection could invalidate the relationship.
    /// The collection should not contain duplicates.
    fn collection_mut_risky(&mut self) -> &mut Self::Collection;

    /// Creates a new [`RelationshipTarget`] from the given [`RelationshipTarget::Collection`].
    ///
    /// # Warning
    /// This should generally not be called by user code, as constructing the internal collection could invalidate the relationship.
    /// The collection should not contain duplicates.
    fn from_collection_risky(collection: Self::Collection) -> Self;

    /// The `on_discard` component hook that maintains the [`Relationship`] / [`RelationshipTarget`] connection.
    // note: think of this as "on_drop"
    fn on_discard(
        mut world: DeferredWorld,
        HookContext {
            entity,
            relationship_hook_mode,
            ..
        }: HookContext,
    ) {
        match relationship_hook_mode {
            RelationshipHookMode::Run => {}
            // For RelationshipTarget we don't want to run this hook even if it isn't linked, but for Relationship we do.
            RelationshipHookMode::Skip | RelationshipHookMode::RunIfNotLinked => return,
        }
        let (entities, mut commands) = world.entities_and_commands();
        let relationship_target = entities.get(entity).unwrap().get::<Self>().unwrap();
        for source_entity in relationship_target.iter() {
            commands
                .entity(source_entity)
                .try_remove::<Self::Relationship>();
        }
    }

    /// The `on_despawn` component hook that despawns entities stored in an entity's [`RelationshipTarget`] when
    /// that entity is despawned.
    // note: think of this as "on_drop"
    fn on_despawn(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
        let (entities, mut commands) = world.entities_and_commands();
        let relationship_target = entities.get(entity).unwrap().get::<Self>().unwrap();
        for source_entity in relationship_target.iter() {
            commands.entity(source_entity).try_despawn();
        }
    }

    /// Creates this [`RelationshipTarget`] with the given pre-allocated entity capacity.
    fn with_capacity(capacity: usize) -> Self {
        let collection =
            <Self::Collection as RelationshipSourceCollection>::with_capacity(capacity);
        Self::from_collection_risky(collection)
    }

    /// Iterates the entities stored in this collection.
    #[inline]
    fn iter(&self) -> SourceIter<'_, Self> {
        self.collection().iter()
    }

    /// Returns the number of entities in this collection.
    #[inline]
    fn len(&self) -> usize {
        self.collection().len()
    }

    /// Returns true if this entity collection is empty.
    #[inline]
    fn is_empty(&self) -> bool {
        self.collection().is_empty()
    }
}

/// The "clone behavior" for [`RelationshipTarget`]. The [`RelationshipTarget`] will be populated with the proper components
/// when the corresponding [`Relationship`] sources of truth are inserted. Cloning the actual entities
/// in the original [`RelationshipTarget`] would result in duplicates, so we don't do that!
///
/// This will also queue up clones of the relationship sources if the [`EntityCloner`](crate::entity::EntityCloner) is configured
/// to spawn recursively.
pub fn clone_relationship_target<T: RelationshipTarget>(
    component: &T,
    cloned: &mut T,
    context: &mut ComponentCloneCtx,
) {
    if context.linked_cloning() && T::LINKED_SPAWN {
        let collection = cloned.collection_mut_risky();
        for entity in component.iter() {
            collection.add(entity);
            context.queue_entity_clone(entity);
        }
    } else if context.moving() {
        let target = context.target();
        let collection = cloned.collection_mut_risky();
        for entity in component.iter() {
            collection.add(entity);
            context.queue_deferred(move |world, _mapper| {
                // We don't want relationships hooks to run because we are manually constructing the collection here
                _ = DeferredWorld::from(world)
                    .modify_component_with_relationship_hook_mode::<T::Relationship, ()>(
                        entity,
                        RelationshipHookMode::Skip,
                        |r| r.set_risky(target),
                    );
            });
        }
    }
}

/// Configures the conditions under which the Relationship insert/discard hooks will be run.
#[derive(Copy, Clone, Debug)]
pub enum RelationshipHookMode {
    /// Relationship insert/discard hooks will always run
    Run,
    /// Relationship insert/discard hooks will run if [`RelationshipTarget::LINKED_SPAWN`] is false
    RunIfNotLinked,
    /// Relationship insert/discard hooks will always be skipped
    Skip,
}

/// Wrapper for components clone specialization using autoderef.
#[doc(hidden)]
pub struct RelationshipCloneBehaviorSpecialization<T>(PhantomData<T>);

impl<T> Default for RelationshipCloneBehaviorSpecialization<T> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

/// Base trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorBase {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

impl<C> RelationshipCloneBehaviorBase for RelationshipCloneBehaviorSpecialization<C> {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        // Relationships currently must have `Clone`/`Reflect`-based handler for cloning/moving logic to properly work.
        ComponentCloneBehavior::Ignore
    }
}

/// Specialized trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorViaReflect {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

#[cfg(feature = "bevy_reflect")]
impl<C: Relationship + bevy_reflect::Reflect> RelationshipCloneBehaviorViaReflect
    for &RelationshipCloneBehaviorSpecialization<C>
{
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        ComponentCloneBehavior::reflect()
    }
}

/// Specialized trait for relationship clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipCloneBehaviorViaClone {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

impl<C: Relationship + Clone> RelationshipCloneBehaviorViaClone
    for &&RelationshipCloneBehaviorSpecialization<C>
{
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        ComponentCloneBehavior::clone::<C>()
    }
}

/// Specialized trait for relationship target clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorViaReflect {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

#[cfg(feature = "bevy_reflect")]
impl<C: RelationshipTarget + bevy_reflect::Reflect + bevy_reflect::TypePath>
    RelationshipTargetCloneBehaviorViaReflect for &&&RelationshipCloneBehaviorSpecialization<C>
{
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        ComponentCloneBehavior::Custom(|source, context| {
            if let Some(component) = source.read::<C>()
                && let Ok(mut cloned) = component.reflect_clone_and_take::<C>()
            {
                cloned.collection_mut_risky().clear();
                clone_relationship_target(component, &mut cloned, context);
                context.write_target_component(cloned);
            }
        })
    }
}

/// Specialized trait for relationship target clone specialization using autoderef.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorViaClone {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

impl<C: RelationshipTarget + Clone> RelationshipTargetCloneBehaviorViaClone
    for &&&&RelationshipCloneBehaviorSpecialization<C>
{
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        ComponentCloneBehavior::Custom(|source, context| {
            if let Some(component) = source.read::<C>() {
                let mut cloned = component.clone();
                cloned.collection_mut_risky().clear();
                clone_relationship_target(component, &mut cloned, context);
                context.write_target_component(cloned);
            }
        })
    }
}

/// We know there's no additional data on Children, so this handler is an optimization to avoid cloning the entire Collection.
#[doc(hidden)]
pub trait RelationshipTargetCloneBehaviorHierarchy {
    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
}

impl RelationshipTargetCloneBehaviorHierarchy
    for &&&&&RelationshipCloneBehaviorSpecialization<crate::hierarchy::Children>
{
    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
        ComponentCloneBehavior::Custom(|source, context| {
            if let Some(component) = source.read::<crate::hierarchy::Children>() {
                let mut cloned = crate::hierarchy::Children::with_capacity(component.len());
                clone_relationship_target(component, &mut cloned, context);
                context.write_target_component(cloned);
            }
        })
    }
}

/// Initializer enum for [`RelationshipAccessor`] that allows to configure relationship for dynamic components.
#[derive(Clone)]
pub enum RelationshipAccessorInitializer {
    /// Describes a [`Relationship`] component.
    Relationship {
        /// Offset of the field containing [`Entity`] from the base of the component.
        ///
        /// Dynamic equivalent of [`Relationship::get`].
        entity_field_offset: usize,
        /// Value of [`RelationshipTarget::LINKED_SPAWN`] for the [`Relationship::RelationshipTarget`] of this [`Relationship`].
        linked_spawn: bool,
        /// Value of [`Relationship::ALLOW_SELF_REFERENTIAL`] of this [`Relationship`].
        allow_self_referential: bool,
        /// Getter for [`ComponentId`] of the [`RelationshipTarget`] counterpart.
        /// Should return `None` if [`RelationshipTarget`] isn't registered yet.
        relationship_target_getter: Arc<dyn Fn(&Components) -> Option<ComponentId>>,
    },
    /// Describes a [`RelationshipTarget`] component.
    RelationshipTarget {
        /// Function that returns an iterator over all [`Entity`]s of this [`RelationshipTarget`]'s collection.
        ///
        /// Dynamic equivalent of [`RelationshipTarget::iter`].
        /// # Safety
        /// Passed pointer must point to the value of the same component as the one that this accessor was registered to.
        iter: for<'a> unsafe fn(Ptr<'a>) -> Box<dyn Iterator<Item = Entity> + 'a>,
        /// Value of [`RelationshipTarget::LINKED_SPAWN`] of this [`RelationshipTarget`].
        linked_spawn: bool,
        /// Value of [`Relationship::ALLOW_SELF_REFERENTIAL`] for the [`Relationship`] of this [`RelationshipTarget`].
        allow_self_referential: bool,
        /// Getter for [`ComponentId`] of the [`Relationship`] counterpart.
        /// Should return `None` if [`Relationship`] isn't registered yet.
        relationship_getter: Arc<dyn Fn(&Components) -> Option<ComponentId>>,
    },
}

impl core::fmt::Debug for RelationshipAccessorInitializer {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Relationship {
                entity_field_offset,
                linked_spawn,
                allow_self_referential,
                relationship_target_getter: _,
            } => f
                .debug_struct("Relationship")
                .field("entity_field_offset", entity_field_offset)
                .field("linked_spawn", linked_spawn)
                .field("allow_self_referential", allow_self_referential)
                .finish(),
            Self::RelationshipTarget {
                iter,
                linked_spawn,
                allow_self_referential,
                relationship_getter: _,
            } => f
                .debug_struct("RelationshipTarget")
                .field("iter", iter)
                .field("linked_spawn", linked_spawn)
                .field("allow_self_referential", allow_self_referential)
                .finish(),
        }
    }
}

#[derive(Clone, Debug, Default)]
pub(crate) enum MaybeRelationshipAccessor {
    /// Not a relationship
    #[default]
    NoAccessor,
    /// Uninitialized relationship, which will be initialized when the second component of the relationship is registered.
    /// Boxed to reduce size overhead.
    Initializer(Box<RelationshipAccessorInitializer>),
    /// Relationship
    Accessor(RelationshipAccessor),
}

impl MaybeRelationshipAccessor {
    /// Returns [`RelationshipAccessor`] if this component is a part of relationship and the accessor is initialized.
    pub fn accessor(&self) -> Option<&RelationshipAccessor> {
        match self {
            MaybeRelationshipAccessor::Accessor(relationship_accessor) => {
                Some(relationship_accessor)
            }
            _ => None,
        }
    }

    /// Initializes the relationship accessor if it isn't initialized already and the counterpart is registered.
    pub fn initialize(&mut self, id: ComponentId, components: &mut Components) {
        _ = (|| {
            let accessor = self.initializer_to_accessor(|getter| getter(components))?;
            let counterpart_id = accessor.counterpart_id();
            let counterpart_slot = components.get_relationship_accessor_mut(counterpart_id)?;
            let counterpart_accessor = counterpart_slot.initializer_to_accessor(|_| Some(id))?;
            *counterpart_slot = MaybeRelationshipAccessor::Accessor(counterpart_accessor);
            *self = MaybeRelationshipAccessor::Accessor(accessor);
            Some(())
        })();
    }

    fn initializer_to_accessor(
        &self,
        mapper: impl FnOnce(&dyn Fn(&Components) -> Option<ComponentId>) -> Option<ComponentId>,
    ) -> Option<RelationshipAccessor> {
        let MaybeRelationshipAccessor::Initializer(initializer) = self else {
            return None;
        };
        Some(match *initializer.as_ref() {
            RelationshipAccessorInitializer::Relationship {
                entity_field_offset,
                linked_spawn,
                allow_self_referential,
                ref relationship_target_getter,
            } => {
                let relationship_target = mapper(relationship_target_getter.as_ref())?;
                RelationshipAccessor::Relationship {
                    entity_field_offset,
                    linked_spawn,
                    allow_self_referential,
                    relationship_target,
                }
            }
            RelationshipAccessorInitializer::RelationshipTarget {
                iter,
                linked_spawn,
                allow_self_referential,
                ref relationship_getter,
            } => {
                let relationship = mapper(relationship_getter.as_ref())?;
                RelationshipAccessor::RelationshipTarget {
                    iter,
                    linked_spawn,
                    allow_self_referential,
                    relationship,
                }
            }
        })
    }
}

impl From<Option<RelationshipAccessorInitializer>> for MaybeRelationshipAccessor {
    fn from(value: Option<RelationshipAccessorInitializer>) -> Self {
        value
            .map(|v| MaybeRelationshipAccessor::Initializer(Box::new(v)))
            .unwrap_or(MaybeRelationshipAccessor::NoAccessor)
    }
}

/// This enum describes a way to access the entities of [`Relationship`] and [`RelationshipTarget`] components
/// in a type-erased context.
#[derive(Debug, Clone, Copy)]
pub enum RelationshipAccessor {
    /// This component is a [`Relationship`].
    Relationship {
        /// Offset of the field containing [`Entity`] from the base of the component.
        ///
        /// Dynamic equivalent of [`Relationship::get`].
        entity_field_offset: usize,
        /// Value of [`RelationshipTarget::LINKED_SPAWN`] for the [`Relationship::RelationshipTarget`] of this [`Relationship`].
        linked_spawn: bool,
        /// Value of [`Relationship::ALLOW_SELF_REFERENTIAL`] of this [`Relationship`].
        allow_self_referential: bool,
        /// [`ComponentId`] of the [`RelationshipTarget`] counterpart.
        relationship_target: ComponentId,
    },
    /// This component is a [`RelationshipTarget`].
    RelationshipTarget {
        /// Function that returns an iterator over all [`Entity`]s of this [`RelationshipTarget`]'s collection.
        ///
        /// Dynamic equivalent of [`RelationshipTarget::iter`].
        /// # Safety
        /// Passed pointer must point to the value of the same component as the one that this accessor was registered to.
        iter: for<'a> unsafe fn(Ptr<'a>) -> Box<dyn Iterator<Item = Entity> + 'a>,
        /// Value of [`RelationshipTarget::LINKED_SPAWN`] of this [`RelationshipTarget`].
        linked_spawn: bool,
        /// Value of [`Relationship::ALLOW_SELF_REFERENTIAL`] for the [`Relationship`] of this [`RelationshipTarget`].
        allow_self_referential: bool,
        /// [`ComponentId`] of the [`Relationship`] counterpart.
        relationship: ComponentId,
    },
}

impl RelationshipAccessor {
    /// Returns [`ComponentId`] of [`RelationshipTarget`] for this [`Relationship`] and vice-versa.
    pub fn counterpart_id(&self) -> ComponentId {
        match self {
            RelationshipAccessor::Relationship {
                relationship_target,
                ..
            } => *relationship_target,
            RelationshipAccessor::RelationshipTarget { relationship, .. } => *relationship,
        }
    }

    /// Returns the value of [`RelationshipTarget::LINKED_SPAWN`].
    pub fn linked_spawn(&self) -> bool {
        match self {
            RelationshipAccessor::Relationship { linked_spawn, .. }
            | RelationshipAccessor::RelationshipTarget { linked_spawn, .. } => *linked_spawn,
        }
    }

    /// Returns the value of [`Relationship::ALLOW_SELF_REFERENTIAL`].
    pub fn allow_self_referential(&self) -> bool {
        match self {
            RelationshipAccessor::Relationship {
                allow_self_referential,
                ..
            }
            | RelationshipAccessor::RelationshipTarget {
                allow_self_referential,
                ..
            } => *allow_self_referential,
        }
    }
}

/// A type-safe convenience wrapper over [`RelationshipAccessor`].
pub struct ComponentRelationshipAccessor<C: ?Sized> {
    pub(crate) initializer: RelationshipAccessorInitializer,
    phantom: PhantomData<C>,
}

impl<C> ComponentRelationshipAccessor<C> {
    /// Create a new [`ComponentRelationshipAccessor`] for a [`Relationship`] component.
    /// # Safety
    /// `entity_field_offset` should be the offset from the base of this component and point to a field that stores value of type [`Entity`].
    /// This value can be obtained using the [`core::mem::offset_of`] macro.
    pub unsafe fn relationship(entity_field_offset: usize) -> Self
    where
        C: Relationship,
    {
        // Due to https://github.com/taiki-e/portable-atomic/issues/143 we have to box this first, and then get the Arc from the box
        let getter: Box<dyn Fn(&Components) -> Option<ComponentId>> =
            Box::new(|components| components.get_id(TypeId::of::<C::RelationshipTarget>()));
        Self {
            initializer: RelationshipAccessorInitializer::Relationship {
                entity_field_offset,
                linked_spawn: C::RelationshipTarget::LINKED_SPAWN,
                allow_self_referential: C::ALLOW_SELF_REFERENTIAL,
                relationship_target_getter: Arc::from(getter),
            },
            phantom: Default::default(),
        }
    }

    /// Create a new [`ComponentRelationshipAccessor`] for a [`RelationshipTarget`] component.
    pub fn relationship_target() -> Self
    where
        C: RelationshipTarget,
    {
        // Due to https://github.com/taiki-e/portable-atomic/issues/143 we have to box this first, and then get the Arc from the box
        let getter: Box<dyn Fn(&Components) -> Option<ComponentId>> =
            Box::new(|components| components.get_id(TypeId::of::<C::Relationship>()));
        Self {
            initializer: RelationshipAccessorInitializer::RelationshipTarget {
                // Safety: caller ensures that `ptr` is of type `C`.
                iter: |ptr| unsafe { Box::new(RelationshipTarget::iter(ptr.deref::<C>())) },
                linked_spawn: C::LINKED_SPAWN,
                allow_self_referential: C::Relationship::ALLOW_SELF_REFERENTIAL,
                relationship_getter: Arc::from(getter),
            },
            phantom: Default::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use core::marker::PhantomData;
    use core::sync::atomic::AtomicBool;

    use crate::lifecycle::HookContext;
    use crate::prelude::{ChildOf, Children};
    use crate::relationship::{Relationship, RelationshipAccessor};
    use crate::world::{DeferredWorld, World};
    use crate::{component::Component, entity::Entity};
    use alloc::vec::Vec;

    #[test]
    fn custom_relationship() {
        #[derive(Component)]
        #[relationship(relationship_target = LikedBy)]
        struct Likes(pub Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Likes)]
        struct LikedBy(Vec<Entity>);

        let mut world = World::new();
        let a = world.spawn_empty().id();
        let b = world.spawn(Likes(a)).id();
        let c = world.spawn(Likes(a)).id();
        assert_eq!(world.entity(a).get::<LikedBy>().unwrap().0, &[b, c]);
    }

    #[test]
    fn self_relationship_fails_by_default() {
        #[derive(Component)]
        #[relationship(relationship_target = RelTarget)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Vec<Entity>);

        let mut world = World::new();
        let a = world.spawn_empty().id();
        world.entity_mut(a).insert(Rel(a));
        assert!(!world.entity(a).contains::<Rel>());
        assert!(!world.entity(a).contains::<RelTarget>());
    }

    #[test]
    fn self_relationship_succeeds_with_allow_self_referential() {
        #[derive(Component)]
        #[relationship(relationship_target = RelTarget, allow_self_referential)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Vec<Entity>);

        let mut world = World::new();
        let a = world.spawn_empty().id();
        world.entity_mut(a).insert(Rel(a));
        assert!(world.entity(a).contains::<Rel>());
        assert!(world.entity(a).contains::<RelTarget>());
        assert_eq!(world.entity(a).get::<Rel>().unwrap().get(), a);
        assert_eq!(&*world.entity(a).get::<RelTarget>().unwrap().0, &[a]);
    }

    #[test]
    fn self_relationship_removal_with_allow_self_referential() {
        #[derive(Component)]
        #[relationship(relationship_target = RelTarget, allow_self_referential)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Vec<Entity>);

        let mut world = World::new();
        let a = world.spawn_empty().id();
        world.entity_mut(a).insert(Rel(a));
        assert!(world.entity(a).contains::<Rel>());
        assert!(world.entity(a).contains::<RelTarget>());

        // Remove the relationship and verify cleanup
        world.entity_mut(a).remove::<Rel>();
        assert!(!world.entity(a).contains::<Rel>());
        assert!(!world.entity(a).contains::<RelTarget>());
    }

    #[test]
    fn relationship_with_missing_target_fails() {
        #[derive(Component)]
        #[relationship(relationship_target = RelTarget)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Vec<Entity>);

        let mut world = World::new();
        let a = world.spawn_empty().id();
        world.despawn(a);
        let b = world.spawn(Rel(a)).id();
        assert!(!world.entity(b).contains::<Rel>());
        assert!(!world.entity(b).contains::<RelTarget>());
    }

    #[test]
    fn relationship_with_multiple_non_target_fields_compiles() {
        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship(relationship_target=Target)]
        struct Source {
            #[relationship]
            target: Entity,
            foo: u8,
            bar: u8,
        }

        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship_target(relationship=Source)]
        struct Target(Vec<Entity>);

        // No assert necessary, looking to make sure compilation works with the macros
    }
    #[test]
    fn relationship_target_with_multiple_non_target_fields_compiles() {
        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship(relationship_target=Target)]
        struct Source(Entity);

        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship_target(relationship=Source)]
        struct Target {
            #[relationship]
            target: Vec<Entity>,
            foo: u8,
            bar: u8,
        }

        // No assert necessary, looking to make sure compilation works with the macros
    }

    #[test]
    fn relationship_with_multiple_unnamed_non_target_fields_compiles() {
        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship(relationship_target=Target<T>)]
        struct Source<T: Send + Sync + 'static>(#[relationship] Entity, PhantomData<T>);

        #[expect(
            dead_code,
            reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
        )]
        #[derive(Component)]
        #[relationship_target(relationship=Source<T>)]
        struct Target<T: Send + Sync + 'static>(#[relationship] Vec<Entity>, PhantomData<T>);

        // No assert necessary, looking to make sure compilation works with the macros
    }

    #[test]
    fn parent_child_relationship_with_custom_relationship() {
        #[derive(Component)]
        #[relationship(relationship_target = RelTarget)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Entity);

        let mut world = World::new();

        // Rel on Parent
        // Despawn Parent
        let mut commands = world.commands();
        let child = commands.spawn_empty().id();
        let parent = commands.spawn(Rel(child)).add_child(child).id();
        commands.entity(parent).despawn();
        world.flush();

        assert!(world.get_entity(child).is_err());
        assert!(world.get_entity(parent).is_err());

        // Rel on Parent
        // Despawn Child
        let mut commands = world.commands();
        let child = commands.spawn_empty().id();
        let parent = commands.spawn(Rel(child)).add_child(child).id();
        commands.entity(child).despawn();
        world.flush();

        assert!(world.get_entity(child).is_err());
        assert!(!world.entity(parent).contains::<Rel>());

        // Rel on Child
        // Despawn Parent
        let mut commands = world.commands();
        let parent = commands.spawn_empty().id();
        let child = commands.spawn((ChildOf(parent), Rel(parent))).id();
        commands.entity(parent).despawn();
        world.flush();

        assert!(world.get_entity(child).is_err());
        assert!(world.get_entity(parent).is_err());

        // Rel on Child
        // Despawn Child
        let mut commands = world.commands();
        let parent = commands.spawn_empty().id();
        let child = commands.spawn((ChildOf(parent), Rel(parent))).id();
        commands.entity(child).despawn();
        world.flush();

        assert!(world.get_entity(child).is_err());
        assert!(!world.entity(parent).contains::<RelTarget>());
    }

    #[test]
    fn spawn_batch_with_relationship() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        let children = world
            .spawn_batch((0..10).map(|_| ChildOf(parent)))
            .collect::<Vec<_>>();

        for &child in &children {
            assert!(world
                .get::<ChildOf>(child)
                .is_some_and(|child_of| child_of.parent() == parent));
        }
        assert!(world
            .get::<Children>(parent)
            .is_some_and(|children| children.len() == 10));
    }

    #[test]
    fn insert_batch_with_relationship() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        let child = world.spawn_empty().id();
        world.insert_batch([(child, ChildOf(parent))]);
        world.flush();

        assert!(world.get::<ChildOf>(child).is_some());
        assert!(world.get::<Children>(parent).is_some());
    }

    #[test]
    fn dynamically_traverse_hierarchy() {
        let mut world = World::new();
        let child_of_id = world.register_component::<ChildOf>();
        let children_id = world.register_component::<Children>();

        let parent = world.spawn_empty().id();
        let child = world.spawn_empty().id();
        world.entity_mut(child).insert(ChildOf(parent));
        world.flush();

        let children_ptr = world.get_by_id(parent, children_id).unwrap();
        let RelationshipAccessor::RelationshipTarget { iter, .. } = world
            .components()
            .get_info(children_id)
            .unwrap()
            .relationship_accessor()
            .unwrap()
        else {
            unreachable!()
        };
        // Safety: `children_ptr` contains value of the same type as the one this accessor was registered for.
        let children: Vec<_> = unsafe { iter(children_ptr).collect() };
        assert_eq!(children, alloc::vec![child]);

        let child_of_ptr = world.get_by_id(child, child_of_id).unwrap();
        let RelationshipAccessor::Relationship {
            entity_field_offset,
            ..
        } = world
            .components()
            .get_info(child_of_id)
            .unwrap()
            .relationship_accessor()
            .unwrap()
        else {
            unreachable!()
        };
        // Safety:
        // - offset is in bounds, aligned and has the same lifetime as the original pointer.
        // - value at offset is guaranteed to be a valid Entity
        let child_of_entity: Entity =
            unsafe { *child_of_ptr.byte_add(*entity_field_offset).deref() };
        assert_eq!(child_of_entity, parent);
    }

    #[test]
    fn relationship_accessor() {
        #[derive(Component)]
        #[relationship(relationship_target = LikedBy)]
        struct Likes {
            _a: u16,
            #[relationship]
            e: Entity,
            _b: (i8, u8),
        }

        #[derive(Component)]
        #[relationship_target(relationship = Likes)]
        struct LikedBy(Vec<Entity>);

        let mut world = World::new();
        let likes_id = world.register_component::<Likes>();
        let liked_by_id = world.register_component::<LikedBy>();

        let likes_accessor = world
            .components()
            .get_info(likes_id)
            .unwrap()
            .relationship_accessor()
            .unwrap();
        match *likes_accessor {
            RelationshipAccessor::Relationship {
                entity_field_offset,
                linked_spawn,
                allow_self_referential,
                relationship_target,
            } => {
                assert_eq!(entity_field_offset, core::mem::offset_of!(Likes, e));
                assert!(!linked_spawn);
                assert!(!allow_self_referential);
                assert_eq!(relationship_target, liked_by_id);
            }
            _ => {
                panic!("Not a Relationship")
            }
        }

        let liked_by_accessor = world
            .components()
            .get_info(liked_by_id)
            .unwrap()
            .relationship_accessor()
            .unwrap();
        match *liked_by_accessor {
            RelationshipAccessor::RelationshipTarget {
                iter,
                linked_spawn,
                allow_self_referential,
                relationship,
            } => {
                let liked_by = LikedBy(alloc::vec![
                    world.spawn_empty().id(),
                    world.spawn_empty().id(),
                    world.spawn_empty().id()
                ]);
                // SAFETY: liked_by is of type LikedBy
                unsafe {
                    assert_eq!(iter((&liked_by).into()).collect::<Vec<_>>(), liked_by.0);
                }
                assert!(!linked_spawn);
                assert!(!allow_self_referential);
                assert_eq!(relationship, likes_id);
            }
            _ => {
                panic!("Not a RelationshipTarget")
            }
        }

        #[derive(Component)]
        #[relationship(relationship_target = RelTarget, allow_self_referential)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel, linked_spawn)]
        struct RelTarget(Vec<Entity>);

        let rel_id = world.register_component::<Rel>();
        let rel_target_id = world.register_component::<RelTarget>();

        let rel_accessor = world
            .components()
            .get_info(rel_id)
            .unwrap()
            .relationship_accessor()
            .unwrap();
        assert!(rel_accessor.linked_spawn());
        assert!(rel_accessor.allow_self_referential());
        let rel_target_accessor = world
            .components()
            .get_info(rel_target_id)
            .unwrap()
            .relationship_accessor()
            .unwrap();
        assert!(rel_target_accessor.linked_spawn());
        assert!(rel_target_accessor.allow_self_referential());
    }

    #[test]
    pub fn component_hooks_compatibility() {
        static ADD_CALLED: AtomicBool = AtomicBool::new(false);
        static INSERT_CALLED: AtomicBool = AtomicBool::new(false);
        static DISCARD_CALLED: AtomicBool = AtomicBool::new(false);
        static REMOVE_CALLED: AtomicBool = AtomicBool::new(false);
        static DESPAWN_CALLED: AtomicBool = AtomicBool::new(false);

        #[derive(Component)]
        #[relationship(relationship_target = RelTarget)]
        #[component(on_add, on_insert, on_discard, on_remove, on_despawn)]
        struct Rel(Entity);

        #[derive(Component)]
        #[relationship_target(relationship = Rel)]
        struct RelTarget(Entity);

        impl Rel {
            fn on_add(world: DeferredWorld, context: HookContext) {
                let &Rel(target) = world.get(context.entity).unwrap();
                assert!(!world.entity(target).contains::<RelTarget>());
                ADD_CALLED.store(true, core::sync::atomic::Ordering::Relaxed);
            }

            fn on_insert(world: DeferredWorld, context: HookContext) {
                let &Rel(target) = world.get(context.entity).unwrap();
                assert!(!world.entity(target).contains::<RelTarget>());
                INSERT_CALLED.store(true, core::sync::atomic::Ordering::Relaxed);
            }

            fn on_discard(world: DeferredWorld, context: HookContext) {
                let &Rel(target) = world.get(context.entity).unwrap();
                assert!(world.entity(target).contains::<RelTarget>());
                DISCARD_CALLED.store(true, core::sync::atomic::Ordering::Relaxed);
            }

            fn on_remove(world: DeferredWorld, context: HookContext) {
                let &Rel(target) = world.get(context.entity).unwrap();
                assert!(world.entity(target).contains::<RelTarget>());
                REMOVE_CALLED.store(true, core::sync::atomic::Ordering::Relaxed);
            }

            fn on_despawn(world: DeferredWorld, context: HookContext) {
                let &Rel(target) = world.get(context.entity).unwrap();
                assert!(world.entity(target).contains::<RelTarget>());
                DESPAWN_CALLED.store(true, core::sync::atomic::Ordering::Relaxed);
            }
        }

        let mut world = World::new();
        let target = world.spawn_empty().id();
        let source = world.spawn(Rel(target)).id();
        assert!(world.entity(target).contains::<RelTarget>());
        assert!(ADD_CALLED.load(core::sync::atomic::Ordering::Relaxed));
        assert!(INSERT_CALLED.load(core::sync::atomic::Ordering::Relaxed));
        world.despawn(source);
        assert!(DISCARD_CALLED.load(core::sync::atomic::Ordering::Relaxed));
        assert!(REMOVE_CALLED.load(core::sync::atomic::Ordering::Relaxed));
        assert!(DESPAWN_CALLED.load(core::sync::atomic::Ordering::Relaxed));
    }
}