tengri/core/src/lib.rs
unspeaker a46d0d2258
Some checks are pending
/ build (push) Waiting to run
wip: fix(dsl): maybe getting somewhere?
2025-06-21 15:50:00 +03:00

71 lines
2.1 KiB
Rust

pub(crate) use std::error::Error;
/// Standard result type.
pub type Usually<T> = Result<T, Box<dyn Error>>;
/// Standard optional result type.
pub type Perhaps<T> = Result<Option<T>, Box<dyn Error>>;
/// Implement the `From` trait.
#[macro_export] macro_rules! from {
($(<$($lt:lifetime),+>)?|$state:ident:$Source:ty|$Target:ty=$cb:expr) => {
impl $(<$($lt),+>)? From<$Source> for $Target {
fn from ($state:$Source) -> Self { $cb }
}
};
}
pub trait Has<T>: Send + Sync {
fn get (&self) -> &T;
fn get_mut (&mut self) -> &mut T;
}
#[macro_export] macro_rules! has {
($T:ty: |$self:ident : $S:ty| $x:expr) => {
impl Has<$T> for $S {
fn get (&$self) -> &$T { &$x }
fn get_mut (&mut $self) -> &mut $T { &mut $x }
}
};
}
pub trait MaybeHas<T>: Send + Sync {
fn get (&self) -> Option<&T>;
fn get_mut (&mut self) -> Option<&mut T>;
}
#[macro_export] macro_rules! maybe_has {
($T:ty: |$self:ident : $S:ty| $x:block; $y:block $(;)?) => {
impl MaybeHas<$T> for $S {
fn get (&$self) -> Option<&$T> $x
fn get_mut (&mut $self) -> Option<&mut $T> $y
}
};
}
/// May compute a `RetVal` from `Args`.
pub trait Eval<Args, RetVal> {
/// A custom operation on [Args] that may return [Result::Err] or [Option::None].
fn try_eval (&self, args: &Args) -> Perhaps<RetVal>;
/// Invoke a custom operation, converting a `None` result to a custom `Box<dyn Error>`.
fn eval <E: Into<Box<dyn std::error::Error>>> (&self, args: &Args, error: impl Fn()->E)
-> Usually<RetVal>
{
match self.try_eval(args)? {
Some(value) => Ok(value),
_ => Result::Err(format!("Eval: {}", error().into()).into())
}
}
}
//impl<S: Eval<I, O>, I, O> Eval<I, O> for &S {
//fn try_eval (&self, input: I) -> Perhaps<O> {
//(*self).try_eval(input)
//}
//}
//impl<S: Eval<I, O>, I: Ast, O: Dsl<S>> Eval<I, O> for S {
//fn try_eval (&self, input: I) -> Perhaps<O> {
//Dsl::try_provide(self, input)
//}
//}