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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
use std::fmt::Debug;
use std::marker::PhantomData;
use crate::ctx::Context;
use crate::ctx::CtxGuard;
use crate::ctx::Match;
use crate::ctx::Span;
use crate::err::Error;
use crate::map::Select0;
use crate::map::Select1;
use crate::map::SelectEq;
use crate::re::ctor::Map;
use crate::re::def_not;
use crate::re::trace;
use crate::re::Ctor;
use crate::re::Extract;
use crate::re::Handler;
use crate::re::Regex;
///
/// Like [`Then`](crate::re::ctor::Then), but create with [`.dyn_then_ctor`](crate::re::ctor::DynamicCreateCtorThenHelper#tymethod.dyn_then_ctor) of regex.
///
/// # Ctor
///
/// Return a tuple of `P`'s result and new regex result.
///
/// # Example
///
/// ```
/// # use neure::{prelude::*, re::DynamicCreateCtorThenHelper};
/// #
/// # fn main() -> color_eyre::Result<()> {
/// # color_eyre::install()?;
/// let len = re::consume(2).map(map::from_le_bytes::<i16>());
/// let data = len.dyn_then_ctor(|v: &i16| Ok(re::consume(*v as usize)));
/// let ret = BytesCtx::new(b"\x1f\0Hello there, where are you from?").ctor(&data)?;
///
/// assert_eq!(ret, (0x1f, b"Hello there, where are you from".as_ref()));
///
/// Ok(())
/// # }
/// ```
#[derive(Default, Copy)]
pub struct DynamicCreateCtorThen<C, P, F> {
pat: P,
func: F,
marker: PhantomData<C>,
}
def_not!(DynamicCreateCtorThen<C, P, F>);
impl<C, P, F> Debug for DynamicCreateCtorThen<C, P, F>
where
P: Debug,
F: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DynamicCreateCtorThen")
.field("pat", &self.pat)
.field("func", &self.func)
.finish()
}
}
impl<C, P, F> Clone for DynamicCreateCtorThen<C, P, F>
where
P: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
pat: self.pat.clone(),
func: self.func.clone(),
marker: self.marker,
}
}
}
impl<C, P, F> DynamicCreateCtorThen<C, P, F> {
pub fn new(pat: P, func: F) -> Self {
Self {
pat,
func,
marker: PhantomData,
}
}
pub fn pat(&self) -> &P {
&self.pat
}
pub fn pat_mut(&mut self) -> &mut P {
&mut self.pat
}
pub fn func(&self) -> &F {
&self.func
}
pub fn func_mut(&mut self) -> &mut F {
&mut self.func
}
pub fn set_pat(&mut self, pat: P) -> &mut Self {
self.pat = pat;
self
}
pub fn set_func(&mut self, func: F) -> &mut Self {
self.func = func;
self
}
pub fn _0<O>(self) -> Map<C, Self, Select0, O> {
Map::new(self, Select0)
}
pub fn _1<O>(self) -> Map<C, Self, Select1, O> {
Map::new(self, Select1)
}
pub fn _eq<I1, I2>(self) -> Map<C, Self, SelectEq, (I1, I2)> {
Map::new(self, SelectEq)
}
}
impl<'a, C, P, F, T, M, O1, O2, H, A> Ctor<'a, C, M, (O1, O2), H, A>
for DynamicCreateCtorThen<C, P, F>
where
P: Ctor<'a, C, M, O1, H, A>,
T: Ctor<'a, C, M, O2, H, A>,
C: Context<'a> + Match<C>,
F: Fn(&O1) -> Result<T, Error>,
H: Handler<A, Out = M, Error = Error>,
A: Extract<'a, C, Span, Out<'a> = A, Error = Error>,
{
#[inline(always)]
fn constrct(&self, ctx: &mut C, func: &mut H) -> Result<(O1, O2), Error> {
let mut g = CtxGuard::new(ctx);
let beg = g.beg();
let l = trace!("dynamic_create_ctor_then", beg @ "pat", self.pat.constrct(g.ctx(), func));
let l = g.process_ret(l)?;
let r = trace!("dynamic_create_ctor_then", beg @ "dynamic ctor", (self.func)(&l)?.constrct(g.ctx(), func));
let r = g.process_ret(r)?;
trace!("dynamic_create_ctor_then", beg -> g.end(), true);
Ok((l, r))
}
}
impl<'a, C, P, F> Regex<C> for DynamicCreateCtorThen<C, P, F>
where
P: Regex<C, Ret = Span>,
C: Context<'a> + Match<C>,
{
type Ret = P::Ret;
fn try_parse(&self, _: &mut C) -> Result<Self::Ret, Error> {
unimplemented!("Can't not using DynamicThen for regex")
}
}
pub trait DynamicCreateCtorThenHelper<'a, C>
where
Self: Sized,
C: Context<'a> + Match<C>,
{
fn dyn_then_ctor<F>(self, func: F) -> DynamicCreateCtorThen<C, Self, F>;
}
impl<'a, C, T> DynamicCreateCtorThenHelper<'a, C> for T
where
Self: Sized,
C: Context<'a> + Match<C>,
{
///
/// Construct a new regex with `Ctor` implementation based on previous result.
///
/// # Example
///
/// ```
/// # use neure::{err::Error, prelude::*, re::DynamicCreateCtorThenHelper};
/// #
/// # fn main() -> color_eyre::Result<()> {
/// # color_eyre::install()?;
/// let num = u8::is_ascii_digit
/// .repeat_one()
/// .map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
/// .map(map::from_str::<usize>());
/// let num = num.clone().sep_once(b",", num);
/// let re = num.dyn_then_ctor(|a: &(usize, usize)| {
/// // leave the a's type empty cause rustc reject compile
/// Ok(b'+'
/// .repeat_range(a.0..a.0 + 1)
/// .then(b'-'.repeat_range(a.1..a.1 + 1)))
/// });
///
/// assert_eq!(
/// BytesCtx::new(b"3,0+++").ctor(&re)?,
/// ((3, 0), ([43, 43, 43].as_slice(), [].as_slice()))
/// );
/// assert_eq!(
/// BytesCtx::new(b"2,1++-").ctor(&re)?,
/// ((2, 1), ([43, 43].as_slice(), [45].as_slice()))
/// );
/// assert_eq!(
/// BytesCtx::new(b"0,3---").ctor(&re)?,
/// ((0, 3), ([].as_slice(), [45, 45, 45].as_slice()))
/// );
/// Ok(())
/// # }
/// ```
fn dyn_then_ctor<F>(self, func: F) -> DynamicCreateCtorThen<C, Self, F> {
DynamicCreateCtorThen::new(self, func)
}
}