tengri/input/src/input_dsl.rs
2025-05-26 01:30:13 +03:00

53 lines
2 KiB
Rust

use crate::*;
use std::marker::PhantomData;
use std::fmt::Debug;
/// List of input layers with optional conditional filters.
#[derive(Default, Debug)] pub struct InputLayers<S>(Vec<InputLayer<S>>);
#[derive(Default, Debug)] pub struct InputLayer<S>{
__: PhantomData<S>,
condition: Option<Ast>,
binding: Ast,
}
impl<S> InputLayers<S> {
pub fn new (layer: Ast) -> Self {
Self(vec![]).layer(layer)
}
pub fn layer (mut self, layer: Ast) -> Self {
self.add_layer(layer); self
}
pub fn layer_if (mut self, condition: Ast, layer: Ast) -> Self {
self.add_layer_if(Some(condition), layer); self
}
pub fn add_layer (&mut self, layer: Ast) -> &mut Self {
self.add_layer_if(None, layer.into()); self
}
pub fn add_layer_if (&mut self, condition: Option<Ast>, binding: Ast) -> &mut Self {
self.0.push(InputLayer { condition, binding, __: Default::default() });
self
}
}
impl<S: Eval<Ast, bool> + Eval<Ast, C>, C: Command<S>, I: Debug + Eval<Ast, bool>> Eval<(S, I), C> for InputLayers<S> {
fn try_eval (&self, (state, input): (S, I)) -> Perhaps<C> {
for InputLayer { condition, binding, .. } in self.0.iter() {
let mut matches = true;
if let Some(condition) = condition {
matches = state.eval(condition.clone(), ||"input: no condition")?;
}
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:?}")
}
}
}
Ok(None)
}
}