fix(input): sorting out event map

This commit is contained in:
🪞👃🪞 2025-07-19 19:53:02 +03:00
parent 238ac2e888
commit d72a3b5b8f
5 changed files with 155 additions and 316 deletions

View file

@ -1,48 +1,38 @@
pub(crate) use std::error::Error; pub(crate) use std::error::Error;
/// Standard result type. /// Standard result type.
pub type Usually<T> = Result<T, Box<dyn Error>>; pub type Usually<T> = Result<T, Box<dyn Error>>;
/// Standard optional result type. /// Standard optional result type.
pub type Perhaps<T> = Result<Option<T>, Box<dyn Error>>; pub type Perhaps<T> = Result<Option<T>, Box<dyn Error>>;
/// Implement [`Debug`] in bulk.
/// Implement the `From` trait. #[macro_export] macro_rules! impl_debug(($($S:ty|$self:ident,$w:ident|$body:block)*)=>{
#[macro_export] macro_rules! from { $(impl std::fmt::Debug for $S {
fn fmt (&$self, $w: &mut std::fmt::Formatter) -> std::fmt::Result $body
})* });
/// Implement [`From`] in bulk.
#[macro_export] macro_rules! from(
($(<$($lt:lifetime),+>)?|$state:ident:$Source:ty|$Target:ty=$cb:expr) => { ($(<$($lt:lifetime),+>)?|$state:ident:$Source:ty|$Target:ty=$cb:expr) => {
impl $(<$($lt),+>)? From<$Source> for $Target { impl $(<$($lt),+>)? From<$Source> for $Target {
fn from ($state:$Source) -> Self { $cb } fn from ($state:$Source) -> Self { $cb }}};
} ($($Struct:ty { $(
}; $(<$($l:lifetime),* $($T:ident$(:$U:ident)?),*>)? ($source:ident: $From:ty) $expr:expr
} );+ $(;)? })*) => { $(
$(impl $(<$($l),* $($T$(:$U)?),*>)? From<$From> for $Struct {
pub trait Has<T>: Send + Sync { fn from ($source: $From) -> Self { $expr } })+ )* }; );
fn get (&self) -> &T; /// Type-dispatched `get` and `get_mut`.
fn get_mut (&mut self) -> &mut T; pub trait Has<T>: Send + Sync { fn get (&self) -> &T; fn get_mut (&mut self) -> &mut T; }
} /// Implement [Has].
#[macro_export] macro_rules! has(($T:ty: |$self:ident : $S:ty| $x:expr) => {
#[macro_export] macro_rules! has {
($T:ty: |$self:ident : $S:ty| $x:expr) => {
impl Has<$T> for $S { impl Has<$T> for $S {
fn get (&$self) -> &$T { &$x } fn get (&$self) -> &$T { &$x }
fn get_mut (&mut $self) -> &mut $T { &mut $x } fn get_mut (&mut $self) -> &mut $T { &mut $x } } };);
} /// Type-dispatched `get` and `get_mut` that return an [Option]-wrapped result.
}; pub trait MaybeHas<T>: Send + Sync { fn get (&self) -> Option<&T>; fn get_mut (&mut self) -> Option<&mut T>; }
} /// Implement [MaybeHas].
#[macro_export] macro_rules! maybe_has(
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 $(;)?) => { ($T:ty: |$self:ident : $S:ty| $x:block; $y:block $(;)?) => {
impl MaybeHas<$T> for $S { impl MaybeHas<$T> for $S {
fn get (&$self) -> Option<&$T> $x fn get (&$self) -> Option<&$T> $x
fn get_mut (&mut $self) -> Option<&mut $T> $y fn get_mut (&mut $self) -> Option<&mut $T> $y } };);
}
};
}
/// May compute a `RetVal` from `Args`. /// May compute a `RetVal` from `Args`.
pub trait Eval<Args, RetVal> { pub trait Eval<Args, RetVal> {
/// A custom operation on [Args] that may return [Result::Err] or [Option::None]. /// A custom operation on [Args] that may return [Result::Err] or [Option::None].
@ -57,15 +47,3 @@ pub trait Eval<Args, RetVal> {
} }
} }
} }
//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)
//}
//}

