1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use crate::ctx::Context;
use crate::ctx::Match;
use crate::ctx::Span;
use crate::err::Error;
use crate::re::def_not;
use crate::re::Ctor;
use crate::re::Extract;
use crate::re::Handler;
use crate::re::Regex;

pub type DynamicRegexHandler<'a, C, R> = Box<dyn Fn(&mut C) -> Result<R, Error> + 'a>;

pub struct DynamicRegex<'a, C, R> {
    inner: DynamicRegexHandler<'a, C, R>,
}

def_not!(DynamicRegex<'a, C, R>);

impl<'a, C, R> DynamicRegex<'a, C, R> {
    pub fn new(inner: DynamicRegexHandler<'a, C, R>) -> Self {
        Self { inner }
    }

    pub fn with_inner(mut self, inner: DynamicRegexHandler<'a, C, R>) -> Self {
        self.inner = inner;
        self
    }

    pub fn inner(&self) -> &DynamicRegexHandler<'a, C, R> {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut DynamicRegexHandler<'a, C, R> {
        &mut self.inner
    }

    pub fn set_inner(&mut self, inner: DynamicRegexHandler<'a, C, R>) -> &mut Self {
        self.inner = inner;
        self
    }
}

impl<'a, C, R> Regex<C> for DynamicRegex<'a, C, R> {
    type Ret = R;

    #[inline(always)]
    fn try_parse(&self, ctx: &mut C) -> Result<Self::Ret, Error> {
        self.inner.try_parse(ctx)
    }
}

impl<'a, 'b, C, O> Ctor<'a, C, O, O> for DynamicRegex<'b, C, Span>
where
    C: Context<'a> + Match<C>,
{
    #[inline(always)]
    fn constrct<H, A>(&self, ctx: &mut C, handler: &mut H) -> Result<O, Error>
    where
        H: Handler<A, Out = O, Error = Error>,
        A: Extract<'a, C, Span, Out<'a> = A, Error = Error>,
    {
        let ret = ctx.try_mat_t(&self.inner)?;

        handler.invoke(A::extract(ctx, &ret)?)
    }
}

pub fn into_dyn_regex<'a, 'b, C, R>(
    invoke: impl Fn(&mut C) -> Result<R, Error> + 'b,
) -> DynamicRegex<'b, C, R>
where
    C: Context<'a>,
{
    DynamicRegex::new(Box::new(invoke))
}

pub trait DynamicRegexHelper<'a, 'b, C, R>
where
    C: Context<'a>,
{
    fn into_dyn_regex(self) -> DynamicRegex<'b, C, R>
    where
        Self: Sized;
}

impl<'a, 'b, C, R, T> DynamicRegexHelper<'a, 'b, C, R> for T
where
    C: Context<'a> + Match<C>,
    T: Fn(&mut C) -> Result<R, Error> + 'b,
{
    fn into_dyn_regex(self) -> DynamicRegex<'b, C, R>
    where
        Self: Sized,
    {
        DynamicRegex::new(Box::new(self))
    }
}