use std::cell::RefCell; use std::rc::Rc; use nom::branch::alt; use nom::error::VerboseError; use nom::IResult; use nom::Parser; type MatcherRef = Rc IResult<&str, &str, VerboseError<&str>>>>; struct FailChecker<'a>(&'a NomContext<'a>); impl<'a> FailChecker<'a> { fn new(func: &'a NomContext<'a>) -> Self { Self(func) } } enum ChainBehavior { AndParent(Option), IgnoreParent(Option), } pub struct NomContext<'a> { parent: Option<&'a Self>, fail_matcher: ChainBehavior, /// You can't have nested bolds or links in org-mode can_match_bold: bool, can_match_link: bool, } impl<'a> NomContext<'a> { pub fn new(fail_matcher: MatcherRef) -> Self { NomContext { parent: None, fail_matcher: ChainBehavior::IgnoreParent(Some(fail_matcher)), can_match_bold: true, can_match_link: true, } } pub fn with_additional_fail_matcher(&self, other: MatcherRef) -> NomContext { NomContext { parent: Some(&self), fail_matcher: ChainBehavior::AndParent(Some(other)), can_match_bold: self.can_match_bold, can_match_link: self.can_match_link, } } } impl<'a, 'b> Parser<&'b str, &'b str, VerboseError<&'b str>> for FailChecker<'a> { fn parse(&mut self, i: &'b str) -> IResult<&'b str, &'b str, VerboseError<&'b str>> { let fail_func = match &self.0.fail_matcher { ChainBehavior::AndParent(inner) => inner, ChainBehavior::IgnoreParent(inner) => inner, }; if let Some(inner) = fail_func { let parsed = (&mut *inner.borrow_mut())(i); if parsed.is_ok() { return parsed; } } match (self.0.parent, &self.0.fail_matcher) { (None, _) | (_, ChainBehavior::IgnoreParent(_)) => Err(nom::Err::Error( nom::error::make_error(i, nom::error::ErrorKind::Alt), )), (Some(parent), ChainBehavior::AndParent(_)) => { let mut parent_fail_checker = FailChecker::new(parent); parent_fail_checker.parse(i) } } } }