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
mod action;
mod res;
mod state;
mod view;
mod world;

use core::{
    any::{type_name, TypeId},
    marker::PhantomData,
    ptr::NonNull,
};

use crate::{archetype::Archetype, component::ComponentInfo, world::World};

use super::{Access, ActionBufferQueue, IntoSystem, System};

pub use self::{
    action::ActionEncoderState,
    res::{ResMutLocal, ResMutNoSendState, ResMutState, ResLocal, ResNoSyncState, ResState},
    state::{State, StateState},
    view::QueryArg,
};

/// Marker for [`IntoSystem`] for functions.
pub struct IsFunctionSystem<Args> {
    marker: PhantomData<fn(Args)>,
}

/// State for an argument that is stored between calls to function-system.
///
/// # Safety
///
/// If [`FnArgState::is_local`] returns false [`FnArgState::get_unchecked`] must be safe to call from any thread.
/// Otherwise [`FnArgState::get_unchecked`] must be safe to call from local thread.
pub unsafe trait FnArgState: Send + 'static {
    /// Corresponding argument type of the function-system.
    type Arg<'a>: FnArg<State = Self> + 'a;

    /// Constructs the state instance.
    #[must_use]
    fn new() -> Self;

    /// Returns `true` for local arguments that can be used only for local function-systems.
    ///
    /// If this function returns `false` - executor may call `get_unchecked` from any thread.
    /// Otherwise `get_unchecked` executor must call `get_unchecked` from the thread,
    /// where executor is running.
    #[must_use]
    fn is_local(&self) -> bool;

    /// Returns access type performed on the entire [`World`].
    ///
    /// Return [`Access::Write`] if argument allows world mutation -
    /// `&mut World` or similar.
    /// Note that `&mut World`-like arguments also requires `is_local` to return `true`.
    /// Most arguments will return some [`Access::Read`].
    /// If argument doesn't access the world at all - return `None`.
    #[must_use]
    fn world_access(&self) -> Option<Access>;

    /// Checks if this argument will visit specified archetype.
    /// Called only for scheduling purposes.
    #[must_use]
    fn visit_archetype(&self, archetype: &Archetype) -> bool;

    /// Returns true if components accessed by the argument are borrowed at runtime,
    /// allowing other args that conflict with it run if they too
    /// borrow components at runtime.
    #[must_use]
    fn borrows_components_at_runtime(&self) -> bool;

    /// Returns access type to the specified component type this argument may perform.
    /// Called only for scheduling purposes.
    #[must_use]
    fn component_access(&self, comp: &ComponentInfo) -> Option<Access>;

    /// Returns access type to the specified resource type this argument may perform.
    /// Called only for scheduling purposes.
    #[must_use]
    fn resource_type_access(&self, ty: TypeId) -> Option<Access>;

    /// Extracts argument from the world.
    /// This method is called with synchronization guarantees provided
    /// according to requirements returned by [`FnArgState::is_local`], [`FnArgState::world_access`],
    /// [`FnArgState::visit_archetype`], [`FnArgState::component_access`] and [`FnArgState::resource_type_access`].
    ///
    /// # Safety
    ///
    /// `world` may be dereferenced mutably only if [`FnArgState::world_access`] returns [`Access::Write`]
    /// and [`FnArgState::is_local`] returns `true`.
    /// Otherwise `world` may be dereferenced immutably only if [`FnArgState::world_access`] returns [`Access::Read`].
    /// Otherwise `world` must not be dereferenced.
    unsafe fn get_unchecked<'a>(
        &'a mut self,
        world: NonNull<World>,
        queue: &mut dyn ActionBufferQueue,
    ) -> Self::Arg<'a>;

    /// Flushes the argument state.
    /// This method is called after system execution, when `Arg` is already dropped.
    #[inline(always)]
    unsafe fn flush_unchecked(&mut self, world: NonNull<World>, queue: &mut dyn ActionBufferQueue) {
        let _ = world;
        let _ = queue;
    }
}

/// Types that can be used as arguments for function-systems.
#[diagnostic::on_unimplemented(label = "`{Self}` cannot be used as function-system argument")]
pub trait FnArg {
    /// State for an argument that is stored between calls to function-system.
    type State: FnArgState;
}

