dptree-fork 0.7.0

An asynchronous event dispatch mechanism for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! An implementation of the [chain (tree) of responsibility] pattern.
//!
//! [[`examples/web_server.rs`](https://github.com/teloxide/dptree/blob/master/examples/web_server.rs)]
//! ```rust
//! use dptree::prelude::*;
//!
//! type WebHandler = Endpoint<'static, String>;
//!
//! #[rustfmt::skip]
//! #[tokio::main(flavor = "current_thread")]
//! async fn main() {
//!     let web_server = dptree::entry()
//!         .branch(smiles_handler())
//!         .branch(sqrt_handler())
//!         .branch(not_found_handler());
//!
//!     assert_eq!(
//!         web_server.dispatch(dptree::deps!["/smile"]).await,
//!         ControlFlow::Break("🙃".to_owned())
//!     );
//!     assert_eq!(
//!         web_server.dispatch(dptree::deps!["/sqrt 16"]).await,
//!         ControlFlow::Break("4".to_owned())
//!     );
//!     assert_eq!(
//!         web_server.dispatch(dptree::deps!["/lol"]).await,
//!         ControlFlow::Break("404 Not Found".to_owned())
//!     );
//! }
//!
//! fn smiles_handler() -> WebHandler {
//!     dptree::filter(|req: &'static str| req.starts_with("/smile"))
//!         .endpoint(|| async { "🙃".to_owned() })
//! }
//!
//! fn sqrt_handler() -> WebHandler {
//!     dptree::filter_map(|req: &'static str| {
//!         if req.starts_with("/sqrt") {
//!             let (_, n) = req.split_once(' ')?;
//!             n.parse::<f64>().ok()
//!         } else {
//!             None
//!         }
//!     })
//!     .endpoint(|n: f64| async move { format!("{}", n.sqrt()) })
//! }
//!
//! fn not_found_handler() -> WebHandler {
//!     dptree::endpoint(|| async { "404 Not Found".to_owned() })
//! }
//! ```
//!
//! For a high-level overview, please see [`README.md`](https://github.com/teloxide/dptree).
//!
//! [chain (tree) of responsibility]: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

mod handler;

pub mod di;
pub mod prelude;
pub mod send;

pub use handler::*;

