wip: dsl: more rework

This commit is contained in:
🪞👃🪞 2025-05-26 01:30:13 +03:00
parent f1b24d436a
commit 7097333993
4 changed files with 145 additions and 159 deletions

View file

@ -2,40 +2,40 @@ use crate::*;
use std::sync::Arc; use std::sync::Arc;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
/// Emits tokens.
pub trait Ast: Debug {
fn peek (&self) -> Option<AstValue>;
fn next (&mut self) -> Option<AstValue>;
fn rest (self) -> Option<Box<dyn Ast>>;
}
/// A [Cst] can be used as an [Ast].
impl<'source: 'static> Ast for Cst<'source> {
fn peek (&self) -> Option<AstValue> {
Cst::peek(self).map(|token|token.value.into())
}
fn next (&mut self) -> Option<AstValue> {
Iterator::next(self).map(|token|token.value.into())
}
fn rest (self) -> Option<Box<dyn Ast>> {
self.peek().is_some().then(||Box::new(self) as Box<dyn Ast>)
}
}
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
pub enum AstValue { pub enum Ast {
#[default] Nil, #[default] Nil,
Err(DslError), Err(DslError),
Num(usize), Num(usize),
Sym(Arc<str>), Sym(Arc<str>),
Key(Arc<str>), Key(Arc<str>),
Str(Arc<str>), Str(Arc<str>),
Exp(Arc<Box<dyn Ast>>), Exp(Arc<Box<dyn AstIter>>),
} }
impl std::fmt::Display for AstValue { /// Emits tokens.
pub trait AstIter: Debug {
fn peek (&self) -> Option<Ast>;
fn next (&mut self) -> Option<Ast>;
fn rest (self) -> Option<Box<dyn AstIter>>;
}
/// A [Cst] can be used as an [Ast].
impl<'source: 'static> AstIter for Cst<'source> {
fn peek (&self) -> Option<Ast> {
Cst::peek(self).map(|token|token.value.into())
}
fn next (&mut self) -> Option<Ast> {
Iterator::next(self).map(|token|token.value.into())
}
fn rest (self) -> Option<Box<dyn AstIter>> {
self.peek().is_some().then(||Box::new(self) as Box<dyn AstIter>)
}
}
impl std::fmt::Display for Ast {
fn fmt (&self, out: &mut Formatter) -> Result<(), std::fmt::Error> { fn fmt (&self, out: &mut Formatter) -> Result<(), std::fmt::Error> {
use AstValue::*; use Ast::*;
write!(out, "{}", match self { write!(out, "{}", match self {
Nil => String::new(), Nil => String::new(),
Err(e) => format!("[error: {e}]"), Err(e) => format!("[error: {e}]"),
@ -48,7 +48,7 @@ impl std::fmt::Display for AstValue {
} }
} }
impl<'source: 'static> From<CstValue<'source>> for AstValue { impl<'source: 'static> From<CstValue<'source>> for Ast {
fn from (other: CstValue<'source>) -> Self { fn from (other: CstValue<'source>) -> Self {
use CstValue::*; use CstValue::*;
match other { match other {
@ -63,8 +63,8 @@ impl<'source: 'static> From<CstValue<'source>> for AstValue {
} }
} }
impl<'source: 'static> Into<Box<dyn Ast>> for Cst<'source> { impl<'source: 'static> Into<Box<dyn AstIter>> for Cst<'source> {
fn into (self) -> Box<dyn Ast> { fn into (self) -> Box<dyn AstIter> {
Box::new(self) Box::new(self)
} }
} }

View file

@ -1,25 +1,37 @@
use crate::*; use crate::*;
pub trait Eval<Input, Output> { pub trait Eval<Input, Output> {
fn eval (&self, input: Input) -> Perhaps<Output>; fn try_eval (&self, input: Input) -> Perhaps<Output>;
fn eval <E: Into<Box<dyn std::error::Error>>, F: Fn()->E> (
&self, input: Input, error: F
) -> Usually<Output> {
if let Some(value) = self.try_eval(input)? {
Ok(value)
} else {
Result::Err(format!("Eval: {}", error().into()).into())
}
}
} }
/// May construct [Self] from token stream. /// May construct [Self] from token stream.
pub trait Dsl: Sized { pub trait Dsl<State>: Sized {
type State; fn try_provide (state: State, source: Ast) -> Perhaps<Self>;
fn try_provide (state: Self::State, source: impl Ast) -> Perhaps<Self>;
fn provide <E: Into<Box<dyn std::error::Error>>, F: Fn()->E> ( fn provide <E: Into<Box<dyn std::error::Error>>, F: Fn()->E> (
state: Self::State, source: impl Ast, error: F state: State, source: Ast, error: F
) -> Usually<Self> { ) -> Usually<Self> {
let next = source.peek().clone(); let next = source.clone();
if let Some(value) = Self::try_provide(state, source)? { if let Some(value) = Self::try_provide(state, source)? {
Ok(value) Ok(value)
} else { } else {
Result::Err(format!("dsl: {}: {next:?}", error().into()).into()) Result::Err(format!("Dsl: {}: {next:?}", error().into()).into())
} }
} }
} }
impl<T: Dsl<S>, S> Eval<Ast, T> for S {
fn try_eval (&self, input: Ast) -> Perhaps<T> { todo!() }
}
//pub trait Give<'state, 'source, Type> { //pub trait Give<'state, 'source, Type> {
///// Implement this to be able to [Give] [Type] from the [Cst]. ///// Implement this to be able to [Give] [Type] from the [Cst].
///// Advance the stream if returning `Ok<Some<Type>>`. ///// Advance the stream if returning `Ok<Some<Type>>`.

View file

@ -1,67 +1,53 @@
use crate::*; use crate::*;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::fmt::Debug;
/// List of input layers with optional conditional filters. /// List of input layers with optional conditional filters.
#[derive(Default, Debug)] pub struct InputLayers<S>(Vec<InputLayer<S>>); #[derive(Default, Debug)] pub struct InputLayers<S>(Vec<InputLayer<S>>);
#[derive(Default, Debug)] pub struct InputLayer<S>{ #[derive(Default, Debug)] pub struct InputLayer<S>{
__: PhantomData<S>, __: PhantomData<S>,
condition: Option<Box<dyn Ast>>, condition: Option<Ast>,
bindings: Box<dyn Ast>, binding: Ast,
} }
impl<S> InputLayers<S> { impl<S> InputLayers<S> {
pub fn new (layer: Box<dyn Ast>) -> Self pub fn new (layer: Ast) -> Self {
{ Self(vec![]).layer(layer) } Self(vec![]).layer(layer)
pub fn layer (mut self, layer: Box<dyn Ast>) -> Self }
{ self.add_layer(layer); self } pub fn layer (mut self, layer: Ast) -> Self {
pub fn layer_if (mut self, condition: Box<dyn Ast>, layer: Box<dyn Ast>) -> Self self.add_layer(layer); self
{ self.add_layer_if(Some(condition), layer); self } }
pub fn add_layer (&mut self, layer: Box<dyn Ast>) -> &mut Self pub fn layer_if (mut self, condition: Ast, layer: Ast) -> Self {
{ self.add_layer_if(None, layer.into()); self } self.add_layer_if(Some(condition), layer); self
pub fn add_layer_if ( }
&mut self, pub fn add_layer (&mut self, layer: Ast) -> &mut Self {
condition: Option<Box<dyn Ast>>, self.add_layer_if(None, layer.into()); self
bindings: Box<dyn Ast> }
) -> &mut Self { pub fn add_layer_if (&mut self, condition: Option<Ast>, binding: Ast) -> &mut Self {
self.0.push(InputLayer { condition, bindings, __: Default::default() }); self.0.push(InputLayer { condition, binding, __: Default::default() });
self self
} }
} }
impl<S: Eval<I, O>, I: Input, O: Command<S>> Eval<I, O> for InputLayers<S> { impl<S: Eval<Ast, bool> + Eval<Ast, C>, C: Command<S>, I: Debug + Eval<Ast, bool>> Eval<(S, I), C> for InputLayers<S> {
fn eval (&self, input: I) -> Perhaps<O> { fn try_eval (&self, (state, input): (S, I)) -> Perhaps<C> {
for layer in self.0.iter() { for InputLayer { condition, binding, .. } in self.0.iter() {
if let Some(command) = Ok(if let Some(condition) = layer.condition.as_ref() { let mut matches = true;
if self.matches(condition)? { if let Some(condition) = condition {
self.state().eval(*self)? matches = state.eval(condition.clone(), ||"input: no condition")?;
} else { }
None if matches {
if let Ast::Exp(e) = binding {
if let Some(ast) = e.peek() {
if input.eval(ast.clone(), ||"InputLayers: input.eval(binding) failed")?
&& let Some(command) = state.try_eval(ast)? {
return Ok(Some(command))
}
} else {
unreachable!("InputLayer")
}
} else {
panic!("InputLayer: expected expression, got: {input:?}")
} }
} else {
self.state().eval(*self)?
})? {
return Ok(Some(command))
} }
} }
}
}
/// [Input] state that can be matched against a [CstValue].
pub trait InputState<S>: Input {
fn state (&self) -> &S;
fn matches (&self, condition: &Box<dyn Ast>) -> Usually<bool>;
}
impl<S: Eval<I, O>, I: InputState<S>, O: Command<S>> Eval<I, O>
for InputLayer<S> {
fn eval (&self, input: I) -> Perhaps<O> {
if let Some(AstToken::Exp(exp)) = iter.peek() {
let mut e = exp.clone();
if let Some(AstToken::Sym(binding)) = e.next()
&& input.matches_dsl(binding)
&& let Some(command) = Dsl::from_dsl(input.state(), e)? {
return Ok(Some(command))
} else {
unreachable!("InputLayer: expected symbol, got: {e:?}")
}
} else {
panic!("InputLayer: expected expression, got: {self:?}")
}
Ok(None) Ok(None)
} }
} }

View file

@ -1,143 +1,131 @@
use crate::*; use crate::*;
impl<I: Ast, S, A> Eval<I, When<A>> for S where impl<S, A> Dsl<S> for When<A> where S: Eval<Ast, bool> + Eval<Ast, A> {
S: Eval<AstValue, bool> + Eval<AstValue, A> fn try_provide (state: S, source: Ast) -> Perhaps<Self> {
{
fn eval (&self, source: I) -> Perhaps<Self> {
Ok(match source.peek() { Ok(match source.peek() {
Some(Value::Key("when")) => Some(Self( Some(Value::Key("when")) => Some(Self(
self.provide(source, ||"when: expected condition")?, state.eval(source, ||"when: expected condition")?,
self.provide(source, ||"when: expected content")?, state.eval(source, ||"when: expected content")?,
)), )),
_ => None _ => None
}) })
} }
} }
impl<I: Ast, S, A, B> Eval<I, Either<A, B>> for S where impl<S, A, B> Dsl<S> for Either<A, B> where S: Eval<Ast, bool> + Eval<Ast, A> + Eval<Ast, B> {
S: Eval<AstValue, bool> + Eval<AstValue, A> + Eval<AstValue, B> fn try_provide (state: S, source: Ast) -> Perhaps<Self> {
{
fn eval (&self, source: I) -> Perhaps<Self> {
Ok(match source.peek() { Ok(match source.peek() {
Some(Value::Key("either")) => Some(Self( Some(Value::Key("either")) => Some(Self(
self.provide(source, ||"either: expected condition")?, state.eval(source, ||"either: expected condition")?,
self.provide(source, ||"either: expected content 1")?, state.eval(source, ||"either: expected content 1")?,
self.provide(source, ||"either: expected content 2")? state.eval(source, ||"either: expected content 2")?
)), )),
_ => None _ => None
}) })
} }
} }
impl<I: Ast, S, A, B> Eval<I, Bsp<A, B>> for S where impl<S, A, B> Dsl<S> for Bsp<A, B> where S: Eval<Ast, A> + Eval<Ast, B> {
S: Eval<AstValue, A> + Eval<AstValue, B> fn try_provide (state: S, source: Ast) -> Perhaps<Self> {
{ Ok(Some(match source.peek() {
fn eval (&self, source: I) -> Perhaps<Self> { Some(Value::Key("bsp/n")) => {
Ok(if let Some(Value::Key(key)) = source.peek() { let _ = source.next();
Some(match key { let a: A = state.eval(source, ||"bsp/n: expected content 1")?;
"bsp/n" => { let b: B = state.eval(source, ||"bsp/n: expected content 2")?;
let _ = source.next(); Self::n(a, b)
let a: A = self.provide(source, ||"bsp/n: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/n: expected content 2")?; Some(Value::Key("bsp/s")) => {
Self::n(a, b) let _ = source.next();
}, let a: A = state.eval(source, ||"bsp/s: expected content 1")?;
"bsp/s" => { let b: B = state.eval(source, ||"bsp/s: expected content 2")?;
let _ = source.next(); Self::s(a, b)
let a: A = self.provide(source, ||"bsp/s: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/s: expected content 2")?; Some(Value::Key("bsp/e")) => {
Self::s(a, b) let _ = source.next();
}, let a: A = state.eval(source, ||"bsp/e: expected content 1")?;
"bsp/e" => { let b: B = state.eval(source, ||"bsp/e: expected content 2")?;
let _ = source.next(); Self::e(a, b)
let a: A = self.provide(source, ||"bsp/e: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/e: expected content 2")?; Some(Value::Key("bsp/w")) => {
Self::e(a, b) let _ = source.next();
}, let a: A = state.eval(source, ||"bsp/w: expected content 1")?;
"bsp/w" => { let b: B = state.eval(source, ||"bsp/w: expected content 2")?;
let _ = source.next(); Self::w(a, b)
let a: A = self.provide(source, ||"bsp/w: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/w: expected content 2")?; Some(Value::Key("bsp/a")) => {
Self::w(a, b) let _ = source.next();
}, let a: A = state.eval(source, ||"bsp/a: expected content 1")?;
"bsp/a" => { let b: B = state.eval(source, ||"bsp/a: expected content 2")?;
let _ = source.next(); Self::a(a, b)
let a: A = self.provide(source, ||"bsp/a: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/a: expected content 2")?; Some(Value::Key("bsp/b")) => {
Self::a(a, b) let _ = source.next();
}, let a: A = state.eval(source, ||"bsp/b: expected content 1")?;
"bsp/b" => { let b: B = state.eval(source, ||"bsp/b: expected content 2")?;
let _ = source.next(); Self::b(a, b)
let a: A = self.provide(source, ||"bsp/b: expected content 1")?; },
let b: B = self.provide(source, ||"bsp/b: expected content 2")?; _ => return Ok(None),
Self::b(a, b) }))
},
_ => return Ok(None),
})
} else {
None
})
} }
} }
impl<I: Ast, S, A> Eval<I, Align<A>> for S where impl<S, A> Dsl<S> for Align<A> where S: Eval<Ast, A> {
S: Eval<AstValue, A> fn try_provide (state: S, source: Ast) -> Perhaps<Self> {
{
fn eval (&self, source: I) -> Perhaps<Self> {
Ok(if let Some(Value::Key(key)) = source.peek() { Ok(if let Some(Value::Key(key)) = source.peek() {
Some(match key { Some(match key {
"align/c" => { "align/c" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/c: expected content")?; let content: A = state.eval(source, ||"align/c: expected content")?;
Self::c(content) Self::c(content)
}, },
"align/x" => { "align/x" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/x: expected content")?; let content: A = state.eval(source, ||"align/x: expected content")?;
Self::x(content) Self::x(content)
}, },
"align/y" => { "align/y" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/y: expected content")?; let content: A = state.eval(source, ||"align/y: expected content")?;
Self::y(content) Self::y(content)
}, },
"align/n" => { "align/n" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/n: expected content")?; let content: A = state.eval(source, ||"align/n: expected content")?;
Self::n(content) Self::n(content)
}, },
"align/s" => { "align/s" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/s: expected content")?; let content: A = state.eval(source, ||"align/s: expected content")?;
Self::s(content) Self::s(content)
}, },
"align/e" => { "align/e" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/e: expected content")?; let content: A = state.eval(source, ||"align/e: expected content")?;
Self::e(content) Self::e(content)
}, },
"align/w" => { "align/w" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/w: expected content")?; let content: A = state.eval(source, ||"align/w: expected content")?;
Self::w(content) Self::w(content)
}, },
"align/nw" => { "align/nw" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/nw: expected content")?; let content: A = state.eval(source, ||"align/nw: expected content")?;
Self::nw(content) Self::nw(content)
}, },
"align/ne" => { "align/ne" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/ne: expected content")?; let content: A = state.eval(source, ||"align/ne: expected content")?;
Self::ne(content) Self::ne(content)
}, },
"align/sw" => { "align/sw" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/sw: expected content")?; let content: A = state.eval(source, ||"align/sw: expected content")?;
Self::sw(content) Self::sw(content)
}, },
"align/se" => { "align/se" => {
let _ = source.next(); let _ = source.next();
let content: A = self.provide(source, ||"align/se: expected content")?; let content: A = state.eval(source, ||"align/se: expected content")?;
Self::se(content) Self::se(content)
}, },
_ => return Ok(None), _ => return Ok(None),