Compare commits

..

3 commits

Author SHA1 Message Date
455d6d00d5 read explicit lifetime to FromDsl
Some checks are pending
/ build (push) Waiting to run
2025-05-20 22:02:51 +03:00
7c1cddc759 wip: directionalize!
can't fit all into 1 trait because of directionality
of trait implementation rules and constraints :(
2025-05-20 19:04:39 +03:00
f797a7143d extact dsl_token; flip Dsl; try to obviate ViewContext 2025-05-20 16:27:05 +03:00
19 changed files with 540 additions and 520 deletions

View file

@ -171,112 +171,3 @@ pub const fn to_digit (c: char) -> DslResult<usize> {
_ => return Result::Err(Unexpected(c)) _ => return Result::Err(Unexpected(c))
}) })
} }
#[derive(Debug, Copy, Clone, Default, PartialEq)] pub struct Token<'source> {
pub source: &'source str,
pub start: usize,
pub length: usize,
pub value: Value<'source>,
}
#[derive(Debug, Copy, Clone, Default, PartialEq)] pub enum Value<'source> {
#[default] Nil,
Err(DslError),
Num(usize),
Sym(&'source str),
Key(&'source str),
Str(&'source str),
Exp(usize, TokenIter<'source>),
}
impl<'source> std::fmt::Display for Value<'source> {
fn fmt (&self, out: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(out, "{}", match self {
Nil => String::new(),
Err(e) => format!("[error: {e}]"),
Num(n) => format!("{n}"),
Sym(s) => format!("{s}"),
Key(s) => format!("{s}"),
Str(s) => format!("{s}"),
Exp(_, e) => format!("{e:?}"),
})
}
}
impl<'source> Token<'source> {
pub const fn new (
source: &'source str, start: usize, length: usize, value: Value<'source>
) -> Self {
Self { source, start, length, value }
}
pub const fn end (&self) -> usize {
self.start.saturating_add(self.length)
}
pub const fn slice (&'source self) -> &'source str {
self.slice_source(self.source)
}
pub const fn slice_source <'range> (&'source self, source: &'range str) -> &'range str {
str_range(source, self.start, self.end())
}
pub const fn slice_source_exp <'range> (&'source self, source: &'range str) -> &'range str {
str_range(source, self.start.saturating_add(1), self.end())
}
pub const fn with_value (self, value: Value<'source>) -> Self {
Self { value, ..self }
}
pub const fn value (&self) -> Value {
self.value
}
pub const fn error (self, error: DslError) -> Self {
Self { value: Value::Err(error), ..self }
}
pub const fn grow (self) -> Self {
Self { length: self.length.saturating_add(1), ..self }
}
pub const fn grow_num (self, m: usize, c: char) -> Self {
match to_digit(c) {
Ok(n) => Self { value: Num(10*m+n), ..self.grow() },
Result::Err(e) => Self { value: Err(e), ..self.grow() },
}
}
pub const fn grow_key (self) -> Self {
let token = self.grow();
token.with_value(Key(token.slice_source(self.source)))
}
pub const fn grow_sym (self) -> Self {
let token = self.grow();
token.with_value(Sym(token.slice_source(self.source)))
}
pub const fn grow_str (self) -> Self {
let token = self.grow();
token.with_value(Str(token.slice_source(self.source)))
}
pub const fn grow_exp (self) -> Self {
let token = self.grow();
if let Exp(depth, _) = token.value {
token.with_value(Exp(depth, TokenIter::new(token.slice_source_exp(self.source))))
} else {
unreachable!()
}
}
pub const fn grow_in (self) -> Self {
let token = self.grow_exp();
if let Value::Exp(depth, source) = token.value {
token.with_value(Value::Exp(depth.saturating_add(1), source))
} else {
unreachable!()
}
}
pub const fn grow_out (self) -> Self {
let token = self.grow_exp();
if let Value::Exp(depth, source) = token.value {
if depth > 0 {
token.with_value(Value::Exp(depth - 1, source))
} else {
return self.error(Unexpected(')'))
}
} else {
unreachable!()
}
}
}

View file

@ -1,45 +1,27 @@
use crate::*; use crate::*;
/// Implement the [Dsl] trait, which boils down to pub trait Dsl<Other>: Sized {
/// specifying two types and providing an expression. fn take <'state, 'source: 'state> (
#[macro_export] macro_rules! dsl { &'state self,
($T:ty: |$self:ident:$S:ty, $iter:ident|$expr:expr) => { token: &mut TokenIter<'source>
impl ::tengri::dsl::Dsl<$T> for $S { )
fn take <'state, 'source> ( -> Perhaps<Other>;
&'state $self, $iter: &mut ::tengri::dsl::TokenIter<'source>, fn take_or_fail <'state, 'source: 'state> (
) -> ::tengri::Perhaps<$T> {
$expr
}
}
}
}
/// Maps a sequencer of EDN tokens to parameters of supported types
/// for a given context.
pub trait Dsl<Value>: Sized {
fn take <'state, 'source> (&'state self, _: &mut TokenIter<'source>) -> Perhaps<Value> {
unimplemented!()
}
fn take_or_fail <'state, 'source> (
&'state self, &'state self,
token: &mut TokenIter<'source>, token: &mut TokenIter<'source>,
error: impl Into<Box<dyn std::error::Error>> error: impl Into<Box<dyn std::error::Error>>
) -> Usually<Value> { ) -> Usually<Other> {
if let Some(value) = Dsl::<Value>::take(self, token)? { if let Some(value) = Dsl::<Other>::take(self, token)? {
Ok(value) Ok(value)
} else { } else {
Result::Err(error.into()) Result::Err(error.into())
} }
} }
} }
pub trait FromDsl<'source, State>: Sized {
pub trait FromDsl<'state, State>: Sized { fn take_from <'state> (state: &'state State, token: &mut TokenIter<'source>)
fn take_from <'source: 'state> (state: &'state State, _token: &mut TokenIter<'source>) -> Perhaps<Self>;
-> Perhaps<Self> fn take_from_or_fail <'state> (
{
unimplemented!()
}
fn take_from_or_fail <'source: 'state> (
state: &'state State, state: &'state State,
token: &mut TokenIter<'source>, token: &mut TokenIter<'source>,
error: impl Into<Box<dyn std::error::Error>> error: impl Into<Box<dyn std::error::Error>>
@ -51,6 +33,67 @@ pub trait FromDsl<'state, State>: Sized {
} }
} }
} }
//impl<State: Dsl<T>, T> FromDsl<State> for T {
//fn take_from <'state, 'source: 'state> (state: &'state State, token: &mut TokenIter<'source>)
//-> Perhaps<Self>
//{
//Dsl::take(state, token)
//}
//}
/// Implement the [Dsl] trait, which boils down to
/// specifying two types and providing an expression.
#[macro_export] macro_rules! from_dsl {
(@a: $T:ty: |$state:ident, $words:ident|$expr:expr) => {
impl<'source, State: Dsl<A>, A> FromDsl<'source, State> for $T {
fn take_from <'state> (
$state: &'state State,
$words: &mut TokenIter<'source>,
) -> Perhaps<$T> {
$expr
}
}
};
(@ab: $T:ty: |$state:ident, $words:ident|$expr:expr) => {
impl<'source, State: Dsl<A> + Dsl<B>, A, B> FromDsl<'source, State> for $T {
fn take_from <'state> (
$state: &'state State,
$words: &mut TokenIter<'source>,
) -> Perhaps<$T> {
$expr
}
}
};
($T:ty: |$state:ident:$S:ty, $words:ident|$expr:expr) => {
impl<'source> FromDsl<'source, $S> for $T {
fn take_from <'state> (
$state: &'state $S,
$words: &mut TokenIter<'source>,
) -> Perhaps<$T> {
$expr
}
}
};
}
///// Maps a sequencer of EDN tokens to parameters of supported types
///// for a given context.
//pub trait Dsl<Value>: Sized {
//fn take <'state, 'source> (&'state self, _: &mut TokenIter<'source>) -> Perhaps<Value> {
//unimplemented!()
//}
//fn take_or_fail <'state, 'source> (
//&'state self,
//token: &mut TokenIter<'source>,
//error: impl Into<Box<dyn std::error::Error>>
//) -> Usually<Value> {
//if let Some(value) = Dsl::<Value>::take(self, token)? {
//Ok(value)
//} else {
//Result::Err(error.into())
//}
//}
//}
//impl<T: Dsl<U>, U> Dsl<U> for &T { //impl<T: Dsl<U>, U> Dsl<U> for &T {
//fn take <'state, 'source> (&'state self, iter: &mut TokenIter<'source>) -> Perhaps<U> { //fn take <'state, 'source> (&'state self, iter: &mut TokenIter<'source>) -> Perhaps<U> {
@ -64,8 +107,8 @@ pub trait FromDsl<'state, State>: Sized {
//} //}
//} //}
impl<'state, X, Y> Dsl<X> for Y where Y: FromDsl<'state, X> { //impl<'state, X, Y> Dsl<X> for Y where Y: Dsl<'state, X> {
} //}
//impl<T, U: FromDsl<T>> Dsl<U> for T { //impl<T, U: Dsl<T>> Dsl<U> for T {
//} //}