/// Filters by a pattern, passing its payload forwards.
///
/// This macro expands to a [`crate::Handler`] that acts on your enumeration
/// type: if the enumeration is of a certain variant, the execution continues;
/// otherwise, `dptree` will try the next branch. This is very useful for
/// dialogue FSM transitions and incoming command filtering; for a real-world
/// example, please see teloxide's [`examples/purchase.rs`].
///
/// Variants can take the following forms:
///
///  - `Enum::MyVariant` for empty variants;
///  - `Enum::MyVariant(param1, ..., paramN)` for tuple-like variants;
///  - `Enum::MyVariant { param1, ..., paramN }` for `struct`-like variants.
///
/// In the first case, this macro results in a simple [`crate::filter`]; in the
/// second and third cases, this macro results in [`crate::filter_map`] that
/// passes the payload of `MyVariant` to the next handler if the match occurs.
/// (This next handler can be an endpoint or a more complex one.) The payload
/// format depends on the form of `MyVariant`:
///
///  - For `Enum::MyVariant(param)` and `Enum::MyVariant { param }`, the payload
///    is `param`.
///  - For `Enum::MyVariant(param,)` and `Enum::MyVariant { param, }`, the
///    payload is `(param,)`.
///  - For `Enum::MyVariant(param1, ..., paramN)` and `Enum::MyVariant { param1,
///    ..., paramN }`, the payload is `(param1, ..., paramN)` (where `N`>1).
///
/// Tuple-like and struct-like patterns may also destructure structs and nested
/// variants. At each level, payloads are collected in the order written:
///
///  - An identifier contributes its bound value. In a named field `key: pattern`,
///    the payload comes from `pattern`, not `key`.
///  - A nested unit variant (such as `Other::Ready`) or typed unit variant
///    (such as `None::<T>`) contributes that value. A standalone path without
///    type arguments remains a filter that injects nothing.
///  - A nested tuple-like or struct-like pattern contributes its own payload as
///    one element; its tuple, if any, is not flattened into the outer tuple.
///  - `..` contributes no element. A comma still makes the payload a tuple:
///    `Variant(x, ..)` contributes `(x,)`, and `Variant(..)` contributes `()`.
///
/// For other Rust patterns, such as or-patterns or guards, use [`crate::filter`]
/// or [`crate::filter_map`] directly.
///
/// ## Dependency requirements
///
///  - The type matched by the pattern.
///
/// ## Examples
///
/// ```rust
/// use dptree::prelude::*;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// #[derive(Clone)]
/// enum Command {
///     Meow,
///     Add(i32, i32),
///     Repeat { times: Option<usize> },
/// }
///
/// let h: Handler<_> = dptree::entry()
///     .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
///     .branch(
///         dptree::case![Command::Add(x, y)]
///             .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
///     )
///     .branch(
///         dptree::case![Command::Repeat { times: Some(n) }]
///             .endpoint(|n: usize| async move { "Meow!".repeat(n) }),
///     );
///
/// assert_eq!(
///     h.dispatch(dptree::deps![Command::Meow]).await,
///     ControlFlow::Break("Meow!".to_owned())
/// );
/// assert_eq!(
///     h.dispatch(dptree::deps![Command::Add(1, 2)]).await,
///     ControlFlow::Break("3".to_owned())
/// );
/// assert_eq!(
///     h.dispatch(dptree::deps![Command::Repeat { times: Some(2) }]).await,
///     ControlFlow::Break("Meow!Meow!".to_owned())
/// );
/// # }
/// ```
///
/// [`examples/purchase.rs`]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/purchase.rs
#[macro_export]
macro_rules! case {
    ($($variant:ident)::+) => {
        $crate::filter(|x| matches!(x, $($variant)::+))
    };
    ($($variant:ident)::+ ($param:ident)) => {
        $crate::filter_map(|x| match x {
            $($variant)::+($param) => Some($param),
            _ => None,
        })
    };
    ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => {
        $crate::filter_map(|x| match x {
            $($variant)::+($($param),+) => Some(($($param),+ ,)),
            _ => None,
        })
    };
    ($($variant:ident)::+ {$param:ident}) => {
        $crate::filter_map(|x| match x {
            $($variant)::+{$param} => Some($param),
            _ => None,
        })
    };
    ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {
        $crate::filter_map(|x| match x {
            $($variant)::+ { $($param),+ } => Some(($($param),+ ,)),
            _ => None,
        })
    };
    ($($pattern:tt)+) => {
        $crate::filter_map(|x| {
            #[allow(unreachable_patterns)]
            match x {
                $($pattern)+ => Some($crate::__case_payload!(@fields scalar [] $($pattern)+)),
                _ => None,
            }
        })
    };
}