/// Wrapper for function-like values and implements [`System`].
pub struct FunctionSystem<F, ArgStates> {
    f: F,
    args: ArgStates,
}

macro_rules! impl_func {
    ($($a:ident)*) => {
        #[allow(unused_variables, unused_mut, non_snake_case)]
        unsafe impl<Func $(,$a)*> System for FunctionSystem<Func, ($($a,)*)>
        where
            $($a: FnArgState,)*
            Func: for<'a> FnMut($($a::Arg<'a>,)*),
        {
            #[inline(always)]
            fn is_local(&self) -> bool {
                let ($($a,)*) = &self.args;
                false $( || $a.is_local() )*
            }

            #[inline(always)]
            fn world_access(&self) -> Option<Access> {
                let ($($a,)*) = &self.args;
                let mut result = None;
                $(
                    result = match (result, $a.world_access()) {
                        (None, one) | (one, None) => one,
                        (Some(Access::Read), Some(Access::Read)) => Some(Access::Read),
                        _ => {
                            panic!("Mutable `World` aliasing in system `{}`", type_name::<Self>());
                        }
                    };
                )*
                result
            }

            #[inline(always)]
            fn visit_archetype(&self, archetype: &Archetype) -> bool {
                let ($($a,)*) = &self.args;
                false $( || $a.visit_archetype(archetype) )*
            }

            #[inline(always)]
            fn component_access(&self, comp: &ComponentInfo) -> Option<Access> {
                let ($($a,)*) = &self.args;
                let mut result = None;
                let mut runtime_borrow = true;
                $(
                    if let Some(access) = $a.component_access(comp) {
                        runtime_borrow &= $a.borrows_components_at_runtime();
                        result = match (result, access) {
                            (None, one) => Some(one),
                            (Some(Access::Read), Access::Read) => Some(Access::Read),
                            _ => {
                                if runtime_borrow {
                                    // All args that access this component use runtime borrow.
                                    // Conflict will be resolved at runtime.
                                    Some(Access::Write)
                                } else {
                                    panic!("Conflicting args in system `{}`.\nA component is aliased mutably.\nIf arguments require mutable aliasing, all arguments that access a type must use runtime borrow check.\nFor example `View` type does not use runtime borrow check and should be replaced with `ViewCell`.", type_name::<Func>());
                                }
                            }
                        };
                    }
                )*
                result
            }

            #[inline(always)]
            fn resource_type_access(&self, ty: TypeId) -> Option<Access> {
                let ($($a,)*) = &self.args;
                let mut result = None;
                $(
                    result = match (result, $a.resource_type_access(ty)) {
                        (None, one) | (one, None) => one,
                        (Some(Access::Read), Some(Access::Read)) => Some(Access::Read),
                        _ => {
                            panic!("Conflicting args in system `{}`.
                                A resource is aliased mutably.",
                                type_name::<$a>());
                        }
                    };
                )*
                result
            }

            #[inline(always)]
            unsafe fn run_unchecked(&mut self, world: NonNull<World>, queue: &mut dyn ActionBufferQueue) {
                let ($($a,)*) = &mut self.args;

                {
                    $(
                        let $a = unsafe { $a.get_unchecked(world, queue) };
                    )*

                    (self.f)($($a,)*);
                }

                $(
                    unsafe { $a.flush_unchecked(world, queue) };
                )*
            }
        }

        impl<Func $(, $a)*> IntoSystem<IsFunctionSystem<($($a,)*)>> for Func
        where
            $($a: FnArg,)*
            Func: FnMut($($a),*) + Send + 'static,
            Func: for<'a> FnMut($(<$a::State as FnArgState>::Arg<'a>),*),
        {
            type System = FunctionSystem<Self, ($($a::State,)*)>;

            #[inline(always)]
            fn into_system(self) -> Self::System {
                FunctionSystem {
                    f: self,
                    args: ($($a::State::new(),)*),
                }
            }
        }
    }
}

for_tuple!(impl_func);

/// Trait for values that can be created from [`World`] reference.
pub trait FromWorld {
    /// Returns new value created from [`World`] reference.
    #[must_use]
    fn from_world(world: &World) -> Self;
}

impl<T> FromWorld for T
where
    T: Default,
{
    #[inline(always)]
    fn from_world(_: &World) -> Self {
        T::default()
    }
}