wip: refactor dsl
Some checks failed
/ build (push) Has been cancelled

This commit is contained in:
🪞👃🪞 2025-06-14 16:08:02 +03:00
parent c8827b43c3
commit 91dc77cfea
16 changed files with 931 additions and 823 deletions

View file

@ -1,51 +1,55 @@
use crate::*;
//use std::marker::PhantomData;
use std::fmt::Debug;
/// A collection of input bindings.
///
/// Each contained layer defines a mapping from input event to command invocation
/// over a given state. Furthermore, each layer may have an associated condition,
/// so that only certain layers are active at a given time depending on state.
#[derive(Default, Debug)] pub struct InputLayers(Vec<InputLayer>);
#[derive(Default, Debug)] pub struct InputLayer {
condition: Option<Ast>,
bindings: Ast,
}
/// A single input binding layer.
#[derive(Default, Debug)] struct InputLayer { condition: Option<Ast>, bindings: Ast, }
impl InputLayers {
/// Create an input map with a single non-conditional layer.
/// (Use [Default::default] to get an empty map.)
pub fn new (layer: Ast) -> Self {
Self(vec![]).layer(layer)
Self::default().layer(layer)
}
/// Add layer, return `Self`.
pub fn layer (mut self, layer: Ast) -> Self {
self.add_layer(layer); self
}
/// Add conditional layer, return `Self`.
pub fn layer_if (mut self, condition: Ast, layer: Ast) -> Self {
self.add_layer_if(Some(condition), layer); self
}
/// Add layer, return `&mut Self`.
pub fn add_layer (&mut self, layer: Ast) -> &mut Self {
self.add_layer_if(None, layer.into()); self
}
/// Add conditional layer, return `&mut Self`.
pub fn add_layer_if (&mut self, condition: Option<Ast>, bindings: Ast) -> &mut Self {
self.0.push(InputLayer { condition, bindings });
self
}
pub fn handle <S: Eval<Ast, bool> + Eval<Ast, O>, I: Eval<Ast, bool>, O: Command<S>> (&self, state: &mut S, input: I) -> Perhaps<O> {
InputHandle(state, self.0.as_slice()).try_eval(input)
}
}
pub struct InputHandle<'a, S>(&'a mut S, &'a [InputLayer]);
impl<'a, S: Eval<Ast, bool> + Eval<Ast, O>, I: Eval<Ast, bool>, O: Command<S>> Eval<I, O> for InputHandle<'a, S> {
fn try_eval (&self, input: I) -> Perhaps<O> {
let Self(state, layers) = self;
/// Evaluate the active layers for a given state,
/// returning the command to be executed, if any.
pub fn handle <S, I, O> (&self, state: &mut S, input: I) -> Perhaps<O> where
S: Eval<Ast, bool> + Eval<Ast, O>,
I: Eval<Ast, bool>,
O: Command<S>
{
let layers = self.0.as_slice();
for InputLayer { condition, bindings } in layers.iter() {
let mut matches = true;
if let Some(condition) = condition {
matches = state.eval(condition.clone(), ||"input: no condition")?;
}
if matches
&& let Some(exp) = bindings.exp()
&& let Some(ast) = exp.peek()
&& input.eval(ast.clone(), ||"InputLayers: input.eval(binding) failed")?
&& let Some(command) = state.try_eval(ast)? {
&& let Some(exp) = bindings.0.exp_head()
&& input.eval(Ast(exp.clone()), ||"InputLayers: input.eval(binding) failed")?
&& let Some(command) = state.try_eval(exp)? {
return Ok(Some(command))
}
}