bevy_dev_tools 0.19.0-rc.1

Collection of developer tools for the Bevy Engine
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
//! Utilities for serializing schedule data for an [`App`](bevy_app::App).
//!
//! These are mostly around providing types implementing [`Serialize`]/[`Deserialize`] that
//! represent schedule data. In addition, there are tools for extracting this data from the
//! [`World`](bevy_ecs::world::World).

use bevy_ecs::{
    component::{ComponentId, Components},
    schedule::{
        ApplyDeferred, ConditionWithAccess, InternedScheduleLabel, NodeId, Schedule,
        ScheduleBuildMetadata, Schedules,
    },
    system::SystemStateFlags,
};
use bevy_platform::collections::{hash_map::Entry, HashMap};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// The data for the entire app's schedule.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AppData {
    /// A list of all schedules in the app.
    pub schedules: Vec<ScheduleData>,
}

impl AppData {
    /// Creates the data from the underlying [`Schedules`].
    ///
    /// Note: we assume all schedules in `schedules` have been initialized through
    /// [`Schedule::initialize`].
    pub fn from_schedules(
        schedules: &Schedules,
        world_components: &Components,
        label_to_build_metadata: &HashMap<InternedScheduleLabel, ScheduleBuildMetadata>,
    ) -> Result<Self, ExtractAppDataError> {
        Ok(Self {
            schedules: schedules
                .iter()
                .map(|(_, schedule)| {
                    ScheduleData::from_schedule(
                        schedule,
                        world_components,
                        label_to_build_metadata.get(&schedule.label()),
                    )
                })
                .collect::<Result<_, ExtractAppDataError>>()?,
        })
    }
}

/// Data about a particular schedule.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ScheduleData {
    /// The name of the schedule.
    pub name: String,
    /// The systems in this schedule.
    pub systems: Vec<SystemData>,
    /// The system sets in this schedule.
    pub system_sets: Vec<SystemSetData>,
    /// A list of relationships indicating that a system/system set is contained in a system set.
    ///
    /// The order is (parent, child).
    pub hierarchy: Vec<(SystemSetIndex, ScheduleIndex)>,
    /// A list of ordering constraints, ensuring that one system/system set runs before another.
    ///
    /// The order is (first, second).
    pub dependency: Vec<(ScheduleIndex, ScheduleIndex)>,
    /// The components that these systems access.
    pub components: Vec<ComponentData>,
    /// A list of conflicts between systems.
    pub conflicts: Vec<SystemConflict>,
}

/// Data about a component type.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct ComponentData {
    /// The name of the component.
    pub name: String,
}

/// Data about a particular system.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct SystemData {
    /// The name of the system.
    pub name: String,
    /// Whether this system is a sync point (aka [`ApplyDeferred`]).
    pub apply_deferred: bool,
    /// Whether this system is exclusive.
    pub exclusive: bool,
    /// Whether this system has deferred buffers to apply.
    pub deferred: bool,
    // TODO: Store the conditions specific to this system.
}

/// Data about a particular system set.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct SystemSetData {
    /// The name of the system set.
    pub name: String,
    /// The conditions applied to this system.
    pub conditions: Vec<ConditionData>,
}

/// Data about a run condition for a system.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct ConditionData {
    /// The name of the condition.
    pub name: String,
}

/// An index of an element in a schedule.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum ScheduleIndex {
    /// The index of a system.
    System(u32),
    /// The index of a system set.
    SystemSet(u32),
}

/// Data about an access conflict between two systems.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct SystemConflict {
    /// The first system index.
    pub system_1: u32,
    /// The second system index.
    pub system_2: u32,
    /// The kind of conflict between these systems.
    pub conflicting_access: AccessConflict,
}

/// Data for describing the kind of access conflict.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub enum AccessConflict {
    /// There is a conflict on the **whole world**, since one of the systems requires world access
    /// and the other needs mutable access to (some of) the world.
    World,
    /// There is incompatible accesses to the listed components.
    Components(Vec<u32>),
}

