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
use core::{
    any::{type_name, TypeId},
    marker::PhantomData,
    ptr::NonNull,
};

use crate::{
    archetype::Archetype,
    component::ComponentInfo,
    query::SendQuery,
    system::ActionBufferQueue,
    view::{acquire, release, RuntimeBorrowState, StaticallyBorrowed, View, ViewCell, ViewValue},
    world::World,
    Access,
};

use super::{FnArg, FnArgState};

/// Query suitable for [`View`] args for function-systems.
pub trait QueryArg: SendQuery {
    /// Creates new query state.
    fn new() -> Self;

    /// Hook called before function-system runs to update the state.
    #[inline(always)]
    fn before(&mut self, world: &World) {
        let _ = world;
    }

    /// Hook called after function-system runs to update the state.
    #[inline(always)]
    fn after(&mut self, world: &World) {
        let _ = world;
    }
}

/// State type used by corresponding [`View`].
#[derive(Default)]
pub struct ViewState<Q, F, B> {
    query: Q,
    filter: F,
    marker: PhantomData<B>,
}

impl<'a, Q, F> FnArg for ViewValue<'a, Q, F, RuntimeBorrowState>
where
    Q: QueryArg,
    F: QueryArg,
{
    type State = ViewState<Q, F, RuntimeBorrowState>;
}

unsafe impl<Q, F> FnArgState for ViewState<Q, F, RuntimeBorrowState>
where
    Q: QueryArg,
    F: QueryArg,
{
    type Arg<'a> = ViewValue<'a, Q, F, RuntimeBorrowState>;

    #[inline(always)]
    fn new() -> Self {
        ViewState {
            query: Q::new(),
            filter: F::new(),
            marker: PhantomData,
        }
    }

    #[inline(always)]
    fn is_local(&self) -> bool {
        false
    }

    #[inline(always)]
    fn world_access(&self) -> Option<Access> {
        Some(Access::Read)
    }

    #[inline(always)]
    fn visit_archetype(&self, archetype: &Archetype) -> bool {
        self.query.visit_archetype(archetype) && self.filter.visit_archetype(archetype)
    }

    #[inline(always)]
    fn borrows_components_at_runtime(&self) -> bool {
        true
    }

    #[inline(always)]
    fn component_access(&self, comp: &ComponentInfo) -> Option<Access> {
        let q = self
            .query
            .component_access(comp)
            .unwrap_or(Some(Access::Write));
        let f = self
            .filter
            .component_access(comp)
            .unwrap_or(Some(Access::Write));

        match (q, f) {
            (None, one) | (one, None) => one,
            (Some(Access::Read), Some(Access::Read)) => Some(Access::Read),
            _ => {
                // This view uses runtime borrow, so conflict can be resolved at runtime.
                Some(Access::Write)
            }
        }
    }

    #[inline(always)]
    fn resource_type_access(&self, _ty: TypeId) -> Option<Access> {
        None
    }

    #[inline(always)]
    unsafe fn get_unchecked<'a>(
        &'a mut self,
        world: NonNull<World>,
        _queue: &mut dyn ActionBufferQueue,
    ) -> ViewCell<'a, Q, F> {
        // Safety: Declares read access.
        let world = unsafe { world.as_ref() };
        self.query.before(world);
        self.filter.before(world);
        ViewValue::new_cell(world, self.query, self.filter)
    }

    #[inline(always)]
    unsafe fn flush_unchecked(
        &mut self,
        world: NonNull<World>,
        _queue: &mut dyn ActionBufferQueue,
    ) {
        // Safety: Declares read access.
        let world = unsafe { world.as_ref() };
        self.query.after(world);
        self.filter.after(world);
    }
}

impl<'a, Q, F> FnArg for ViewValue<'a, Q, F, StaticallyBorrowed>
where
    Q: QueryArg,
    F: QueryArg,
{
    type State = ViewState<Q, F, StaticallyBorrowed>;
}

unsafe impl<Q, F> FnArgState for ViewState<Q, F, StaticallyBorrowed>
where
    Q: QueryArg,
    F: QueryArg,
{
    type Arg<'a> = ViewValue<'a, Q, F, StaticallyBorrowed>;

    #[inline(always)]
    fn new() -> Self {
        ViewState {
            query: Q::new(),
            filter: F::new(),
            marker: PhantomData,
        }
    }

    #[inline(always)]
    fn is_local(&self) -> bool {
        false
    }

    #[inline(always)]
    fn world_access(&self) -> Option<Access> {
        Some(Access::Read)
    }

    #[inline(always)]
    fn visit_archetype(&self, archetype: &Archetype) -> bool {
        self.query.visit_archetype(archetype) && self.filter.visit_archetype(archetype)
    }

    #[inline(always)]
    fn borrows_components_at_runtime(&self) -> bool {
        false
    }

    #[inline(always)]
    fn component_access(&self, comp: &ComponentInfo) -> Option<Access> {
        let Ok(q) = self.query.component_access(comp) else {
            panic!("Mutable alias in query of `{}`", type_name::<Self>());
        };
        let Ok(f) = self.filter.component_access(comp) else {
            panic!("Mutable alias in filter of `{}`", type_name::<Self>());
        };

        match (q, f) {
            (None, one) | (one, None) => one,
            (Some(Access::Read), Some(Access::Read)) => Some(Access::Read),
            _ => {
                panic!(
                    "Conflicting query and filter in `{}`.
                        A component is aliased mutably.",
                    core::any::type_name::<Self>()
                );
            }
        }
    }

    #[inline(always)]
    fn resource_type_access(&self, _ty: TypeId) -> Option<Access> {
        None
    }

    #[inline(always)]
    unsafe fn get_unchecked<'a>(
        &'a mut self,
        world: NonNull<World>,
        _queue: &mut dyn ActionBufferQueue,
    ) -> View<'a, Q, F> {
        // Safety: Declares read access.
        let world = unsafe { world.as_ref() };

        #[cfg(debug_assertions)]
        acquire(self.query, self.filter, world.archetypes());

        self.query.before(world);
        self.filter.before(world);

        // Safety: Declares access for these queries.
        unsafe { ViewValue::new_static(world, self.query, self.filter) }
    }

    #[inline(always)]
    unsafe fn flush_unchecked(
        &mut self,
        world: NonNull<World>,
        _queue: &mut dyn ActionBufferQueue,
    ) {
        // Safety: Declares read access.
        let world = unsafe { world.as_ref() };

        #[cfg(debug_assertions)]
        release(self.query, self.filter, world.archetypes());

        self.query.after(world);
        self.filter.after(world);
    }
}

#[test]
fn test_system() {
    fn foo(_: ViewCell<&u32>) {}
    fn is_system<M, T: super::IntoSystem<M>>(_: T) {}
    is_system(foo);
}