Skip to main content

tree_sitter_utils/combinators/
and_then.rs

1//! The [`AndThen`] combinator — flat-map on success.
2
3use crate::handler::{Handler, HandlerResult};
4use crate::input::Input;
5use std::marker::PhantomData;
6
7/// A handler that, on success, feeds `(input, out)` into a second function
8/// that may itself fail.
9///
10/// Constructed via [`HandlerExt::and_then`](crate::HandlerExt::and_then).
11///
12/// # Example
13///
14/// ```rust
15/// use tree_sitter_utils::{handler_fn, HandlerExt, Input};
16///
17/// let h = handler_fn(|_: Input<()>| 42u32)
18///     .and_then(|_input: Input<()>, n: u32| if n > 0 { Some(n.to_string()) } else { None });
19/// let _ = h;
20/// ```
21pub struct AndThen<H, F, R> {
22    /// The source handler.
23    pub inner: H,
24    /// The flat-mapping function.
25    pub f: F,
26    pub(crate) _marker: PhantomData<fn(R)>,
27}
28
29impl<Ctx, R, R2, H, F> Handler<Ctx, R2> for AndThen<H, F, R>
30where
31    H: Handler<Ctx, R>,
32    F: Fn(Input<'_, Ctx>, R) -> HandlerResult<R2> + Send + Sync,
33    Ctx: Copy,
34{
35    #[inline]
36    fn handle<'tree>(&self, input: Input<'tree, Ctx>) -> HandlerResult<R2> {
37        self.inner.handle(input).and_then(|out| (self.f)(input, out))
38    }
39}