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,
19//!         ControlFlow::Break("🙃".to_owned())
20//!     );
21//!     assert_eq!(
22//!         web_server.dispatch(dptree::deps!["/sqrt 16"]).await,
23//!         ControlFlow::Break("4".to_owned())
24//!     );
25//!     assert_eq!(
26//!         web_server.dispatch(dptree::deps!["/lol"]).await,
27//!         ControlFlow::Break("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/// Tuple-like and struct-like patterns may also destructure structs and nested
93/// variants. At each level, payloads are collected in the order written:
94///
95///  - An identifier contributes its bound value. In a named field `key: pattern`,
96///    the payload comes from `pattern`, not `key`.
97///  - A nested unit variant (such as `Other::Ready`) or typed unit variant
98///    (such as `None::<T>`) contributes that value. A standalone path without
99///    type arguments remains a filter that injects nothing.
100///  - A nested tuple-like or struct-like pattern contributes its own payload as
101///    one element; its tuple, if any, is not flattened into the outer tuple.
102///  - `..` contributes no element. A comma still makes the payload a tuple:
103///    `Variant(x, ..)` contributes `(x,)`, and `Variant(..)` contributes `()`.
104///
105/// For other Rust patterns, such as or-patterns or guards, use [`crate::filter`]
106/// or [`crate::filter_map`] directly.
107///
108/// ## Dependency requirements
109///
110///  - The type matched by the pattern.
111///
112/// ## Examples
113///
114/// ```rust
115/// use dptree::prelude::*;
116///
117/// # #[tokio::main(flavor = "current_thread")]
118/// # async fn main() {
119/// #[derive(Clone)]
120/// enum Command {
121///     Meow,
122///     Add(i32, i32),
123///     Repeat { times: Option<usize> },
124/// }
125///
126/// let h: Handler<_> = dptree::entry()
127///     .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
128///     .branch(
129///         dptree::case![Command::Add(x, y)]
130///             .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
131///     )
132///     .branch(
133///         dptree::case![Command::Repeat { times: Some(n) }]
134///             .endpoint(|n: usize| async move { "Meow!".repeat(n) }),
135///     );
136///
137/// assert_eq!(
138///     h.dispatch(dptree::deps![Command::Meow]).await,
139///     ControlFlow::Break("Meow!".to_owned())
140/// );
141/// assert_eq!(
142///     h.dispatch(dptree::deps![Command::Add(1, 2)]).await,
143///     ControlFlow::Break("3".to_owned())
144/// );
145/// assert_eq!(
146///     h.dispatch(dptree::deps![Command::Repeat { times: Some(2) }]).await,
147///     ControlFlow::Break("Meow!Meow!".to_owned())
148/// );
149/// # }
150/// ```
151///
152/// [`examples/purchase.rs`]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/purchase.rs
153#[macro_export]
154macro_rules! case {
155    ($($variant:ident)::+) => {
156        $crate::filter(|x| matches!(x, $($variant)::+))
157    };
158    ($($variant:ident)::+ ($param:ident)) => {
159        $crate::filter_map(|x| match x {
160            $($variant)::+($param) => Some($param),
161            _ => None,
162        })
163    };
164    ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => {
165        $crate::filter_map(|x| match x {
166            $($variant)::+($($param),+) => Some(($($param),+ ,)),
167            _ => None,
168        })
169    };
170    ($($variant:ident)::+ {$param:ident}) => {
171        $crate::filter_map(|x| match x {
172            $($variant)::+{$param} => Some($param),
173            _ => None,
174        })
175    };
176    ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {
177        $crate::filter_map(|x| match x {
178            $($variant)::+ { $($param),+ } => Some(($($param),+ ,)),
179            _ => None,
180        })
181    };
182    ($($pattern:tt)+) => {
183        $crate::filter_map(|x| {
184            #[allow(unreachable_patterns)]
185            match x {
186                $($pattern)+ => Some($crate::__case_payload!(@fields scalar [] $($pattern)+)),
187                _ => None,
188            }
189        })
190    };
191}
192
193// Parse one comma-separated field at a time. A nested group starts a fresh
194// accumulator and contributes one expression to its parent, so nested tuples
195// retain their shape. `scalar` changes to `tuple` after the first comma, even
196// when that comma follows an ignored rest or is the last token.
197#[doc(hidden)]
198#[macro_export]
199macro_rules! __case_payload {
200    (@fields $shape:ident [$($items:expr,)*]) => { ($($items,)*) };
201
202    (@fields $shape:ident [$($items:expr,)*] .. $(, $($tail:tt)*)?) => {
203        $crate::__case_payload!(@fields tuple [$($items,)*] $($($tail)*)?)
204    };
205
206    (@fields $shape:ident $items:tt $($path:ident)::+ ($($fields:tt)*) $($tail:tt)*) => {
207        $crate::__case_payload!(@push $shape $items
208            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
209    };
210    (@fields $shape:ident $items:tt $($path:ident)::+ {$($fields:tt)*} $($tail:tt)*) => {
211        $crate::__case_payload!(@push $shape $items
212            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
213    };
214
215    // Require a comma or the end of the group after a leaf, so a path prefix
216    // doesn't consume a named field or a typed unit variant.
217    (@fields $shape:ident $items:tt $($path:ident)::+ ::<$($ty:ty),+ $(,)?> $(, $($tail:tt)*)?) => {
218        $crate::__case_payload!(@push $shape $items [$($path)::+ ::<$($ty),+>] $(, $($tail)*)?)
219    };
220    (@fields $shape:ident $items:tt $($value:ident)::+ $(, $($tail:tt)*)?) => {
221        $crate::__case_payload!(@push $shape $items [$($value)::+] $(, $($tail)*)?)
222    };
223    (@fields $shape:ident $items:tt $key:ident : $($tail:tt)+) => {
224        $crate::__case_payload!(@fields $shape $items $($tail)+)
225    };
226
227    (@push $shape:ident [$($items:expr,)*] [$value:expr], $($tail:tt)*) => {
228        $crate::__case_payload!(@fields tuple [$($items,)* $value,] $($tail)*)
229    };
230    (@push scalar [] [$value:expr]) => { $value };
231    (@push tuple [$($items:expr,)*] [$value:expr]) => { ($($items,)* $value,) };
232
233    ($($unsupported:tt)*) => {{
234        compile_error!("unsupported pattern in case!; use filter or filter_map for arbitrary Rust patterns")
235    }};
236}
237
238/// Conditionally applies `#[tokio::test]`/`#[test]` for native builds
239/// and `#[wasm_bindgen_test]` for Wasm targets.
240#[cfg(test)]
241macro_rules! cross_test {
242    () => {};
243    ($(#[$($attr:tt)*])* async fn $name:ident() $body:block $($rest:tt)*) => {
244        #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
245        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
246        $(#[$($attr)*])*
247        async fn $name() $body
248
249        crate::cross_test! { $($rest)* }
250    };
251    ($(#[$($attr:tt)*])* fn $name:ident() $body:block $($rest:tt)*) => {
252        #[cfg_attr(not(target_arch = "wasm32"), test)]
253        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
254        $(#[$($attr)*])*
255        fn $name() $body
256
257        crate::cross_test! { $($rest)* }
258    };
259}
260
261#[cfg(test)]
262pub(crate) use cross_test;
263
264#[cfg(test)]
265mod tests {
266    use std::ops::ControlFlow;
267
268    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
269    enum State {
270        A,
271        B(i32),
272        C(i32, &'static str),
273        D { foo: i32 },
274        E { foo: i32, bar: &'static str },
275        Other,
276    }
277
278    #[derive(Clone)]
279    enum Dialogue {
280        Start,
281        GotNumber(i32),
282        ReceiveAge { full_name: String },
283        ReceiveLocation { full_name: String, age: u8 },
284    }
285
286    #[derive(Clone)]
287    enum Nested {
288        Tuple(State, Option<State>),
289        Named { inner: Named, flag: bool },
290        Maybe(Option<Result<u8, u16>>, i32),
291        Rest((), (), i32),
292    }
293
294    #[derive(Clone)]
295    struct Named {
296        state: State,
297        count: u8,
298    }
299
300    crate::cross_test! {
301        async fn handler_empty_variant() {
302            let input = State::A;
303            let h: crate::Handler<_> = case![State::A].endpoint(|| async move { 123 });
304
305            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
306            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
307        }
308
309        async fn handler_single_fn_variant() {
310            let input = State::B(42);
311            let h: crate::Handler<_> = case![State::B(x)].endpoint(|x: i32| async move {
312                assert_eq!(x, 42);
313                123
314            });
315
316            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
317            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
318        }
319
320        async fn handler_single_fn_variant_trailing_comma() {
321            let input = State::B(42);
322            let h: crate::Handler<_> = case![State::B(x,)].endpoint(|(x,): (i32,)| async move {
323                assert_eq!(x, 42);
324                123
325            });
326
327            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
328            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
329        }
330
331        async fn handler_fn_variant() {
332            let input = State::C(42, "abc");
333            let h: crate::Handler<_> =
334                case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {
335                    assert_eq!(x, 42);
336                    assert_eq!(str, "abc");
337                    123
338                });
339
340            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
341            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
342        }
343
344        async fn handler_single_struct_variant() {
345            let input = State::D { foo: 42 };
346            let h: crate::Handler<_> = case![State::D { foo }].endpoint(|x: i32| async move {
347                assert_eq!(x, 42);
348                123
349            });
350
351            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
352            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
353        }
354
355        async fn handler_single_struct_variant_trailing_comma() {
356            let input = State::D { foo: 42 };
357            #[rustfmt::skip] // rustfmt removes the trailing comma from `State::D { foo, }`, but it plays a vital role in this test.
358            let h: crate::Handler<_> = case![State::D { foo, }].endpoint(|(x,): (i32,)| async move {
359                assert_eq!(x, 42);
360                123
361            });
362
363            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
364            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
365        }
366
367        async fn handler_struct_variant() {
368            let input = State::E { foo: 42, bar: "abc" };
369            let h: crate::Handler<_> =
370                case![State::E { foo, bar }].endpoint(|(x, str): (i32, &'static str)| async move {
371                    assert_eq!(x, 42);
372                    assert_eq!(str, "abc");
373                    123
374                });
375
376            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
377            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
378        }
379
380        async fn handler_teloxide_dialogue_forms() {
381            let h: crate::Handler<_> = crate::entry()
382                .branch(case![Dialogue::Start].endpoint(|| async { "start".to_owned() }))
383                .branch(
384                    case![Dialogue::GotNumber(n)].endpoint(|n: i32| async move { n.to_string() }),
385                )
386                .branch(
387                    case![Dialogue::ReceiveAge { full_name }]
388                        .endpoint(|name: String| async move { name }),
389                )
390                .branch(
391                    case![Dialogue::ReceiveLocation { full_name, age }].endpoint(
392                        |(name, age): (String, u8)| async move { format!("{name}: {age}") },
393                    ),
394                );
395
396            for (input, expected) in [
397                (Dialogue::Start, "start"),
398                (Dialogue::GotNumber(42), "42"),
399                (Dialogue::ReceiveAge { full_name: "Ada".to_owned() }, "Ada"),
400                (Dialogue::ReceiveLocation { full_name: "Ada".to_owned(), age: 37 }, "Ada: 37"),
401            ] {
402                assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(expected.to_owned()));
403            }
404        }
405
406        async fn handler_nested_variants_preserve_tuple_shape() {
407            let h: crate::Handler<_> = case![Nested::Tuple(State::C(n, label), Some(State::A))]
408                .endpoint(|payload: ((i32, &'static str), State)| async move { payload });
409            let dispatch = |input| h.dispatch(crate::deps![input]);
410
411            assert_eq!(
412                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::A))).await,
413                ControlFlow::Break(((42, "answer"), State::A)),
414            );
415            assert!(matches!(
416                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::Other))).await,
417                ControlFlow::Continue(_),
418            ));
419
420            let h: crate::Handler<_> = case![Nested::Tuple(State::B(n,), ..)]
421                .endpoint(|payload: ((i32,),)| async move { payload });
422            assert_eq!(
423                h.dispatch(crate::deps![Nested::Tuple(State::B(42), None)]).await,
424                ControlFlow::Break(((42,),)),
425            );
426        }
427
428        async fn handler_nested_named_fields_and_rest() {
429            let h: crate::Handler<_> =
430                case![Nested::Named { inner: Named { state: State::B(n), .. }, flag: enabled }]
431                    .endpoint(|payload: ((i32,), bool)| async move { payload });
432            let input = Nested::Named { inner: Named { state: State::B(42), count: 5 }, flag: true };
433            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(((42,), true)));
434
435            let h: crate::Handler<_> =
436                case![Named { count: n, .. }].endpoint(|payload: (u8,)| async move { payload });
437            let input = Named { state: State::Other, count: 5 };
438            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break((5,)));
439        }
440
441        async fn handler_typed_unit_variant() {
442            let h: crate::Handler<_> = case![Nested::Maybe(None::<Result<u8, u16>>, n)]
443                .endpoint(|payload: (Option<Result<u8, u16>>, i32)| async move { payload });
444
445            assert_eq!(
446                h.dispatch(crate::deps![Nested::Maybe(None, 42)]).await,
447                ControlFlow::Break((None, 42)),
448            );
449            assert!(matches!(
450                h.dispatch(crate::deps![Nested::Maybe(Some(Ok(5)), 42)]).await,
451                ControlFlow::Continue(_),
452            ));
453
454            let h: crate::Handler<_> = case![Option::None::<u8>]
455                .endpoint(|payload: Option<u8>| async move { payload });
456            assert_eq!(h.dispatch(crate::deps![None::<u8>]).await, ControlFlow::Break(None));
457        }
458
459        async fn handler_tuple_rest_and_empty_payload() {
460            let h: crate::Handler<_> =
461                case![Nested::Rest(.., n)].endpoint(|payload: (i32,)| async move { payload });
462            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await, ControlFlow::Break((3,)));
463
464            let h: crate::Handler<_> = case![Nested::Rest(..)].endpoint(|(): ()| async { 42 });
465            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await, ControlFlow::Break(42));
466        }
467    }
468}