/// A newtype for the index of a system set.
///
/// This is the same kind of index as [`ScheduleIndex::SystemSet`], but for cases where we know we
/// can't have a system.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, PartialOrd, Ord)]
pub struct SystemSetIndex(pub u32);

impl ScheduleData {
    /// Creates the data from the underlying [`Schedule`].
    ///
    /// Note: we assume `schedule` has already been initialized.
    pub fn from_schedule(
        schedule: &Schedule,
        world_components: &Components,
        build_metadata: Option<&ScheduleBuildMetadata>,
    ) -> Result<Self, ExtractAppDataError> {
        let graph = schedule.graph();

        let mut system_key_to_index = HashMap::new();
        let mut system_set_key_to_index = HashMap::new();

        fn extract_condition_data(conditions: &[ConditionWithAccess]) -> Vec<ConditionData> {
            conditions
                .iter()
                .map(|condition| ConditionData {
                    name: format!("{}", condition.condition.name()),
                })
                .collect()
        }

        let systems = schedule
            .systems()
            .map_err(|_| {
                ExtractAppDataError::ScheduleNotInitialized(format!("{:?}", schedule.label()))
            })?
            .enumerate()
            .map(|(index, (key, system))| {
                system_key_to_index.insert(key, index);

                let flags = system.flags();

                SystemData {
                    name: format!("{}", system.name()),
                    apply_deferred: system.system_type()
                        == core::any::TypeId::of::<ApplyDeferred>(),
                    exclusive: flags.contains(SystemStateFlags::EXCLUSIVE),
                    deferred: flags.contains(SystemStateFlags::DEFERRED),
                }
            })
            .collect();

        let system_sets = graph
            .system_sets
            .iter()
            .enumerate()
            .map(|(index, (key, system_set, conditions))| {
                system_set_key_to_index.insert(key, index);

                SystemSetData {
                    name: format!("{:?}", system_set),
                    conditions: extract_condition_data(conditions),
                }
            })
            .collect();

        let node_id_to_schedule_index = |node_id: NodeId| match node_id {
            NodeId::System(key) => ScheduleIndex::System(
                *system_key_to_index
                    .get(&key)
                    .expect("the system this key refers to should have already been seen")
                    as _,
            ),
            NodeId::Set(key) => ScheduleIndex::SystemSet(
                *system_set_key_to_index
                    .get(&key)
                    .expect("the system set this key refers to should have already been seen")
                    as _,
            ),
        };

        let hierarchy = graph
            .hierarchy()
            .graph()
            .all_edges()
            .map(|(parent, child)| {
                let parent = system_set_key_to_index
                    .get(
                        &parent
                            .as_set()
                            .expect("the parent of a system/set is always a set"),
                    )
                    .expect("the system set this key refers to should have already been seen");
                let child = node_id_to_schedule_index(child);

                (SystemSetIndex(*parent as _), child)
            })
            .collect();

        let mut dependency = graph
            .dependency()
            .graph()
            .all_edges()
            .map(|(a, b)| (node_id_to_schedule_index(a), node_id_to_schedule_index(b)))
            .collect::<Vec<_>>();

        if let Some(build_metadata) = build_metadata {
            // Add in all the edges that were created by build passes.
            dependency.extend(
                build_metadata
                    .edges_added_by_build_passes
                    .iter()
                    .map(|(a, b)| {
                        (
                            node_id_to_schedule_index(NodeId::System(*a)),
                            node_id_to_schedule_index(NodeId::System(*b)),
                        )
                    }),
            );
        }

        let mut component_id_to_index = HashMap::<ComponentId, usize>::new();
        let mut components = vec![];

        let conflicts = graph
            .conflicting_systems()
            .iter()
            .map(|(system_1, system_2, conflicts)| {
                let system_1 = system_key_to_index
                    .get(system_1)
                    .expect("the system this key refers to should have already been seen");
                let system_2 = system_key_to_index
                    .get(system_2)
                    .expect("the system this key refers to should have already been seen");

                SystemConflict {
                    system_1: *system_1 as _,
                    system_2: *system_2 as _,
                    conflicting_access: if conflicts.is_empty() {
                        // The systems conflict on the world if there's no particular component IDs.
                        AccessConflict::World
                    } else {
                        AccessConflict::Components(
                            conflicts
                                .iter()
                                .map(|id| match component_id_to_index.entry(*id) {
                                    Entry::Occupied(entry) => *entry.get() as _,
                                    Entry::Vacant(entry) => {
                                        let component = world_components.get_info(*id).expect(
                                    "the component has already been registered by the system",
                                );

                                        components.push(ComponentData {
                                            name: format!("{}", component.name()),
                                        });
                                        *entry.insert(components.len() - 1) as _
                                    }
                                })
                                .collect(),
                        )
                    },
                }
            })
            .collect();

        Ok(Self {
            name: format!("{:?}", schedule.label()),
            components,
            systems,
            system_sets,
            hierarchy,
            dependency,
            conflicts,
        })
    }
}

