mirror of
https://codeberg.org/unspeaker/tengri.git
synced 2025-12-06 11:46:42 +01:00
53 lines
2 KiB
Rust
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)
|
|
}
|
|
}
|