110
dsl/src/dsl_token.rs Normal file
View file

@ -0,0 +1,110 @@
use crate::*;
#[derive(Debug, Copy, Clone, Default, PartialEq)] pub struct Token<'source> {
pub source: &'source str,
pub start: usize,
pub length: usize,
pub value: Value<'source>,
}
#[derive(Debug, Copy, Clone, Default, PartialEq)] pub enum Value<'source> {
#[default] Nil,
Err(DslError),
Num(usize),
Sym(&'source str),
Key(&'source str),
Str(&'source str),
Exp(usize, TokenIter<'source>),
}
impl<'source> std::fmt::Display for Value<'source> {
fn fmt (&self, out: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(out, "{}", match self {
Nil => String::new(),
Err(e) => format!("[error: {e}]"),
Num(n) => format!("{n}"),
Sym(s) => format!("{s}"),
Key(s) => format!("{s}"),
Str(s) => format!("{s}"),
Exp(_, e) => format!("{e:?}"),
})
}
}
impl<'source> Token<'source> {
pub const fn new (
source: &'source str, start: usize, length: usize, value: Value<'source>
) -> Self {
Self { source, start, length, value }
}
pub const fn end (&self) -> usize {
self.start.saturating_add(self.length)
}
pub const fn slice (&'source self) -> &'source str {
self.slice_source(self.source)
}
pub const fn slice_source <'range> (&'source self, source: &'range str) -> &'range str {
str_range(source, self.start, self.end())
}
pub const fn slice_source_exp <'range> (&'source self, source: &'range str) -> &'range str {
str_range(source, self.start.saturating_add(1), self.end())
}
pub const fn with_value (self, value: Value<'source>) -> Self {
Self { value, ..self }
}
pub const fn value (&self) -> Value {
self.value
}
pub const fn error (self, error: DslError) -> Self {
Self { value: Value::Err(error), ..self }
}
pub const fn grow (self) -> Self {
Self { length: self.length.saturating_add(1), ..self }
}
pub const fn grow_num (self, m: usize, c: char) -> Self {
match to_digit(c) {
Ok(n) => Self { value: Num(10*m+n), ..self.grow() },
Result::Err(e) => Self { value: Err(e), ..self.grow() },
}
}
pub const fn grow_key (self) -> Self {
let token = self.grow();
token.with_value(Key(token.slice_source(self.source)))
}
pub const fn grow_sym (self) -> Self {
let token = self.grow();
token.with_value(Sym(token.slice_source(self.source)))
}
pub const fn grow_str (self) -> Self {
let token = self.grow();
token.with_value(Str(token.slice_source(self.source)))
}
pub const fn grow_exp (self) -> Self {
let token = self.grow();
if let Exp(depth, _) = token.value {
token.with_value(Exp(depth, TokenIter::new(token.slice_source_exp(self.source))))
} else {
unreachable!()
}
}
pub const fn grow_in (self) -> Self {
let token = self.grow_exp();
if let Value::Exp(depth, source) = token.value {
token.with_value(Value::Exp(depth.saturating_add(1), source))
} else {
unreachable!()
}
}
pub const fn grow_out (self) -> Self {
let token = self.grow_exp();
if let Value::Exp(depth, source) = token.value {
if depth > 0 {
token.with_value(Value::Exp(depth - 1, source))
} else {
return self.error(Unexpected(')'))
}
} else {
unreachable!()
}
}
}

View file

@ -46,6 +46,7 @@ pub(crate) use self::Value::*;
pub(crate) use self::DslError::*; pub(crate) use self::DslError::*;
mod dsl_error; pub use self::dsl_error::*; mod dsl_error; pub use self::dsl_error::*;
mod dsl_token; pub use self::dsl_token::*;
mod dsl_parse; pub use self::dsl_parse::*; mod dsl_parse; pub use self::dsl_parse::*;
mod dsl_provide; pub use self::dsl_provide::*; mod dsl_provide; pub use self::dsl_provide::*;

View file

@ -5,13 +5,15 @@ use std::marker::PhantomData;
pub trait DslInput: Input { fn matches_dsl (&self, token: &str) -> bool; } pub trait DslInput: Input { fn matches_dsl (&self, token: &str) -> bool; }
/// A pre-configured mapping of input events to commands. /// A pre-configured mapping of input events to commands.
pub trait KeyMap<S: Dsl<C>, C: Command<S>, I: DslInput> { pub trait KeyMap<'source, S, C: FromDsl<'source, S> + Command<S>, I: DslInput> {
/// Try to find a command that matches the current input event. /// Try to find a command that matches the current input event.
fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C>; fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C>;
} }
/// A [SourceIter] can be a [KeyMap]. /// A [SourceIter] can be a [KeyMap].
impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for SourceIter<'source> { impl<'source, S, C: FromDsl<'source, S> + Command<S>, I: DslInput>
KeyMap<'source, S, C, I>
for SourceIter<'source> {
fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> { fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> {
let mut iter = self.clone(); let mut iter = self.clone();
while let Some((token, rest)) = iter.next() { while let Some((token, rest)) = iter.next() {
@ -22,7 +24,7 @@ impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for SourceI
match exp_iter.next() { match exp_iter.next() {
Some(Token { value: Value::Sym(binding), .. }) => { Some(Token { value: Value::Sym(binding), .. }) => {
if input.matches_dsl(binding) { if input.matches_dsl(binding) {
if let Some(command) = Dsl::<C>::take(state, &mut exp_iter)? { if let Some(command) = FromDsl::take_from(state, &mut exp_iter)? {
return Ok(Some(command)) return Ok(Some(command))
} }
} }
@ -38,7 +40,9 @@ impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for SourceI
} }
/// A [TokenIter] can be a [KeyMap]. /// A [TokenIter] can be a [KeyMap].
impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for TokenIter<'source> { impl<'source, S, C: FromDsl<'source, S> + Command<S>, I: DslInput>
KeyMap<'source, S, C, I>
for TokenIter<'source> {
fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> { fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> {
let mut iter = self.clone(); let mut iter = self.clone();
while let Some(next) = iter.next() { while let Some(next) = iter.next() {
@ -48,7 +52,7 @@ impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for TokenIt
match e.next() { match e.next() {
Some(Token { value: Value::Sym(binding), .. }) => { Some(Token { value: Value::Sym(binding), .. }) => {
if input.matches_dsl(binding) { if input.matches_dsl(binding) {
if let Some(command) = Dsl::<C>::take(state, &mut e)? { if let Some(command) = FromDsl::take_from(state, &mut e)? {
return Ok(Some(command)) return Ok(Some(command))
} }
} }
@ -63,25 +67,37 @@ impl<'source, S: Dsl<C>, C: Command<S>, I: DslInput> KeyMap<S, C, I> for TokenIt
} }
} }
pub type InputLayerCond<S> = Box<dyn Fn(&S)->Usually<bool> + Send + Sync>; pub type InputLayerCond<'source, S> = Box<dyn Fn(&S)->Usually<bool> + 'source>;
/// A collection of pre-configured mappings of input events to commands, /// A collection of pre-configured mappings of input events to commands,
/// which may be made available subject to given conditions. /// which may be made available subject to given conditions.
pub struct InputMap<S, C, I, M> pub struct InputMap<'source,
where S: Dsl<C>, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send + Sync { S,
__: PhantomData<(S, C, I)>, C: Command<S> + FromDsl<'source, S>,
pub layers: Vec<(InputLayerCond<S>, M)>, I: DslInput,
M: KeyMap<'source, S, C, I>
> {
__: PhantomData<&'source (S, C, I)>,
pub layers: Vec<(InputLayerCond<'source, S>, M)>,
} }
impl<S, C, I, M> Default for InputMap<S, C, I, M> impl<'source,
where S: Dsl<C>, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send + Sync { S,
C: Command<S> + FromDsl<'source, S>,
I: DslInput,
M: KeyMap<'source, S, C, I>
> Default for InputMap<'source, S, C, I, M>{
fn default () -> Self { fn default () -> Self {
Self { __: PhantomData, layers: vec![] } Self { __: PhantomData, layers: vec![] }
} }
} }
impl<S, C, I, M> InputMap<S, C, I, M> impl<'source,
where S: Dsl<C> + 'static, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send + Sync { S,
C: Command<S> + FromDsl<'source, S>,
I: DslInput,
M: KeyMap<'source, S, C, I>
> InputMap<'source, S, C, I, M> {
pub fn new (keymap: M) -> Self { pub fn new (keymap: M) -> Self {
Self::default().layer(keymap) Self::default().layer(keymap)
} }
@ -93,26 +109,34 @@ where S: Dsl<C> + 'static, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send
self.add_layer_if(Box::new(|_|Ok(true)), keymap); self.add_layer_if(Box::new(|_|Ok(true)), keymap);
self self
} }
pub fn layer_if (mut self, condition: InputLayerCond<S>, keymap: M) -> Self { pub fn layer_if (mut self, condition: InputLayerCond<'source, S>, keymap: M) -> Self {
self.add_layer_if(condition, keymap); self.add_layer_if(condition, keymap);
self self
} }
pub fn add_layer_if (&mut self, condition: InputLayerCond<S>, keymap: M) -> &mut Self { pub fn add_layer_if (&mut self, condition: InputLayerCond<'source, S>, keymap: M) -> &mut Self {
self.layers.push((Box::new(condition), keymap)); self.layers.push((Box::new(condition), keymap));
self self
} }
} }
impl<S, C, I, M> std::fmt::Debug for InputMap<S, C, I, M> impl<'source,
where S: Dsl<C>, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send + Sync { S,
C: Command<S> + FromDsl<'source, S>,
I: DslInput,
M: KeyMap<'source, S, C, I>
> std::fmt::Debug for InputMap<'source, S, C, I, M> {
fn fmt (&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { fn fmt (&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "[InputMap: {} layer(s)]", self.layers.len()) write!(f, "[InputMap: {} layer(s)]", self.layers.len())
} }
} }
/// An [InputMap] can be a [KeyMap]. /// An [InputMap] can be a [KeyMap].
impl<S, C, I, M> KeyMap<S, C, I> for InputMap<S, C, I, M> impl<'source,
where S: Dsl<C>, C: Command<S>, I: DslInput, M: KeyMap<S, C, I> + Send + Sync { S,
C: Command<S> + FromDsl<'source, S>,
I: DslInput,
M: KeyMap<'source, S, C, I>
> KeyMap<'source, S, C, I> for InputMap<'source, S, C, I, M> {
fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> { fn keybind_resolve (&self, state: &S, input: &I) -> Perhaps<C> {
for (condition, keymap) in self.layers.iter() { for (condition, keymap) in self.layers.iter() {
if !condition(state)? { if !condition(state)? {

View file

@ -2,7 +2,7 @@ use crate::*;
use std::sync::{Mutex, Arc, RwLock}; use std::sync::{Mutex, Arc, RwLock};
/// Event source /// Event source
pub trait Input: Send + Sync + Sized { pub trait Input: Sized {
/// Type of input event /// Type of input event
type Event; type Event;
/// Result of handling input /// Result of handling input
@ -36,7 +36,7 @@ pub trait Input: Send + Sync + Sized {
} }
/// Handle input /// Handle input
pub trait Handle<E: Input>: Send + Sync { pub trait Handle<E: Input> {
fn handle (&mut self, _input: &E) -> Perhaps<E::Handled> { fn handle (&mut self, _input: &E) -> Perhaps<E::Handled> {
Ok(None) Ok(None)
} }

View file

@ -36,20 +36,13 @@ pub enum Alignment { #[default] Center, X, Y, NW, N, NE, E, SE, S, SW, W }
pub struct Align<A>(Alignment, A); pub struct Align<A>(Alignment, A);
#[cfg(feature = "dsl")] #[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>> from_dsl!(@a: Align<A>: |state, iter|if let Some(Token { value: Value::Key(key), .. }) = iter.peek() {
FromDsl<'state, T> for Align<RenderBox<'state, E>> {
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
if let Some(Token { value: Value::Key(key), .. }) = iter.peek() {
match key { match key {
"align/c"|"align/x"|"align/y"| "align/c"|"align/x"|"align/y"|
"align/n"|"align/s"|"align/e"|"align/w"| "align/n"|"align/s"|"align/e"|"align/w"|
"align/nw"|"align/sw"|"align/ne"|"align/se" => { "align/nw"|"align/sw"|"align/ne"|"align/se" => {
let _ = iter.next().unwrap(); let _ = iter.next().unwrap();
let content = if let Some(content) = state.get_content(&mut iter.clone())? { let content = state.take_or_fail(&mut iter.clone(), "expected content")?;
content
} else {
panic!("no content corresponding to {:?}", &iter);
};
return Ok(Some(match key { return Ok(Some(match key {
"align/c" => Self::c(content), "align/c" => Self::c(content),
"align/x" => Self::x(content), "align/x" => Self::x(content),
@ -69,9 +62,7 @@ FromDsl<'state, T> for Align<RenderBox<'state, E>> {
} }
} else { } else {
Ok(None) Ok(None)
} });
}
}
impl<A> Align<A> { impl<A> Align<A> {
#[inline] pub const fn c (a: A) -> Self { Self(Alignment::Center, a) } #[inline] pub const fn c (a: A) -> Self { Self(Alignment::Center, a) }
@ -88,7 +79,7 @@ impl<A> Align<A> {
} }
impl<E: Output, A: Content<E>> Content<E> for Align<A> { impl<E: Output, A: Content<E>> Content<E> for Align<A> {
fn content (&self) -> impl Render<E> { fn content (&self) -> impl Render<E> + '_ {
&self.1 &self.1
} }
fn layout (&self, on: E::Area) -> E::Area { fn layout (&self, on: E::Area) -> E::Area {

View file

@ -21,40 +21,35 @@ impl<E: Output, A: Content<E>, B: Content<E>> Content<E> for Bsp<A, B> {
} }
} }
#[cfg(feature = "dsl")] #[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>> from_dsl!(@ab: Bsp<A, B>: |state, iter|Ok(if let Some(Token {
FromDsl<'state, T> for Bsp<RenderBox<'state, E>, RenderBox<'state, E>> {
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
Ok(if let Some(Token {
value: Value::Key("bsp/n"|"bsp/s"|"bsp/e"|"bsp/w"|"bsp/a"|"bsp/b"), value: Value::Key("bsp/n"|"bsp/s"|"bsp/e"|"bsp/w"|"bsp/a"|"bsp/b"),
.. ..
}) = iter.peek() { }) = iter.peek() {
let base = iter.clone(); let base = iter.clone();
return Ok(Some(match iter.next() { return Ok(Some(match iter.next() {
Some(Token { value: Value::Key("bsp/n"), .. }) => Some(Token { value: Value::Key("bsp/n"), .. }) =>
Self::n(state.get_content_or_fail(iter)?, Self::n(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
Some(Token { value: Value::Key("bsp/s"), .. }) => Some(Token { value: Value::Key("bsp/s"), .. }) =>
Self::s(state.get_content_or_fail(iter)?, Self::s(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
Some(Token { value: Value::Key("bsp/e"), .. }) => Some(Token { value: Value::Key("bsp/e"), .. }) =>
Self::e(state.get_content_or_fail(iter)?, Self::e(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
Some(Token { value: Value::Key("bsp/w"), .. }) => Some(Token { value: Value::Key("bsp/w"), .. }) =>
Self::w(state.get_content_or_fail(iter)?, Self::w(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
Some(Token { value: Value::Key("bsp/a"), .. }) => Some(Token { value: Value::Key("bsp/a"), .. }) =>
Self::a(state.get_content_or_fail(iter)?, Self::a(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
Some(Token { value: Value::Key("bsp/b"), .. }) => Some(Token { value: Value::Key("bsp/b"), .. }) =>
Self::b(state.get_content_or_fail(iter)?, Self::b(state.take_or_fail(iter, "expected content 1")?,
state.get_content_or_fail(iter)?), state.take_or_fail(iter, "expected content 2")?),
_ => unreachable!(), _ => unreachable!(),
})) }))
} else { } else {
None None
}) }));
}
}
impl<A, B> Bsp<A, B> { impl<A, B> Bsp<A, B> {
#[inline] pub const fn n (a: A, b: B) -> Self { Self(North, a, b) } #[inline] pub const fn n (a: A, b: B) -> Self { Self(North, a, b) }
#[inline] pub const fn s (a: A, b: B) -> Self { Self(South, a, b) } #[inline] pub const fn s (a: A, b: B) -> Self { Self(South, a, b) }

View file

@ -17,44 +17,26 @@ impl<A, B> Either<A, B> {
Self(c, a, b) Self(c, a, b)
} }
} }
#[cfg(feature = "dsl")] #[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>> impl<'source, A, T: Dsl<bool> + Dsl<A>> FromDsl<'source, T> for When<A> {
FromDsl<'state, T> for When<RenderBox<'state, E>> { fn take_from <'state> (
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> { state: &'state T,
token: &mut TokenIter<'source>
) -> Perhaps<Self> {
Ok(if let Some(Token { Ok(if let Some(Token {
value: Value::Key("when"), value: Value::Key("when"),
.. ..
}) = iter.peek() { }) = token.peek() {
let base = iter.clone(); let base = token.clone();
return Ok(Some(Self( return Ok(Some(Self(
state.take(iter)?.unwrap_or_else(||panic!("cond: no condition: {base:?}")), state.take_or_fail(token, "cond: no condition")?,
state.get_content_or_fail(iter)? state.take_or_fail(token, "cond: no content")?,
))) )))
} else { } else {
None None
}) })
} }
} }
#[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>>
FromDsl<'state, T> for Either<RenderBox<'state, E>, RenderBox<'state, E>> {
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
if let Some(Token { value: Value::Key("either"), .. }) = iter.peek() {
let base = iter.clone();
let _ = iter.next().unwrap();
//panic!("{iter:?}");
return Ok(Some(Self(
state.take(iter)?.unwrap_or_else(||panic!("either: no condition: {base:?}")),
state.get_content_or_fail(iter)?,
state.get_content_or_fail(iter)?,
)))
}
Ok(None)
}
}
impl<E: Output, A: Render<E>> Content<E> for When<A> { impl<E: Output, A: Render<E>> Content<E> for When<A> {
fn layout (&self, to: E::Area) -> E::Area { fn layout (&self, to: E::Area) -> E::Area {
let Self(cond, item) = self; let Self(cond, item) = self;
@ -73,7 +55,24 @@ impl<E: Output, A: Render<E>> Content<E> for When<A> {
if *cond { item.render(to) } if *cond { item.render(to) }
} }
} }
#[cfg(feature = "dsl")]
impl<'source, A, B, T: Dsl<bool> + Dsl<A> + Dsl<B>> FromDsl<'source, T> for Either<A, B> {
fn take_from <'state> (
state: &'state T,
token: &mut TokenIter<'source>
) -> Perhaps<Self> {
if let Some(Token { value: Value::Key("either"), .. }) = token.peek() {
let base = token.clone();
let _ = token.next().unwrap();
return Ok(Some(Self(
state.take_or_fail(token, "either: no condition")?,
state.take_or_fail(token, "either: no content 1")?,
state.take_or_fail(token, "either: no content 2")?,
)))
}
Ok(None)
}
}
impl<E: Output, A: Render<E>, B: Render<E>> Content<E> for Either<A, B> { impl<E: Output, A: Render<E>, B: Render<E>> Content<E> for Either<A, B> {
fn layout (&self, to: E::Area) -> E::Area { fn layout (&self, to: E::Area) -> E::Area {
let Self(cond, a, b) = self; let Self(cond, a, b) = self;

View file

@ -1,4 +1,5 @@
use crate::*; use crate::*;
use Direction::*;
pub struct Stack<E, F> { pub struct Stack<E, F> {
__: PhantomData<E>, __: PhantomData<E>,
@ -10,68 +11,76 @@ impl<E, F> Stack<E, F> {
Self { direction, callback, __: Default::default(), } Self { direction, callback, __: Default::default(), }
} }
pub fn north (callback: F) -> Self { pub fn north (callback: F) -> Self {
Self::new(Direction::North, callback) Self::new(North, callback)
} }
pub fn south (callback: F) -> Self { pub fn south (callback: F) -> Self {
Self::new(Direction::South, callback) Self::new(South, callback)
} }
pub fn east (callback: F) -> Self { pub fn east (callback: F) -> Self {
Self::new(Direction::East, callback) Self::new(East, callback)
} }
pub fn west (callback: F) -> Self { pub fn west (callback: F) -> Self {
Self::new(Direction::West, callback) Self::new(West, callback)
} }
} }
impl<E: Output, F: Fn(&mut dyn FnMut(&dyn Render<E>)->())->()> Content<E> for Stack<E, F> { impl<E: Output, F: Fn(&mut dyn FnMut(&dyn Render<E>)->())->()> Content<E> for Stack<E, F> {
fn layout (&self, mut to: E::Area) -> E::Area { fn layout (&self, mut to: E::Area) -> E::Area {
let mut x = to.x(); let mut x = to.x();
let mut y = to.y(); let mut y = to.y();
let mut w = to.w(); let (mut w_used, mut w_remaining) = (E::Unit::zero(), to.w());
let mut h = to.h(); let (mut h_used, mut h_remaining) = (E::Unit::zero(), to.h());
(self.callback)(&mut move |component: &dyn Render<E>|{ (self.callback)(&mut move |component: &dyn Render<E>|{
let layout = component.layout([x, y, w, h].into()); let [_, _, w, h] = component.layout([x, y, w_remaining, h_remaining].into()).xywh();
match self.direction { match self.direction {
Direction::North => { South => {
todo!() y = y.plus(h);
h_used = h_used.plus(h);
h_remaining = h_remaining.minus(h);
w_used = w_used.max(w);
}, },
Direction::South => { East => {
y = y + layout.h(); x = x.plus(w);
h = h.minus(layout.h()); w_used = w_used.plus(w);
w_remaining = w_remaining.minus(w);
h_used = h_used.max(h);
}, },
Direction::East => { North | West => {
x = x + layout.w();
w = w.minus(layout.w());
},
Direction::West => {
todo!() todo!()
}, },
_ => unreachable!(), _ => unreachable!(),
} }
}); });
to match self.direction {
North | West => {
todo!()
},
South | East => {
[to.x(), to.y(), w_used.into(), h_used.into()].into()
},
_ => unreachable!(),
}
} }
fn render (&self, to: &mut E) { fn render (&self, to: &mut E) {
let mut x = to.x(); let mut x = to.x();
let mut y = to.y(); let mut y = to.y();
let mut w = to.w(); let (mut w_used, mut w_remaining) = (E::Unit::zero(), to.w());
let mut h = to.h(); let (mut h_used, mut h_remaining) = (E::Unit::zero(), to.h());
(self.callback)(&mut move |component: &dyn Render<E>|{ (self.callback)(&mut move |component: &dyn Render<E>|{
let layout = component.layout([x, y, w, h].into()); let layout = component.layout([x, y, w_remaining, h_remaining].into());
match self.direction { match self.direction {
Direction::North => { South => {
todo!() y = y.plus(layout.h());
}, h_remaining = h_remaining.minus(layout.h());
Direction::South => { h_used = h_used.plus(layout.h());
y = y + layout.h();
h = h.minus(layout.h());
to.place(layout, component); to.place(layout, component);
}, },
Direction::East => { East => {
x = x + layout.w(); x = x.plus(layout.w());
w = w.minus(layout.w()); w_remaining = w_remaining.minus(layout.w());
w_used = w_used.plus(layout.h());
to.place(layout, component); to.place(layout, component);
}, },
Direction::West => { North | West => {
todo!() todo!()
}, },
_ => unreachable!() _ => unreachable!()

View file

@ -2,72 +2,67 @@ use crate::*;
use std::marker::PhantomData; use std::marker::PhantomData;
/// Lazily-evaluated [Render]able. /// Lazily-evaluated [Render]able.
pub struct Thunk<E: Output, T: Render<E>, F: Fn()->T + Send + Sync>( pub struct Thunk<E: Output, T: Render<E>, F: Fn()->T>(
PhantomData<E>, PhantomData<E>,
F F
); );
impl<E: Output, T: Render<E>, F: Fn()->T + Send + Sync> Thunk<E, T, F> { impl<E: Output, T: Render<E>, F: Fn()->T> Thunk<E, T, F> {
pub const fn new (thunk: F) -> Self { pub const fn new (thunk: F) -> Self {
Self(PhantomData, thunk) Self(PhantomData, thunk)
} }
} }
impl<E: Output, T: Render<E>, F: Fn()->T + Send + Sync> Content<E> for Thunk<E, T, F> { impl<E: Output, T: Render<E>, F: Fn()->T> Content<E> for Thunk<E, T, F> {
fn content (&self) -> impl Render<E> { (self.1)() } fn content (&self) -> impl Render<E> { (self.1)() }
} }
pub struct ThunkBox<'a, E: Output>( pub struct ThunkBox<E: Output>(
PhantomData<E>, PhantomData<E>,
Box<dyn Fn()->RenderBox<'a, E> + Send + Sync + 'a> Box<dyn Fn()->Box<dyn Render<E>>>,
); );
impl<'a, E: Output> ThunkBox<'a, E> { impl<E: Output> ThunkBox<E> {
pub const fn new (thunk: Box<dyn Fn()->RenderBox<'a, E> + Send + Sync + 'a>) -> Self { pub const fn new (thunk: Box<dyn Fn()->Box<dyn Render<E>>>) -> Self {
Self(PhantomData, thunk) Self(PhantomData, thunk)
} }
} }
impl<'a, E: Output> Content<E> for ThunkBox<'a, E> { impl<E: Output> Content<E> for ThunkBox<E> {
fn content (&self) -> impl Render<E> { (self.1)() } fn content (&self) -> impl Render<E> { (&self.1)() }
} }
impl<'a, E, F, T> From<F> for ThunkBox<'a, E> impl<E: Output> From<Box<dyn Fn()->Box<dyn Render<E>>>> for ThunkBox<E> {
where fn from (f: Box<dyn Fn()->Box<dyn Render<E>>>) -> Self {
E: Output, Self(PhantomData, f)
F: Fn()->T + Send + Sync + 'a,
T: Render<E> + Send + Sync + 'a
{
fn from (f: F) -> Self {
Self(PhantomData, Box::new(move||f().boxed()))
} }
} }
//impl<'a, E: Output, F: Fn()->Box<dyn Render<E> + 'a> + Send + Sync + 'a> From<F> for ThunkBox<'a, E> { //impl<'a, E: Output, F: Fn()->Box<dyn Render<E> + 'a> + 'a> From<F> for ThunkBox<'a, E> {
//fn from (f: F) -> Self { //fn from (f: F) -> Self {
//Self(Default::default(), Box::new(f)) //Self(Default::default(), Box::new(f))
//} //}
//} //}
pub struct ThunkRender<E: Output, F: Fn(&mut E) + Send + Sync>(PhantomData<E>, F); pub struct ThunkRender<E: Output, F: Fn(&mut E)>(PhantomData<E>, F);
impl<E: Output, F: Fn(&mut E) + Send + Sync> ThunkRender<E, F> { impl<E: Output, F: Fn(&mut E)> ThunkRender<E, F> {
pub fn new (render: F) -> Self { Self(PhantomData, render) } pub fn new (render: F) -> Self { Self(PhantomData, render) }
} }
impl<E: Output, F: Fn(&mut E) + Send + Sync> Content<E> for ThunkRender<E, F> { impl<E: Output, F: Fn(&mut E)> Content<E> for ThunkRender<E, F> {
fn render (&self, to: &mut E) { (self.1)(to) } fn render (&self, to: &mut E) { (self.1)(to) }
} }
pub struct ThunkLayout< pub struct ThunkLayout<
E: Output, E: Output,
F1: Fn(E::Area)->E::Area + Send + Sync, F1: Fn(E::Area)->E::Area,
F2: Fn(&mut E) + Send + Sync F2: Fn(&mut E)
>( >(
PhantomData<E>, PhantomData<E>,
F1, F1,
F2 F2
); );
impl<E: Output, F1: Fn(E::Area)->E::Area + Send + Sync, F2: Fn(&mut E) + Send + Sync> ThunkLayout<E, F1, F2> { impl<E: Output, F1: Fn(E::Area)->E::Area, F2: Fn(&mut E)> ThunkLayout<E, F1, F2> {
pub fn new (layout: F1, render: F2) -> Self { Self(PhantomData, layout, render) } pub fn new (layout: F1, render: F2) -> Self { Self(PhantomData, layout, render) }
} }
impl<E, F1, F2> Content<E> for ThunkLayout<E, F1, F2> impl<E, F1, F2> Content<E> for ThunkLayout<E, F1, F2>
where where
E: Output, E: Output,
F1: Fn(E::Area)->E::Area + Send + Sync, F1: Fn(E::Area)->E::Area,
F2: Fn(&mut E) + Send + Sync F2: Fn(&mut E)
{ {
fn layout (&self, to: E::Area) -> E::Area { (self.1)(to) } fn layout (&self, to: E::Area) -> E::Area { (self.1)(to) }
fn render (&self, to: &mut E) { (self.2)(to) } fn render (&self, to: &mut E) { (self.2)(to) }

View file

@ -26,31 +26,24 @@ use crate::*;
/// along either the X axis, the Y axis, or both. /// along either the X axis, the Y axis, or both.
macro_rules! transform_xy { macro_rules! transform_xy {
($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$area:expr) => { ($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$area:expr) => {
pub enum $Enum<T> { X(T), Y(T), XY(T) } pub enum $Enum<A> { X(A), Y(A), XY(A) }
impl<T> $Enum<T> { impl<A> $Enum<A> {
#[inline] pub const fn x (item: T) -> Self { #[inline] pub const fn x (item: A) -> Self { Self::X(item) }
Self::X(item) #[inline] pub const fn y (item: A) -> Self { Self::Y(item) }
} #[inline] pub const fn xy (item: A) -> Self { Self::XY(item) }
#[inline] pub const fn y (item: T) -> Self {
Self::Y(item)
}
#[inline] pub const fn xy (item: T) -> Self {
Self::XY(item)
}
} }
#[cfg(feature = "dsl")] #[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>> impl<'source, A, T: Dsl<A>> FromDsl<'source, T> for $Enum<A> {
FromDsl<'state, T> for $Enum<RenderBox<'state, E>> { fn take_from <'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
if let Some(Token { value: Value::Key(k), .. }) = iter.peek() { if let Some(Token { value: Value::Key(k), .. }) = iter.peek() {
let mut base = iter.clone(); let mut base = iter.clone();
return Ok(Some(match iter.next() { return Ok(Some(match iter.next() {
Some(Token{value:Value::Key($x),..}) => Some(Token{value:Value::Key($x),..}) =>
Self::x(state.get_content_or_fail(iter)?), Self::x(state.take_or_fail(iter, "x: no content")?),
Some(Token{value:Value::Key($y),..}) => Some(Token{value:Value::Key($y),..}) =>
Self::y(state.get_content_or_fail(iter)?), Self::y(state.take_or_fail(iter, "y: no content")?),
Some(Token{value:Value::Key($xy),..}) => Some(Token{value:Value::Key($xy),..}) =>
Self::xy(state.get_content_or_fail(iter)?), Self::xy(state.take_or_fail(iter, "xy: no content")?),
_ => unreachable!() _ => unreachable!()
})) }))
} }
@ -58,7 +51,7 @@ macro_rules! transform_xy {
} }
} }
impl<E: Output, T: Content<E>> Content<E> for $Enum<T> { impl<E: Output, T: Content<E>> Content<E> for $Enum<T> {
fn content (&self) -> impl Render<E> { fn content (&self) -> impl Render<E> + '_ {
match self { match self {
Self::X(item) => item, Self::X(item) => item,
Self::Y(item) => item, Self::Y(item) => item,
@ -77,31 +70,30 @@ macro_rules! transform_xy {
/// along either the X axis, the Y axis, or both. /// along either the X axis, the Y axis, or both.
macro_rules! transform_xy_unit { macro_rules! transform_xy_unit {
($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$layout:expr) => { ($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$layout:expr) => {
pub enum $Enum<U, T> { X(U, T), Y(U, T), XY(U, U, T), } pub enum $Enum<U, A> { X(U, A), Y(U, A), XY(U, U, A), }
impl<U, T> $Enum<U, T> { impl<U, A> $Enum<U, A> {
#[inline] pub const fn x (x: U, item: T) -> Self { Self::X(x, item) } #[inline] pub const fn x (x: U, item: A) -> Self { Self::X(x, item) }
#[inline] pub const fn y (y: U, item: T) -> Self { Self::Y(y, item) } #[inline] pub const fn y (y: U, item: A) -> Self { Self::Y(y, item) }
#[inline] pub const fn xy (x: U, y: U, item: T) -> Self { Self::XY(x, y, item) } #[inline] pub const fn xy (x: U, y: U, item: A) -> Self { Self::XY(x, y, item) }
} }
#[cfg(feature = "dsl")] #[cfg(feature = "dsl")]
impl<'state, E: Output + 'state, T: ViewContext<'state, E>> impl<'source, A, U: Coordinate, T: Dsl<A> + Dsl<U>> FromDsl<'source, T> for $Enum<U, A> {
FromDsl<'state, T> for $Enum<E::Unit, RenderBox<'state, E>> { fn take_from <'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
fn take_from <'source: 'state> (state: &'state T, iter: &mut TokenIter<'source>) -> Perhaps<Self> {
Ok(if let Some(Token { value: Value::Key($x|$y|$xy), .. }) = iter.peek() { Ok(if let Some(Token { value: Value::Key($x|$y|$xy), .. }) = iter.peek() {
let mut base = iter.clone(); let mut base = iter.clone();
Some(match iter.next() { Some(match iter.next() {
Some(Token { value: Value::Key($x), .. }) => Self::x( Some(Token { value: Value::Key($x), .. }) => Self::x(
state.take_or_fail(iter, "no unit specified")?, state.take_or_fail(iter, "x: no unit")?,
state.get_content_or_fail(iter)?, state.take_or_fail(iter, "x: no content")?,
), ),
Some(Token { value: Value::Key($y), .. }) => Self::y( Some(Token { value: Value::Key($y), .. }) => Self::y(
state.take_or_fail(iter, "no unit specified")?, state.take_or_fail(iter, "y: no unit")?,
state.get_content_or_fail(iter)?, state.take_or_fail(iter, "y: no content")?,
), ),
Some(Token { value: Value::Key($x), .. }) => Self::xy( Some(Token { value: Value::Key($x), .. }) => Self::xy(
state.take_or_fail(iter, "no unit specified")?, state.take_or_fail(iter, "xy: no unit x")?,
state.take_or_fail(iter, "no unit specified")?, state.take_or_fail(iter, "xy: no unit y")?,
state.get_content_or_fail(iter)? state.take_or_fail(iter, "xy: no content")?
), ),
_ => unreachable!(), _ => unreachable!(),
}) })
@ -111,7 +103,7 @@ macro_rules! transform_xy_unit {
} }
} }
impl<E: Output, T: Content<E>> Content<E> for $Enum<E::Unit, T> { impl<E: Output, T: Content<E>> Content<E> for $Enum<E::Unit, T> {
fn content (&self) -> impl Render<E> { fn content (&self) -> impl Render<E> + '_ {
Some(match self { Some(match self {
Self::X(_, content) => content, Self::X(_, content) => content,
Self::Y(_, content) => content, Self::Y(_, content) => content,

View file

@ -29,8 +29,8 @@ pub trait Render<E: Output> {
/// Write data to display. /// Write data to display.
fn render (&self, output: &mut E); fn render (&self, output: &mut E);
/// Perform type erasure, turning `self` into an opaque [RenderBox]. /// Perform type erasure, turning `self` into an opaque [RenderBox].
fn boxed <'a> (self) -> RenderBox<'a, E> where Self: Send + Sync + Sized + 'a { fn boxed <'a> (self) -> Box<dyn Render<E> + 'a> where Self: Sized + 'a {
Box::new(self) as RenderBox<'a, E> Box::new(self) as Box<dyn Render<E> + 'a>
} }
} }
@ -47,20 +47,20 @@ impl<E: Output, C: Content<E>> Render<E> for C {
/// Opaque pointer to a renderable living on the heap. /// Opaque pointer to a renderable living on the heap.
/// ///
/// Return this from [Content::content] to use dynamic dispatch. /// Return this from [Content::content] to use dynamic dispatch.
pub type RenderBox<'a, E> = Box<RenderDyn<'a, E>>; pub type RenderBox<E> = Box<RenderDyn<E>>;
/// You can render from a box. /// You can render from a box.
impl<'a, E: Output> Content<E> for RenderBox<'a, E> { impl<E: Output> Content<E> for RenderBox<E> {
fn content (&self) -> impl Render<E> { self.deref() } fn content (&self) -> impl Render<E> + '_ { self.deref() }
//fn boxed <'b> (self) -> RenderBox<'b, E> where Self: Sized + 'b { self } //fn boxed <'b> (self) -> RenderBox<'b, E> where Self: Sized + 'b { self }
} }
/// Opaque pointer to a renderable. /// Opaque pointer to a renderable.
pub type RenderDyn<'a, E> = dyn Render<E> + Send + Sync + 'a; pub type RenderDyn<E> = dyn Render<E>;
/// You can render from an opaque pointer. /// You can render from an opaque pointer.
impl<'a, E: Output> Content<E> for &RenderDyn<'a, E> where Self: Sized { impl<E: Output> Content<E> for &RenderDyn<E> where Self: Sized {
fn content (&self) -> impl Render<E> { fn content (&self) -> impl Render<E> + '_ {
#[allow(suspicious_double_ref_op)] #[allow(suspicious_double_ref_op)]
self.deref() self.deref()
} }
@ -77,7 +77,7 @@ impl<'a, E: Output> Content<E> for &RenderDyn<'a, E> where Self: Sized {
/// Composable renderable with static dispatch. /// Composable renderable with static dispatch.
pub trait Content<E: Output> { pub trait Content<E: Output> {
/// Return a [Render]able of a specific type. /// Return a [Render]able of a specific type.
fn content (&self) -> impl Render<E> { () } fn content (&self) -> impl Render<E> + '_ { () }
/// Perform layout. By default, delegates to [Self::content]. /// Perform layout. By default, delegates to [Self::content].
fn layout (&self, area: E::Area) -> E::Area { self.content().layout(area) } fn layout (&self, area: E::Area) -> E::Area { self.content().layout(area) }
/// Draw to output. By default, delegates to [Self::content]. /// Draw to output. By default, delegates to [Self::content].
@ -86,7 +86,7 @@ pub trait Content<E: Output> {
/// Every pointer to [Content] is a [Content]. /// Every pointer to [Content] is a [Content].
impl<E: Output, C: Content<E>> Content<E> for &C { impl<E: Output, C: Content<E>> Content<E> for &C {
fn content (&self) -> impl Render<E> { (*self).content() } fn content (&self) -> impl Render<E> + '_ { (*self).content() }
fn layout (&self, area: E::Area) -> E::Area { (*self).layout(area) } fn layout (&self, area: E::Area) -> E::Area { (*self).layout(area) }
fn render (&self, output: &mut E) { (*self).render(output) } fn render (&self, output: &mut E) { (*self).render(output) }
} }
@ -98,7 +98,7 @@ impl<E: Output> Content<E> for () {
} }
impl<E: Output, T: Content<E>> Content<E> for Option<T> { impl<E: Output, T: Content<E>> Content<E> for Option<T> {
fn content (&self) -> impl Render<E> { fn content (&self) -> impl Render<E> + '_ {
self.as_ref() self.as_ref()
} }
fn layout (&self, area: E::Area) -> E::Area { fn layout (&self, area: E::Area) -> E::Area {
@ -117,7 +117,7 @@ impl<E: Output, T: Content<E>> Content<E> for Option<T> {
// Implement for all [Output]s. // Implement for all [Output]s.
(|$self:ident:$Struct:ty| $content:expr) => { (|$self:ident:$Struct:ty| $content:expr) => {
impl<E: Output> Content<E> for $Struct { impl<E: Output> Content<E> for $Struct {
fn content (&$self) -> impl Render<E> { Some($content) } fn content (&$self) -> impl Render<E> + '_ { Some($content) }
} }
}; };
// Implement for specific [Output]. // Implement for specific [Output].
@ -127,7 +127,7 @@ impl<E: Output, T: Content<E>> Content<E> for Option<T> {
|$content:expr) => { |$content:expr) => {
impl $(<$($($L)? $($T)? $(:$Trait)?),+>)? Content<$Output> impl $(<$($($L)? $($T)? $(:$Trait)?),+>)? Content<$Output>
for $Struct $(<$($($L)? $($T)?),+>)? { for $Struct $(<$($($L)? $($T)?),+>)? {
fn content (&$self) -> impl Render<$Output> { $content } fn content (&$self) -> impl Render<$Output> + '_ { $content }
} }
}; };
} }

View file

@ -1,63 +1,54 @@
use crate::*; use crate::*;
#[cfg(feature = "dsl")] //#[cfg(feature = "dsl")]
#[macro_export] macro_rules! try_delegate { //#[macro_export] macro_rules! try_delegate {
($s:ident, $dsl:expr, $T:ty) => { //($s:ident, $dsl:expr, $T:ty) => {
let value: Option<$T> = FromDsl::take_from($s, $dsl)?; //let value: Option<$T> = Dsl::take_from($s, $dsl)?;
if let Some(value) = value { //if let Some(value) = value {
return Ok(Some(value.boxed())) //return Ok(Some(value.boxed()))
} //}
} //}
} //}
// Provides components to the view. //// Provides components to the view.
#[cfg(feature = "dsl")] //#[cfg(feature = "dsl")]
pub trait ViewContext<'state, E: Output + 'state>: Send + Sync //pub trait ViewContext<'state, E: Output + 'state>:
+ Dsl<bool> //FromDsl<bool> + FromDsl<usize> + FromDsl<E::Unit> + Send + Sync
+ Dsl<usize> //{
+ Dsl<E::Unit> //fn get_content_sym <'source: 'state> (&'state self, iter: &mut TokenIter<'source>)
{ //-> Perhaps<RenderBox<'state, E>>;
fn get_content_or_fail <'source: 'state> (&'state self, iter: &mut TokenIter<'source>) //fn get_content_exp <'source: 'state> (&'state self, iter: &mut TokenIter<'source>)
-> Usually<RenderBox<'state, E>> //-> Perhaps<RenderBox<'state, E>>
{ //{
let base = iter.clone(); //try_delegate!(self, iter, When::<RenderBox<'state, E>>);
if let Some(content) = self.get_content(iter)? { //try_delegate!(self, iter, Either::<RenderBox<'state, E>, RenderBox<'state, E>>);
Ok(content) //try_delegate!(self, iter, Align::<RenderBox<'state, E>>);
} else { //try_delegate!(self, iter, Bsp::<RenderBox<'state, E>, RenderBox<'state, E>>);
Err(format!("not found: {iter:?}").into()) //try_delegate!(self, iter, Fill::<RenderBox<'state, E>>);
} //try_delegate!(self, iter, Fixed::<_, RenderBox<'state, E>>);
} //try_delegate!(self, iter, Min::<_, RenderBox<'state, E>>);
fn get_content <'source: 'state> (&'state self, iter: &mut TokenIter<'source>) //try_delegate!(self, iter, Max::<_, RenderBox<'state, E>>);
-> Perhaps<RenderBox<'state, E>> //try_delegate!(self, iter, Shrink::<_, RenderBox<'state, E>>);
{ //try_delegate!(self, iter, Expand::<_, RenderBox<'state, E>>);
match iter.peek() { //try_delegate!(self, iter, Push::<_, RenderBox<'state, E>>);
Some(Token { value: Value::Sym(_), .. }) => //try_delegate!(self, iter, Pull::<_, RenderBox<'state, E>>);
self.get_content_sym(iter), //try_delegate!(self, iter, Margin::<_, RenderBox<'state, E>>);
Some(Token { value: Value::Exp(_, _), .. }) => //try_delegate!(self, iter, Padding::<_, RenderBox<'state, E>>);
self.get_content_exp(iter), //Ok(None)
None => Ok(None), //}
_ => panic!("only :symbols and (expressions) accepted here") //}
}
} //#[cfg(feature = "dsl")]
fn get_content_sym <'source: 'state> (&'state self, iter: &mut TokenIter<'source>) //impl<'context, O: Output + 'context, T: ViewContext<'context, O>> FromDsl<T> for RenderBox<'context, O> {
-> Perhaps<RenderBox<'state, E>>; //fn take_from <'state, 'source: 'state> (state: &'state T, token: &mut TokenIter<'source>)
fn get_content_exp <'source: 'state> (&'state self, iter: &mut TokenIter<'source>) //-> Perhaps<RenderBox<'context, O>>
-> Perhaps<RenderBox<'state, E>> //{
{ //Ok(if let Some(content) = state.get_content_sym(token)? {
try_delegate!(self, iter, When::<RenderBox<'state, E>>); //Some(content)
try_delegate!(self, iter, Either::<RenderBox<'state, E>, RenderBox<'state, E>>); //} else if let Some(content) = state.get_content_exp(token)? {
try_delegate!(self, iter, Align::<RenderBox<'state, E>>); //Some(content)
try_delegate!(self, iter, Bsp::<RenderBox<'state, E>, RenderBox<'state, E>>); //} else {
try_delegate!(self, iter, Fill::<RenderBox<'state, E>>); //None
try_delegate!(self, iter, Fixed::<_, RenderBox<'state, E>>); //})
try_delegate!(self, iter, Min::<_, RenderBox<'state, E>>); //}
try_delegate!(self, iter, Max::<_, RenderBox<'state, E>>); //}
try_delegate!(self, iter, Shrink::<_, RenderBox<'state, E>>);
try_delegate!(self, iter, Expand::<_, RenderBox<'state, E>>);
try_delegate!(self, iter, Push::<_, RenderBox<'state, E>>);
try_delegate!(self, iter, Pull::<_, RenderBox<'state, E>>);
try_delegate!(self, iter, Margin::<_, RenderBox<'state, E>>);
try_delegate!(self, iter, Padding::<_, RenderBox<'state, E>>);
Ok(None)
}
}

View file

@ -84,7 +84,7 @@ impl ToTokens for CommandDef {
let mut out = TokenStream2::new(); let mut out = TokenStream2::new();
for (arg, ty) in arm.args() { for (arg, ty) in arm.args() {
write_quote_to(&mut out, quote! { write_quote_to(&mut out, quote! {
#arg: Dsl::take_or_fail(self, words)?, #arg: FromDsl::take_from_or_fail(self, words)?,
}); });
} }
out out
@ -137,19 +137,23 @@ impl ToTokens for CommandDef {
#[derive(Clone, Debug)] pub enum #command_enum { #(#variants)* } #[derive(Clone, Debug)] pub enum #command_enum { #(#variants)* }
/// Not generated by [tengri_proc]. /// Not generated by [tengri_proc].
#block #block
/// Generated by [tengri_proc]. /// Generated by [tengri_proc::command].
///
/// Means [#command_enum] is now a [Command] over [#state].
/// Instances of [#command_enum] can be consumed by a
/// mutable pointer to [#state], invoking predefined operations
/// and optionally returning undo history data.
impl ::tengri::input::Command<#state> for #command_enum { impl ::tengri::input::Command<#state> for #command_enum {
fn execute (self, state: &mut #state) -> Perhaps<Self> { fn execute (self, state: &mut #state) -> Perhaps<Self> {
match self { #(#implementations)* } match self { #(#implementations)* }
} }
} }
/// Generated by [tengri_proc]. /// Generated by [tengri_proc::command].
impl ::tengri::dsl::Dsl<#command_enum> for #state { impl<'source> ::tengri::dsl::FromDsl<'source, #state> for #command_enum {
fn take <'source, 'state> ( fn take_from <'state> (
&'state self, words: &mut TokenIter<'source> state: &'state #state,
) words: &mut ::tengri::dsl::TokenIter<'source>
-> ::tengri::Perhaps<#command_enum> ) -> Perhaps<Self> {
{
let mut words = words.clone(); let mut words = words.clone();
let token = words.next(); let token = words.next();
todo!()//Ok(match token { #(#matchers)* _ => None }) todo!()//Ok(match token { #(#matchers)* _ => None })

View file

@ -60,7 +60,7 @@ impl ToTokens for ExposeDef {
impl ToTokens for ExposeImpl { impl ToTokens for ExposeImpl {
fn to_tokens (&self, out: &mut TokenStream2) { fn to_tokens (&self, out: &mut TokenStream2) {
let Self(block, exposed) = self; let Self(block, exposed) = self;
let target = &block.self_ty; let state = &block.self_ty;
write_quote_to(out, quote! { #block }); write_quote_to(out, quote! { #block });
for (t, variants) in exposed.iter() { for (t, variants) in exposed.iter() {
let formatted_type = format!("{}", quote! { #t }); let formatted_type = format!("{}", quote! { #t });
@ -84,14 +84,15 @@ impl ToTokens for ExposeImpl {
}; };
let values = variants.iter().map(ExposeArm::from); let values = variants.iter().map(ExposeArm::from);
write_quote_to(out, quote! { write_quote_to(out, quote! {
/// Generated by [tengri_proc]. /// Generated by [tengri_proc::expose].
impl ::tengri::dsl::Dsl<#t> for #target { impl<'source> ::tengri::dsl::FromDsl<'source, #state> for #t {
fn take <'state, 'source> ( fn take_from <'state> (
&'state self, iter: &mut ::tengri::dsl::TokenIter<'source> state: &'state #state,
) -> Perhaps<#t> { words: &mut ::tengri::dsl::TokenIter<'source>
Ok(Some(match iter.next().map(|x|x.value) { ) -> Perhaps<Self> {
Ok(Some(match words.next().map(|x|x.value) {
#predefined #predefined
#(#values,)* #(#values)*
_ => return Ok(None) _ => return Ok(None)
})) }))
} }
@ -115,7 +116,7 @@ impl ToTokens for ExposeArm {
let Self(key, value) = self; let Self(key, value) = self;
let key = LitStr::new(&key, Span::call_site()); let key = LitStr::new(&key, Span::call_site());
write_quote_to(out, quote! { write_quote_to(out, quote! {
Some(::tengri::dsl::Value::Sym(#key)) => self.#value() Some(::tengri::dsl::Value::Sym(#key)) => state.#value(),
}) })
} }
} }

View file

@ -14,8 +14,6 @@ pub(crate) struct ViewImpl {
exposed: BTreeMap<String, Ident>, exposed: BTreeMap<String, Ident>,
} }
struct ViewArm(String, Ident);
impl Parse for ViewMeta { impl Parse for ViewMeta {
fn parse (input: ParseStream) -> Result<Self> { fn parse (input: ParseStream) -> Result<Self> {
Ok(Self { Ok(Self {
@ -46,95 +44,70 @@ impl ToTokens for ViewDef {
let Self(ViewMeta { output }, ViewImpl { block, exposed }) = self; let Self(ViewMeta { output }, ViewImpl { block, exposed }) = self;
let view = &block.self_ty; let view = &block.self_ty;
let mut available = vec![]; let mut available = vec![];
let exposed: Vec<_> = exposed.iter().map(|(k,v)|{ let exposed: Vec<_> = exposed.iter().map(|(key, value)|{
available.push(k.clone()); available.push(key.clone());
ViewArm(k.clone(), v.clone()) write_quote(quote! { #key => Some(state.#value().boxed()), })
}).collect(); }).collect();
let available: String = available.join(", "); let available: String = available.join(", ");
let error_msg = LitStr::new( let error_msg = LitStr::new(
&format!("expected Sym(content), got: {{token:?}}, available: {available}"), &format!("expected Sym(content), got: {{token:?}}, available: {available}"),
Span::call_site() Span::call_site()
); );
for token in quote! { write_quote_to(out, quote! {
#block #block
/// Generated by [tengri_proc]. /// Generated by [tengri_proc].
///
/// Delegates the rendering of [#view] to the [#view::view} method,
/// which you will need to implement, e.g. passing a [TokenIter]
/// containing a layout and keybindings config from user dirs.
impl ::tengri::output::Content<#output> for #view { impl ::tengri::output::Content<#output> for #view {
fn content (&self) -> impl Render<#output> { fn content (&self) -> impl Render<#output> {
self.view() self.view()
} }
} }
/// Generated by [tengri_proc]. /// Generated by [tengri_proc].
impl<'state> ::tengri::dsl::FromDsl<'state, #view> for ::tengri::output::RenderBox<'state, #output> { ///
fn take_from <'source: 'state> ( /// Gives [#view] the ability to construct the [Render]able
/// which might corresponds to a given [TokenStream],
/// while taking [#view]'s state into consideration.
impl<'source> ::tengri::dsl::FromDsl<'source, #view> for Box<dyn Render<#output> + 'source> {
fn take_from <'state> (
state: &'state #view, state: &'state #view,
token: &mut ::tengri::dsl::TokenIter<'source> words: &mut ::tengri::dsl::TokenIter<'source>,
) -> Perhaps<Self> { ) -> Perhaps<Self> {
Ok(match token.peek() { #(#exposed)* _ => None }) Ok(words.peek().and_then(|::tengri::dsl::Token{ value, .. }|match value {
::tengri::dsl::Value::Exp(_, exp) => {
todo!("builtin layout ops");
//#builtins
None
},
::tengri::dsl::Value::Sym(sym) => match sym {
#(#exposed)*
_ => None
},
_ => None
}))
} }
} }
} { })
out.append(token)
}
} }
} }
impl ToTokens for ViewArm { fn builtins () -> [TokenStream2;14] {
fn to_tokens (&self, out: &mut TokenStream2) { [
let Self(key, value) = self; quote! { When::<A> },
out.append(Ident::new("Some", Span::call_site())); quote! { Either::<A, B> },
out.append(Group::new(Delimiter::Parenthesis, { quote! { Align::<A> },
let mut out = TokenStream2::new(); quote! { Bsp::<A, B> },
out.append(Punct::new(':', Joint)); quote! { Fill::<A> },
out.append(Punct::new(':', Alone)); quote! { Fixed::<_, A> },
out.append(Ident::new("tengri", Span::call_site())); quote! { Min::<_, A> },
out.append(Punct::new(':', Joint)); quote! { Max::<_, A> },
out.append(Punct::new(':', Alone)); quote! { Shrink::<_, A> },
out.append(Ident::new("dsl", Span::call_site())); quote! { Expand::<_, A> },
out.append(Punct::new(':', Joint)); quote! { Push::<_, A> },
out.append(Punct::new(':', Alone)); quote! { Pull::<_, A> },
out.append(Ident::new("Token", Span::call_site())); quote! { Margin::<_, A> },
out.append(Group::new(Delimiter::Brace, { quote! { Padding::<_, A> },
let mut out = TokenStream2::new(); ]
out.append(Ident::new("value", Span::call_site()));
out.append(Punct::new(':', Alone));
out.append(Punct::new(':', Joint));
out.append(Punct::new(':', Alone));
out.append(Ident::new("tengri", Span::call_site()));
out.append(Punct::new(':', Joint));
out.append(Punct::new(':', Alone));
out.append(Ident::new("dsl", Span::call_site()));
out.append(Punct::new(':', Joint));
out.append(Punct::new(':', Alone));
out.append(Ident::new("Value", Span::call_site()));
out.append(Punct::new(':', Joint));
out.append(Punct::new(':', Alone));
out.append(Ident::new("Sym", Span::call_site()));
out.append(Group::new(Delimiter::Parenthesis, {
let mut out = TokenStream2::new();
out.append(LitStr::new(key, Span::call_site()).token());
out
}));
out.append(Punct::new(',', Alone));
out.append(Punct::new('.', Joint));
out.append(Punct::new('.', Alone));
out
}));
out
}));
out.append(Punct::new('=', Joint));
out.append(Punct::new('>', Alone));
out.append(Ident::new("Some", Span::call_site()));
out.append(Group::new(Delimiter::Parenthesis, {
let mut out = TokenStream2::new();
out.append(Ident::new("state", Span::call_site()));
out.append(Punct::new('.', Alone));
out.append(value.clone());
out.append(Group::new(Delimiter::Parenthesis, TokenStream2::new()));
out.append(Punct::new('.', Alone));
out.append(Ident::new("boxed", Span::call_site()));
out.append(Group::new(Delimiter::Parenthesis, TokenStream2::new()));
out
}));
out.append(Punct::new(',', Alone));
}
} }

View file

@ -72,7 +72,8 @@ pub trait TuiRun<R: Render<TuiOut> + Handle<TuiIn> + 'static> {
fn run (&self, state: &Arc<RwLock<R>>) -> Usually<()>; fn run (&self, state: &Arc<RwLock<R>>) -> Usually<()>;
} }
impl<T: Render<TuiOut> + Handle<TuiIn> + 'static> TuiRun<T> for Arc<RwLock<Tui>> { impl<T: Render<TuiOut> + Handle<TuiIn> + Send + Sync + 'static>
TuiRun<T> for Arc<RwLock<Tui>> {
fn run (&self, state: &Arc<RwLock<T>>) -> Usually<()> { fn run (&self, state: &Arc<RwLock<T>>) -> Usually<()> {
let _input_thread = TuiIn::run_input(self, state, Duration::from_millis(100)); let _input_thread = TuiIn::run_input(self, state, Duration::from_millis(100));
self.write().unwrap().setup()?; self.write().unwrap().setup()?;

View file

@ -21,7 +21,7 @@ impl Input for TuiIn {
impl TuiIn { impl TuiIn {
/// Spawn the input thread. /// Spawn the input thread.
pub fn run_input <T: Handle<TuiIn> + 'static> ( pub fn run_input <T: Handle<TuiIn> + Send + Sync + 'static> (
engine: &Arc<RwLock<Tui>>, engine: &Arc<RwLock<Tui>>,
state: &Arc<RwLock<T>>, state: &Arc<RwLock<T>>,
timer: Duration timer: Duration