Skip to main content

nexus_rt/
handler.rs

1//! Handler parameter resolution and dispatch primitives.
2
3// Handler arity is architecturally required by the Param trait — handlers
4// take N typed parameters and the macro-generated dispatch impls expand
5// per-arity into call_inner functions with N + Input arguments. Module-level
6// allow rather than one inline attribute per arity expansion.
7#![allow(clippy::too_many_arguments)]
8
9use std::ops::{Deref, DerefMut};
10
11use crate::Resource;
12use crate::callback::Callback;
13use crate::resource::{Res, ResMut, Seq, SeqMut};
14use crate::shutdown::Shutdown;
15use crate::world::{Registry, ResourceId, World};
16
17// =============================================================================
18// Param
19// =============================================================================
20
21/// Trait for types that can be resolved from a [`Registry`] at build time
22/// and fetched from [`World`] at dispatch time.
23///
24/// Analogous to Bevy's `SystemParam`.
25///
26/// Two-phase resolution:
27///
28/// 1. **Build time** — [`init`](Self::init) resolves opaque state (e.g. a
29///    [`ResourceId`]) from the registry. This panics if the required type
30///    isn't registered — giving an early build-time error.
31/// 2. **Dispatch time** — [`fetch`](Self::fetch) uses the cached state to
32///    produce a reference via a single pointer deref — zero framework overhead.
33///
34/// # Built-in impls
35///
36/// | Param | State | Description |
37/// |-------|-------|-------------|
38/// | [`Res<T>`] | `ResourceId` | Shared read |
39/// | [`ResMut<T>`] | `ResourceId` | Exclusive write |
40/// | [`Option<Res<T>>`] | `Option<ResourceId>` | Optional shared read |
41/// | [`Option<ResMut<T>>`] | `Option<ResourceId>` | Optional exclusive write |
42/// | [`Local<T>`] | `T` | Per-handler state (not in World) |
43/// | [`RegistryRef`] | `()` | Read-only registry access |
44/// | `()` | `()` | Event-only handlers |
45/// | Tuples of params | Tuple of states | Up to 8 params |
46pub trait Param {
47    /// Opaque state cached at build time (e.g. [`ResourceId`]).
48    ///
49    /// `Send` is required because state is stored in handler types
50    /// ([`Callback`]), and handlers must be `Send` (they live in
51    /// [`World`], which is `Send`).
52    type State: Send;
53
54    /// The item produced at dispatch time.
55    type Item<'w>;
56
57    /// Resolve state from the registry. Called once at build time.
58    ///
59    /// # Panics
60    ///
61    /// Panics if the required resource is not registered.
62    fn init(registry: &Registry) -> Self::State;
63
64    /// Fetch the item using cached state.
65    ///
66    /// # Safety
67    ///
68    /// - `state` must have been produced by [`init`](Self::init) on the
69    ///   same registry that built the `world`.
70    /// - Caller ensures no aliasing violations.
71    unsafe fn fetch<'w>(world: &'w World, state: &'w mut Self::State) -> Self::Item<'w>;
72
73    /// The ResourceId this param accesses, if any.
74    ///
75    /// Returns `None` for params that don't access World resources
76    /// (e.g. `Local<T>`). Used by [`Registry::check_access`] to enforce
77    /// one borrow per resource per handler.
78    fn resource_id(state: &Self::State) -> Option<ResourceId> {
79        let _ = state;
80        None
81    }
82}
83
84// -- Res<T> ------------------------------------------------------------------
85
86impl<T: Resource> Param for Res<'_, T> {
87    type State = ResourceId;
88    type Item<'w> = Res<'w, T>;
89
90    fn init(registry: &Registry) -> ResourceId {
91        registry.id::<T>()
92    }
93
94    #[inline(always)]
95    unsafe fn fetch<'w>(world: &'w World, state: &'w mut ResourceId) -> Res<'w, T> {
96        let id = *state;
97        #[cfg(debug_assertions)]
98        world.track_borrow(id);
99        // SAFETY: state was produced by init() on the same world.
100        // Caller ensures no mutable alias exists for T.
101        unsafe { Res::new(world.get::<T>(id)) }
102    }
103
104    fn resource_id(state: &ResourceId) -> Option<ResourceId> {
105        Some(*state)
106    }
107}
108
109// -- ResMut<T> ---------------------------------------------------------------
110
111impl<T: Resource> Param for ResMut<'_, T> {
112    type State = ResourceId;
113    type Item<'w> = ResMut<'w, T>;
114
115    fn init(registry: &Registry) -> ResourceId {
116        registry.id::<T>()
117    }
118
119    #[inline(always)]
120    unsafe fn fetch<'w>(world: &'w World, state: &'w mut ResourceId) -> ResMut<'w, T> {
121        let id = *state;
122        #[cfg(debug_assertions)]
123        world.track_borrow(id);
124        // SAFETY: state was produced by init() on the same world.
125        // Caller ensures no aliases exist for T.
126        unsafe { ResMut::new(world.get_mut::<T>(id)) }
127    }
128
129    fn resource_id(state: &ResourceId) -> Option<ResourceId> {
130        Some(*state)
131    }
132}
133
134// -- Option<Res<T>> ----------------------------------------------------------
135
136impl<T: Resource> Param for Option<Res<'_, T>> {
137    type State = Option<ResourceId>;
138    type Item<'w> = Option<Res<'w, T>>;
139
140    fn init(registry: &Registry) -> Option<ResourceId> {
141        registry.try_id::<T>()
142    }
143
144    #[inline(always)]
145    unsafe fn fetch<'w>(world: &'w World, state: &'w mut Option<ResourceId>) -> Option<Res<'w, T>> {
146        state.map(|id| {
147            #[cfg(debug_assertions)]
148            world.track_borrow(id);
149            // SAFETY: state was produced by init() on the same world.
150            // Caller ensures no mutable alias exists for T.
151            unsafe { Res::new(world.get::<T>(id)) }
152        })
153    }
154
155    fn resource_id(state: &Option<ResourceId>) -> Option<ResourceId> {
156        *state
157    }
158}
159
160// -- Option<ResMut<T>> -------------------------------------------------------
161
162impl<T: Resource> Param for Option<ResMut<'_, T>> {
163    type State = Option<ResourceId>;
164    type Item<'w> = Option<ResMut<'w, T>>;
165
166    fn init(registry: &Registry) -> Option<ResourceId> {
167        registry.try_id::<T>()
168    }
169
170    #[inline(always)]
171    unsafe fn fetch<'w>(
172        world: &'w World,
173        state: &'w mut Option<ResourceId>,
174    ) -> Option<ResMut<'w, T>> {
175        state.map(|id| {
176            #[cfg(debug_assertions)]
177            world.track_borrow(id);
178            // SAFETY: state was produced by init() on the same world.
179            // Caller ensures no aliases exist for T.
180            unsafe { ResMut::new(world.get_mut::<T>(id)) }
181        })
182    }
183
184    fn resource_id(state: &Option<ResourceId>) -> Option<ResourceId> {
185        *state
186    }
187}
188
189// -- Seq (read-only sequence) ------------------------------------------------
190
191impl Param for Seq {
192    type State = ();
193    type Item<'w> = Seq;
194
195    fn init(_registry: &Registry) {}
196
197    #[inline(always)]
198    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> Seq {
199        Seq(world.current_sequence())
200    }
201}
202
203// -- SeqMut (mutable sequence) -----------------------------------------------
204
205impl Param for SeqMut<'_> {
206    type State = ();
207    type Item<'w> = SeqMut<'w>;
208
209    fn init(_registry: &Registry) {}
210
211    #[inline(always)]
212    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> SeqMut<'w> {
213        SeqMut(world.sequence_cell())
214    }
215}
216
217// -- Shutdown ----------------------------------------------------------------
218
219impl Param for Shutdown<'_> {
220    type State = ();
221    type Item<'w> = Shutdown<'w>;
222
223    fn init(_registry: &Registry) {}
224
225    #[inline(always)]
226    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> Shutdown<'w> {
227        // Borrow the AtomicBool directly — lifetime-bound to World.
228        // No Arc::clone, no raw pointer. Safe by construction.
229        Shutdown(world.shutdown_flag())
230    }
231}
232
233// =============================================================================
234// Tuple impls
235// =============================================================================
236
237/// Unit impl — event-only handlers with no resource parameters.
238impl Param for () {
239    type State = ();
240    type Item<'w> = ();
241
242    fn init(_registry: &Registry) {}
243
244    #[inline(always)]
245    unsafe fn fetch<'w>(_world: &'w World, _state: &'w mut ()) {}
246}
247
248macro_rules! impl_param_tuple {
249    ($($P:ident),+) => {
250        impl<$($P: Param),+> Param for ($($P,)+) {
251            type State = ($($P::State,)+);
252            type Item<'w> = ($($P::Item<'w>,)+);
253
254            fn init(registry: &Registry) -> Self::State {
255                ($($P::init(registry),)+)
256            }
257
258            #[inline(always)]
259            #[allow(non_snake_case)]
260            unsafe fn fetch<'w>(world: &'w World, state: &'w mut Self::State) -> Self::Item<'w> {
261                let ($($P,)+) = state;
262                // SAFETY: caller upholds aliasing invariants for all params.
263                unsafe { ($($P::fetch(world, $P),)+) }
264            }
265        }
266    };
267}
268
269all_tuples!(impl_param_tuple);
270
271// =============================================================================
272// Local<T> — per-handler state
273// =============================================================================
274
275/// Per-handler local state. Stored inside the dispatch wrapper (e.g.
276/// [`Callback`] or pipeline step), not in [`World`].
277///
278/// Analogous to Bevy's `Local<T>`.
279///
280/// Initialized with [`Default::default()`] at handler creation time. Mutated
281/// freely at dispatch time — each handler/stage instance has its own
282/// independent copy.
283///
284/// # Examples
285///
286/// ```ignore
287/// fn count_events(mut count: Local<u64>, event: u32) {
288///     *count += 1;
289///     println!("event #{}: {}", *count, event);
290/// }
291/// ```
292pub struct Local<'s, T: Default + Send + 'static> {
293    value: &'s mut T,
294}
295
296impl<'s, T: Default + Send + 'static> Local<'s, T> {
297    pub(crate) fn new(value: &'s mut T) -> Self {
298        Self { value }
299    }
300}
301
302impl<T: Default + Send + std::fmt::Debug + 'static> std::fmt::Debug for Local<'_, T> {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        self.value.fmt(f)
305    }
306}
307
308impl<T: Default + Send + 'static> Deref for Local<'_, T> {
309    type Target = T;
310
311    #[inline(always)]
312    fn deref(&self) -> &T {
313        self.value
314    }
315}
316
317impl<T: Default + Send + 'static> DerefMut for Local<'_, T> {
318    #[inline(always)]
319    fn deref_mut(&mut self) -> &mut T {
320        self.value
321    }
322}
323
324impl<T: Default + Send + 'static> Param for Local<'_, T> {
325    type State = T;
326    type Item<'s> = Local<'s, T>;
327
328    fn init(_registry: &Registry) -> T {
329        T::default()
330    }
331
332    #[inline(always)]
333    unsafe fn fetch<'s>(_world: &'s World, state: &'s mut T) -> Local<'s, T> {
334        // SAFETY: The dispatch wrapper (Callback or Stage) owns state
335        // exclusively. Single-threaded dispatch ensures no aliasing.
336        // Lifetime 's is bounded by the handler/stage's run() call.
337        Local::new(state)
338    }
339}
340
341// =============================================================================
342// RegistryRef — read-only access to the type registry during dispatch
343// =============================================================================
344
345/// Read-only access to the [`Registry`] during handler dispatch.
346///
347/// Allows handlers to create new handlers at runtime by calling
348/// [`into_handler`](crate::IntoHandler::into_handler) or
349/// [`into_callback`](crate::IntoCallback::into_callback) on the
350/// borrowed registry.
351///
352/// No [`ResourceId`] needed — the registry is part of [`World`]'s
353/// structure, not a registered resource.
354pub struct RegistryRef<'w> {
355    registry: &'w Registry,
356}
357
358impl Deref for RegistryRef<'_> {
359    type Target = Registry;
360
361    #[inline(always)]
362    fn deref(&self) -> &Registry {
363        self.registry
364    }
365}
366
367impl Param for RegistryRef<'_> {
368    type State = ();
369    type Item<'w> = RegistryRef<'w>;
370
371    fn init(_registry: &Registry) {}
372
373    #[inline(always)]
374    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> RegistryRef<'w> {
375        RegistryRef {
376            registry: world.registry(),
377        }
378    }
379}
380
381// =============================================================================
382// Handler<E> — object-safe dispatch trait
383// =============================================================================
384
385/// Object-safe dispatch trait for event handlers.
386///
387/// Analogous to Bevy's `System` trait.
388///
389/// Enables `Box<dyn Handler<E>>` for type-erased heterogeneous dispatch.
390/// Storage and scheduling are the driver's responsibility — this trait
391/// only defines the dispatch interface.
392///
393/// `Send` is required because handlers live in [`World`] (via driver
394/// storage like timer wheels), and `World` is `Send`. All concrete
395/// handler types ([`Callback`], [`HandlerFn`]) satisfy this automatically
396/// for typical usage (function pointers, `ResourceId` state, `Send` context).
397///
398/// Takes `&mut World` — drivers call this directly in their poll loop.
399pub trait Handler<E>: Send {
400    /// Run this handler with the given event.
401    fn run(&mut self, world: &mut World, event: E);
402
403    /// Returns the handler's name.
404    ///
405    /// Default returns `"<unnamed>"`. [`Callback`] captures the
406    /// function's [`type_name`](std::any::type_name) at construction time.
407    fn name(&self) -> &'static str {
408        "<unnamed>"
409    }
410}
411
412impl<E> Handler<E> for Box<dyn Handler<E>> {
413    fn run(&mut self, world: &mut World, event: E) {
414        (**self).run(world, event);
415    }
416
417    fn name(&self) -> &'static str {
418        (**self).name()
419    }
420}
421
422// =============================================================================
423// CtxFree<F> — coherence wrapper for context-free handlers
424// =============================================================================
425
426/// Wrapper that marks a function as context-free.
427///
428/// Prevents coherence overlap between the context-owning and context-free
429/// [`Handler`] impls on [`Callback`]. `CtxFree<F>` is a plain struct and
430/// can never satisfy `FnMut` bounds, so the compiler proves the two impls
431/// are disjoint.
432///
433/// Users don't construct this directly — [`IntoHandler`] wraps the
434/// function automatically.
435#[doc(hidden)]
436pub struct CtxFree<F>(pub(crate) F);
437
438/// Wrapper that marks a function as taking no event parameter.
439///
440/// Used in the `F` position of [`Callback`] and [`Step`](crate::pipeline::Step)
441/// to add `Handler<()>` / `StepCall<()>` impls that don't pass `()` to the
442/// user function. Same coherence trick as [`CtxFree`]: `NoEvent<F>` is a
443/// plain struct and never satisfies `FnMut`, so the new impls are provably
444/// disjoint from the existing ones.
445///
446/// For arity-0 functions (`fn()` with no parameters), the compiler can
447/// distinguish `FnMut()` from `FnMut(())` and picks the no-event impl
448/// automatically. For arities 1+, wrap the function with [`no_event()`]
449/// to disambiguate from the event-taking impls:
450///
451/// ```ignore
452/// // Arity 0 — works directly:
453/// fn standalone() { }
454/// let h = standalone.into_handler(reg);
455///
456/// // Arities 1+ — wrap with no_event():
457/// fn tick(mut counter: ResMut<Counter>) { counter.0 += 1; }
458/// let h = no_event(tick).into_handler(reg);
459/// ```
460pub struct NoEvent<F>(pub(crate) F);
461
462/// Wrap a function for use as a no-event handler, callback, or pipeline step.
463///
464/// When `E = ()`, functions with 1+ parameters are ambiguous: the compiler
465/// can't tell if the last parameter is the event or a [`Param`]. Wrapping
466/// with `no_event()` resolves this — the function receives only its
467/// [`Param`] parameters, no event.
468///
469/// Arity-0 functions (`fn()`) don't need this wrapper — the compiler can
470/// distinguish `FnMut()` from `FnMut(())` automatically.
471///
472/// # Examples
473///
474/// ```
475/// use nexus_rt::{no_event, ResMut, IntoHandler, Handler, WorldBuilder, Resource};
476///
477/// #[derive(Resource)]
478/// struct Counter(u64);
479///
480/// fn tick(mut counter: ResMut<Counter>) {
481///     counter.0 += 1;
482/// }
483///
484/// let mut builder = WorldBuilder::new();
485/// builder.register(Counter(0));
486/// let mut world = builder.build();
487///
488/// let mut h = no_event(tick).into_handler(world.registry());
489/// h.run(&mut world, ());
490///
491/// assert_eq!(world.resource::<Counter>().0, 1);
492/// ```
493pub fn no_event<F>(f: F) -> NoEvent<F> {
494    NoEvent(f)
495}
496
497/// Type alias for context-free handlers (no owned context).
498///
499/// This is `Callback<(), CtxFree<F>, Params>` — the `ctx: ()` field
500/// is a ZST (zero bytes), identical codegen.
501///
502/// Created by [`IntoHandler::into_handler`]. Use [`HandlerFn`] in type
503/// annotations when you need to name the concrete type rather than
504/// `Box<dyn Handler<E>>`.
505pub type HandlerFn<F, Params> = Callback<(), CtxFree<F>, Params>;
506
507// =============================================================================
508// IntoHandler — conversion trait
509// =============================================================================
510
511/// Converts a plain function into a [`Handler`].
512///
513/// Analogous to Bevy's `IntoSystem`.
514///
515/// Event `E` is always the last function parameter. Everything before
516/// it is resolved as [`Param`] from a [`Registry`].
517///
518/// # Named functions only
519///
520/// Closures do not work with `IntoHandler` due to Rust's HRTB inference
521/// limitations with GATs. Use named `fn` items instead. This is the same
522/// limitation as Bevy's system registration.
523///
524/// # Factory functions and `use<>` (Rust 2024)
525///
526/// If you write a function that takes `&Registry` and returns
527/// `impl Handler<E>`, Rust 2024 captures the registry borrow in the
528/// return type. Add `+ use<...>` listing only the type parameters the
529/// handler actually holds:
530///
531/// ```ignore
532/// fn build_handler<C: Config>(
533///     reg: &Registry,
534/// ) -> impl Handler<Order> + use<C> {
535///     process_order::<C>.into_handler(reg)
536/// }
537/// ```
538///
539/// See the [crate-level docs](crate#returning-impl-handler-from-functions-rust-2024)
540/// for details.
541///
542/// # Examples
543///
544/// ```
545/// use nexus_rt::{Res, ResMut, IntoHandler, WorldBuilder, Resource};
546///
547/// #[derive(Resource)]
548/// struct Counter(u64);
549/// #[derive(Resource)]
550/// struct Flag(bool);
551///
552/// fn tick(counter: Res<Counter>, mut flag: ResMut<Flag>, event: u32) {
553///     if event > 0 {
554///         flag.0 = true;
555///     }
556/// }
557///
558/// let mut builder = WorldBuilder::new();
559/// builder.register(Counter(0));
560/// builder.register(Flag(false));
561///
562/// let mut handler = tick.into_handler(builder.registry());
563/// ```
564#[diagnostic::on_unimplemented(
565    message = "this function cannot be converted into a handler",
566    note = "handler signature: `fn(Res<A>, ResMut<B>, ..., Event)` — resources first, event last",
567    note = "for Handler<()> with params, wrap with `no_event(fn_name)` to omit the event parameter",
568    note = "closures with resource parameters (Res<T>, ResMut<T>) are not supported — use a named `fn`",
569    note = "arity-0 closures (`fn(Event)` with no resources) ARE supported"
570)]
571pub trait IntoHandler<E, Params> {
572    /// The concrete handler type produced.
573    type Handler: Handler<E> + 'static;
574
575    /// Convert this function into a handler, resolving parameters from the registry.
576    #[must_use = "the handler must be stored or dispatched — discarding it does nothing"]
577    fn into_handler(self, registry: &Registry) -> Self::Handler;
578}
579
580// =============================================================================
581// Per-arity impls via macro — context-free path (Callback<(), CtxFree<F>, P>)
582// =============================================================================
583
584// Arity 0: fn(E) — event-only handler, no resource params.
585impl<E, F: FnMut(E) + Send + 'static> IntoHandler<E, ()> for F {
586    type Handler = Callback<(), CtxFree<F>, ()>;
587
588    fn into_handler(self, registry: &Registry) -> Self::Handler {
589        Callback {
590            ctx: (),
591            f: CtxFree(self),
592            state: <() as Param>::init(registry),
593            name: std::any::type_name::<F>(),
594        }
595    }
596}
597
598impl<E, F: FnMut(E) + Send + 'static> Handler<E> for Callback<(), CtxFree<F>, ()> {
599    fn run(&mut self, _world: &mut World, event: E) {
600        (self.f.0)(event);
601    }
602
603    fn name(&self) -> &'static str {
604        self.name
605    }
606}
607
608macro_rules! impl_into_handler {
609    ($($P:ident),+) => {
610        impl<E, F: Send + 'static, $($P: Param + 'static),+> IntoHandler<E, ($($P,)+)> for F
611        where
612            // Double-bound pattern (from Bevy):
613            // - First bound: compiler uses P directly to infer Param
614            //   types from the function signature (GATs aren't injective,
615            //   so P::Item<'w> alone can't determine P).
616            // - Second bound: verifies the function is callable with the
617            //   fetched items at any lifetime.
618            for<'a> &'a mut F: FnMut($($P,)+ E) + FnMut($($P::Item<'a>,)+ E),
619        {
620            type Handler = Callback<(), CtxFree<F>, ($($P,)+)>;
621
622            fn into_handler(self, registry: &Registry) -> Self::Handler {
623                let state = <($($P,)+) as Param>::init(registry);
624                {
625                    #[allow(non_snake_case)]
626                    let ($($P,)+) = &state;
627                    registry.check_access(&[
628                        $(
629                            (<$P as Param>::resource_id($P),
630                             std::any::type_name::<$P>()),
631                        )+
632                    ]);
633                }
634                Callback {
635                    ctx: (),
636                    f: CtxFree(self),
637                    state,
638                    name: std::any::type_name::<F>(),
639                }
640            }
641        }
642
643        impl<E, F: Send + 'static, $($P: Param + 'static),+> Handler<E>
644            for Callback<(), CtxFree<F>, ($($P,)+)>
645        where
646            for<'a> &'a mut F: FnMut($($P,)+ E) + FnMut($($P::Item<'a>,)+ E),
647        {
648            #[allow(non_snake_case)]
649            fn run(&mut self, world: &mut World, event: E) {
650                // Helper binds the HRTB lifetime at a concrete call site.
651                fn call_inner<$($P,)+ Ev>(
652                    mut f: impl FnMut($($P,)+ Ev),
653                    $($P: $P,)+
654                    event: Ev,
655                ) {
656                    f($($P,)+ event);
657                }
658
659                #[cfg(debug_assertions)]
660                world.clear_borrows();
661                // SAFETY: state was produced by init() on the same registry
662                // that built this world. Single-threaded sequential dispatch
663                // ensures no mutable aliasing across params.
664                let ($($P,)+) = unsafe {
665                    <($($P,)+) as Param>::fetch(world, &mut self.state)
666                };
667                call_inner(&mut self.f.0, $($P,)+ event);
668            }
669
670            fn name(&self) -> &'static str {
671                self.name
672            }
673        }
674    };
675}
676
677all_tuples!(impl_into_handler);
678
679// =============================================================================
680// No-event impls — Handler<()> without trailing `_: ()` parameter
681// =============================================================================
682
683// Arity 0: fn() → Handler<()>
684impl<F: FnMut() + Send + 'static> IntoHandler<(), NoEvent<F>> for F {
685    type Handler = Callback<(), CtxFree<NoEvent<F>>, ()>;
686
687    fn into_handler(self, registry: &Registry) -> Self::Handler {
688        Callback {
689            ctx: (),
690            f: CtxFree(NoEvent(self)),
691            state: <() as Param>::init(registry),
692            name: std::any::type_name::<F>(),
693        }
694    }
695}
696
697impl<F: FnMut() + Send + 'static> Handler<()> for Callback<(), CtxFree<NoEvent<F>>, ()> {
698    fn run(&mut self, _world: &mut World, _event: ()) {
699        (self.f.0.0)();
700    }
701
702    fn name(&self) -> &'static str {
703        self.name
704    }
705}
706
707macro_rules! impl_into_handler_no_event {
708    ($($P:ident),+) => {
709        impl<F: Send + 'static, $($P: Param + 'static),+>
710            IntoHandler<(), ($($P,)+)> for NoEvent<F>
711        where
712            for<'a> &'a mut F: FnMut($($P,)+) + FnMut($($P::Item<'a>,)+),
713        {
714            type Handler = Callback<(), CtxFree<NoEvent<F>>, ($($P,)+)>;
715
716            fn into_handler(self, registry: &Registry) -> Self::Handler {
717                let state = <($($P,)+) as Param>::init(registry);
718                {
719                    #[allow(non_snake_case)]
720                    let ($($P,)+) = &state;
721                    registry.check_access(&[
722                        $(
723                            (<$P as Param>::resource_id($P),
724                             std::any::type_name::<$P>()),
725                        )+
726                    ]);
727                }
728                Callback {
729                    ctx: (),
730                    f: CtxFree(self),
731                    state,
732                    name: std::any::type_name::<F>(),
733                }
734            }
735        }
736
737        impl<F: Send + 'static, $($P: Param + 'static),+> Handler<()>
738            for Callback<(), CtxFree<NoEvent<F>>, ($($P,)+)>
739        where
740            for<'a> &'a mut F: FnMut($($P,)+) + FnMut($($P::Item<'a>,)+),
741        {
742            #[allow(non_snake_case)]
743            fn run(&mut self, world: &mut World, _event: ()) {
744                fn call_inner<$($P),+>(
745                    mut f: impl FnMut($($P),+),
746                    $($P: $P,)+
747                ) {
748                    f($($P),+)
749                }
750
751                #[cfg(debug_assertions)]
752                world.clear_borrows();
753                // SAFETY: state was produced by init() on the same registry
754                // that built this world. Single-threaded sequential dispatch
755                // ensures no mutable aliasing across params.
756                let ($($P,)+) = unsafe {
757                    <($($P,)+) as Param>::fetch(world, &mut self.state)
758                };
759                call_inner(&mut self.f.0 .0, $($P,)+);
760            }
761
762            fn name(&self) -> &'static str {
763                self.name
764            }
765        }
766    };
767}
768
769all_tuples!(impl_into_handler_no_event);
770
771// =============================================================================
772// IntoHandlerIgnoringEvent — build a handler that drops the event (any E)
773// =============================================================================
774
775/// Handler produced by
776/// [`into_handler_event_ignored`](IntoHandlerIgnoringEvent::into_handler_event_ignored).
777///
778/// Implements [`Handler<E>`] for **every** `E`: it fetches its [`Param`]s,
779/// calls the function, and drops the event. It stores no `E`, so it carries no
780/// event lifetime — borrowed / non-`'static` events (e.g. wire buffers) work.
781pub struct IgnoreEventHandler<F, P: Param> {
782    f: F,
783    state: P::State,
784    name: &'static str,
785}
786
787/// Convert a function that omits the event parameter into a [`Handler<E>`] that
788/// drops the event — for **any** event type `E`.
789///
790/// The event-ignoring counterpart of [`IntoHandler`]. Use it when a handler
791/// reads only resources and doesn't need the event (e.g. a timer handler that
792/// ignores the `Instant`):
793///
794/// ```
795/// use nexus_rt::{Handler, IntoHandlerIgnoringEvent, ResMut, Resource, WorldBuilder};
796///
797/// #[derive(Resource)]
798/// struct Count(u64);
799///
800/// fn on_tick(mut c: ResMut<Count>) {
801///     c.0 += 1;
802/// } // no `_: Event` parameter
803///
804/// let mut wb = WorldBuilder::new();
805/// wb.register(Count(0));
806/// let mut world = wb.build();
807///
808/// // `E` (here `u32`) is inferred from the storage type; the event is dropped.
809/// let mut h: Box<dyn Handler<u32>> =
810///     Box::new(on_tick.into_handler_event_ignored(world.registry()));
811/// h.run(&mut world, 42);
812/// assert_eq!(world.resource::<Count>().0, 1);
813/// ```
814///
815/// This trait is deliberately **not** generic over the event type — that is
816/// what lets the produced handler support non-`'static` events. The method name
817/// is what disambiguates it from the event-taking
818/// [`into_handler`](IntoHandler::into_handler); no wrapper is needed.
819pub trait IntoHandlerIgnoringEvent<Params> {
820    /// The concrete handler type produced.
821    type Handler: Send + 'static;
822
823    /// Build the event-ignoring handler, resolving params from the registry.
824    #[must_use = "the handler must be stored or dispatched — discarding it does nothing"]
825    fn into_handler_event_ignored(self, registry: &Registry) -> Self::Handler;
826}
827
828// Arity 0: fn() with no params — ignores the event (any E). `all_tuples!` starts
829// at one param, so this arity is hand-written (mirrors the arity-0 no-event path).
830impl<F: FnMut() + Send + 'static> IntoHandlerIgnoringEvent<()> for F {
831    type Handler = IgnoreEventHandler<F, ()>;
832
833    fn into_handler_event_ignored(self, _registry: &Registry) -> Self::Handler {
834        IgnoreEventHandler {
835            f: self,
836            state: <() as Param>::init(_registry),
837            name: std::any::type_name::<F>(),
838        }
839    }
840}
841
842impl<E, F: FnMut() + Send + 'static> Handler<E> for IgnoreEventHandler<F, ()> {
843    fn run(&mut self, _world: &mut World, _event: E) {
844        (self.f)();
845    }
846
847    fn name(&self) -> &'static str {
848        self.name
849    }
850}
851
852macro_rules! impl_into_handler_ignoring_event {
853    ($($P:ident),+) => {
854        impl<F: Send + 'static, $($P: Param + 'static),+>
855            IntoHandlerIgnoringEvent<($($P,)+)> for F
856        where
857            for<'a> &'a mut F: FnMut($($P,)+) + FnMut($($P::Item<'a>,)+),
858        {
859            type Handler = IgnoreEventHandler<F, ($($P,)+)>;
860
861            fn into_handler_event_ignored(self, registry: &Registry) -> Self::Handler {
862                let state = <($($P,)+) as Param>::init(registry);
863                {
864                    #[allow(non_snake_case)]
865                    let ($($P,)+) = &state;
866                    registry.check_access(&[
867                        $(
868                            (<$P as Param>::resource_id($P),
869                             std::any::type_name::<$P>()),
870                        )+
871                    ]);
872                }
873                IgnoreEventHandler {
874                    f: self,
875                    state,
876                    name: std::any::type_name::<F>(),
877                }
878            }
879        }
880
881        impl<E, F: Send + 'static, $($P: Param + 'static),+> Handler<E>
882            for IgnoreEventHandler<F, ($($P,)+)>
883        where
884            for<'a> &'a mut F: FnMut($($P,)+) + FnMut($($P::Item<'a>,)+),
885        {
886            #[allow(non_snake_case)]
887            fn run(&mut self, world: &mut World, _event: E) {
888                fn call_inner<$($P),+>(
889                    mut f: impl FnMut($($P),+),
890                    $($P: $P,)+
891                ) {
892                    f($($P),+)
893                }
894
895                #[cfg(debug_assertions)]
896                world.clear_borrows();
897                // SAFETY: state was produced by init() on the same registry that
898                // built this world. Single-threaded sequential dispatch ensures
899                // no mutable aliasing across params.
900                let ($($P,)+) = unsafe {
901                    <($($P,)+) as Param>::fetch(world, &mut self.state)
902                };
903                call_inner(&mut self.f, $($P,)+);
904            }
905
906            fn name(&self) -> &'static str {
907                self.name
908            }
909        }
910    };
911}
912
913all_tuples!(impl_into_handler_ignoring_event);
914
915// =============================================================================
916// Opaque — marker for closures with unresolved dependencies
917// =============================================================================
918
919/// Marker occupying the `Params` position in step and handler traits to
920/// indicate that a closure manages its own resource access via
921/// `world.resource::<T>()` rather than through [`Param`] resolution.
922///
923/// `Opaque` is **not** a [`Param`]. It exists solely so the compiler can
924/// distinguish three disjoint impl tiers without coherence conflicts:
925///
926/// | `Params` type | Function shape | Resolution |
927/// |---|---|---|
928/// | `()` | `FnMut(E)` | No resources needed |
929/// | `(P0,)` … `(P0..P7,)` | `fn(Res<A>, ResMut<B>, E)` | Build-time [`Param::init`], dispatch-time [`Param::fetch`] |
930/// | `Opaque` | `FnMut(&mut World, E)` | None — caller owns all access |
931///
932/// Because `&mut World` does not implement `Param`, the `Opaque` impls
933/// are always disjoint from the arity-based impls — the compiler infers
934/// `Params` unambiguously from the closure/function signature.
935///
936/// # When to use
937///
938/// Prefer named functions with [`Param`] parameters — they resolve to a
939/// direct pointer dereference per resource (single deref, no HashMap
940/// lookup). Use `Opaque` closures as an escape hatch when:
941///
942/// - You need **conditional** resource access (different resources
943///   depending on runtime state).
944/// - You need access to a resource whose type isn't known at build time.
945/// - You're prototyping and want to defer the named-function refactor.
946///
947/// # Example
948///
949/// ```ignore
950/// // Named function — preferred, hot path:
951/// pipeline.guard(check_risk, &reg)    // fn(Res<Config>, &Order) -> bool
952///
953/// // Arity-0 closure — no World access:
954/// pipeline.guard(|o: &Order| o.price > 100.0, &reg)
955///
956/// // Opaque closure — escape hatch, HashMap lookups:
957/// pipeline.guard(|w: &mut World, o: &Order| {
958///     let cfg = w.resource::<Config>();
959///     o.price > cfg.threshold
960/// }, &reg)
961/// ```
962pub struct Opaque;
963
964/// Marker type for handlers whose parameters are already resolved.
965///
966/// Used by the blanket [`IntoHandler`] impl for any [`Handler<E>`].
967/// Enables passing already-built pipelines, templates, callbacks, and
968/// `Box<dyn Handler<E>>` where `IntoHandler` is expected.
969///
970/// The `registry` argument to [`IntoHandler::into_handler`] is ignored —
971/// the handler's parameters were resolved against the registry it was
972/// originally built with. Callers must ensure the handler is run against
973/// the same [`World`] it was resolved for.
974///
975/// When returning a resolved handler from a factory function, the Rust
976/// 2024 `+ use<...>` annotation applies — see [`IntoHandler`] docs.
977///
978/// Users never need to name this type — it's inferred automatically.
979pub struct Resolved;
980
981impl<E, H: Handler<E> + 'static> IntoHandler<E, Resolved> for H {
982    type Handler = H;
983
984    fn into_handler(self, _registry: &Registry) -> H {
985        self
986    }
987}
988
989// =============================================================================
990// OpaqueHandler — Handler<E> for FnMut(&mut World, E) closures
991// =============================================================================
992
993/// Wrapper for closures that receive `&mut World` directly as a [`Handler`].
994///
995/// Created by [`IntoHandler::into_handler`] when the function signature is
996/// `FnMut(&mut World, E)`. The closure handles its own resource access —
997/// no [`Param`] resolution occurs.
998///
999/// Prefer named functions with [`Param`] resolution for hot-path handlers.
1000/// `OpaqueHandler` is an escape hatch for cases where dynamic or conditional
1001/// resource access is needed.
1002pub struct OpaqueHandler<F> {
1003    f: F,
1004    name: &'static str,
1005}
1006
1007impl<E, F: FnMut(&mut World, E) + Send + 'static> Handler<E> for OpaqueHandler<F> {
1008    fn run(&mut self, world: &mut World, event: E) {
1009        (self.f)(world, event);
1010    }
1011
1012    fn name(&self) -> &'static str {
1013        self.name
1014    }
1015}
1016
1017impl<E, F: FnMut(&mut World, E) + Send + 'static> IntoHandler<E, Opaque> for F {
1018    type Handler = OpaqueHandler<F>;
1019
1020    fn into_handler(self, _registry: &Registry) -> Self::Handler {
1021        OpaqueHandler {
1022            f: self,
1023            name: std::any::type_name::<F>(),
1024        }
1025    }
1026}
1027
1028// =============================================================================
1029// Tests
1030// =============================================================================
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035    use crate::WorldBuilder;
1036    use crate::world::Sequence;
1037
1038    // -- Param tests ----------------------------------------------------
1039
1040    #[test]
1041    fn res_param() {
1042        let mut builder = WorldBuilder::new();
1043        builder.register::<u64>(42);
1044        let mut world = builder.build();
1045
1046        let mut state = <Res<u64> as Param>::init(world.registry_mut());
1047        // SAFETY: state from init on same registry, no aliasing.
1048        let res = unsafe { <Res<u64> as Param>::fetch(&world, &mut state) };
1049        assert_eq!(*res, 42);
1050    }
1051
1052    #[test]
1053    fn res_mut_param() {
1054        let mut builder = WorldBuilder::new();
1055        builder.register::<u64>(1);
1056        let mut world = builder.build();
1057
1058        let mut state = <ResMut<u64> as Param>::init(world.registry_mut());
1059        // SAFETY: state from init on same registry, no aliasing.
1060        unsafe {
1061            let mut res = <ResMut<u64> as Param>::fetch(&world, &mut state);
1062            *res = 99;
1063        }
1064        // New dispatch phase — previous borrows dropped above.
1065        #[cfg(debug_assertions)]
1066        world.clear_borrows();
1067        // SAFETY: state from init on same registry; previous mutable borrow was dropped.
1068        unsafe {
1069            let mut read_state = <Res<u64> as Param>::init(world.registry_mut());
1070            let res = <Res<u64> as Param>::fetch(&world, &mut read_state);
1071            assert_eq!(*res, 99);
1072        }
1073    }
1074
1075    #[test]
1076    fn tuple_param() {
1077        let mut builder = WorldBuilder::new();
1078        builder.register::<u64>(10);
1079        builder.register::<bool>(true);
1080        let mut world = builder.build();
1081
1082        let mut state = <(Res<u64>, ResMut<bool>) as Param>::init(world.registry_mut());
1083        // SAFETY: different types, no aliasing.
1084        unsafe {
1085            let (counter, mut flag) =
1086                <(Res<u64>, ResMut<bool>) as Param>::fetch(&world, &mut state);
1087            assert_eq!(*counter, 10);
1088            assert!(*flag);
1089            *flag = false;
1090        }
1091        // New dispatch phase — previous borrows dropped above.
1092        #[cfg(debug_assertions)]
1093        world.clear_borrows();
1094        // SAFETY: state from init on same registry; previous mutable borrow was dropped.
1095        unsafe {
1096            let mut read_state = <Res<bool> as Param>::init(world.registry_mut());
1097            let res = <Res<bool> as Param>::fetch(&world, &mut read_state);
1098            assert!(!*res);
1099        }
1100    }
1101
1102    #[test]
1103    fn empty_tuple_param() {
1104        let mut world = WorldBuilder::new().build();
1105        <() as Param>::init(world.registry_mut());
1106        // SAFETY: no params to alias.
1107        unsafe { <() as Param>::fetch(&world, &mut ()) };
1108    }
1109
1110    // -- Handler dispatch tests -----------------------------------------------
1111
1112    fn event_only_handler(event: u32) {
1113        assert_eq!(event, 42);
1114    }
1115
1116    #[test]
1117    fn event_only_dispatch() {
1118        let mut world = WorldBuilder::new().build();
1119        let mut sys = event_only_handler.into_handler(world.registry_mut());
1120        sys.run(&mut world, 42u32);
1121    }
1122
1123    fn one_res_handler(counter: Res<u64>, event: u32) {
1124        assert_eq!(*counter, 10);
1125        assert_eq!(event, 5);
1126    }
1127
1128    #[test]
1129    fn one_res_and_event() {
1130        let mut builder = WorldBuilder::new();
1131        builder.register::<u64>(10);
1132        let mut world = builder.build();
1133
1134        let mut sys = one_res_handler.into_handler(world.registry_mut());
1135        sys.run(&mut world, 5u32);
1136    }
1137
1138    fn two_res_handler(counter: Res<u64>, flag: Res<bool>, event: u32) {
1139        assert_eq!(*counter, 10);
1140        assert!(*flag);
1141        assert_eq!(event, 7);
1142    }
1143
1144    #[test]
1145    fn two_res_and_event() {
1146        let mut builder = WorldBuilder::new();
1147        builder.register::<u64>(10);
1148        builder.register::<bool>(true);
1149        let mut world = builder.build();
1150
1151        let mut sys = two_res_handler.into_handler(world.registry_mut());
1152        sys.run(&mut world, 7u32);
1153    }
1154
1155    fn accumulate(mut counter: ResMut<u64>, event: u64) {
1156        *counter += event;
1157    }
1158
1159    #[test]
1160    fn mutation_through_res_mut() {
1161        let mut builder = WorldBuilder::new();
1162        builder.register::<u64>(0);
1163        let mut world = builder.build();
1164
1165        let mut sys = accumulate.into_handler(world.registry_mut());
1166
1167        sys.run(&mut world, 10u64);
1168        sys.run(&mut world, 5u64);
1169
1170        assert_eq!(*world.resource::<u64>(), 15);
1171    }
1172
1173    fn add_handler(mut counter: ResMut<u64>, event: u64) {
1174        *counter += event;
1175    }
1176
1177    fn mul_handler(mut counter: ResMut<u64>, event: u64) {
1178        *counter *= event;
1179    }
1180
1181    #[test]
1182    fn box_dyn_type_erasure() {
1183        let mut builder = WorldBuilder::new();
1184        builder.register::<u64>(0);
1185        let mut world = builder.build();
1186
1187        let sys_a = add_handler.into_handler(world.registry_mut());
1188        let sys_b = mul_handler.into_handler(world.registry_mut());
1189
1190        let mut handlers: Vec<Box<dyn Handler<u64>>> = vec![Box::new(sys_a), Box::new(sys_b)];
1191
1192        for h in &mut handlers {
1193            h.run(&mut world, 3u64);
1194        }
1195        // 0 + 3 = 3, then 3 * 3 = 9
1196        assert_eq!(*world.resource::<u64>(), 9);
1197    }
1198
1199    // -- Local<T> tests -------------------------------------------------------
1200
1201    fn local_counter(mut count: Local<u64>, _event: u32) {
1202        *count += 1;
1203    }
1204
1205    #[test]
1206    fn local_default_init() {
1207        let mut world = WorldBuilder::new().build();
1208        let mut sys = local_counter.into_handler(world.registry_mut());
1209        // Ran once — count should be 1 (started at 0). No panic means init worked.
1210        sys.run(&mut world, 1u32);
1211    }
1212
1213    #[test]
1214    fn local_persists_across_runs() {
1215        let mut builder = WorldBuilder::new();
1216        builder.register::<u64>(0);
1217        let mut world = builder.build();
1218
1219        fn accumulate_local(mut count: Local<u64>, mut total: ResMut<u64>, _event: u32) {
1220            *count += 1;
1221            *total = *count;
1222        }
1223
1224        let mut sys = accumulate_local.into_handler(world.registry_mut());
1225        sys.run(&mut world, 0u32);
1226        sys.run(&mut world, 0u32);
1227        sys.run(&mut world, 0u32);
1228
1229        assert_eq!(*world.resource::<u64>(), 3);
1230    }
1231
1232    #[test]
1233    fn local_independent_per_handler() {
1234        let mut builder = WorldBuilder::new();
1235        builder.register::<u64>(0);
1236        let mut world = builder.build();
1237
1238        fn inc_local(mut count: Local<u64>, mut total: ResMut<u64>, _event: u32) {
1239            *count += 1;
1240            *total += *count;
1241        }
1242
1243        let mut sys_a = inc_local.into_handler(world.registry_mut());
1244        let mut sys_b = inc_local.into_handler(world.registry_mut());
1245
1246        sys_a.run(&mut world, 0u32); // local=1, total=0+1=1
1247        sys_b.run(&mut world, 0u32); // local=1, total=1+1=2
1248        sys_a.run(&mut world, 0u32); // local=2, total=2+2=4
1249
1250        assert_eq!(*world.resource::<u64>(), 4);
1251    }
1252
1253    // -- Option<Res<T>> / Option<ResMut<T>> tests -----------------------------
1254
1255    #[test]
1256    fn option_res_none_when_missing() {
1257        let mut world = WorldBuilder::new().build();
1258        let mut state = <Option<Res<u64>> as Param>::init(world.registry_mut());
1259        // SAFETY: state from init on same registry; no mutable alias.
1260        let opt = unsafe { <Option<Res<u64>> as Param>::fetch(&world, &mut state) };
1261        assert!(opt.is_none());
1262    }
1263
1264    #[test]
1265    fn option_res_some_when_present() {
1266        let mut builder = WorldBuilder::new();
1267        builder.register::<u64>(42);
1268        let mut world = builder.build();
1269
1270        let mut state = <Option<Res<u64>> as Param>::init(world.registry_mut());
1271        // SAFETY: state from init on same registry; no mutable alias.
1272        let opt = unsafe { <Option<Res<u64>> as Param>::fetch(&world, &mut state) };
1273        assert_eq!(*opt.unwrap(), 42);
1274    }
1275
1276    #[test]
1277    fn option_res_mut_some_when_present() {
1278        let mut builder = WorldBuilder::new();
1279        builder.register::<u64>(1);
1280        let mut world = builder.build();
1281
1282        let mut state = <Option<ResMut<u64>> as Param>::init(world.registry_mut());
1283        // SAFETY: state from init on same registry; exclusive access.
1284        unsafe {
1285            let opt = <Option<ResMut<u64>> as Param>::fetch(&world, &mut state);
1286            *opt.unwrap() = 99;
1287        }
1288        #[cfg(debug_assertions)]
1289        world.clear_borrows();
1290        // SAFETY: state from init on same registry; previous mutable borrow was dropped.
1291        unsafe {
1292            let mut read_state = <Res<u64> as Param>::init(world.registry_mut());
1293            let res = <Res<u64> as Param>::fetch(&world, &mut read_state);
1294            assert_eq!(*res, 99);
1295        }
1296    }
1297
1298    fn optional_handler(opt: Option<Res<String>>, _event: u32) {
1299        assert!(opt.is_none());
1300    }
1301
1302    #[test]
1303    fn option_in_handler() {
1304        let mut world = WorldBuilder::new().build();
1305        let mut sys = optional_handler.into_handler(world.registry_mut());
1306        sys.run(&mut world, 0u32);
1307    }
1308
1309    // -- Access conflict detection ----------------------------------------
1310
1311    #[test]
1312    #[should_panic(expected = "conflicting access")]
1313    fn duplicate_res_panics() {
1314        let mut builder = WorldBuilder::new();
1315        builder.register::<u64>(0);
1316        let mut world = builder.build();
1317
1318        fn bad(a: Res<u64>, b: Res<u64>) {
1319            let _ = (*a, *b);
1320        }
1321
1322        let _sys = no_event(bad).into_handler(world.registry_mut());
1323    }
1324
1325    #[test]
1326    #[should_panic(expected = "conflicting access")]
1327    fn duplicate_res_mut_panics() {
1328        let mut builder = WorldBuilder::new();
1329        builder.register::<u64>(0);
1330        let mut world = builder.build();
1331
1332        fn bad(a: ResMut<u64>, b: ResMut<u64>) {
1333            let _ = (&*a, &*b);
1334        }
1335
1336        let _sys = no_event(bad).into_handler(world.registry_mut());
1337    }
1338
1339    #[test]
1340    #[should_panic(expected = "conflicting access")]
1341    fn duplicate_mixed_panics() {
1342        let mut builder = WorldBuilder::new();
1343        builder.register::<u64>(0);
1344        let mut world = builder.build();
1345
1346        fn bad(a: Res<u64>, b: ResMut<u64>) {
1347            let _ = (*a, &*b);
1348        }
1349
1350        let _sys = no_event(bad).into_handler(world.registry_mut());
1351    }
1352
1353    #[test]
1354    fn different_types_no_conflict() {
1355        let mut builder = WorldBuilder::new();
1356        builder.register::<u64>(0);
1357        builder.register::<u32>(0);
1358        let mut world = builder.build();
1359
1360        fn ok(a: Res<u64>, b: ResMut<u32>) {
1361            let _ = (*a, &*b);
1362        }
1363
1364        let _sys = no_event(ok).into_handler(world.registry_mut());
1365    }
1366
1367    #[test]
1368    fn local_no_conflict() {
1369        let mut builder = WorldBuilder::new();
1370        builder.register::<u64>(0);
1371        let mut world = builder.build();
1372
1373        fn ok(local: Local<u64>, val: ResMut<u64>) {
1374            let _ = (&*local, &*val);
1375        }
1376
1377        let _sys = no_event(ok).into_handler(world.registry_mut());
1378    }
1379
1380    // -- OpaqueHandler tests --------------------------------------------------
1381
1382    #[test]
1383    fn opaque_handler_dispatch() {
1384        let mut builder = WorldBuilder::new();
1385        builder.register::<u64>(0);
1386        let mut world = builder.build();
1387
1388        let opaque_fn = |w: &mut World, event: u64| {
1389            let current = *w.resource::<u64>();
1390            *w.resource_mut::<u64>() = current + event;
1391        };
1392
1393        let mut h = opaque_fn.into_handler(world.registry_mut());
1394        h.run(&mut world, 10u64);
1395        h.run(&mut world, 5u64);
1396
1397        assert_eq!(*world.resource::<u64>(), 15);
1398    }
1399
1400    #[test]
1401    fn opaque_handler_boxed() {
1402        let mut builder = WorldBuilder::new();
1403        builder.register::<u64>(0);
1404        let mut world = builder.build();
1405
1406        let opaque_fn = |w: &mut World, event: u64| {
1407            *w.resource_mut::<u64>() += event;
1408        };
1409
1410        let mut h: Box<dyn Handler<u64>> = Box::new(opaque_fn.into_handler(world.registry_mut()));
1411        h.run(&mut world, 7u64);
1412
1413        assert_eq!(*world.resource::<u64>(), 7);
1414    }
1415
1416    // -- Seq / SeqMut tests ------------------------------------------------
1417
1418    #[test]
1419    fn seq_reads_current() {
1420        fn check(seq: Seq, mut out: ResMut<i64>) {
1421            *out = seq.get().as_i64();
1422        }
1423
1424        let mut builder = WorldBuilder::new();
1425        builder.register::<i64>(0);
1426        let mut world = builder.build();
1427        world.next_sequence(); // seq=1
1428
1429        let mut handler = no_event(check).into_handler(world.registry_mut());
1430        handler.run(&mut world, ());
1431        assert_eq!(*world.resource::<i64>(), 1);
1432    }
1433
1434    #[test]
1435    fn seq_mut_advances() {
1436        fn stamp(mut seq: SeqMut, mut counter: ResMut<u64>) {
1437            let a = seq.advance();
1438            let b = seq.advance();
1439            *counter = a.as_i64() as u64 * 100 + b.as_i64() as u64;
1440        }
1441
1442        let mut builder = WorldBuilder::new();
1443        builder.register::<u64>(0);
1444        let mut world = builder.build();
1445        // seq starts at 0, handler advances twice → 1, 2
1446        let mut handler = no_event(stamp).into_handler(world.registry_mut());
1447        handler.run(&mut world, ());
1448        assert_eq!(*world.resource::<u64>(), 100 + 2);
1449        // World sequence is now 2
1450        assert_eq!(world.current_sequence(), Sequence(2));
1451    }
1452
1453    #[test]
1454    fn seq_mut_persistent_across_dispatches() {
1455        fn advance(mut seq: SeqMut) {
1456            seq.advance();
1457        }
1458
1459        let builder = WorldBuilder::new();
1460        let mut world = builder.build();
1461        let mut handler = no_event(advance).into_handler(world.registry_mut());
1462        handler.run(&mut world, ());
1463        handler.run(&mut world, ());
1464        handler.run(&mut world, ());
1465        assert_eq!(world.current_sequence(), Sequence(3));
1466    }
1467
1468    // -- Seq position / arity coverage ------------------------------------
1469
1470    #[test]
1471    fn seq_only_param() {
1472        fn handle(seq: Seq) {
1473            assert!(seq.get().as_i64() >= 0);
1474        }
1475
1476        let builder = WorldBuilder::new();
1477        let mut world = builder.build();
1478        let mut h = no_event(handle).into_handler(world.registry_mut());
1479        h.run(&mut world, ());
1480    }
1481
1482    #[test]
1483    fn seq_first_with_res() {
1484        fn handle(seq: Seq, config: Res<u64>, mut out: ResMut<i64>) {
1485            *out = seq.get().as_i64() + *config as i64;
1486        }
1487
1488        let mut builder = WorldBuilder::new();
1489        builder.register::<u64>(100);
1490        builder.register::<i64>(0);
1491        let mut world = builder.build();
1492        world.next_sequence();
1493        let mut h = no_event(handle).into_handler(world.registry_mut());
1494        h.run(&mut world, ());
1495        assert_eq!(*world.resource::<i64>(), 101);
1496    }
1497
1498    #[test]
1499    fn seq_middle_position() {
1500        fn handle(config: Res<u64>, seq: Seq, mut out: ResMut<i64>) {
1501            *out = *config as i64 + seq.get().as_i64();
1502        }
1503
1504        let mut builder = WorldBuilder::new();
1505        builder.register::<u64>(50);
1506        builder.register::<i64>(0);
1507        let mut world = builder.build();
1508        world.next_sequence(); // seq=1
1509        let mut h = no_event(handle).into_handler(world.registry_mut());
1510        h.run(&mut world, ());
1511        assert_eq!(*world.resource::<i64>(), 51);
1512    }
1513
1514    #[test]
1515    fn seq_last_position() {
1516        fn handle(mut out: ResMut<i64>, seq: Seq) {
1517            *out = seq.get().as_i64();
1518        }
1519
1520        let mut builder = WorldBuilder::new();
1521        builder.register::<i64>(0);
1522        let mut world = builder.build();
1523        world.next_sequence();
1524        world.next_sequence(); // seq=2
1525        let mut h = no_event(handle).into_handler(world.registry_mut());
1526        h.run(&mut world, ());
1527        assert_eq!(*world.resource::<i64>(), 2);
1528    }
1529
1530    #[test]
1531    fn seq_mut_only_param() {
1532        fn handle(mut seq: SeqMut) {
1533            seq.advance();
1534        }
1535
1536        let builder = WorldBuilder::new();
1537        let mut world = builder.build();
1538        let mut h = no_event(handle).into_handler(world.registry_mut());
1539        h.run(&mut world, ());
1540        assert_eq!(world.current_sequence(), Sequence(1));
1541    }
1542
1543    #[test]
1544    fn seq_mut_first_with_res() {
1545        fn handle(mut seq: SeqMut, mut out: ResMut<i64>) {
1546            let s = seq.advance();
1547            *out = s.0;
1548        }
1549
1550        let mut builder = WorldBuilder::new();
1551        builder.register::<i64>(0);
1552        let mut world = builder.build();
1553        let mut h = no_event(handle).into_handler(world.registry_mut());
1554        h.run(&mut world, ());
1555        assert_eq!(*world.resource::<i64>(), 1);
1556    }
1557
1558    #[test]
1559    fn seq_mut_middle_position() {
1560        fn handle(config: Res<u64>, mut seq: SeqMut, mut out: ResMut<i64>) {
1561            let s = seq.advance();
1562            *out = s.0 + *config as i64;
1563        }
1564
1565        let mut builder = WorldBuilder::new();
1566        builder.register::<u64>(10);
1567        builder.register::<i64>(0);
1568        let mut world = builder.build();
1569        let mut h = no_event(handle).into_handler(world.registry_mut());
1570        h.run(&mut world, ());
1571        assert_eq!(*world.resource::<i64>(), 11);
1572    }
1573
1574    #[test]
1575    fn seq_mut_last_position() {
1576        fn handle(mut out: ResMut<i64>, mut seq: SeqMut) {
1577            let s = seq.advance();
1578            *out = s.0;
1579        }
1580
1581        let mut builder = WorldBuilder::new();
1582        builder.register::<i64>(0);
1583        let mut world = builder.build();
1584        let mut h = no_event(handle).into_handler(world.registry_mut());
1585        h.run(&mut world, ());
1586        assert_eq!(*world.resource::<i64>(), 1);
1587    }
1588
1589    #[test]
1590    fn seq_mut_multiple_advances_in_one_dispatch() {
1591        fn handle(mut seq: SeqMut, mut out: ResMut<Vec<i64>>) {
1592            out.push(seq.advance().0);
1593            out.push(seq.advance().0);
1594            out.push(seq.advance().0);
1595        }
1596
1597        let mut builder = WorldBuilder::new();
1598        builder.register::<Vec<i64>>(Vec::new());
1599        let mut world = builder.build();
1600        let mut h = no_event(handle).into_handler(world.registry_mut());
1601        h.run(&mut world, ());
1602        assert_eq!(*world.resource::<Vec<i64>>(), vec![1, 2, 3]);
1603        assert_eq!(world.current_sequence(), Sequence(3));
1604    }
1605
1606    // =========================================================================
1607    // Resolved — blanket IntoHandler for Handler<E>
1608    // =========================================================================
1609
1610    #[test]
1611    fn concrete_handler_satisfies_into_handler() {
1612        // A concrete Handler<E> type should satisfy IntoHandler<E, Resolved>
1613        fn accept_into_handler<E, P>(h: impl IntoHandler<E, P>, reg: &Registry) -> impl Handler<E> {
1614            h.into_handler(reg)
1615        }
1616
1617        let mut builder = WorldBuilder::new();
1618        builder.register::<u64>(0);
1619        let world = builder.build();
1620
1621        fn bump(mut val: ResMut<u64>, event: u64) {
1622            *val += event;
1623        }
1624
1625        // Build a concrete handler, pass it where IntoHandler is expected
1626        let handler = bump.into_handler(world.registry());
1627        let _resolved = accept_into_handler(handler, world.registry());
1628    }
1629
1630    #[test]
1631    fn handler_impl_into_handler_dispatches() {
1632        let mut builder = WorldBuilder::new();
1633        builder.register::<u64>(0);
1634
1635        fn add_event(mut val: ResMut<u64>, event: u64) {
1636            *val += event;
1637        }
1638
1639        // Build handler from function, then re-pass as IntoHandler via Resolved
1640        let handler = add_event.into_handler(builder.registry());
1641        let mut resolved = handler.into_handler(builder.registry());
1642        let mut world = builder.build();
1643
1644        resolved.run(&mut world, 42);
1645        assert_eq!(*world.resource::<u64>(), 42);
1646    }
1647
1648    // =========================================================================
1649    // NoEvent — Handler<()> without trailing `_: ()`
1650    // =========================================================================
1651
1652    fn no_event_standalone() {}
1653
1654    #[test]
1655    fn no_event_arity_0() {
1656        let mut world = WorldBuilder::new().build();
1657        let mut h = no_event_standalone.into_handler(world.registry_mut());
1658        h.run(&mut world, ());
1659    }
1660
1661    fn no_event_tick(mut counter: ResMut<u64>) {
1662        *counter += 1;
1663    }
1664
1665    #[test]
1666    fn no_event_arity_1() {
1667        use crate::no_event;
1668
1669        let mut builder = WorldBuilder::new();
1670        builder.register::<u64>(0);
1671        let mut world = builder.build();
1672
1673        let mut h = no_event(no_event_tick).into_handler(world.registry_mut());
1674        h.run(&mut world, ());
1675        h.run(&mut world, ());
1676        assert_eq!(*world.resource::<u64>(), 2);
1677    }
1678
1679    fn no_event_two_params(src: Res<u32>, mut dst: ResMut<u64>) {
1680        *dst += *src as u64;
1681    }
1682
1683    #[test]
1684    fn no_event_arity_2() {
1685        use crate::no_event;
1686
1687        let mut builder = WorldBuilder::new();
1688        builder.register::<u32>(7);
1689        builder.register::<u64>(0);
1690        let mut world = builder.build();
1691
1692        let mut h = no_event(no_event_two_params).into_handler(world.registry_mut());
1693        h.run(&mut world, ());
1694        assert_eq!(*world.resource::<u64>(), 7);
1695    }
1696
1697    #[test]
1698    fn no_event_boxed() {
1699        use crate::no_event;
1700
1701        let mut builder = WorldBuilder::new();
1702        builder.register::<u64>(0);
1703        let mut world = builder.build();
1704
1705        let h = no_event(no_event_tick).into_handler(world.registry_mut());
1706        let mut boxed: Box<dyn Handler<()>> = Box::new(h);
1707        boxed.run(&mut world, ());
1708        assert_eq!(*world.resource::<u64>(), 1);
1709    }
1710
1711    #[test]
1712    fn no_event_coexists_with_event_handler() {
1713        use crate::no_event;
1714
1715        let mut builder = WorldBuilder::new();
1716        builder.register::<u64>(0);
1717        let mut world = builder.build();
1718
1719        // No-event handler
1720        let mut h1 = no_event(no_event_tick).into_handler(world.registry_mut());
1721        h1.run(&mut world, ());
1722        assert_eq!(*world.resource::<u64>(), 1);
1723
1724        // Event handler on same resource — still works
1725        fn add_event(mut val: ResMut<u64>, event: u64) {
1726            *val += event;
1727        }
1728        let mut h2 = add_event.into_handler(world.registry_mut());
1729        h2.run(&mut world, 10);
1730        assert_eq!(*world.resource::<u64>(), 11);
1731    }
1732}