Skip to main content

tree_sitter_utils/combinators/
or.rs

1//! The [`Or`] combinator — try the first handler, fall back to the second.
2
3use crate::handler::{Handler, HandlerResult};
4use crate::input::Input;
5
6/// A handler that tries `A` first; if it returns `None`, tries `B`.
7///
8/// Constructed via [`HandlerExt::or`](crate::HandlerExt::or).
9///
10/// # Example
11///
12/// ```rust
13/// use tree_sitter_utils::{handler_fn, HandlerExt, never};
14///
15/// let h = never::<(), String>()
16///     .or(handler_fn(|_: tree_sitter_utils::Input<()>| "fallback".to_owned()));
17/// let _ = h;
18/// ```
19pub struct Or<A, B> {
20    /// Primary handler.
21    pub first: A,
22    /// Fallback handler.
23    pub second: B,
24}
25
26impl<Ctx, R, A, B> Handler<Ctx, R> for Or<A, B>
27where
28    A: Handler<Ctx, R>,
29    B: Handler<Ctx, R>,
30    Ctx: Copy,
31{
32    #[inline]
33    fn handle<'tree>(&self, input: Input<'tree, Ctx>) -> HandlerResult<R> {
34        self.first.handle(input).or_else(|| self.second.handle(input))
35    }
36}