/// An error occurring while attempting to extract schedule data from an app.
#[derive(Error, Debug)]
pub enum ExtractAppDataError {
    /// A schedule has not been initialized through [`Schedule::initialize`].
    #[error("executable schedule has not been created for label \"{0}\"")]
    ScheduleNotInitialized(String),
}

#[cfg(test)]
/// Tests for extracted schedule data.
///
/// This is public to allow other test modules in this crate to use its utilities.
pub mod tests {
    use bevy_app::{App, Update};
    use bevy_ecs::{
        component::Component,
        query::{With, Without},
        schedule::{IntoScheduleConfigs, Schedules, SystemSet},
        system::{Commands, Query},
    };
    use bevy_platform::collections::HashMap;

    use crate::schedule_data::serde::{
        AccessConflict, AppData, ComponentData, ExtractAppDataError, ScheduleData, ScheduleIndex,
        SystemConflict, SystemData, SystemSetData, SystemSetIndex,
    };

    fn app_data_from_app(app: &mut App) -> Result<AppData, ExtractAppDataError> {
        let schedules = app.world_mut().resource::<Schedules>();
        // TODO: This is a pain. It would be nice to be able to just hokey-pokey the whole
        // `Schedules` resource, but initializing a schedule writes to `Schedules`. Also we need to
        // use interned labels since `Box<dyn ScheduleLabel>` doesn't impl `ScheduleLabel`!
        let interned_labels = schedules
            .iter()
            .map(|(_, schedule)| schedule.label())
            .collect::<Vec<_>>();

        let mut label_to_build_metadata = HashMap::new();

        for label in interned_labels {
            let build_metadata = app
                .world_mut()
                .schedule_scope(label, |world, schedule| schedule.initialize(world))
                .unwrap()
                .unwrap();
            label_to_build_metadata.insert(label, build_metadata);
        }

        let mut app_data = AppData::from_schedules(
            app.world().resource::<Schedules>(),
            app.world().components(),
            &label_to_build_metadata,
        )?;

        remove_module_paths(&mut app_data);
        sort_app_data(&mut app_data);
        Ok(app_data)
    }

    /// Removes the module paths from all items in the [`AppData`], so that moving tests around
    /// doesn't change the output.
    pub fn remove_module_paths(app_data: &mut AppData) {
        for schedule in app_data.schedules.iter_mut() {
            for system in schedule.systems.iter_mut() {
                system.name = system.name.rsplit_once(":").unwrap().1.to_string();
            }
            for set in schedule.system_sets.iter_mut() {
                let name_modless = set
                    .name
                    .rsplit_once(":")
                    .map(|(_, suffix)| suffix)
                    .unwrap_or(set.name.as_str())
                    .to_string();
                if set.name.starts_with("SystemTypeSet") {
                    // This is a set corresponding to a system. Make sure to keep the
                    // `SystemTypeSet` prefix.
                    set.name = format!("SystemTypeSet:{name_modless}");
                } else {
                    set.name = name_modless;
                }
            }
            for component in schedule.components.iter_mut() {
                component.name = component.name.rsplit_once(":").unwrap().1.to_string();
            }
        }
    }