// Parse one comma-separated field at a time. A nested group starts a fresh
// accumulator and contributes one expression to its parent, so nested tuples
// retain their shape. `scalar` changes to `tuple` after the first comma, even
// when that comma follows an ignored rest or is the last token.
#[doc(hidden)]
#[macro_export]
macro_rules! __case_payload {
    (@fields $shape:ident [$($items:expr,)*]) => { ($($items,)*) };

    (@fields $shape:ident [$($items:expr,)*] .. $(, $($tail:tt)*)?) => {
        $crate::__case_payload!(@fields tuple [$($items,)*] $($($tail)*)?)
    };

    (@fields $shape:ident $items:tt $($path:ident)::+ ($($fields:tt)*) $($tail:tt)*) => {
        $crate::__case_payload!(@push $shape $items
            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
    };
    (@fields $shape:ident $items:tt $($path:ident)::+ {$($fields:tt)*} $($tail:tt)*) => {
        $crate::__case_payload!(@push $shape $items
            [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
    };

    // Require a comma or the end of the group after a leaf, so a path prefix
    // doesn't consume a named field or a typed unit variant.
    (@fields $shape:ident $items:tt $($path:ident)::+ ::<$($ty:ty),+ $(,)?> $(, $($tail:tt)*)?) => {
        $crate::__case_payload!(@push $shape $items [$($path)::+ ::<$($ty),+>] $(, $($tail)*)?)
    };
    (@fields $shape:ident $items:tt $($value:ident)::+ $(, $($tail:tt)*)?) => {
        $crate::__case_payload!(@push $shape $items [$($value)::+] $(, $($tail)*)?)
    };
    (@fields $shape:ident $items:tt $key:ident : $($tail:tt)+) => {
        $crate::__case_payload!(@fields $shape $items $($tail)+)
    };

    (@push $shape:ident [$($items:expr,)*] [$value:expr], $($tail:tt)*) => {
        $crate::__case_payload!(@fields tuple [$($items,)* $value,] $($tail)*)
    };
    (@push scalar [] [$value:expr]) => { $value };
    (@push tuple [$($items:expr,)*] [$value:expr]) => { ($($items,)* $value,) };

    ($($unsupported:tt)*) => {{
        compile_error!("unsupported pattern in case!; use filter or filter_map for arbitrary Rust patterns")
    }};
}

/// Conditionally applies `#[tokio::test]`/`#[test]` for native builds
/// and `#[wasm_bindgen_test]` for Wasm targets.
#[cfg(test)]
macro_rules! cross_test {
    () => {};
    ($(#[$($attr:tt)*])* async fn $name:ident() $body:block $($rest:tt)*) => {
        #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        $(#[$($attr)*])*
        async fn $name() $body

        crate::cross_test! { $($rest)* }
    };
    ($(#[$($attr:tt)*])* fn $name:ident() $body:block $($rest:tt)*) => {
        #[cfg_attr(not(target_arch = "wasm32"), test)]
        #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
        $(#[$($attr)*])*
        fn $name() $body

        crate::cross_test! { $($rest)* }
    };
}

#[cfg(test)]
pub(crate) use cross_test;

#[cfg(test)]
mod tests {
    use std::ops::ControlFlow;

    #[derive(Debug, Copy, Clone, Eq, PartialEq)]
    enum State {
        A,
        B(i32),
        C(i32, &'static str),
        D { foo: i32 },
        E { foo: i32, bar: &'static str },
        Other,
    }

    #[derive(Clone)]
    enum Dialogue {
        Start,
        GotNumber(i32),
        ReceiveAge { full_name: String },
        ReceiveLocation { full_name: String, age: u8 },
    }

    #[derive(Clone)]
    enum Nested {
        Tuple(State, Option<State>),
        Named { inner: Named, flag: bool },
        Maybe(Option<Result<u8, u16>>, i32),
        Rest((), (), i32),
    }

    #[derive(Clone)]
    struct Named {
        state: State,
        count: u8,
    }

    crate::cross_test! {
        async fn handler_empty_variant() {
            let input = State::A;
            let h: crate::Handler<_> = case![State::A].endpoint(|| async move { 123 });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_single_fn_variant() {
            let input = State::B(42);
            let h: crate::Handler<_> = case![State::B(x)].endpoint(|x: i32| async move {
                assert_eq!(x, 42);
                123
            });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_single_fn_variant_trailing_comma() {
            let input = State::B(42);
            let h: crate::Handler<_> = case![State::B(x,)].endpoint(|(x,): (i32,)| async move {
                assert_eq!(x, 42);
                123
            });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_fn_variant() {
            let input = State::C(42, "abc");
            let h: crate::Handler<_> =
                case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {
                    assert_eq!(x, 42);
                    assert_eq!(str, "abc");
                    123
                });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_single_struct_variant() {
            let input = State::D { foo: 42 };
            let h: crate::Handler<_> = case![State::D { foo }].endpoint(|x: i32| async move {
                assert_eq!(x, 42);
                123
            });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_single_struct_variant_trailing_comma() {
            let input = State::D { foo: 42 };
            #[rustfmt::skip] // rustfmt removes the trailing comma from `State::D { foo, }`, but it plays a vital role in this test.
            let h: crate::Handler<_> = case![State::D { foo, }].endpoint(|(x,): (i32,)| async move {
                assert_eq!(x, 42);
                123
            });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_struct_variant() {
            let input = State::E { foo: 42, bar: "abc" };
            let h: crate::Handler<_> =
                case![State::E { foo, bar }].endpoint(|(x, str): (i32, &'static str)| async move {
                    assert_eq!(x, 42);
                    assert_eq!(str, "abc");
                    123
                });

            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(123));
            assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
        }

        async fn handler_teloxide_dialogue_forms() {
            let h: crate::Handler<_> = crate::entry()
                .branch(case![Dialogue::Start].endpoint(|| async { "start".to_owned() }))
                .branch(
                    case![Dialogue::GotNumber(n)].endpoint(|n: i32| async move { n.to_string() }),
                )
                .branch(
                    case![Dialogue::ReceiveAge { full_name }]
                        .endpoint(|name: String| async move { name }),
                )
                .branch(
                    case![Dialogue::ReceiveLocation { full_name, age }].endpoint(
                        |(name, age): (String, u8)| async move { format!("{name}: {age}") },
                    ),
                );

            for (input, expected) in [
                (Dialogue::Start, "start"),
                (Dialogue::GotNumber(42), "42"),
                (Dialogue::ReceiveAge { full_name: "Ada".to_owned() }, "Ada"),
                (Dialogue::ReceiveLocation { full_name: "Ada".to_owned(), age: 37 }, "Ada: 37"),
            ] {
                assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(expected.to_owned()));
            }
        }

        async fn handler_nested_variants_preserve_tuple_shape() {
            let h: crate::Handler<_> = case![Nested::Tuple(State::C(n, label), Some(State::A))]
                .endpoint(|payload: ((i32, &'static str), State)| async move { payload });
            let dispatch = |input| h.dispatch(crate::deps![input]);

            assert_eq!(
                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::A))).await,
                ControlFlow::Break(((42, "answer"), State::A)),
            );
            assert!(matches!(
                dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::Other))).await,
                ControlFlow::Continue(_),
            ));

            let h: crate::Handler<_> = case![Nested::Tuple(State::B(n,), ..)]
                .endpoint(|payload: ((i32,),)| async move { payload });
            assert_eq!(
                h.dispatch(crate::deps![Nested::Tuple(State::B(42), None)]).await,
                ControlFlow::Break(((42,),)),
            );
        }

        async fn handler_nested_named_fields_and_rest() {
            let h: crate::Handler<_> =
                case![Nested::Named { inner: Named { state: State::B(n), .. }, flag: enabled }]
                    .endpoint(|payload: ((i32,), bool)| async move { payload });
            let input = Nested::Named { inner: Named { state: State::B(42), count: 5 }, flag: true };
            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break(((42,), true)));

            let h: crate::Handler<_> =
                case![Named { count: n, .. }].endpoint(|payload: (u8,)| async move { payload });
            let input = Named { state: State::Other, count: 5 };
            assert_eq!(h.dispatch(crate::deps![input]).await, ControlFlow::Break((5,)));
        }

        async fn handler_typed_unit_variant() {
            let h: crate::Handler<_> = case![Nested::Maybe(None::<Result<u8, u16>>, n)]
                .endpoint(|payload: (Option<Result<u8, u16>>, i32)| async move { payload });

            assert_eq!(
                h.dispatch(crate::deps![Nested::Maybe(None, 42)]).await,
                ControlFlow::Break((None, 42)),
            );
            assert!(matches!(
                h.dispatch(crate::deps![Nested::Maybe(Some(Ok(5)), 42)]).await,
                ControlFlow::Continue(_),
            ));

            let h: crate::Handler<_> = case![Option::None::<u8>]
                .endpoint(|payload: Option<u8>| async move { payload });
            assert_eq!(h.dispatch(crate::deps![None::<u8>]).await, ControlFlow::Break(None));
        }

        async fn handler_tuple_rest_and_empty_payload() {
            let h: crate::Handler<_> =
                case![Nested::Rest(.., n)].endpoint(|payload: (i32,)| async move { payload });
            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await, ControlFlow::Break((3,)));

            let h: crate::Handler<_> = case![Nested::Rest(..)].endpoint(|(): ()| async { 42 });
            assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await, ControlFlow::Break(42));
        }
    }
}