Skip to main content

dptree/
lib.rs

1//! An implementation of the [chain (tree) of responsibility] pattern.
2//!
3//! [[`examples/web_server.rs`](https://github.com/teloxide/dptree/blob/master/examples/web_server.rs)]
4//! ```rust
5//! use dptree::prelude::*;
6//!
7//! type WebHandler = Endpoint<'static, String>;
8//!
9//! #[rustfmt::skip]
10//! #[tokio::main(flavor = "current_thread")]
11//! async fn main() {
12//!     let web_server = dptree::entry()
13//!         .branch(smiles_handler())
14//!         .branch(sqrt_handler())
15//!         .branch(not_found_handler());
16//!
17//!     assert_eq!(
18//!         web_server.dispatch(dptree::deps!["/smile"]).await.break_value(),
19//!         Some("🙃".to_owned())
20//!     );
21//!     assert_eq!(
22//!         web_server.dispatch(dptree::deps!["/sqrt 16"]).await.break_value(),
23//!         Some("4".to_owned())
24//!     );
25//!     assert_eq!(
26//!         web_server.dispatch(dptree::deps!["/lol"]).await.break_value(),
27//!         Some("404 Not Found".to_owned())
28//!     );
29//! }
30//!
31//! fn smiles_handler() -> WebHandler {
32//!     dptree::filter(|req: &'static str| req.starts_with("/smile"))
33//!         .endpoint(|| async { "🙃".to_owned() })
34//! }
35//!
36//! fn sqrt_handler() -> WebHandler {
37//!     dptree::filter_map(|req: &'static str| {
38//!         if req.starts_with("/sqrt") {
39//!             let (_, n) = req.split_once(' ')?;
40//!             n.parse::<f64>().ok()
41//!         } else {
42//!             None
43//!         }
44//!     })
45//!     .endpoint(|n: f64| async move { format!("{}", n.sqrt()) })
46//! }
47//!
48//! fn not_found_handler() -> WebHandler {
49//!     dptree::endpoint(|| async { "404 Not Found".to_owned() })
50//! }
51//! ```
52//!
53//! For a high-level overview, please see [`README.md`](https://github.com/teloxide/dptree).
54//!
55//! [chain (tree) of responsibility]: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
56
57mod handler;
58
59pub mod di;
60pub mod prelude;
61pub mod send;
62
63pub use handler::*;
64
65/// Filters by a pattern, passing its payload forwards.
66///
67/// This macro expands to a [`crate::Handler`] that acts on your enumeration
68/// type: if the enumeration is of a certain variant, the execution continues;
69/// otherwise, `dptree` will try the next branch. This is very useful for
70/// dialogue FSM transitions and incoming command filtering; for a real-world
71/// example, please see teloxide's [`examples/purchase.rs`].
72///
73/// Variants can take the following forms:
74///
75///  - `Enum::MyVariant` for empty variants;
76///  - `Enum::MyVariant(param1, ..., paramN)` for tuple-like variants;
77///  - `Enum::MyVariant { param1, ..., paramN }` for `struct`-like variants.
78///
79/// In the first case, this macro results in a simple [`crate::filter`]; in the
80/// second and third cases, this macro results in [`crate::filter_map`] that
81/// passes the payload of `MyVariant` to the next handler if the match occurs.
82/// (This next handler can be an endpoint or a more complex one.) The payload
83/// format depends on the form of `MyVariant`:
84///
85///  - For `Enum::MyVariant(param)` and `Enum::MyVariant { param }`, the payload
86///    is `param`.
87///  - For `Enum::MyVariant(param,)` and `Enum::MyVariant { param, }`, the
88///    payload is `(param,)`.
89///  - For `Enum::MyVariant(param1, ..., paramN)` and `Enum::MyVariant { param1,
90///    ..., paramN }`, the payload is `(param1, ..., paramN)` (where `N`>1).
91///
92/// Paths may start with `::`, and type arguments may use turbofish syntax on
93/// the enum or the variant. A typed unit variant injects the matching value;
94/// an untyped standalone unit variant only filters.
95///
96/// ```
97/// use dptree::{case, Handler};
98///
99/// let _: Handler<u8> = case![Some::<u8>(v)].endpoint(|v: u8| async move { v });
100/// let _: Handler<Option<u8>> = case![::core::option::Option::<u8>::None]
101///     .endpoint(|v: Option<u8>| async move { v });
102/// let _: Handler<()> = case![::core::cmp::Ordering::Equal].endpoint(|| async {});
103/// ```
104///
105/// Tuple-like and struct-like patterns may also destructure structs and nested
106/// variants. At each level, payloads are collected in the order written:
107///
108///  - An identifier contributes its bound value. In a named field `key: pattern`,
109///    the payload comes from `pattern`, not `key`.
110///  - A nested unit variant (such as `Other::Ready`) or typed unit variant
111///    (such as `None::<T>`) contributes that value. A standalone path without
112///    type arguments remains a filter that injects nothing.
113///  - A nested tuple-like or struct-like pattern contributes its own payload as
114///    one element; its tuple, if any, is not flattened into the outer tuple.
115///  - `..` contributes no element. A comma still makes the payload a tuple:
116///    `Variant(x, ..)` contributes `(x,)`, and `Variant(..)` contributes `()`.
117///
118/// For other Rust patterns, such as or-patterns or guards, use [`crate::filter`]
119/// or [`crate::filter_map`] directly.
120///
121/// ## Dependency requirements
122///
123///  - The type matched by the pattern.
124///
125/// ## Examples
126///
127/// ```rust
128/// use dptree::prelude::*;
129///
130/// # #[tokio::main(flavor = "current_thread")]
131/// # async fn main() {
132/// #[derive(Clone)]
133/// enum Command {
134///     Meow,
135///     Add(i32, i32),
136///     Repeat { times: Option<usize> },
137/// }
138///
139/// let h: Handler<_> = dptree::entry()
140///     .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
141///     .branch(
142///         dptree::case![Command::Add(x, y)]
143///             .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
144///     )
145///     .branch(
146///         dptree::case![Command::Repeat { times: Some(n) }]
147///             .endpoint(|n: usize| async move { "Meow!".repeat(n) }),
148///     );
149///
150/// assert_eq!(
151///     h.dispatch(dptree::deps![Command::Meow]).await.break_value(),
152///     Some("Meow!".to_owned())
153/// );
154/// assert_eq!(
155///     h.dispatch(dptree::deps![Command::Add(1, 2)]).await.break_value(),
156///     Some("3".to_owned())
157/// );
158/// assert_eq!(
159///     h.dispatch(dptree::deps![Command::Repeat { times: Some(2) }]).await.break_value(),
160///     Some("Meow!Meow!".to_owned())
161/// );
162/// # }
163/// ```
164///
165/// The macro works even when `matches!`, `Some`, and `None` are shadowed:
166///
167/// ```
168/// # #[tokio::main(flavor = "current_thread")]
169/// # async fn main() {
170/// use dptree::{case, deps, Handler};
171/// #[allow(unused_macros)]
172/// macro_rules! matches { ($($tt:tt)*) => { compile_error!("local matches!") }; }
173/// #[derive(Clone)]
174/// enum Choice { Some(u8), None }
175/// use Choice::{Some, None};
176///
177/// let empty: Handler<_> = case![Choice::None].endpoint(|| async { 0 });
178/// let payload: Handler<_> = case![Choice::Some(n)].endpoint(|n: u8| async move { n });
179/// assert_eq!(empty.dispatch(deps![None]).await.break_value(), ::core::option::Option::Some(0));
180/// assert_eq!(payload.dispatch(deps![Some(42)]).await.break_value(), ::core::option::Option::Some(42));
181/// assert!(payload.dispatch(deps![None]).await.is_continue());
182/// # }
183/// ```
184///
185/// [`examples/purchase.rs`]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/purchase.rs
186#[macro_export]
187macro_rules! case {
188    (:: $($variant:ident)::+) => {
189        $crate::filter(|x| ::core::matches!(x, ::$($variant)::+))
190    };
191    ($($variant:ident)::+) => {
192        $crate::filter(|x| ::core::matches!(x, $($variant)::+))
193    };
194    ($($variant:ident)::+ ($param:ident)) => {
195        $crate::filter_map(|x| match x {
196            $($variant)::+($param) => ::core::option::Option::Some($param),
197            _ => ::core::option::Option::None,
198        })
199    };
200    ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => {
201        $crate::filter_map(|x| match x {
202            $($variant)::+($($param),+) => ::core::option::Option::Some(($($param),+ ,)),
203            _ => ::core::option::Option::None,
204        })
205    };
206    ($($variant:ident)::+ {$param:ident}) => {
207        $crate::filter_map(|x| match x {
208            $($variant)::+{$param} => ::core::option::Option::Some($param),
209            _ => ::core::option::Option::None,
210        })
211    };
212    ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {
213        $crate::filter_map(|x| match x {
214            $($variant)::+ { $($param),+ } => ::core::option::Option::Some(($($param),+ ,)),
215            _ => ::core::option::Option::None,
216        })
217    };
218    ($($pattern:tt)+) => {
219        $crate::filter_map(|x| {
220            #[allow(unreachable_patterns)]
221            match x {
222                $($pattern)+ => ::core::option::Option::Some(
223                    $crate::__case_payload!(@fields scalar [] $($pattern)+)
224                ),
225                _ => ::core::option::Option::None,
226            }
227        })
228    };
229}
230
231// Parse one comma-separated field at a time. A nested group starts a fresh
232// accumulator and contributes one expression to its parent, so nested tuples
233// retain their shape. `scalar` changes to `tuple` after the first comma, even
234// when that comma follows an ignored rest or is the last token.
235#[doc(hidden)]
236#[macro_export]
237macro_rules! __case_payload {
238    (@fields $shape:ident [$($items:expr,)*]) => { ($($items,)*) };
239
240    (@fields $shape:ident [$($items:expr,)*] .. $(, $($tail:tt)*)?) => {
241        $crate::__case_payload!(@fields tuple [$($items,)*] $($($tail)*)?)
242    };
243
244    (@fields $shape:ident $items:tt $key:ident : $($tail:tt)+) => {
245        $crate::__case_payload!(@fields $shape $items $($tail)+)
246    };
247    (@fields $shape:ident $items:tt :: $first:ident $($tail:tt)*) => {
248        $crate::__case_payload!(@path $shape $items [::$first] $($tail)*)
249    };
250    (@fields $shape:ident $items:tt $first:ident $($tail:tt)*) => {
251        $crate::__case_payload!(@path $shape $items [$first] $($tail)*)
252    };
253
254    // Accumulate path segments and type arguments before extracting the payload.
255    (@path $shape:ident $items:tt [$($path:tt)+] :: $next:ident $($tail:tt)*) => {
256        $crate::__case_payload!(@path $shape $items [$($path)+ :: $next] $($tail)*)
257    };
258    (@path $shape:ident $items:tt [$($path:tt)+] ::<$($ty:ty),+ $(,)?> $($tail:tt)*) => {
259        $crate::__case_payload!(@path $shape $items [$($path)+ ::<$($ty),+>] $($tail)*)
260    };
261    (@path $shape:ident $items:tt [$($path:tt)+] ($($fields:tt)*) $($tail:tt)*) => {
262        $crate::__case_payload!(@push $shape $items
263            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
264    };
265    (@path $shape:ident $items:tt [$($path:tt)+] {$($fields:tt)*} $($tail:tt)*) => {
266        $crate::__case_payload!(@push $shape $items
267            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
268    };
269
270    (@path $shape:ident $items:tt [$($path:tt)+] $(, $($tail:tt)*)?) => {
271        $crate::__case_payload!(@push $shape $items [$($path)+] $(, $($tail)*)?)
272    };
273
274    (@push $shape:ident [$($items:expr,)*] [$value:expr], $($tail:tt)*) => {
275        $crate::__case_payload!(@fields tuple [$($items,)* $value,] $($tail)*)
276    };
277    (@push scalar [] [$value:expr]) => { $value };
278    (@push tuple [$($items:expr,)*] [$value:expr]) => { ($($items,)* $value,) };
279
280    ($($unsupported:tt)*) => {{
281        compile_error!("unsupported pattern in case!; use filter or filter_map for arbitrary Rust patterns")
282    }};
283}
284
285/// Conditionally applies `#[tokio::test]`/`#[test]` for native builds
286/// and `#[wasm_bindgen_test]` for Wasm targets.
287#[cfg(test)]
288macro_rules! cross_test {
289    () => {};
290    ($(#[$($attr:tt)*])* async fn $name:ident() $body:block $($rest:tt)*) => {
291        #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
292        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
293        $(#[$($attr)*])*
294        async fn $name() $body
295
296        crate::cross_test! { $($rest)* }
297    };
298    ($(#[$($attr:tt)*])* fn $name:ident() $body:block $($rest:tt)*) => {
299        #[cfg_attr(not(target_arch = "wasm32"), test)]
300        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
301        $(#[$($attr)*])*
302        fn $name() $body
303
304        crate::cross_test! { $($rest)* }
305    };
306}
307
308#[cfg(test)]
309pub(crate) use cross_test;
310
311#[cfg(test)]
312mod tests {
313    use std::ops::ControlFlow;
314
315    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
316    enum State {
317        A,
318        B(i32),
319        C(i32, &'static str),
320        D { foo: i32 },
321        E { foo: i32, bar: &'static str },
322        Other,
323    }
324
325    #[derive(Clone)]
326    enum Dialogue {
327        Start,
328        GotNumber(i32),
329        ReceiveAge { full_name: String },
330        ReceiveLocation { full_name: String, age: u8 },
331    }
332
333    #[derive(Clone)]
334    enum Nested {
335        Tuple(State, Option<State>),
336        Named { inner: Named, flag: bool },
337        Maybe(Option<Result<u8, u16>>, i32),
338        Rest((), (), i32),
339    }
340
341    #[derive(Clone)]
342    struct Named {
343        state: State,
344        count: u8,
345    }
346
347    crate::cross_test! {
348        async fn handler_empty_variant() {
349            let input = State::A;
350            let h: crate::Handler<_> = case![State::A].endpoint(|| async move { 123 });
351
352            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
353            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
354        }
355
356        async fn handler_single_fn_variant() {
357            let input = State::B(42);
358            let h: crate::Handler<_> = case![State::B(x)].endpoint(|x: i32| async move {
359                assert_eq!(x, 42);
360                123
361            });
362
363            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
364            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
365        }
366
367        async fn handler_single_fn_variant_trailing_comma() {
368            let input = State::B(42);
369            let h: crate::Handler<_> = case![State::B(x,)].endpoint(|(x,): (i32,)| async move {
370                assert_eq!(x, 42);
371                123
372            });
373
374            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
375            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
376        }
377
378        async fn handler_fn_variant() {
379            let input = State::C(42, "abc");
380            let h: crate::Handler<_> =
381                case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {
382                    assert_eq!(x, 42);
383                    assert_eq!(str, "abc");
384                    123
385                });
386
387            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
388            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
389        }
390
391        async fn handler_single_struct_variant() {
392            let input = State::D { foo: 42 };
393            let h: crate::Handler<_> = case![State::D { foo }].endpoint(|x: i32| async move {
394                assert_eq!(x, 42);
395                123
396            });
397
398            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
399            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
400        }
401
402        async fn handler_single_struct_variant_trailing_comma() {
403            let input = State::D { foo: 42 };
404            #[rustfmt::skip] // rustfmt removes the trailing comma from `State::D { foo, }`, but it plays a vital role in this test.
405            let h: crate::Handler<_> = case![State::D { foo, }].endpoint(|(x,): (i32,)| async move {
406                assert_eq!(x, 42);
407                123
408            });
409
410            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
411            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
412        }
413
414        async fn handler_struct_variant() {
415            let input = State::E { foo: 42, bar: "abc" };
416            let h: crate::Handler<_> =
417                case![State::E { foo, bar }].endpoint(|(x, str): (i32, &'static str)| async move {
418                    assert_eq!(x, 42);
419                    assert_eq!(str, "abc");
420                    123
421                });
422
423            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
424            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
425        }
426
427        async fn handler_teloxide_dialogue_forms() {
428            let h: crate::Handler<_> = crate::entry()
429                .branch(case![Dialogue::Start].endpoint(|| async { "start".to_owned() }))
430                .branch(
431                    case![Dialogue::GotNumber(n)].endpoint(|n: i32| async move { n.to_string() }),
432                )
433                .branch(
434                    case![Dialogue::ReceiveAge { full_name }]
435                        .endpoint(|name: String| async move { name }),
436                )
437                .branch(
438                    case![Dialogue::ReceiveLocation { full_name, age }].endpoint(
439                        |(name, age): (String, u8)| async move { format!("{name}: {age}") },
440                    ),
441                );
442
443            for (input, expected) in [
444                (Dialogue::Start, "start"),
445                (Dialogue::GotNumber(42), "42"),
446                (Dialogue::ReceiveAge { full_name: "Ada".to_owned() }, "Ada"),
447                (Dialogue::ReceiveLocation { full_name: "Ada".to_owned(), age: 37 }, "Ada: 37"),
448            ] {
449                assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(expected.to_owned()));
450            }
451        }
452
453        async fn handler_nested_variants_preserve_tuple_shape() {
454            let h: crate::Handler<_> = case![Nested::Tuple(State::C(n, label), Some(State::A))]
455                .endpoint(|payload: ((i32, &'static str), State)| async move { payload });
456            let dispatch = |input| h.dispatch(crate::deps![input]);
457
458            assert_eq!(
459                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::A))).await.break_value(),
460                Some(((42, "answer"), State::A)),
461            );
462            assert!(matches!(
463                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::Other))).await,
464                ControlFlow::Continue(_),
465            ));
466
467            let h: crate::Handler<_> = case![Nested::Tuple(State::B(n,), ..)]
468                .endpoint(|payload: ((i32,),)| async move { payload });
469            assert_eq!(
470                h.dispatch(crate::deps![Nested::Tuple(State::B(42), None)]).await.break_value(),
471                Some(((42,),)),
472            );
473        }
474
475        async fn handler_nested_named_fields_and_rest() {
476            let h: crate::Handler<_> =
477                case![Nested::Named { inner: Named { state: State::B(n), .. }, flag: enabled }]
478                    .endpoint(|payload: ((i32,), bool)| async move { payload });
479            let input = Nested::Named { inner: Named { state: State::B(42), count: 5 }, flag: true };
480            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(((42,), true)));
481
482            let h: crate::Handler<_> =
483                case![Named { count: n, .. }].endpoint(|payload: (u8,)| async move { payload });
484            let input = Named { state: State::Other, count: 5 };
485            assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some((5,)));
486        }
487
488        async fn handler_typed_unit_variant() {
489            let h: crate::Handler<_> = case![Nested::Maybe(None::<Result<u8, u16>>, n)]
490                .endpoint(|payload: (Option<Result<u8, u16>>, i32)| async move { payload });
491
492            assert_eq!(
493                h.dispatch(crate::deps![Nested::Maybe(None, 42)]).await.break_value(),
494                Some((None, 42)),
495            );
496            assert!(matches!(
497                h.dispatch(crate::deps![Nested::Maybe(Some(Ok(5)), 42)]).await,
498                ControlFlow::Continue(_),
499            ));
500
501            let h: crate::Handler<_> = case![Option::None::<u8>]
502                .endpoint(|payload: Option<u8>| async move { payload });
503            assert_eq!(h.dispatch(crate::deps![None::<u8>]).await.break_value(), Some(None));
504        }
505
506        async fn handler_tuple_rest_and_empty_payload() {
507            let h: crate::Handler<_> =
508                case![Nested::Rest(.., n)].endpoint(|payload: (i32,)| async move { payload });
509            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await.break_value(), Some((3,)));
510
511            let h: crate::Handler<_> = case![Nested::Rest(..)].endpoint(|(): ()| async { 42 });
512            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await.break_value(), Some(42));
513        }
514    }
515}