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