Skip to main content

tree_sitter_utils/combinators/
map.rs

1//! The [`Map`] combinator — transform a successful output value.
2
3use crate::handler::{Handler, HandlerResult};
4use crate::input::Input;
5use std::marker::PhantomData;
6
7/// A handler that applies `f` to the output of `inner` when it succeeds.
8///
9/// Constructed via [`HandlerExt::map`](crate::HandlerExt::map).
10///
11/// # Example
12///
13/// ```rust
14/// use tree_sitter_utils::{handler_fn, HandlerExt};
15///
16/// let h = handler_fn(|_: tree_sitter_utils::Input<()>| 42u32)
17///     .map(|n| n.to_string());
18/// let _ = h;
19/// ```
20pub struct Map<H, F, R> {
21    /// The source handler.
22    pub inner: H,
23    /// The mapping function.
24    pub f: F,
25    pub(crate) _marker: PhantomData<fn(R)>,
26}
27
28impl<Ctx, R, R2, H, F> Handler<Ctx, R2> for Map<H, F, R>
29where
30    H: Handler<Ctx, R>,
31    F: Fn(R) -> R2 + Send + Sync,
32    Ctx: Copy,
33{
34    #[inline]
35    fn handle<'tree>(&self, input: Input<'tree, Ctx>) -> HandlerResult<R2> {
36        self.inner.handle(input).map(|out| (self.f)(out))
37    }
38}