Skip to main content

dptree/handler/
core.rs

1// In order not to break the unit tests if this file is edited, we place this
2// constant right at the beginning.
3#[cfg(test)]
4const FIXED_LOCATION: &Location = Location::caller();
5
6use crate::{
7    description,
8    prelude::DependencyMap,
9    send::{BoxFuture, MaybeSend, MaybeSync},
10    HandlerDescription,
11};
12
13use std::{
14    any::TypeId,
15    collections::{BTreeMap, BTreeSet},
16    fmt::Write,
17    future::Future,
18    hash::{Hash, Hasher},
19    ops::ControlFlow,
20    panic::Location,
21    sync::Arc,
22};
23
24use colored::Colorize;
25
26/// An instance that receives an input and decides whether to break a chain or
27/// pass the value further.
28///
29/// In order to create this structure, you can use the predefined functions from
30/// [`crate`].
31///
32/// ## The difference between chaining and branching
33///
34/// Handlers can be chained via [`Handler::chain`] and branched via
35/// [`Handler::branch`]. To understand the difference between the two, consider
36/// the following examples: `a.chain(b).c` and `a.branch(b).c`.
37///
38/// In `a.chain(b).c`, the handler `a` is given the rest of the handler chain,
39/// `b` and `c`; if `a` decides to pass the value further, it invokes `b`. Then,
40/// if `b` decides to pass the value further, it invokes `c`. Thus, the handler
41/// chain is _linear_.
42///
43/// In `a.branch(b).c`, if `a` decides to pass the value further, it invokes
44/// `b`. But since `b` is "branched", it receives an empty chain, so it cannot
45/// invoke `c`. Instead, if `b` decides to continue execution
46/// ([`ControlFlow::Continue`]), `a` invokes `c`; otherwise
47/// ([`ControlFlow::Break`]), the process is terminated. The handler chain is
48/// _nested_.
49///
50/// To sum up, chaining looks like this:
51///
52/// ```txt
53/// a -> b -> c
54/// ```
55///
56/// And branching looks like this:
57///
58/// ```txt
59/// a -> b
60///   -> c
61/// ```
62///
63/// This is very crucial when `b` is a filter: if it is chained, it decides
64/// whether or not to call `c`, but when it is branched, whether `c` is called
65/// depends solely on `a`.
66pub struct Handler<'a, Output, Descr = description::Unspecified> {
67    data: Arc<HandlerData<Descr, DynFn<'a, Output>>>,
68}
69
70struct HandlerData<Descr, F: ?Sized> {
71    description: Descr,
72    sig: HandlerSignature,
73    may_skip_continuation: bool,
74    f: F,
75}
76
77/// A run-time handler signature. Used only for run-time type inference and
78/// checking of handler chains.
79///
80/// See [`crate::type_check`].
81#[derive(Clone, Debug, Eq, PartialEq)]
82pub enum HandlerSignature {
83    /// The signature corresponding to [`crate::entry`].
84    Entry,
85    /// The handler signature with exact input and output types.
86    Other {
87        /// The map from types that this handler accepts to locations where they
88        /// are required in source code.
89        obligations: BTreeMap<Type, &'static Location<'static>>,
90
91        /// Types guaranteed to be provided whenever this handler calls its
92        /// continuation. These types are not necessarily available when the
93        /// handler returns [`ControlFlow::Continue`] to a sibling branch.
94        guaranteed_outcomes: BTreeSet<Type>,
95
96        /// Types this handler may pass to its continuation, but does not
97        /// guarantee on every call. They cannot satisfy obligations.
98        conditional_outcomes: BTreeSet<Type>,
99
100        /// Whether this handler might call its continuation. Even when
101        /// false, it may return [`ControlFlow::Continue`] without calling it.
102        continues: bool,
103    },
104}
105
106/// A run-time representation of a type. Used only for run-time type inference
107/// and checking of handler chains.
108///
109/// Type name field placed before type identifier field so that the derived Ord
110/// implementation sorts types alphabetically.
111/// See [`crate::type_check`].
112#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
113pub struct Type {
114    /// The type name used for printing.
115    pub name: &'static str,
116
117    /// The unique type identifier.
118    pub id: TypeId,
119}
120
121impl Hash for Type {
122    /// Hashing is done by type identifiers (type names are ignored).
123    fn hash<H: Hasher>(&self, state: &mut H) {
124        self.id.hash(state);
125    }
126}
127
128#[cfg(not(target_arch = "wasm32"))]
129type DynFn<'a, Output> =
130    dyn Fn(DependencyMap, Cont<'a, Output>) -> HandlerResult<'a, Output> + Send + Sync + 'a;
131#[cfg(target_arch = "wasm32")]
132type DynFn<'a, Output> = dyn Fn(DependencyMap, Cont<'a, Output>) -> HandlerResult<'a, Output> + 'a;
133
134/// A continuation representing the rest of a handler chain.
135pub type Cont<'a, Output> = ContInner<'a, Output>;
136#[cfg(not(target_arch = "wasm32"))]
137type ContInner<'a, Output> =
138    Box<dyn FnOnce(DependencyMap) -> HandlerResult<'a, Output> + Send + Sync + 'a>;
139#[cfg(target_arch = "wasm32")]
140type ContInner<'a, Output> = Box<dyn FnOnce(DependencyMap) -> HandlerResult<'a, Output> + 'a>;
141
142/// An output type produced by a handler.
143pub type HandlerResult<'a, Output> = BoxFuture<'a, ControlFlow<Output, DependencyMap>>;
144
145// `#[derive(Clone)]` obligates all type parameters to satisfy `Clone` as well,
146// but we do not need it here because of `Arc`.
147impl<Output, Descr> Clone for Handler<'_, Output, Descr> {
148    fn clone(&self) -> Self {
149        Handler { data: Arc::clone(&self.data) }
150    }
151}
152
153impl<'a, Output, Descr> Handler<'a, Output, Descr>
154where
155    Output: 'a,
156    Descr: HandlerDescription,
157{
158    /// Chain two handlers to form a [chain of responsibility].
159    ///
160    /// Chaining is different from branching. See ["The difference between
161    /// chaining and
162    /// branching"](#the-difference-between-chaining-and-branching).
163    ///
164    /// This method makes use of [`HandlerSignature`] (stored in every handler)
165    /// to perform run-time type inference of the resulting handler
166    /// signature; this information is used by [`crate::type_check`] to make
167    /// sure that all required types are provided _before_ execution.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// # #[tokio::main(flavor = "current_thread")]
173    /// # async fn main() {
174    /// use dptree::prelude::*;
175    ///
176    /// let handler: Handler<_> =
177    ///     dptree::filter(|x: i32| x > 0).chain(dptree::endpoint(|| async { "done" }));
178    ///
179    /// assert_eq!(handler.dispatch(dptree::deps![10]).await.break_value(), Some("done"));
180    /// let ControlFlow::Continue(deps) = handler.dispatch(dptree::deps![-10]).await else {
181    ///     panic!("expected the handler to continue");
182    /// };
183    /// assert_eq!(*deps.get::<i32>(), -10);
184    ///
185    /// # }
186    /// ```
187    ///
188    /// [chain of responsibility]: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
189    #[must_use]
190    #[track_caller]
191    pub fn chain(self, next: Self) -> Self {
192        let required_update_kinds_set = self.description().merge_chain(next.description());
193
194        self.check_next(&next, "chain");
195        let next_sig = SignatureRef::from(&next.data.sig);
196        let new_sig =
197            SignatureRef::from(&self.data.sig).compose(&next_sig, next_sig.continues, true);
198        let may_skip_continuation =
199            self.data.may_skip_continuation || next.data.may_skip_continuation;
200
201        from_fn_with_flow(
202            required_update_kinds_set,
203            move |event, cont| {
204                let this = self.clone();
205                let next = next.clone();
206
207                this.execute(event, |event| next.execute(event, cont))
208            },
209            new_sig,
210            may_skip_continuation,
211        )
212    }
213
214    /// Chain two handlers to make a tree of responsibility.
215    ///
216    /// Chaining is different from branching. See ["The difference between
217    /// chaining and
218    /// branching"](#the-difference-between-chaining-and-branching).
219    ///
220    /// This method makes use of [`HandlerSignature`] (stored in every handler)
221    /// to perform run-time type inference of the resulting handler
222    /// signature; this information is used by [`crate::type_check`] to make
223    /// sure that all required types are provided _before_ execution.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use dptree::prelude::*;
229    ///
230    /// # #[tokio::main(flavor = "current_thread")]
231    /// # async fn main() {
232    ///
233    /// #[derive(Debug, PartialEq)]
234    /// enum Output {
235    ///     Five,
236    ///     One,
237    ///     GT,
238    /// }
239    ///
240    /// let dispatcher: Handler<_> = dptree::entry()
241    ///     .branch(dptree::filter(|num: i32| num == 5).endpoint(|| async move { Output::Five }))
242    ///     .branch(dptree::filter(|num: i32| num == 1).endpoint(|| async move { Output::One }))
243    ///     .branch(dptree::filter(|num: i32| num > 2).endpoint(|| async move { Output::GT }));
244    ///
245    /// assert_eq!(dispatcher.dispatch(dptree::deps![5]).await.break_value(), Some(Output::Five));
246    /// assert_eq!(dispatcher.dispatch(dptree::deps![1]).await.break_value(), Some(Output::One));
247    /// assert_eq!(dispatcher.dispatch(dptree::deps![3]).await.break_value(), Some(Output::GT));
248    /// let ControlFlow::Continue(deps) = dispatcher.dispatch(dptree::deps![0]).await else {
249    ///     panic!("expected the handler to continue");
250    /// };
251    /// assert_eq!(*deps.get::<i32>(), 0);
252    /// # }
253    /// ```
254    #[must_use]
255    #[track_caller]
256    pub fn branch(self, next: Self) -> Self
257    where
258        Output: MaybeSend,
259    {
260        let required_update_kinds_set = self.description().merge_branch(next.description());
261
262        self.check_next(&next, "branch");
263        let next_sig = SignatureRef::from(&next.data.sig);
264        let new_sig = SignatureRef::from(&self.data.sig).compose(
265            &next_sig,
266            next_sig.continues || next.data.may_skip_continuation,
267            false,
268        );
269        let may_skip_continuation = self.data.may_skip_continuation;
270
271        from_fn_with_flow(
272            required_update_kinds_set,
273            move |event, cont| {
274                let this = self.clone();
275                let next = next.clone();
276
277                this.execute(event, |event| async move {
278                    match next.dispatch(event).await {
279                        ControlFlow::Continue(event) => cont(event).await,
280                        done => done,
281                    }
282                })
283            },
284            new_sig,
285            may_skip_continuation,
286        )
287    }
288
289    #[track_caller]
290    fn check_next(&self, next: &Self, operation: &str) {
291        if matches!(next.sig(), HandlerSignature::Entry) {
292            panic!("Ill-typed handler {}: the second handler cannot be an entry", operation);
293        }
294        if !SignatureRef::from(self.sig()).continues {
295            panic!(
296                "Dead code detected: since the first handler does not call its continuation, the \
297                 second handler will never be called."
298            );
299        }
300    }
301
302    /// Executes this handler with a continuation.
303    ///
304    /// Usually, you do not want to call this method by yourself, if you do not
305    /// write your own handler implementation. If you wish to execute handler
306    /// without a continuation, take a look at the [`Handler::dispatch`] method.
307    ///
308    /// **NOTE**: If you are using [`DependencyMap`], you should first call
309    /// [`crate::type_check`] to type-check your handler against a container;
310    /// otherwise, type checking will be delayed until the actual execution,
311    /// which can make things harder to debug.
312    ///
313    /// # Examples
314    ///
315    /// ```
316    /// # #[tokio::main(flavor = "current_thread")]
317    /// # async fn main() {
318    /// use dptree::prelude::*;
319    ///
320    /// let handler: Handler<_> = dptree::filter(|x: i32| x > 0);
321    ///
322    /// let output = handler.execute(dptree::deps![10], |_| async { ControlFlow::Break("done") }).await;
323    /// assert_eq!(output.break_value(), Some("done"));
324    ///
325    /// # }
326    /// ```
327    pub async fn execute<Cont, ContFut>(
328        self,
329        input: DependencyMap,
330        cont: Cont,
331    ) -> ControlFlow<Output, DependencyMap>
332    where
333        Cont: FnOnce(DependencyMap) -> ContFut,
334        Cont: MaybeSend + MaybeSync + 'a,
335        ContFut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
336    {
337        (self.data.f)(input, Box::new(|event| Box::pin(cont(event)))).await
338    }
339
340    /// Executes this handler.
341    ///
342    /// Returns [`ControlFlow::Break`] when executed successfully,
343    /// [`ControlFlow::Continue`] otherwise.
344    ///
345    /// **NOTE**: If you are using [`DependencyMap`], you should first call
346    /// [`crate::type_check`] to type-check your handler against a container;
347    /// otherwise, type checking will be delayed until the actual execution,
348    /// which can make things harder to debug.
349    pub async fn dispatch(&self, input: DependencyMap) -> ControlFlow<Output, DependencyMap> {
350        self.clone().execute(input, |event| async move { ControlFlow::Continue(event) }).await
351    }
352
353    /// Returns the set of updates that can be processed by this handler.
354    pub fn description(&self) -> &Descr {
355        &self.data.description
356    }
357
358    /// Returns this handler's run-time type signature.
359    pub fn sig(&self) -> &HandlerSignature {
360        &self.data.sig
361    }
362}
363
364// All these sets describe calls to the continuation, not maps returned by dispatch.
365struct SignatureRef<'a> {
366    obligations: &'a BTreeMap<Type, &'static Location<'static>>,
367    guaranteed: &'a BTreeSet<Type>,
368    conditional: &'a BTreeSet<Type>,
369    continues: bool,
370}
371
372impl<'a> From<&'a HandlerSignature> for SignatureRef<'a> {
373    fn from(signature: &'a HandlerSignature) -> Self {
374        static NO_OBLIGATIONS: BTreeMap<Type, &Location<'static>> = BTreeMap::new();
375        static NO_OUTCOMES: BTreeSet<Type> = BTreeSet::new();
376        match signature {
377            HandlerSignature::Entry => Self {
378                obligations: &NO_OBLIGATIONS,
379                guaranteed: &NO_OUTCOMES,
380                conditional: &NO_OUTCOMES,
381                continues: true,
382            },
383            HandlerSignature::Other {
384                obligations,
385                guaranteed_outcomes,
386                conditional_outcomes,
387                continues,
388            } => Self {
389                obligations,
390                guaranteed: guaranteed_outcomes,
391                conditional: conditional_outcomes,
392                continues: *continues,
393            },
394        }
395    }
396}
397
398impl SignatureRef<'_> {
399    fn compose(&self, next: &Self, continues: bool, chained: bool) -> HandlerSignature {
400        let mut obligations = next.obligations.clone();
401        obligations.retain(|ty, _| !self.guaranteed.contains(ty));
402        obligations.extend(self.obligations);
403
404        let (mut guaranteed, mut conditional) = (self.guaranteed.clone(), self.conditional.clone());
405        if chained {
406            guaranteed.extend(next.guaranteed);
407            conditional.extend(next.conditional);
408        }
409        // A branch dispatches its child with an empty continuation. Built-in
410        // producers roll their insertions back on Continue, so only the left
411        // handler's outcomes can be relied on by subsequent siblings.
412        conditional.retain(|ty| !guaranteed.contains(ty));
413
414        HandlerSignature::Other {
415            obligations,
416            guaranteed_outcomes: guaranteed,
417            conditional_outcomes: conditional,
418            continues,
419        }
420    }
421}
422
423fn print_types<'a>(
424    types: impl IntoIterator<Item = &'a Type>,
425    f: impl Fn(&Type) -> String,
426) -> String {
427    let mut res = String::new();
428    let mut types = types.into_iter();
429
430    if let Some(ty) = types.next() {
431        write!(res, "{}", f(ty)).unwrap();
432    }
433    for ty in types {
434        write!(res, "\n    {}", f(ty)).unwrap();
435    }
436
437    res
438}
439
440impl Type {
441    /// Constructs [`Type`] from a static type.
442    #[must_use]
443    pub fn of<T>() -> Self
444    where
445        T: 'static,
446    {
447        Self { id: TypeId::of::<T>(), name: std::any::type_name::<T>() }
448    }
449}
450
451/// Constructs a handler from a function.
452///
453/// `sig` is the run-time handler signature used for type inference and
454/// checking.
455///
456/// Most of the time, you do not want to use this function. Take a look at more
457/// specialised functions: [`crate::endpoint`], [`crate::filter`],
458/// [`crate::filter_map`], etc.
459#[must_use]
460pub fn from_fn<'a, F, Fut, Output, Descr>(f: F, sig: HandlerSignature) -> Handler<'a, Output, Descr>
461where
462    F: Fn(DependencyMap, Cont<'a, Output>) -> Fut,
463    F: MaybeSend + MaybeSync + 'a,
464    Fut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
465    Descr: HandlerDescription,
466{
467    from_fn_with_description(Descr::user_defined(), f, sig)
468}
469
470/// [`from_fn`] with a custom description.
471#[must_use]
472pub fn from_fn_with_description<'a, F, Fut, Output, Descr>(
473    description: Descr,
474    f: F,
475    sig: HandlerSignature,
476) -> Handler<'a, Output, Descr>
477where
478    F: Fn(DependencyMap, Cont<'a, Output>) -> Fut,
479    F: MaybeSend + MaybeSync + 'a,
480    Fut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
481{
482    // For user-defined handlers, allow a fallback unless we know it is dead.
483    from_fn_with_flow(description, f, sig, true)
484}
485
486pub(super) fn from_fn_with_flow<'a, F, Fut, Output, Descr>(
487    description: Descr,
488    f: F,
489    sig: HandlerSignature,
490    may_skip_continuation: bool,
491) -> Handler<'a, Output, Descr>
492where
493    F: Fn(DependencyMap, Cont<'a, Output>) -> Fut,
494    F: MaybeSend + MaybeSync + 'a,
495    Fut: Future<Output = ControlFlow<Output, DependencyMap>> + MaybeSend + 'a,
496{
497    Handler {
498        data: Arc::new(HandlerData {
499            f: move |event, cont| Box::pin(f(event, cont)) as HandlerResult<_>,
500            description,
501            sig,
502            may_skip_continuation,
503        }),
504    }
505}
506
507/// Constructs an entry point handler.
508///
509/// This function is only used to specify other handlers upon it (see the root
510/// examples).
511///
512/// # Signature
513///
514/// The run-time type signature of this handler is `HandlerSignature::Entry`.
515#[must_use]
516#[track_caller]
517pub fn entry<'a, Output, Descr>() -> Handler<'a, Output, Descr>
518where
519    Output: 'a,
520    Descr: HandlerDescription,
521{
522    from_fn_with_flow(Descr::entry(), |event, cont| cont(event), HandlerSignature::Entry, false)
523}
524
525/// Performs run-time type checking.
526///
527/// If you are using [`DependencyMap`], you should call this function _before_
528/// executing the handler via [`Handler::execute`] or [`Handler::dispatch`]. If
529/// you do _not_ call this function before execution, type checking will be
530/// delayed until the actual execution, which can make things harder to debug.
531///
532/// `sig` can be obtained from [`Handler::sig`]. `assumptions` are added to the
533/// types of values from `container`.
534///
535/// # Panics
536///
537/// If `container` does not contain all the types that the handler accepts; in
538/// this case, helpful diagnostic information about missing types and code
539/// locations is displayed.
540///
541/// # Examples
542///
543/// ```should_panic
544/// use dptree::prelude::*;
545///
546/// #[derive(Clone)]
547/// struct A;
548/// #[derive(Clone)]
549/// struct B;
550///
551/// // Requires both `A` and `B` to be present in the container.
552/// let handler: Handler<()> = dptree::entry().filter(|_: A| true).endpoint(|_: B| async { () });
553///
554/// // Ok.
555/// dptree::type_check(handler.sig(), &dptree::deps![A, B], &[]);
556///
557/// // Panics with a proper message.
558/// dptree::type_check(handler.sig(), &dptree::deps![A /* Missing `B` */], &[]);
559/// ```
560pub fn type_check(sig: &HandlerSignature, container: &DependencyMap, assumptions: &[Type]) {
561    match sig {
562        HandlerSignature::Entry => {}
563        HandlerSignature::Other {
564            obligations,
565            guaranteed_outcomes: _,
566            conditional_outcomes: _,
567            continues: _,
568        } => {
569            let container_types = container
570                .map
571                .iter()
572                .map(|(type_id, dep)| Type { id: *type_id, name: dep.type_name })
573                .chain(assumptions.iter().cloned())
574                .collect::<BTreeSet<_>>();
575
576            let handler_accepts_msg = "Your handler accepts the following types:".to_owned();
577            let provided_types_msg = "But only the following values were given to it:".to_owned();
578            let missing_types_msg = "The missing values are:".to_owned();
579            let note_msg = "Make sure all the required values are provided to the handler. For more information, visit <https://docs.rs/dptree-fork/latest/dptree>.".to_owned();
580
581            if obligations.iter().any(|(ty, _location)| !container_types.contains(ty)) {
582                panic!(
583                    "{}\n    {}\n{}\n    {}\n{}\n    {}\n\n{}\n",
584                    if cfg!(test) {
585                        handler_accepts_msg
586                    } else {
587                        handler_accepts_msg.red().bold().to_string()
588                    },
589                    print_types(obligations.keys(), |ty| format!("`{}`", ty.name)),
590                    if cfg!(test) {
591                        provided_types_msg
592                    } else {
593                        provided_types_msg.red().bold().to_string()
594                    },
595                    print_types(&container_types, |ty| format!("`{}`", ty.name)),
596                    if cfg!(test) {
597                        missing_types_msg
598                    } else {
599                        missing_types_msg.red().bold().to_string()
600                    },
601                    print_types(
602                        obligations.keys().filter(|ty| !container_types.contains(ty)),
603                        |ty| { format!("`{}` from {}", ty.name, obligations[ty]) },
604                    ),
605                    note_msg,
606                );
607            }
608        }
609    }
610}
611
612#[cfg(test)]
613pub(crate) fn help_inference<Output>(h: Handler<Output>) -> Handler<Output> {
614    h
615}
616
617#[cfg(test)]
618mod tests {
619
620    use super::*;
621
622    use crate::{
623        deps, description, filter_map, filter_map_with_description,
624        handler::{endpoint, filter, filter_async},
625    };
626
627    use std::{any::Any, collections::HashSet, iter::FromIterator};
628
629    use maplit::{btreemap, btreeset, hashset};
630
631    crate::cross_test! {
632        async fn test_from_fn_break() {
633            let input = 123;
634            let output = "ABC";
635
636            let input_types = [Type::of::<i32>()];
637            let location = Location::caller();
638
639            let result = help_inference(from_fn(
640                |event, _cont: Cont<&'static str>| async move {
641                    assert_eq!(*event.get::<i32>(), input);
642                    ControlFlow::Break(output)
643                },
644                HandlerSignature::Other {
645                    obligations: BTreeMap::from_iter(
646                        input_types.iter().cloned().map(|ty| (ty, location)),
647                    ),
648                    guaranteed_outcomes: btreeset! {},
649                    conditional_outcomes: btreeset! {},
650                    continues: false,
651                },
652            ))
653            .dispatch(deps![input])
654            .await;
655
656            assert_eq!(result.break_value(), Some(output));
657        }
658
659        async fn test_from_fn_continue() {
660            let input = 123;
661            type Output = &'static str;
662
663            let input_types = [Type::of::<i32>()];
664            let location = Location::caller();
665
666            let result = help_inference(from_fn(
667                |event, _cont: Cont<&'static str>| async move {
668                    assert_eq!(*event.get::<i32>(), input);
669                    ControlFlow::<Output, _>::Continue(event)
670                },
671                HandlerSignature::Other {
672                    obligations: BTreeMap::from_iter(
673                        input_types.iter().cloned().map(|ty| (ty, location)),
674                    ),
675                    guaranteed_outcomes: btreeset! {Type::of::<i32>()},
676                    conditional_outcomes: btreeset! {},
677                    continues: true,
678                },
679            ))
680            .dispatch(deps![input])
681            .await;
682
683            let ControlFlow::Continue(deps) = result else { panic!("expected Continue") };
684            assert_eq!(*deps.get::<i32>(), input);
685        }
686
687        async fn test_entry() {
688            let input = 123;
689            type Output = &'static str;
690
691            let result = help_inference(entry::<Output, _>()).dispatch(deps![input]).await;
692
693            let ControlFlow::Continue(deps) = result else { panic!("expected Continue") };
694            assert_eq!(*deps.get::<i32>(), input);
695        }
696
697        async fn test_execute() {
698            let input = 123;
699            let output = "ABC";
700
701            let input_types = [Type::of::<i32>()];
702            let location = Location::caller();
703
704            let result = help_inference(from_fn(
705                |event, cont| {
706                    assert_eq!(*event.get::<i32>(), input);
707                    cont(event)
708                },
709                HandlerSignature::Other {
710                    obligations: BTreeMap::from_iter(
711                        input_types.iter().cloned().map(|ty| (ty, location)),
712                    ),
713                    guaranteed_outcomes: btreeset! {Type::of::<i32>()},
714                    conditional_outcomes: btreeset! {},
715                    continues: true,
716                },
717            ))
718            .execute(deps![input], |event| async move {
719                assert_eq!(*event.get::<i32>(), input);
720                ControlFlow::Break(output)
721            })
722            .await;
723
724            assert_eq!(result.break_value(), Some(output));
725        }
726
727        async fn test_deeply_nested_tree() {
728            #[derive(Debug, PartialEq)]
729            enum Output {
730                LT,
731                MinusOne,
732                Zero,
733                One,
734                GT,
735            }
736
737            let negative_handler = filter(|num: i32| num < 0)
738                .branch(
739                    filter_async(|num: i32| async move { num == -1 })
740                        .endpoint(|| async move { Output::MinusOne }),
741                )
742                .branch(endpoint(|| async move { Output::LT }));
743
744            let zero_handler = filter_async(|num: i32| async move { num == 0 })
745                .endpoint(|| async move { Output::Zero });
746
747            let positive_handler = filter_async(|num: i32| async move { num > 0 })
748                .branch(
749                    filter_async(|num: i32| async move { num == 1 })
750                        .endpoint(|| async move { Output::One }),
751                )
752                .branch(endpoint(|| async move { Output::GT }));
753
754            let dispatcher = help_inference(entry())
755                .branch(negative_handler)
756                .branch(zero_handler)
757                .branch(positive_handler);
758
759            assert_eq!(dispatcher.dispatch(deps![2]).await.break_value(), Some(Output::GT));
760            assert_eq!(dispatcher.dispatch(deps![1]).await.break_value(), Some(Output::One));
761            assert_eq!(dispatcher.dispatch(deps![0]).await.break_value(), Some(Output::Zero));
762            assert_eq!(dispatcher.dispatch(deps![-1]).await.break_value(), Some(Output::MinusOne));
763            assert_eq!(dispatcher.dispatch(deps![-2]).await.break_value(), Some(Output::LT));
764        }
765
766        async fn allowed_updates() {
767            use crate::description::{EventKind, InterestSet};
768            use UpdateKind::*;
769
770            #[derive(Debug, Clone, PartialEq, Eq, Hash)]
771            enum UpdateKind {
772                A,
773                B,
774                C,
775            }
776
777            impl EventKind for UpdateKind {
778                fn full_set() -> HashSet<Self> {
779                    hashset! { A, B, C }
780                }
781
782                fn empty_set() -> HashSet<Self> {
783                    hashset! {}
784                }
785            }
786
787            #[derive(Clone)]
788            #[allow(dead_code)]
789            enum Update {
790                A(i32),
791                B(u8),
792                C(u64),
793            }
794
795            fn filter_a<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
796            where
797                Out: Send + Sync + 'static,
798            {
799                filter_map_with_description(
800                    InterestSet::new_filter(hashset! { A }),
801                    |update: Update| match update {
802                        Update::A(x) => Some(x),
803                        _ => None,
804                    },
805                )
806            }
807
808            fn filter_b<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
809            where
810                Out: Send + Sync + 'static,
811            {
812                filter_map_with_description(
813                    InterestSet::new_filter(hashset! { B }),
814                    |update: Update| match update {
815                        Update::B(x) => Some(x),
816                        _ => None,
817                    },
818                )
819            }
820
821            fn filter_c<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
822            where
823                Out: Send + Sync + 'static,
824            {
825                filter_map_with_description(
826                    InterestSet::new_filter(hashset! { C }),
827                    |update: Update| match update {
828                        Update::B(x) => Some(x),
829                        _ => None,
830                    },
831                )
832            }
833
834            // User-defined filter that doesn't provide allowed updates
835            fn user_defined_filter<Out>() -> Handler<'static, Out, InterestSet<UpdateKind>>
836            where
837                Out: Send + Sync + 'static,
838            {
839                filter_map(|update: Update| match update {
840                    Update::B(x) => Some(x),
841                    _ => None,
842                })
843            }
844
845            #[track_caller]
846            fn assert(
847                handler: Handler<'static, (), description::InterestSet<UpdateKind>>,
848                allowed: HashSet<UpdateKind>,
849            ) {
850                assert_eq!(handler.description().observed, allowed);
851            }
852
853            // Filters do not observe anything on their own.
854            assert(filter_a(), hashset! {});
855            assert(entry().chain(filter_b()), hashset! {});
856            assert(filter_a().chain(filter_b()), hashset! {});
857            assert(filter_a().branch(filter_b()), hashset! {});
858            assert(filter_a().branch(filter_b()).branch(filter_c().chain(filter_c())), hashset! {});
859
860            // Anything user-defined observes everything that it can observe.
861            assert(filter_a().chain(filter(|| true)), hashset! { A });
862            assert(user_defined_filter().chain(filter_a()), hashset! { A, B, C });
863            assert(filter_a().chain(user_defined_filter()), hashset! { A });
864            assert(
865                entry().branch(filter_a()).branch(filter_b()).chain(user_defined_filter()),
866                hashset! { A, B, C },
867            );
868            assert(
869                entry()
870                    .branch(filter_a().endpoint(|| async {}))
871                    .branch(filter_b().endpoint(|| async {})),
872                hashset! { A, B },
873            );
874            assert(user_defined_filter(), hashset! { A, B, C });
875            assert(user_defined_filter().branch(filter_a()), hashset! { A, B, C });
876
877            // An entry is "invisible".
878            assert(entry(), hashset! {});
879            assert(entry().chain(filter_a().endpoint(|| async {})), hashset! { A });
880            assert(entry().branch(filter_a()), hashset! {});
881
882            // Chained non-overlapping filters do not allow anything.
883            assert(filter_a().chain(filter_b()).endpoint(|| async {}), hashset! {});
884        }
885
886        async fn type_check_success() {
887            #[derive(Clone)]
888            struct A;
889            #[derive(Clone)]
890            struct B;
891            #[derive(Clone)]
892            struct C;
893
894            macro_rules! test {
895                ($($key:ty),*) => {
896                    type_check(
897                        &HandlerSignature::Other {
898                            obligations: btreemap! {
899                                $(Type::of::<$key>() => Location::caller(),)*
900                            },
901                            guaranteed_outcomes: btreeset! {},
902                            conditional_outcomes: btreeset! {},
903                            continues: true,
904                        },
905                        &deps![A, B, C],
906                        &[],
907                    );
908                };
909            }
910
911            // Type-checking an entry must succeed.
912            type_check(&HandlerSignature::Entry, &deps![], &[]);
913
914            // Type-checking subsets of provided types must succeed.
915            test!(A, B, C);
916            test!(A, B);
917            test!(A, C);
918            test!(B, C);
919            test!(A);
920            test!(B);
921            test!(C);
922        }
923
924        #[should_panic(expected = "Your handler accepts the following types:
925    `dptree::handler::core::tests::type_check_panic::A`
926    `dptree::handler::core::tests::type_check_panic::B`
927    `dptree::handler::core::tests::type_check_panic::C`
928But only the following values were given to it:
929    `dptree::handler::core::tests::type_check_panic::A`
930    `dptree::handler::core::tests::type_check_panic::B`
931The missing values are:
932    `dptree::handler::core::tests::type_check_panic::C` from src/handler/core.rs:4:35
933
934Make sure all the required values are provided to the handler. For more information, visit <https://docs.rs/dptree-fork/latest/dptree>.
935")]
936        fn type_check_panic() {
937            #[derive(Clone)]
938            struct A;
939            #[derive(Clone)]
940            struct B;
941            #[derive(Clone)]
942            struct C;
943
944            type_check(
945                &HandlerSignature::Other {
946                    obligations: btreemap! {
947                        Type::of::<A>() => Location::caller(),
948                        Type::of::<B>() => Location::caller(),
949                        Type::of::<C>() => FIXED_LOCATION,
950                    },
951                    guaranteed_outcomes: btreeset! {},
952                    conditional_outcomes: btreeset! {},
953                    continues: true,
954                },
955                // `C` is required but not provided.
956                &deps![A, B],
957                &[],
958            );
959        }
960
961        fn type_eq_ord_consistent() {
962            #[derive(Clone)]
963            struct A;
964
965            let ta1 = Type { id: A.type_id(), name: "A1" };
966            let ta2 = Type { id: A.type_id(), name: "A2" };
967
968            assert!(!(ta1 == ta2));
969            assert!(ta1 < ta2);
970            assert!(!(ta1 > ta2));
971        }
972
973        fn type_btreeset_not_contains_duplicate_name() {
974            #[derive(Clone)]
975            struct A;
976            #[derive(Clone)]
977            struct B;
978
979            let ta = Type { id: A.type_id(), name: "DuplicateName" };
980            let tb = Type { id: B.type_id(), name: "DuplicateName" };
981            let set = btreeset! {ta};
982
983            assert!(ta != tb);
984            assert!(!set.contains(&tb));
985        }
986
987        async fn type_infer_check_chained_combinators() {
988            #[derive(Clone)]
989            struct A;
990            #[derive(Clone)]
991            struct B;
992            #[derive(Clone)]
993            struct C;
994            #[derive(Clone)]
995            struct D;
996            #[derive(Clone)]
997            struct E;
998            #[derive(Clone)]
999            struct F;
1000            #[derive(Clone)]
1001            struct G;
1002            #[derive(Clone, Debug, Eq, PartialEq)]
1003            struct H;
1004
1005            let h: Handler<H> = entry()
1006                .map(|/* In the final input types. */ _: A| B)
1007                .inspect(
1008                    |/* This type must be removed from the final input types because it is
1009                    * provided by the `.map` above. */
1010                    _: B,
1011                    /* This type must "propagate" to the final input types. */
1012                    _: E| (),
1013                )
1014                .filter_map(|/* In the final input types. */ _: C| Some(D))
1015                .filter(
1016                    |/* This type is provided by the `.filter_map` above. */ _: D,
1017                    /* Must propagate. */ _: F| true,
1018                )
1019                .endpoint(
1020                    /* `B` and `D` are provided at this point. */
1021                    |_: B, _: D, /* Must propagate. */ _: G| async { H },
1022                );
1023
1024            let input_types =
1025                [Type::of::<A>(), Type::of::<C>(), Type::of::<E>(), Type::of::<F>(), Type::of::<G>()];
1026            let outcomes = btreeset! {Type::of::<B>(), Type::of::<D>()};
1027
1028            if let HandlerSignature::Other {
1029                obligations: actual_obligations,
1030                guaranteed_outcomes: actual_guaranteed_outcomes,
1031                conditional_outcomes: actual_conditional_outcomes,
1032                continues: _continues,
1033            } = h.sig()
1034            {
1035                assert_eq!(
1036                    actual_obligations.keys().collect::<Vec<_>>(),
1037                    input_types.iter().collect::<Vec<_>>()
1038                );
1039                let all_outcomes = actual_guaranteed_outcomes
1040                    .union(actual_conditional_outcomes)
1041                    .cloned()
1042                    .collect::<BTreeSet<_>>();
1043                assert_eq!(all_outcomes, outcomes);
1044            } else {
1045                panic!("Expected `HandlerSignature::Other`");
1046            }
1047
1048            let deps = deps![A, C, E, F, G];
1049
1050            type_check(h.sig(), &deps, &[]);
1051
1052            // Must not panic during execution.
1053            assert_eq!(h.dispatch(deps).await.break_value(), Some(H));
1054        }
1055
1056        async fn type_infer_check_branched_combinators() {
1057            #[derive(Clone)]
1058            struct A;
1059            #[derive(Clone)]
1060            struct B;
1061            #[derive(Clone)]
1062            struct C;
1063            #[derive(Clone)]
1064            struct D;
1065            #[derive(Clone)]
1066            struct E;
1067            #[derive(Clone, Debug, Eq, PartialEq)]
1068            struct F;
1069
1070            let h: Handler<F> = entry()
1071                .branch(
1072                    crate::inspect(|_: A| ()).filter(|| true).map(|| B).map(|| C).map(|| D).endpoint(|| async { F }),
1073                )
1074                .branch(crate::inspect(|_: E| ()).map(|| B).map(|| D).endpoint(|| async { F }));
1075
1076            // The union of the input types of both branches.
1077            let input_types = btreeset! {Type::of::<A>(), Type::of::<E>()};
1078            // Neither isolated branch exports its produced values.
1079            let output_types = BTreeSet::new();
1080
1081            if let HandlerSignature::Other {
1082                obligations: actual_obligations,
1083                guaranteed_outcomes: actual_guaranteed_outcomes,
1084                conditional_outcomes: actual_conditional_outcomes,
1085                continues: _continues,
1086            } = h.sig()
1087            {
1088                assert_eq!(
1089                    actual_obligations.keys().collect::<Vec<_>>(),
1090                    input_types.iter().collect::<Vec<_>>()
1091                );
1092                let all_outcomes = actual_guaranteed_outcomes
1093                    .union(actual_conditional_outcomes)
1094                    .cloned()
1095                    .collect::<BTreeSet<_>>();
1096                assert_eq!(all_outcomes, output_types);
1097            } else {
1098                panic!("Expected `HandlerSignature::Other`");
1099            }
1100
1101            let deps = deps![A, E];
1102
1103            type_check(h.sig(), &deps, &[]);
1104
1105            // Must not panic during execution.
1106            assert_eq!(h.dispatch(deps).await.break_value(), Some(F));
1107        }
1108
1109        async fn obligations_priority() {
1110            #[derive(Clone)]
1111            struct A;
1112            #[derive(Clone)]
1113            struct B;
1114            #[derive(Clone, Debug, Eq, PartialEq)]
1115            struct C;
1116
1117            fn test<T: 'static>(h: Handler<C>, column: u32) {
1118                if let HandlerSignature::Other {
1119                    obligations,
1120                    guaranteed_outcomes: _,
1121                    conditional_outcomes: _,
1122                    continues: _,
1123                } = h.sig()
1124                {
1125                    let (_ty, &location) = obligations
1126                        .iter()
1127                        .find(|(ty, _location)| ty.id == TypeId::of::<T>())
1128                        .expect("Missing obligation");
1129                    assert_eq!(location.column(), column);
1130                } else {
1131                    panic!("Expected `HandlerSignature::Other`");
1132                }
1133            }
1134
1135            #[rustfmt::skip]
1136            let h: Handler<C> = entry().map(|_: A| ()).endpoint(|_: A, _: B| async { C });
1137            test::<A>(h, 41);
1138
1139            #[rustfmt::skip]
1140            let h: Handler<C> =
1141                entry().branch(crate::map(|_: A|  { C })).branch(endpoint(|_: A, _: B| async { C }));
1142            test::<A>(h, 32);
1143        }
1144
1145        #[should_panic(expected = "Ill-typed handler chain: the second handler cannot be an entry")]
1146        fn chain_entry() {
1147            let _: Handler<()> = entry().chain(entry());
1148        }
1149
1150        #[should_panic(expected = "Ill-typed handler branch: the second handler cannot be an entry")]
1151        fn branch_entry() {
1152            let _: Handler<()> = entry().branch(entry());
1153        }
1154
1155        async fn chain_branch_type_check() {
1156            #[derive(Clone)]
1157            struct A;
1158
1159            let handler: Handler<()> =
1160                entry().chain(crate::map(|| A)).branch(endpoint(|_: A| async {}));
1161
1162            let _no_panic_here: ControlFlow<(), _> = handler.dispatch(deps![]).await;
1163
1164            type_check(handler.sig(), &deps![], &[]);
1165        }
1166
1167        async fn guaranteed_outcomes_chain_success() {
1168            #[derive(Clone)]
1169            struct A;
1170            #[derive(Clone)]
1171            struct B;
1172
1173            let handler: Handler<()> = entry().map(|| A).map(|_: A| B).endpoint(|_: B| async {});
1174
1175            let result = handler.dispatch(deps![]).await;
1176            assert_eq!(result.break_value(), Some(()));
1177
1178            type_check(handler.sig(), &deps![], &[]);
1179        }
1180
1181        async fn conditional_outcomes_chain_success() {
1182            #[derive(Clone)]
1183            struct A;
1184
1185            let handler: Handler<()> = entry().filter_map(|| Some(A)).endpoint(|_: A| async {});
1186
1187            let result = handler.dispatch(deps![]).await;
1188            assert_eq!(result.break_value(), Some(()));
1189
1190            type_check(handler.sig(), &deps![], &[]);
1191        }
1192
1193        async fn guaranteed_outcomes_branch_success() {
1194            #[derive(Clone)]
1195            struct A;
1196
1197            let producer = entry().map(|| A);
1198
1199            // In branch context, guaranteed outcomes can satisfy obligations.
1200            let handler: Handler<()> = producer.branch(endpoint(|_: A| async {}));
1201
1202            let result = handler.dispatch(deps![]).await;
1203            assert_eq!(result.break_value(), Some(()));
1204
1205            type_check(handler.sig(), &deps![], &[]);
1206        }
1207
1208        async fn mixed_outcomes_chain() {
1209            #[derive(Clone)]
1210            struct A;
1211            #[derive(Clone)]
1212            struct B;
1213            #[derive(Clone)]
1214            struct C;
1215
1216            let handler: Handler<()> = entry()
1217                .map(|| A) // guaranteed
1218                .filter_map(|_: A| Some(B)) // conditional, but `A` is guaranteed
1219                .map(|_: B| C) // guaranteed, but `B` is conditional
1220                .endpoint(|_: C| async {}); // consumes `C`
1221
1222            let result = handler.dispatch(deps![]).await;
1223            assert_eq!(result.break_value(), Some(()));
1224
1225            type_check(handler.sig(), &deps![], &[]);
1226        }
1227
1228        async fn branch_with_guaranteed_continuation() {
1229            #[derive(Clone)]
1230            struct A;
1231
1232            // The first branch produces `A` and continues (`map` always continues).
1233            let first_branch = entry().map(|| A).inspect(|_: A| ()); // `inspect` continues, keeping `A` available
1234
1235            // The second branch can use `A`, because the first branch guarantees it and
1236            // continues the execution.
1237            let handler: Handler<()> = first_branch.branch(endpoint(|_: A| async {}));
1238
1239            let result = handler.dispatch(deps![]).await;
1240            assert_eq!(result.break_value(), Some(()));
1241
1242            type_check(handler.sig(), &deps![], &[]);
1243        }
1244
1245        #[should_panic(expected = "Your handler accepts the following types:")]
1246        async fn deeply_nested_conditional_failure() {
1247            #[derive(Clone)]
1248            struct A;
1249            #[derive(Clone)]
1250            struct B;
1251
1252            // Deep nesting where conditional outcome propagation should fail.
1253            let handler: Handler<()> = entry()
1254                .branch(
1255                    entry()
1256                        .branch(crate::filter_map(|| Some(A)).endpoint(|| async {}))
1257                        .branch(crate::filter_map(|_: A| Some(B)).endpoint(|| async {})),
1258                )
1259                .branch(endpoint(|_: B| async {})); // `B` is not guaranteed to be available
1260
1261            type_check(handler.sig(), &deps![], &[]);
1262        }
1263
1264        #[should_panic(expected = "The missing values are:")]
1265        fn first_branch_producer_does_not_supply_sibling() {
1266            let handler: Handler<()> = entry()
1267                .branch(crate::map(|| 42_u32))
1268                .branch(endpoint(|_: u32| async {}));
1269            type_check(handler.sig(), &deps![], &[]);
1270        }
1271
1272        async fn isolated_branch_rolls_back_shadowing() {
1273            let handler: Handler<u32> = entry()
1274                .branch(crate::map(|| 42_u32))
1275                .branch(endpoint(|value: u32| async move { value }));
1276            let deps = deps![7_u32];
1277            type_check(handler.sig(), &deps, &[]);
1278            assert_eq!(handler.dispatch(deps).await.break_value(), Some(7));
1279        }
1280
1281        async fn reachable_fallback_after_filtered_branch() {
1282            let handler: Handler<_> = entry()
1283                .branch(filter(|flag: bool| flag).endpoint(|| async { "branch" }))
1284                .endpoint(|| async { "fallback" });
1285            type_check(handler.sig(), &deps![false], &[]);
1286            assert_eq!(handler.dispatch(deps![false]).await.break_value(), Some("fallback"));
1287            assert_eq!(handler.dispatch(deps![true]).await.break_value(), Some("branch"));
1288        }
1289
1290        async fn fallback_after_custom_handler_that_never_calls_continuation() {
1291            let handler = help_inference(entry())
1292                .branch(from_fn(
1293                    |deps, _| async move { ControlFlow::Continue(deps) },
1294                    HandlerSignature::Other {
1295                        obligations: BTreeMap::new(),
1296                        guaranteed_outcomes: BTreeSet::new(),
1297                        conditional_outcomes: BTreeSet::new(),
1298                        continues: false,
1299                    },
1300                ))
1301                .endpoint(|| async { 7 });
1302            assert_eq!(handler.dispatch(deps![]).await.break_value(), Some(7));
1303        }
1304
1305        #[should_panic(expected = "Dead code detected:")]
1306        fn endpoint_cannot_have_a_branch() {
1307            let _: Handler<()> = endpoint(|| async {}).branch(endpoint(|_: u32| async {}));
1308        }
1309
1310        #[should_panic(expected = "Dead code detected:")]
1311        fn unconditional_branch_cannot_have_a_fallback() {
1312            let _: Handler<()> = entry().branch(endpoint(|| async {})).endpoint(|| async {});
1313        }
1314
1315        #[should_panic(expected = "The missing values are:")]
1316        fn conditional_outcome_cannot_satisfy_chain_obligation() {
1317            let handler = help_inference(from_fn(
1318                |deps, cont| cont(deps),
1319                HandlerSignature::Other {
1320                    obligations: BTreeMap::new(),
1321                    guaranteed_outcomes: BTreeSet::new(),
1322                    conditional_outcomes: btreeset! {Type::of::<u32>()},
1323                    continues: true,
1324                },
1325            ))
1326            .endpoint(|_: u32| async {});
1327            type_check(handler.sig(), &deps![], &[]);
1328        }
1329
1330        #[should_panic(expected = "Dead code detected: since the first handler does not call its \
1331                                continuation, the second handler will never be called.")]
1332        fn chain_endpoint_with_handler() {
1333            let _: Handler<()> = endpoint(|| async {}).endpoint(|| async {});
1334        }
1335
1336        #[should_panic(expected = "Dead code detected: since the first handler does not call its \
1337                                continuation, the second handler will never be called.")]
1338        fn chain_endpoint_with_filter() {
1339            let _: Handler<()> = endpoint(|| async {}).filter(|_: i32| true);
1340        }
1341
1342        #[should_panic(expected = "Dead code detected: since the first handler does not call its \
1343                                continuation, the second handler will never be called.")]
1344        fn chain_endpoint_with_map() {
1345            let _: Handler<()> = endpoint(|| async {}).map(|| 42);
1346        }
1347
1348        #[should_panic(expected = "Dead code detected: since the first handler does not call its \
1349                                continuation, the second handler will never be called.")]
1350        fn chain_complex_endpoint_dead_code() {
1351            let _: Handler<()> = entry()
1352                .chain(filter(|x: i32| x > 0))
1353                .chain(endpoint(|| async {}))
1354                .chain(crate::map(|| "Unreachable"));
1355        }
1356    }
1357}