View file

@ -18,7 +18,7 @@ pub(crate) use self::DslError::*;
#[macro_export] macro_rules! dsl_read_advance (($exp:ident, $pat:pat => $val:expr)=>{{ #[macro_export] macro_rules! dsl_read_advance (($exp:ident, $pat:pat => $val:expr)=>{{
let (head, tail) = $exp.advance(); $exp = tail; match head { let (head, tail) = $exp.advance(); $exp = tail; match head {
Some($pat) => $val, _ => Err(format!("(e4) unexpected {head:?}").into()) }}}); Some($pat) => Ok($val), _ => Err(format!("(e4) unexpected {head:?}").into()) }}});
/// Coerce to [Val] for predefined [Self::Str] and [Self::Exp]. /// Coerce to [Val] for predefined [Self::Str] and [Self::Exp].
pub trait Dsl: Clone + Debug { pub trait Dsl: Clone + Debug {
@ -36,41 +36,33 @@ pub trait Dsl: Clone + Debug {
fn key (&self) -> Option<Self::Str> {self.val().key()} fn key (&self) -> Option<Self::Str> {self.val().key()}
fn str (&self) -> Option<Self::Str> {self.val().str()} fn str (&self) -> Option<Self::Str> {self.val().str()}
fn exp (&self) -> Option<Self::Exp> {self.val().exp()} fn exp (&self) -> Option<Self::Exp> {self.val().exp()}
fn exp_depth (&self) -> Option<isize> {self.val().exp_depth()} fn depth (&self) -> Option<isize> {self.val().depth()}
fn exp_head (&self) -> Val<Self::Str, Self::Exp> {self.val().exp_head()} fn head (&self) -> Val<Self::Str, Self::Exp> {self.val().head()}
fn exp_tail (&self) -> Self::Exp {self.val().exp_tail()} fn tail (&self) -> Self::Exp {self.val().tail()}
fn exp_each (&self, f: impl Fn(&Self) -> Usually<()>) -> Usually<()> { fn advance (&self) -> (Val<Self::Str, Self::Exp>, Self::Exp) { (self.head(), self.tail()) }
todo!() fn each (&self, f: impl Fn(&Self) -> Usually<()>) -> Usually<()> { todo!() }
fn exp_next (&mut self) -> Option<Val<Self::Str, Self::Exp>> { todo!() }
} }
fn advance (&self) -> (Val<Self::Str, Self::Exp>, Self::Exp) {
(self.exp_head(), self.exp_tail())
}
}
impl<'s> Dsl for &'s str { impl<'s> Dsl for &'s str {
type Str = &'s str; type Str = &'s str;
type Exp = &'s str; type Exp = &'s str;
fn val (&self) -> Val<Self::Str, Self::Exp> { Val::Exp(0, self) } fn val (&self) -> Val<Self::Str, Self::Exp> { Val::Exp(0, self) }
} }
impl<'s> Dsl for Cst<'s> { impl<'s> Dsl for Cst<'s> {
type Str = &'s str; type Str = &'s str;
type Exp = Cst<'s>; type Exp = Cst<'s>;
fn val (&self) -> Val<Self::Str, Self::Exp> { Val::Exp(0, *self) } fn val (&self) -> Val<Self::Str, Self::Exp> { Val::Exp(0, *self) }
} }
impl Dsl for Ast { impl Dsl for Ast {
type Str = Arc<str>; type Str = Arc<str>;
type Exp = Ast; type Exp = Ast;
fn val (&self) -> Val<Self::Str, Ast> { Val::Exp(0, self.clone()) } fn val (&self) -> Val<Self::Str, Ast> { Val::Exp(0, self.clone()) }
} }
impl<Str: DslStr, Exp: DslExp> Dsl for Token<Str, Exp> { impl<Str: DslStr, Exp: DslExp> Dsl for Token<Str, Exp> {
type Str = Str; type Str = Str;
type Exp = Exp; type Exp = Exp;
fn val (&self) -> Val<Str, Exp> { self.value.clone() } fn val (&self) -> Val<Str, Exp> { self.value.clone() }
} }
impl<Str: DslStr, Exp: DslExp> Dsl for Val<Str, Exp> { impl<Str: DslStr, Exp: DslExp> Dsl for Val<Str, Exp> {
type Str = Str; type Str = Str;
type Exp = Exp; type Exp = Exp;
@ -134,7 +126,7 @@ impl<Str: DslStr, Exp: DslExp + Dsl<Str=Str>> Val<Str, Exp> {
pub const fn key (&self) -> Option<&Str> {match self{Val::Key(k)=>Some(k), _=>None}} pub const fn key (&self) -> Option<&Str> {match self{Val::Key(k)=>Some(k), _=>None}}
pub const fn str (&self) -> Option<&Str> {match self{Val::Str(s)=>Some(s), _=>None}} pub const fn str (&self) -> Option<&Str> {match self{Val::Str(s)=>Some(s), _=>None}}
pub const fn exp (&self) -> Option<&Exp> {match self{Val::Exp(_, x)=>Some(x),_=>None}} pub const fn exp (&self) -> Option<&Exp> {match self{Val::Exp(_, x)=>Some(x),_=>None}}
pub const fn exp_depth (&self) -> Option<isize> {match self{Val::Exp(d, _)=>Some(*d), _=>None}} pub const fn depth (&self) -> Option<isize> {match self{Val::Exp(d, _)=>Some(*d), _=>None}}
} }
/// Parsed substring with range and value. /// Parsed substring with range and value.
#[derive(Debug, Clone, Default, PartialEq)] #[derive(Debug, Clone, Default, PartialEq)]
@ -451,33 +443,6 @@ pub const fn to_digit (c: char) -> Result<usize, DslError> {
}) })
} }
/// Implement type conversions.
macro_rules! from(($($Struct:ty { $(
$(<$($l:lifetime),* $($T:ident$(:$U:ident)?),*>)? ($source:ident: $From:ty) $expr:expr
);+ $(;)? })*) => { $(
$(impl $(<$($l),* $($T$(:$U)?),*>)? From<$From> for $Struct {
fn from ($source: $From) -> Self { $expr }
})+
)* });
//from! {
////Vec<Token<'s>> { <'s> (val: CstIter<'s>) val.collect(); }
//CstConstIter<'s> {
//<'s> (src: &'s str) Self(src);
//<'s> (iter: CstIter<'s>) iter.0; }
//CstIter<'s> {
//<'s> (src: &'s str) Self(CstConstIter(src));
//<'s> (iter: CstConstIter<'s>) Self(iter); }
//Cst<'s> { <'s> (src: &'s str) Self(CstIter(CstConstIter(src))); }
//Vec<Ast> { <'s> (val: CstIter<'s>) val.map(Into::into).collect(); }
//Token<Cst<'s>> { <'s> (token: Token<Cst<'s>>) Self { value: token.value.into(), span: token.span.into() } }
//Ast {
//<'s> (src: &'s str) Ast::from(CstIter(CstConstIter(src)));
//<'s> (cst: Cst<'s>) Ast(VecDeque::from([dsl_val(cst.val())]).into());
//<'s> (iter: CstIter<'s>) Ast(iter.map(|x|x.value.into()).collect::<VecDeque<_>>().into());
//<D: Dsl> (token: Token<D>) Ast(VecDeque::from([dsl_val(token.val())]).into()); }
//}
/// `T` + [Dsl] -> `Self`. /// `T` + [Dsl] -> `Self`.
pub trait FromDsl<T>: Sized { pub trait FromDsl<T>: Sized {
fn from_dsl (state: &T, dsl: &impl Dsl) -> Perhaps<Self>; fn from_dsl (state: &T, dsl: &impl Dsl) -> Perhaps<Self>;
@ -489,19 +454,19 @@ pub trait FromDsl<T>: Sized {
} }
} }
impl<T: FromDsl<U>, U> DslInto<T> for U { impl<'s, T: FromDsl<U>, U> DslInto<'s, T> for U {
fn dsl_into (&self, dsl: &impl Dsl) -> Perhaps<T> { fn dsl_into (&self, dsl: &impl Dsl) -> Perhaps<T> {
T::from_dsl(self, dsl) T::from_dsl(self, dsl)
} }
} }
/// `self` + [Dsl] -> `T` /// `self` + [Dsl] -> `T`
pub trait DslInto<T> { pub trait DslInto<'s, T> {
fn dsl_into (&self, dsl: &impl Dsl) -> Perhaps<T>; fn dsl_into (&'s self, dsl: &impl Dsl) -> Perhaps<T>;
fn dsl_into_or (&self, dsl: &impl Dsl, err: Box<dyn Error>) -> Usually<T> { fn dsl_into_or (&'s self, dsl: &impl Dsl, err: Box<dyn Error>) -> Usually<T> {
self.dsl_into(dsl)?.ok_or(err) self.dsl_into(dsl)?.ok_or(err)
} }
fn dsl_into_or_else (&self, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<T> { fn dsl_into_or_else (&'s self, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<T> {
self.dsl_into(dsl)?.ok_or_else(err) self.dsl_into(dsl)?.ok_or_else(err)
} }
} }

View file

@ -1,4 +1,8 @@
use crate::*; use crate::*;
/// Map of each event (e.g. key combination) to
/// all command expressions bound to it by
/// all loaded input layers.
type EventMapImpl<E, C> = BTreeMap<E, Vec<Binding<C>>>;
/// A collection of input bindings. /// A collection of input bindings.
/// ///
/// Each contained layer defines a mapping from input event to command invocation /// Each contained layer defines a mapping from input event to command invocation
@ -8,209 +12,100 @@ use crate::*;
/// When a key is pressed, the bindings for it are checked in sequence. /// When a key is pressed, the bindings for it are checked in sequence.
/// When the first non-conditional or true conditional binding is executed, /// When the first non-conditional or true conditional binding is executed,
/// that .event()binding's value is returned. /// that .event()binding's value is returned.
#[derive(Debug)] pub struct EventMap<E, D: Dsl>( #[derive(Debug)]
/// Map of each event (e.g. key combination) to pub struct EventMap<E, C>(EventMapImpl<E, C>);
/// all command expressions bound to it by /// Default is always empty map regardless if `E` and `C` implement [Default].
/// all loaded input layers. impl<E, C> Default for EventMap<E, C> { fn default () -> Self { Self(Default::default()) } }
pub EventBindings<E, D> impl<E: Clone + Ord, C> EventMap<E, C> {
); /// Create a new event map
type EventBindings<E, D> = BTreeMap<E, Vec<Binding<D>>>; pub fn new () -> Self {
/// An input binding. Default::default()
#[derive(Debug, Default)] pub struct Binding<D: Dsl> {
condition: Option<D>,
command: D,
description: Option<Arc<str>>,
source: Option<Arc<PathBuf>>,
} }
impl<E, D: Dsl> Default for EventMap<E, D> { /// Add a binding to an owned event map.
fn default () -> Self { pub fn def (mut self, event: E, binding: Binding<C>) -> Self {
Self(Default::default()) self.add(event, binding);
self
}
/// Add a binding to an event map.
pub fn add (&mut self, event: E, binding: Binding<C>) -> &mut Self {
if (!self.0.contains_key(&event)) {
self.0.insert(event.clone(), Default::default());
}
self.0.get_mut(&event).unwrap().push(binding);
self
}
/// Return the binding(s) that correspond to an event.
pub fn query (&self, event: &E) -> Option<&[Binding<C>]> {
self.0.get(event).map(|x|x.as_slice())
}
/// Return the first binding that corresponds to an event, considering conditions.
pub fn dispatch (&self, event: &E) -> Option<&Binding<C>> {
self.query(event)
.map(|bb|bb.iter().filter(|b|b.condition.as_ref().map(|c|(c.0)()).unwrap_or(true)).next())
.flatten()
}
/// Create event map from path to text file.
pub fn from_path <P: AsRef<Path>> (path: P) -> Usually<Self> where E: From<Arc<str>> {
if exists(path.as_ref())? {
Self::from_source(read_and_leak(path)?)
} else {
return Err(format!("(e5) not found: {:?}", path.as_ref()).into())
} }
} }
impl<E: Ord + Debug + From<Arc<str>> + Clone> EventMap<E, Ast> { /// Create event map from string.
/// Create input layer collection from DSL. pub fn from_source (source: impl AsRef<str>) -> Usually<Self> where E: From<Arc<str>> {
pub fn new (dsl: Ast) -> Usually<Self> { Self::from_dsl(Cst::from(source.as_ref()))
}
/// Create event map from DSL tokenizer.
pub fn from_dsl (mut dsl: impl Dsl) -> Usually<Self> where E: From<Arc<str>> {
use Val::*; use Val::*;
let mut input_map: EventBindings<E, Ast> = Default::default(); let mut map: Self = Default::default();
match dsl.exp_head() { loop {
match dsl.exp_next().unwrap() {
Str(path) => { Str(path) => {
let path = PathBuf::from(path.as_ref() as &str); map.0.extend(Self::from_path(PathBuf::from(path.as_ref() as &str))?.0)
for (key, val) in Self::from_path(&path)?.0.into_iter() { },
todo!("import {path:?} {key:?} {val:?}"); Exp(_, e) => match e.head() {
let key: E = key.into(); Key(k) if k.as_ref() == "if" => {
if !input_map.contains_key(&key) { todo!("conditional binding {:?}", dsl.tail());
input_map.insert(key, vec![]);
}
}
}, },
Sym(s) => { Sym(s) => {
let key: Arc<str> = s.as_ref().into(); let key: Arc<str> = s.as_ref().into();
let key: E = key.into(); let key: E = key.into();
if !input_map.contains_key(&key) { map.add(key, Binding::from_dsl(e)?);
input_map.insert(key.clone(), vec![]); todo!("binding {s:?} {:?}", dsl.tail());
}
todo!("binding {s:?} {:?}", dsl.exp_tail());
}, },
Key(k) if k.as_ref() == "if" => { _ => panic!(),
todo!("conditional binding {:?}", dsl.exp_tail());
}, },
_ => return Err(format!("invalid form in keymap: {dsl:?}").into()) _ => panic!(),
} }
Ok(Self(input_map))
} }
/// Create input layer collection from string. Ok(map)
pub fn from_source (source: &str) -> Usually<Self> {
Self::new(Ast::from(source))
} }
/// Create input layer collection from path to text file.
pub fn from_path <P: Debug + AsRef<Path>> (path: P) -> Usually<Self> {
if !exists(path.as_ref())? {
return Err(format!("(e5) not found: {path:?}").into())
} }
Self::from_source(read_and_leak(path)?) /// An input binding.
#[derive(Debug)]
pub struct Binding<C> {
pub command: C,
pub condition: Option<Condition>,
pub description: Option<Arc<str>>,
pub source: Option<Arc<PathBuf>>,
} }
/// Evaluate the active layers for a given state, impl<C> Binding<C> {
/// returning the command to be executed, if any. fn from_dsl (dsl: impl Dsl) -> Usually<Self> {
pub fn handle <S, O> (&self, state: &mut S, event: &E) -> Perhaps<O> where let mut command: Option<C> = None;
S: DslInto<bool> + DslInto<O>, let mut condition: Option<Condition> = None;
O: Command<S> let mut description: Option<Arc<str>> = None;
{ let mut source: Option<Arc<PathBuf>> = None;
todo!(); if let Some(command) = command {
//let layers = self.0.as_slice(); Ok(Self { command, condition, description, source })
//for InputLayer { cond, bind } in layers.iter() { } else {
//let mut matches = true; Err(format!("no command in {dsl:?}").into())
//if let Some(cond) = cond {
//matches = state.dsl_into(cond, ||format!("input: no cond").into())?;
//}
//if matches
//&& let Some(exp) = bind.val().exp_head()
//&& input.dsl_into(exp, ||format!("EventMap: input.eval(binding) failed").into())?
//&& let Some(command) = state.try_dsl_into(exp)? {
//return Ok(Some(command))
//}
//}
Ok(None)
} }
/*
/// Create an input map with a single non-condal layer.
/// (Use [Default::default] to get an empty map.)
pub fn new (layer: Val<T::Str, T::Exp>) -> Self {
Self::default().layer(layer)
} }
/// Add layer, return `Self`.
pub fn layer (mut self, layer: Val<T::Str, T::Exp>) -> Self {
self.add_layer(layer); self
} }
/// Add condal layer, return `Self`. pub struct Condition(Box<dyn Fn()->bool + Send + Sync>);
pub fn layer_if (mut self, cond: Val<T::Str, T::Exp>, layer: Val<T::Str, T::Exp>) -> Self { impl_debug!(Condition |self, w| { write!(w, "*") });
self.add_layer_if(Some(cond), layer); self
}
/// Add layer, return `&mut Self`.
pub fn add_layer (&mut self, layer: Val<T::Str, T::Exp>) -> &mut Self {
self.add_layer_if(None, layer.into()); self
}
/// Add condal layer, return `&mut Self`.
pub fn add_layer_if (&mut self, cond: Option<Val<T::Str, T::Exp>>, bind: Val<T::Str, T::Exp>) -> &mut Self {
self.0.push(InputLayer { cond, bind });
self
}
*/
}
//let mut keys = iter.unwrap();
//let mut map = EventMap::default();
//while let Some(token) = keys.next() {
//if let Value::Exp(_, mut exp) = token.value {
//let next = exp.next();
//if let Some(Token { value: Value::Key(sym), .. }) = next {
//match sym {
//"layer" => {
//if let Some(Token { value: Value::Str(path), .. }) = exp.peek() {
//let path = base.as_ref().parent().unwrap().join(unquote(path));
//if !std::fs::exists(&path)? {
//return Err(format!("(e5) not found: {path:?}").into())
//}
//map.add_layer(read_and_leak(path)?.into());
//print!("layer:\n path: {:?}...", exp.0.0.trim());
//println!("ok");
//} else {
//return Err(format!("(e4) unexpected non-string {next:?}").into())
//}
//},
//"layer-if" => {
//let mut cond = None;
//if let Some(Token { value: Value::Sym(sym), .. }) = exp.next() {
//cond = Some(leak(sym));
//} else {
//return Err(format!("(e4) unexpected non-symbol {next:?}").into())
//};
//if let Some(Token { value: Value::Str(path), .. }) = exp.peek() {
//let path = base.as_ref().parent().unwrap().join(unquote(path));
//if !std::fs::exists(&path)? {
//return Err(format!("(e5) not found: {path:?}").into())
//}
//print!("layer-if:\n cond: {}\n path: {path:?}...",
//cond.unwrap_or_default());
//let keys = read_and_leak(path)?.into();
//let cond = cond.unwrap();
//println!("ok");
//map.add_layer_if(
//Box::new(move |state: &App|Take::take_or_fail(
//state, exp, ||"missing input layer conditional"
//)), keys
//);
//} else {
//return Err(format!("(e4) unexpected non-symbol {next:?}").into())
//}
//},
//_ => return Err(format!("(e3) unexpected symbol {sym:?}").into())
//}
//} else {
//return Err(format!("(e2) unexpected exp {:?}", next.map(|x|x.value)).into())
//}
//} else {
//return Err(format!("(e1) unexpected token {token:?}").into())
//}
//}
//Ok(map)
//}
//{
//}
//fn from (source: &'s str) -> Self {
//// this should be for single layer:
//use Val::*;
//let mut layers = vec![];
//let mut source = CstIter::from(source);
//while let Some(Exp(_, mut iter)) = source.next().map(|x|x.value) {
//let mut iter = iter.clone();
//layers.push(match iter.next().map(|x|x.value) {
//Some(Sym(sym)) if sym.starts_with("@") => InputLayer {
//cond: None,
//bind: vec![[
//dsl_val(source.nth(1).unwrap()),
//dsl_val(source.nth(2).unwrap()),
//]],
//},
//Some(Str(layer)) => InputLayer {
//cond: None,
//bind: dsl_val(source.nth(1).unwrap()),
//},
//Some(Key("if")) => InputLayer {
//cond: Some(dsl_val(source.nth(1).unwrap())),
//bind: dsl_val(source.nth(2).unwrap()),
//},
//_ => panic!("invalid token in keymap"),
//})
//}
//Self(layers)
//}
//}
fn unquote (x: &str) -> &str { fn unquote (x: &str) -> &str {
let mut chars = x.chars(); let mut chars = x.chars();

View file

@ -60,10 +60,10 @@ impl ViewDef {
/// Makes [#self_ty] able to construct the [Render]able /// Makes [#self_ty] able to construct the [Render]able
/// which might correspond to a given [TokenStream], /// which might correspond to a given [TokenStream],
/// while taking [#self_ty]'s state into consideration. /// while taking [#self_ty]'s state into consideration.
impl<'state> ::tengri::dsl::DslInto< impl<'state> ::tengri::dsl::DslInto<'state,
Box<dyn ::tengri::output::Render<#output> + 'state> Box<dyn ::tengri::output::Render<#output> + 'state>
> for #self_ty { > for #self_ty {
fn dsl_into (&self, dsl: &impl ::tengri::dsl::Dsl) fn dsl_into (&'state self, dsl: &impl ::tengri::dsl::Dsl)
-> Perhaps<Box<dyn ::tengri::output::Render<#output> + 'state>> -> Perhaps<Box<dyn ::tengri::output::Render<#output> + 'state>>
{ {
Ok(match dsl.val() { #builtins #exposed _ => return Ok(None) }) Ok(match dsl.val() { #builtins #exposed _ => return Ok(None) })
@ -77,8 +77,11 @@ impl ViewDef {
let Self(ViewMeta { output }, ViewImpl { .. }) = self; let Self(ViewMeta { output }, ViewImpl { .. }) = self;
let builtins = builtins_with_boxes_output(quote! { #output }).map(|builtin|quote! { let builtins = builtins_with_boxes_output(quote! { #output }).map(|builtin|quote! {
::tengri::dsl::Val::Exp(_, expr) => return Ok(Some( ::tengri::dsl::Val::Exp(_, expr) => return Ok(Some(
#builtin::from_dsl(self, expr, ||Box::new("failed to load builtin".into()))? #builtin::from_dsl_or_else(
.boxed() self,
&expr,
|| { format!("failed to load builtin").into() }
)?.boxed()
)), )),
}); });
quote! { #(#builtins)* } quote! { #(#builtins)* }
@ -89,7 +92,7 @@ impl ViewDef {
let exposed = exposed.iter().map(|(key, value)|write_quote(quote! { let exposed = exposed.iter().map(|(key, value)|write_quote(quote! {
#key => return Ok(Some(self.#value().boxed())), #key => return Ok(Some(self.#value().boxed())),
})); }));
quote! { ::tengri::dsl::Val::Sym(key) => match key.as_ref() { #(#exposed)* } } quote! { ::tengri::dsl::Val::Sym(key) => match key.as_ref() { #(#exposed)* _ => panic!() } }
} }
} }

View file

@ -20,11 +20,9 @@ pub fn buffer_update (buf: &mut Buffer, area: [u16;4], callback: &impl Fn(&mut C
pub content: Vec<Cell> pub content: Vec<Cell>
} }
impl std::fmt::Debug for BigBuffer { impl_debug!(BigBuffer |self, f| {
fn fmt (&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
write!(f, "[BB {}x{} ({})]", self.width, self.height, self.content.len()) write!(f, "[BB {}x{} ({})]", self.width, self.height, self.content.len())
} });
}
impl BigBuffer { impl BigBuffer {
pub fn new (width: usize, height: usize) -> Self { pub fn new (width: usize, height: usize) -> Self {