harper_core/expr/
optional.rs

1use crate::{Span, Token};
2
3use super::Expr;
4
5/// An optional expression.
6/// Forces the optional expression to always return Some by transmuting `None` into
7/// `Some(cursor..cursor)`.
8pub struct Optional {
9    inner: Box<dyn Expr>,
10}
11
12impl Optional {
13    pub fn new(inner: impl Expr + 'static) -> Self {
14        Self {
15            inner: Box::new(inner),
16        }
17    }
18}
19
20impl Expr for Optional {
21    fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span<Token>> {
22        let res = self.inner.run(cursor, tokens, source);
23
24        if res.is_none() {
25            Some(Span::new_with_len(cursor, 0))
26        } else {
27            res
28        }
29    }
30}