    /// Sorts the [`AppData`] so we have a deterministic order when asserting.
    // Note: we could do this when extracting unconditionally (even in prod), but there's not much
    // point since schedule order is not guaranteed to be deterministic anyway. So relying on the
    // same order seems weird.
    pub fn sort_app_data(app_data: &mut AppData) {
        // Sort schedules by name.
        app_data
            .schedules
            .sort_by_key(|schedule| schedule.name.clone());
        // Sort each schedule.
        app_data.schedules.iter_mut().for_each(sort_schedule);

        /// Sorts a schedule so that systems, system sets, conditions, and components are in name
        /// order, and other structures are in index order.
        fn sort_schedule(schedule: &mut ScheduleData) {
            /// Sorts the slice using `key_fn` and returns a mapping, which maps the original index
            /// to the new index.
            fn reorder_slice<T, K: Ord>(
                slice: &mut [T],
                key_fn: impl Fn(&T) -> K,
            ) -> HashMap<usize, usize> {
                let mut mapping = (0..slice.len()).collect::<Vec<_>>();
                // We assume the two sorts produce the same thing which should be true since we are
                // using a stable sort.
                mapping.sort_by_key(|index| key_fn(&slice[*index]));
                slice.sort_by_key(key_fn);

                mapping
                    .into_iter()
                    // Enumerating produces the new indices.
                    .enumerate()
                    // Flip the order of indices so that we go from old to new.
                    .map(|(new, old)| (old, new))
                    .collect()
            }

            let system_old_index_to_new_index =
                reorder_slice(&mut schedule.systems, |system| system.name.clone());
            let system_set_old_index_to_new_index =
                reorder_slice(&mut schedule.system_sets, |set| set.name.clone());
            let component_old_index_to_new_index =
                reorder_slice(&mut schedule.components, |component| component.name.clone());

            let reindex_system = |index: &mut u32| {
                *index = *system_old_index_to_new_index
                    .get(&(*index as usize))
                    .unwrap() as u32;
            };
            let reindex_system_set = |index: &mut u32| {
                *index = *system_set_old_index_to_new_index
                    .get(&(*index as usize))
                    .unwrap() as u32;
            };
            let reindex_schedule_index = |index: &mut ScheduleIndex| match index {
                ScheduleIndex::System(system) => reindex_system(system),
                ScheduleIndex::SystemSet(set) => reindex_system_set(set),
            };

            let reindex_component = |index: &mut u32| {
                *index = *component_old_index_to_new_index
                    .get(&(*index as usize))
                    .unwrap() as u32;
            };

            // Sort the conditions in a system set.
            for set in schedule.system_sets.iter_mut() {
                set.conditions
                    .sort_by_key(|condition| condition.name.clone());
            }

            // Reindex the hierarchy, and sort it.
            for (parent, child) in schedule.hierarchy.iter_mut() {
                reindex_system_set(&mut parent.0);
                reindex_schedule_index(child);
            }
            schedule.hierarchy.sort();

            // Reindex the dependencies, and sort it.
            for (parent, child) in schedule.dependency.iter_mut() {
                reindex_schedule_index(parent);
                reindex_schedule_index(child);
            }
            schedule.dependency.sort();

            // Reindex the conflicts.
            for conflict in schedule.conflicts.iter_mut() {
                reindex_system(&mut conflict.system_1);
                reindex_system(&mut conflict.system_2);

                // The order of the indices don't matter, so pick the ordering such that `system_1 <
                // system_2`.
                if conflict.system_1 > conflict.system_2 {
                    core::mem::swap(&mut conflict.system_1, &mut conflict.system_2);
                }

                match &mut conflict.conflicting_access {
                    AccessConflict::World => {}
                    AccessConflict::Components(components) => {
                        components.iter_mut().for_each(reindex_component);
                        components.sort();
                    }
                };
            }
            schedule
                .conflicts
                .sort_by_key(|conflict| (conflict.system_1, conflict.system_2));
        }
    }

    /// Convenience to create a [`SystemData`] for the common case of no flags set.
    pub fn simple_system(name: &str) -> SystemData {
        SystemData {
            name: name.into(),
            apply_deferred: false,
            exclusive: false,
            deferred: false,
        }
    }

    /// Convenience to create a [`SystemSetData`] for the common case of being empty.
    pub fn simple_system_set(name: &str) -> SystemSetData {
        SystemSetData {
            name: name.into(),
            conditions: vec![],
        }
    }

    /// Convenience to create a [`ComponentData`] to make test cases shorter.
    pub fn simple_component(name: &str) -> ComponentData {
        ComponentData { name: name.into() }
    }

    /// Convenience to create a [`SystemConflict`] to make test cases shorter.
    pub fn conflict(
        system_1: u32,
        system_2: u32,
        conflicting_access: AccessConflict,
    ) -> SystemConflict {
        SystemConflict {
            system_1,
            system_2,
            conflicting_access,
        }
    }

    /// A convenience system set that is generic allowing us to make many of these quickly.
    #[derive(SystemSet, Hash, PartialEq, Eq, Clone)]
    struct MySet<const NUM: u32>;

    impl<const NUM: u32> core::fmt::Debug for MySet<NUM> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "MySet<{NUM}>")
        }
    }

    /// A convenience component that is generic allowing us to make many of these quickly.
    #[derive(Component)]
    struct MyComponent<const NUM: u32>;

    #[test]
    fn linear() {
        let mut app = App::empty();

        fn a() {}
        fn b() {}
        fn c() {}

        app.add_systems(Update, (a, b, c).chain());

        let data = app_data_from_app(&mut app).unwrap();
        assert_eq!(data.schedules.len(), 1);
        let schedule = &data.schedules[0];
        assert_eq!(schedule.name, "Update");
        assert_eq!(
            schedule.systems,
            [simple_system("a"), simple_system("b"), simple_system("c"),]
        );
        // Each system is also a system set.
        assert_eq!(
            schedule.system_sets,
            [
                simple_system_set("SystemTypeSet:a"),
                simple_system_set("SystemTypeSet:b"),
                simple_system_set("SystemTypeSet:c"),
            ]
        );
        // Every system is in its own system set.
        assert_eq!(
            schedule.hierarchy,
            [
                (SystemSetIndex(0), ScheduleIndex::System(0)),
                (SystemSetIndex(1), ScheduleIndex::System(1)),
                (SystemSetIndex(2), ScheduleIndex::System(2)),
            ]
        );
        // There are 2 dependency edges to connect a-b and b-c.
        assert_eq!(
            schedule.dependency,
            [
                (ScheduleIndex::System(0), ScheduleIndex::System(1)),
                (ScheduleIndex::System(1), ScheduleIndex::System(2)),
            ]
        );
        assert_eq!(schedule.components.len(), 0);
        assert_eq!(schedule.conflicts.len(), 0);
    }

    #[test]
    fn linear_with_system_sets() {
        let mut app = App::empty();

        app.configure_sets(Update, (MySet::<0>, MySet::<1>, MySet::<2>).chain());

        let data = app_data_from_app(&mut app).unwrap();
        assert_eq!(data.schedules.len(), 1);
        let schedule = &data.schedules[0];
        assert_eq!(schedule.name, "Update");
        assert_eq!(schedule.systems, []);
        assert_eq!(
            schedule.system_sets,
            [
                simple_system_set("MySet<0>"),
                simple_system_set("MySet<1>"),
                simple_system_set("MySet<2>"),
            ]
        );
        assert_eq!(schedule.hierarchy, []);
        // There are 2 dependency edges to connect 0-1 and 1-2.
        assert_eq!(
            schedule.dependency,
            [
                (ScheduleIndex::SystemSet(0), ScheduleIndex::SystemSet(1)),
                (ScheduleIndex::SystemSet(1), ScheduleIndex::SystemSet(2)),
            ]
        );
        assert_eq!(schedule.components.len(), 0);
        assert_eq!(schedule.conflicts.len(), 0);
    }

    #[test]
    fn stack_of_system_sets() {
        let mut app = App::empty();

        fn a() {}

        app.add_systems(Update, a.in_set(MySet::<0>))
            .configure_sets(Update, MySet::<0>.in_set(MySet::<1>))
            .configure_sets(Update, MySet::<1>.in_set(MySet::<2>));

        let data = app_data_from_app(&mut app).unwrap();
        assert_eq!(data.schedules.len(), 1);
        let schedule = &data.schedules[0];
        assert_eq!(schedule.name, "Update");
        assert_eq!(schedule.systems, [simple_system("a")]);
        assert_eq!(
            schedule.system_sets,
            [
                simple_system_set("MySet<0>"),
                simple_system_set("MySet<1>"),
                simple_system_set("MySet<2>"),
                simple_system_set("SystemTypeSet:a"),
            ]
        );
        assert_eq!(
            schedule.hierarchy,
            [
                (SystemSetIndex(0), ScheduleIndex::System(0)),
                (SystemSetIndex(1), ScheduleIndex::SystemSet(0)),
                (SystemSetIndex(2), ScheduleIndex::SystemSet(1)),
                (SystemSetIndex(3), ScheduleIndex::System(0)),
            ]
        );
        assert_eq!(schedule.dependency, []);
        assert_eq!(schedule.components.len(), 0);
        assert_eq!(schedule.conflicts.len(), 0);
    }

    #[test]
    fn records_system_kind_flags() {
        let mut app = App::empty();

        fn a0(_commands: Commands) {}
        fn a1(_commands: Commands) {}
        fn b0() {}
        fn b1() {}

        fn c0() {}
        fn c1() {}

        app.add_systems(Update, (((a0, a1), (b0, b1)).chain(), (c0, c1).chain()));

        let data = app_data_from_app(&mut app).unwrap();
        assert_eq!(data.schedules.len(), 1);
        let schedule = &data.schedules[0];
        assert_eq!(schedule.name, "Update");
        assert_eq!(
            schedule.systems,
            [
                SystemData {
                    name: "a0".into(),
                    apply_deferred: false,
                    exclusive: false,
                    deferred: true,
                },
                SystemData {
                    name: "a1".into(),
                    apply_deferred: false,
                    exclusive: false,
                    deferred: true,
                },
                SystemData {
                    name: "apply_deferred".into(),
                    apply_deferred: true,
                    exclusive: true,
                    deferred: false,
                },
                simple_system("b0"),
                simple_system("b1"),
                simple_system("c0"),
                simple_system("c1"),
            ]
        );
        assert_eq!(
            schedule.system_sets,
            [
                simple_system_set("SystemTypeSet:a0"),
                simple_system_set("SystemTypeSet:a1"),
                simple_system_set("SystemTypeSet:b0"),
                simple_system_set("SystemTypeSet:b1"),
                simple_system_set("SystemTypeSet:c0"),
                simple_system_set("SystemTypeSet:c1"),
            ]
        );
        assert_eq!(
            schedule.hierarchy,
            [
                (SystemSetIndex(0), ScheduleIndex::System(0)),
                (SystemSetIndex(1), ScheduleIndex::System(1)),
                (SystemSetIndex(2), ScheduleIndex::System(3)),
                (SystemSetIndex(3), ScheduleIndex::System(4)),
                (SystemSetIndex(4), ScheduleIndex::System(5)),
                (SystemSetIndex(5), ScheduleIndex::System(6)),
            ]
        );
        assert_eq!(
            schedule.dependency,
            [
                // a->sync and a->b
                (ScheduleIndex::System(0), ScheduleIndex::System(2)),
                (ScheduleIndex::System(0), ScheduleIndex::System(3)),
                (ScheduleIndex::System(0), ScheduleIndex::System(4)),
                (ScheduleIndex::System(1), ScheduleIndex::System(2)),
                (ScheduleIndex::System(1), ScheduleIndex::System(3)),
                (ScheduleIndex::System(1), ScheduleIndex::System(4)),
                // sync->b
                (ScheduleIndex::System(2), ScheduleIndex::System(3)),
                (ScheduleIndex::System(2), ScheduleIndex::System(4)),
                // c0->c1
                (ScheduleIndex::System(5), ScheduleIndex::System(6)),
            ]
        );
        assert_eq!(schedule.components.len(), 0);
        assert_eq!(schedule.conflicts.len(), 0);
    }

    #[test]
    fn records_conflicts() {
        let mut app = App::empty();

        // These two systems don't conflict.
        fn a0(_: Query<&MyComponent<0>>) {}
        fn a1(_: Query<&MyComponent<0>>) {}

        // These two systems conflict on one component.
        fn b0(_: Query<&MyComponent<1>>) {}
        fn b1(_: Query<&mut MyComponent<1>>) {}

        // These two systems conflict on two components.
        fn c0(
            _: Query<(
                &MyComponent<2>,
                &mut MyComponent<3>,
                &MyComponent<4>,
                &MyComponent<5>,
            )>,
        ) {
        }
        fn c1(
            _: Query<(
                &mut MyComponent<2>,
                &MyComponent<3>,
                &MyComponent<4>,
                &MyComponent<6>,
            )>,
        ) {
        }

        // These two systems use With/Without to avoid a conflict.
        fn d0(_: Query<&mut MyComponent<7>, With<MyComponent<8>>>) {}
        fn d1(_: Query<&mut MyComponent<7>, Without<MyComponent<8>>>) {}

        // These two systems use an ordering to avoid a conflict.
        fn e0(_: Query<&mut MyComponent<9>>) {}
        fn e1(_: Query<&mut MyComponent<9>>) {}

        app.add_systems(Update, (a0, a1, b0, b1, c0, c1, d0, d1, (e0, e1).chain()));

        let data = app_data_from_app(&mut app).unwrap();
        assert_eq!(data.schedules.len(), 1);
        let schedule = &data.schedules[0];
        assert_eq!(schedule.name, "Update");
        assert_eq!(
            schedule.systems,
            [
                simple_system("a0"),
                simple_system("a1"),
                simple_system("b0"),
                simple_system("b1"),
                simple_system("c0"),
                simple_system("c1"),
                simple_system("d0"),
                simple_system("d1"),
                simple_system("e0"),
                simple_system("e1"),
            ]
        );
        assert_eq!(
            schedule.system_sets,
            [
                simple_system_set("SystemTypeSet:a0"),
                simple_system_set("SystemTypeSet:a1"),
                simple_system_set("SystemTypeSet:b0"),
                simple_system_set("SystemTypeSet:b1"),
                simple_system_set("SystemTypeSet:c0"),
                simple_system_set("SystemTypeSet:c1"),
                simple_system_set("SystemTypeSet:d0"),
                simple_system_set("SystemTypeSet:d1"),
                simple_system_set("SystemTypeSet:e0"),
                simple_system_set("SystemTypeSet:e1"),
            ]
        );
        assert_eq!(
            schedule.hierarchy,
            [
                (SystemSetIndex(0), ScheduleIndex::System(0)),
                (SystemSetIndex(1), ScheduleIndex::System(1)),
                (SystemSetIndex(2), ScheduleIndex::System(2)),
                (SystemSetIndex(3), ScheduleIndex::System(3)),
                (SystemSetIndex(4), ScheduleIndex::System(4)),
                (SystemSetIndex(5), ScheduleIndex::System(5)),
                (SystemSetIndex(6), ScheduleIndex::System(6)),
                (SystemSetIndex(7), ScheduleIndex::System(7)),
                (SystemSetIndex(8), ScheduleIndex::System(8)),
                (SystemSetIndex(9), ScheduleIndex::System(9)),
            ]
        );
        assert_eq!(
            schedule.dependency,
            [
                // e0 -> e1
                (ScheduleIndex::System(8), ScheduleIndex::System(9)),
            ]
        );
        assert_eq!(
            schedule.components,
            [
                simple_component("MyComponent<1>"),
                simple_component("MyComponent<2>"),
                simple_component("MyComponent<3>"),
            ]
        );
        assert_eq!(
            schedule.conflicts,
            [
                conflict(2, 3, AccessConflict::Components(vec![0])),
                conflict(4, 5, AccessConflict::Components(vec![1, 2]))
            ]
        );
    }
}