From ff31957fed1d8e9af677bcb6d8af7562ff09aef4 Mon Sep 17 00:00:00 2001 From: unspeaker Date: Fri, 17 Jan 2025 21:47:34 +0100 Subject: [PATCH] wip: EdnItem -> Atom, rewrite tokenizer --- Justfile | 7 +- edn/src/describe.rs | 11 + edn/src/edn_error.rs | 18 -- edn/src/edn_item.rs | 89 ------ edn/src/edn_token.rs | 99 ------ edn/src/lib.rs | 46 +-- edn/src/{edn_provide.rs => provide.rs} | 36 +-- edn/src/token.rs | 299 ++++++++++++++++++ edn/src/try_from_edn.rs | 6 - input/examples/edn-keys.rs | 1 - input/src/{edn_input.rs => keymap.rs} | 37 +-- input/src/lib.rs | 14 +- output/examples/edn-view.rs | 57 ---- output/src/lib.rs | 2 +- output/src/op_align.rs | 6 +- output/src/op_bsp.rs | 4 +- output/src/op_cond.rs | 8 +- output/src/op_transform.rs | 8 +- output/src/{edn_view.rs => view.rs} | 30 +- .../keys00.edn => tek/examples/arranger.edn | 0 .../keys01.edn => tek/examples/clip.edn | 0 .../keys02.edn => tek/examples/sampler.edn | 0 tek/src/lib.rs | 8 +- {output => tui}/examples/demo.rs.old | 0 {output => tui}/examples/edn01.edn | 0 {output => tui}/examples/edn02.edn | 0 {output => tui}/examples/edn03.edn | 0 {output => tui}/examples/edn04.edn | 0 {output => tui}/examples/edn05.edn | 0 {output => tui}/examples/edn06.edn | 0 {output => tui}/examples/edn07.edn | 0 {output => tui}/examples/edn08.edn | 0 {output => tui}/examples/edn09.edn | 0 {output => tui}/examples/edn10.edn | 0 {output => tui}/examples/edn11.edn | 0 {output => tui}/examples/edn12.edn | 0 {output => tui}/examples/edn13.edn | 0 {output => tui}/examples/edn99.edn | 0 tui/examples/tui.rs | 67 ++++ 39 files changed, 477 insertions(+), 376 deletions(-) create mode 100644 edn/src/describe.rs delete mode 100644 edn/src/edn_error.rs delete mode 100644 edn/src/edn_item.rs delete mode 100644 edn/src/edn_token.rs rename edn/src/{edn_provide.rs => provide.rs} (70%) create mode 100644 edn/src/token.rs delete mode 100644 edn/src/try_from_edn.rs delete mode 100644 input/examples/edn-keys.rs rename input/src/{edn_input.rs => keymap.rs} (80%) delete mode 100644 output/examples/edn-view.rs rename output/src/{edn_view.rs => view.rs} (83%) rename input/examples/keys00.edn => tek/examples/arranger.edn (100%) rename input/examples/keys01.edn => tek/examples/clip.edn (100%) rename input/examples/keys02.edn => tek/examples/sampler.edn (100%) rename {output => tui}/examples/demo.rs.old (100%) rename {output => tui}/examples/edn01.edn (100%) rename {output => tui}/examples/edn02.edn (100%) rename {output => tui}/examples/edn03.edn (100%) rename {output => tui}/examples/edn04.edn (100%) rename {output => tui}/examples/edn05.edn (100%) rename {output => tui}/examples/edn06.edn (100%) rename {output => tui}/examples/edn07.edn (100%) rename {output => tui}/examples/edn08.edn (100%) rename {output => tui}/examples/edn09.edn (100%) rename {output => tui}/examples/edn10.edn (100%) rename {output => tui}/examples/edn11.edn (100%) rename {output => tui}/examples/edn12.edn (100%) rename {output => tui}/examples/edn13.edn (100%) rename {output => tui}/examples/edn99.edn (100%) create mode 100644 tui/examples/tui.rs diff --git a/Justfile b/Justfile index 79e425d1..cd529cd9 100644 --- a/Justfile +++ b/Justfile @@ -1,12 +1,9 @@ default: bacon -sj test -edn-view: +tui: reset - cargo run --example edn-view -edn-keys: - reset - cargo run --example edn-keys + cargo run --example tui test: cargo test --workspace --exclude jack diff --git a/edn/src/describe.rs b/edn/src/describe.rs new file mode 100644 index 00000000..100382fd --- /dev/null +++ b/edn/src/describe.rs @@ -0,0 +1,11 @@ +use crate::*; + +pub trait TryFromEdn<'a, T>: Sized { + fn try_from_edn (state: &'a T, head: &Atom>, tail: &'a [Atom>]) -> + Option; +} + +pub trait TryIntoEdn<'a, T>: Sized { + fn try_from_edn (state: &'a T, head: &Atom>, tail: &'a [Atom>]) -> + Option; +} diff --git a/edn/src/edn_error.rs b/edn/src/edn_error.rs deleted file mode 100644 index 1bd18ec0..00000000 --- a/edn/src/edn_error.rs +++ /dev/null @@ -1,18 +0,0 @@ -use crate::*; -#[derive(Debug)] pub enum ParseError { - Empty, - Incomplete, - Unexpected(char), - Code(u8), -} -impl std::fmt::Display for ParseError { - fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Self::Empty => write!(f, "empty"), - Self::Incomplete => write!(f, "incomplete"), - Self::Unexpected(c) => write!(f, "unexpected '{c}'"), - Self::Code(i) => write!(f, "error #{i}"), - } - } -} -impl std::error::Error for ParseError {} diff --git a/edn/src/edn_item.rs b/edn/src/edn_item.rs deleted file mode 100644 index b7920208..00000000 --- a/edn/src/edn_item.rs +++ /dev/null @@ -1,89 +0,0 @@ -use crate::*; -use std::sync::Arc; -#[derive(Default, Clone, PartialEq)] pub enum EdnItem { - #[default] Nil, - Num(usize), - Sym(T), - Key(T), - Exp(Vec>), -} -impl<'a, T: 'a> EdnItem { - pub fn transform U + Clone> (&'a self, f: F) -> EdnItem { - use EdnItem::*; - match self { - Nil => Nil, - Num(n) => Num(*n), - Sym(t) => Sym(f(t)), - Key(t) => Key(f(t)), - Exp(e) => Exp(e.iter().map(|i|i.transform(f.clone())).collect()) - } - } -} -impl<'a, T: AsRef> EdnItem { - pub fn to_ref (&'a self) -> EdnItem<&'a str> { - self.transform(|t|t.as_ref()) - } - pub fn to_arc (&'a self) -> EdnItem> { - self.transform(|t|t.as_ref().into()) - } -} -impl<'a> EdnItem> { - pub fn read_all (mut source: &'a str) -> Result, ParseError> { - let mut items = vec![]; - loop { - if source.len() == 0 { - break - } - let (remaining, token) = Token::chomp(source)?; - match Self::read(token)? { Self::Nil => {}, item => items.push(item) }; - source = remaining - } - Ok(items) - } - pub fn read_one (source: &'a str) -> Result<(Self, &'a str), ParseError> { - Ok({ - if source.len() == 0 { - return Err(ParseError::Code(5)) - } - let (remaining, token) = Token::chomp(source)?; - (Self::read(token)?, remaining) - }) - } - pub fn read (token: Token<'a>) -> Result { - use EdnItem::*; - Ok(match token { - Token::Nil => Nil, - Token::Num(_, _, _) => Num(Token::number(token.string())), - Token::Sym(_, _, _) => Sym(token.string().into()), - Token::Key(_, _, _) => Key(token.string().into()), - Token::Exp(_, _, _, 0) => Exp(EdnItem::read_all(token.string())?), - _ => panic!("unclosed delimiter") - }) - } -} -impl Debug for EdnItem { - fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { - use EdnItem::*; - match self { - Nil => write!(f, "(nil)"), - Num(u) => write!(f, "(num {u})"), - Sym(u) => write!(f, "(sym {u:?})"), - Key(u) => write!(f, "(key {u:?})"), - Exp(e) => write!(f, "(exp {})", - itertools::join(e.iter().map(|i|format!("{:?}", i)), ",")) - } - } -} -impl Display for EdnItem { - fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { - use EdnItem::*; - use itertools::join; - match self { - Nil => write!(f, ""), - Num(u) => write!(f, "{u}"), - Sym(u) => write!(f, "{u}"), - Key(u) => write!(f, "{u}"), - Exp(e) => write!(f, "({})", join(e.iter().map(|i|format!("{}", i)), " ")) - } - } -} diff --git a/edn/src/edn_token.rs b/edn/src/edn_token.rs deleted file mode 100644 index 9fadfc31..00000000 --- a/edn/src/edn_token.rs +++ /dev/null @@ -1,99 +0,0 @@ -use crate::*; - -#[derive(Debug, Copy, Clone, Default, PartialEq)] -pub enum Token<'a> { - #[default] Nil, - Num(&'a str, usize, usize), - Sym(&'a str, usize, usize), - Key(&'a str, usize, usize), - Exp(&'a str, usize, usize, usize), -} - -pub type ChompResult<'a> = Result<(&'a str, Token<'a>), ParseError>; - -impl<'a> Token<'a> { - pub const fn chomp (source: &'a str) -> ChompResult<'a> { - use Token::*; - use konst::string::{split_at, char_indices}; - let mut state = Self::Nil; - let mut chars = char_indices(source); - while let Some(((index, c), next)) = chars.next() { - state = match state { - // must begin expression - Nil => match c { - ' '|'\n'|'\r'|'\t' => Nil, - '(' => Exp(source, index, 1, 1), - ':'|'@' => Sym(source, index, 1), - '0'..='9' => Num(source, index, 1), - 'a'..='z' => Key(source, index, 1), - _ => return Err(ParseError::Unexpected(c)) - }, - Num(_, _, 0) => unreachable!(), - Sym(_, _, 0) => unreachable!(), - Key(_, _, 0) => unreachable!(), - Num(source, index, length) => match c { - '0'..='9' => Num(source, index, length + 1), - ' '|'\n'|'\r'|'\t' => return Ok(( - split_at(source, index+length).1, - Num(source, index, length) - )), - _ => return Err(ParseError::Unexpected(c)) - }, - Sym(source, index, length) => match c { - 'a'..='z'|'0'..='9'|'-' => Sym(source, index, length + 1), - ' '|'\n'|'\r'|'\t' => return Ok(( - split_at(source, index+length).1, - Sym(source, index, length) - )), - _ => return Err(ParseError::Unexpected(c)) - }, - Key(source, index, length) => match c { - 'a'..='z'|'0'..='9'|'-'|'/' => Key(source, index, length + 1), - ' '|'\n'|'\r'|'\t' => return Ok(( - split_at(source, index+length).1, - Key(source, index, length) - )), - _ => return Err(ParseError::Unexpected(c)) - }, - Exp(source, index, length, 0) => match c { - ' '|'\n'|'\r'|'\t' => return Ok(( - split_at(source, index+length).1, - Exp(source, index, length, 0) - )), - _ => return Err(ParseError::Unexpected(c)) - }, - Exp(source, index, length, balance) => match c { - ')' => Exp(source, index, length + 1, balance - 1), - '(' => Exp(source, index, length + 1, balance + 1), - _ => Exp(source, index, length + 1, balance) - }, - }; - chars = next - } - Ok(("", state)) - } - pub fn string (&self) -> &str { - use Token::*; - match self { - Nil => "", - Num(src, start, len) => &src[*start..start+len], - Sym(src, start, len) => &src[*start..start+len], - Key(src, start, len) => &src[*start..start+len], - Exp(src, start, len, 0) => &src[*start..(start+len).saturating_sub(1)], - _ => panic!("unclosed delimiter") - } - } - pub const fn number (digits: &str) -> usize { - let mut value = 0; - let mut chars = konst::string::char_indices(digits); - while let Some(((_, c), next)) = chars.next() { - value = 10 * value + Self::digit(c); - chars = next - } - value - } - pub const fn digit (c: char) -> usize { - match c { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, - '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, _ => panic!("not a digit") } - } -} diff --git a/edn/src/lib.rs b/edn/src/lib.rs index 5070596b..38b92b92 100644 --- a/edn/src/lib.rs +++ b/edn/src/lib.rs @@ -1,37 +1,39 @@ #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_fn_trait_return)] -mod edn_error; pub use self::edn_error::*; -mod edn_item; pub use self::edn_item::*; -//mod edn_iter; pub use self::edn_iter::*; -mod edn_token; pub use self::edn_token::*; -mod edn_provide; pub use self::edn_provide::*; -mod try_from_edn; pub use self::try_from_edn::*; -pub(crate) use std::{fmt::{Debug, Display, Formatter, Error as FormatError}}; -#[cfg(test)] #[test] fn test_edn () -> Result<(), ParseError> { - use EdnItem::*; - assert_eq!(EdnItem::::read_all("")?, +mod token; pub use self::token::*; +mod provide; pub use self::provide::*; +mod describe; pub use self::describe::*; +pub(crate) use std::fmt::{Debug, Display, Formatter, Error as FormatError}; +pub(crate) use std::sync::Arc; +#[cfg(test)] #[test] fn test_lang () -> Result<(), ParseError> { + use Atom::*; + assert_eq!(Atom::read_all("")?, vec![]); - assert_eq!(EdnItem::::read_all(" ")?, + assert_eq!(Atom::read_all(" ")?, vec![]); - assert_eq!(EdnItem::::read_all("1234")?, + assert_eq!(Atom::read_all("1234")?, vec![Num(1234)]); - assert_eq!(EdnItem::::read_all("1234 5 67")?, + assert_eq!(Atom::read_all("1234 5 67")?, vec![Num(1234), Num(5), Num(67)]); - assert_eq!(EdnItem::::read_all("foo/bar")?, + assert_eq!(Atom::read_all("foo/bar")?, vec![Key("foo/bar".into())]); - assert_eq!(EdnItem::::read_all(":symbol")?, + assert_eq!(Atom::read_all(":symbol")?, vec![Sym(":symbol".into())]); - assert_eq!(EdnItem::::read_all(" foo/bar :baz 456")?, + assert_eq!(Atom::read_all(" foo/bar :baz 456")?, vec![Key("foo/bar".into()), Sym(":baz".into()), Num(456)]); - assert_eq!(EdnItem::::read_all(" (foo/bar :baz 456) ")?, + assert_eq!(Atom::read_all(" (foo/bar :baz 456) ")?, vec![Exp(vec![Key("foo/bar".into()), Sym(":baz".into()), Num(456)])]); Ok(()) } -#[cfg(test)] #[test] fn test_edn_layout () -> Result<(), ParseError> { - EdnItem::::read_all(include_str!("../../output/examples/edn01.edn"))?; - EdnItem::::read_all(include_str!("../../output/examples/edn02.edn"))?; - //panic!("{layout:?}"); - //let content = >::from(&layout); +#[cfg(test)] #[test] fn test_lang_examples () -> Result<(), ParseError> { + for example in [ + include_str!("../../tui/examples/edn01.edn"), + include_str!("../../tui/examples/edn02.edn"), + ] { + let items = Atom::read_all(example)?; + //panic!("{layout:?}"); + //let content = >::from(&layout); + } Ok(()) } #[macro_export] macro_rules! from_edn { diff --git a/edn/src/edn_provide.rs b/edn/src/provide.rs similarity index 70% rename from edn/src/edn_provide.rs rename to edn/src/provide.rs index 47b1f18f..34914b9b 100644 --- a/edn/src/edn_provide.rs +++ b/edn/src/provide.rs @@ -1,26 +1,26 @@ use crate::*; /// Map EDN tokens to parameters of a given type for a given context pub trait EdnProvide<'a, U>: Sized { - fn get (&'a self, _edn: &'a EdnItem>) -> Option { + fn get (&'a self, _edn: &'a Atom>) -> Option { None } - fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + fn get_or_fail (&'a self, edn: &'a Atom>) -> U { self.get(edn).expect("no value") } } impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for &T { - fn get (&'a self, edn: &'a EdnItem>) -> Option { + fn get (&'a self, edn: &'a Atom>) -> Option { (*self).get(edn) } - fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + fn get_or_fail (&'a self, edn: &'a Atom>) -> U { (*self).get_or_fail(edn) } } impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { - fn get (&'a self, edn: &'a EdnItem>) -> Option { + fn get (&'a self, edn: &'a Atom>) -> Option { self.as_ref().map(|s|s.get(edn)).flatten() } - fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + fn get_or_fail (&'a self, edn: &'a Atom>) -> U { self.as_ref().map(|s|s.get_or_fail(edn)).expect("no provider") } } @@ -29,8 +29,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { // Provide a value to the EDN template ($type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, $type> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { - use EdnItem::*; + fn get (&'a $self, edn: &'a Atom>) -> Option<$type> { + use Atom::*; Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None }) } } @@ -38,8 +38,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { // Provide a value more generically ($lt:lifetime: $type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<$lt> EdnProvide<$lt, $type> for $State { - fn get (&$lt $self, edn: &$lt EdnItem>) -> Option<$type> { - use EdnItem::*; + fn get (&$lt $self, edn: &$lt Atom>) -> Option<$type> { + use Atom::*; Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None }) } } @@ -52,8 +52,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { // Provide a value that may also be a numeric literal in the EDN, to a generic implementation. ($type:ty:|$self:ident:<$T:ident:$Trait:path>|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a, $T: $Trait> EdnProvide<'a, $type> for $T { - fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { - use EdnItem::*; + fn get (&'a $self, edn: &'a Atom>) -> Option<$type> { + use Atom::*; Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None }) } } @@ -61,8 +61,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { // Provide a value that may also be a numeric literal in the EDN, to a concrete implementation. ($type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, $type> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { - use EdnItem::*; + fn get (&'a $self, edn: &'a Atom>) -> Option<$type> { + use Atom::*; Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None }) } } @@ -74,9 +74,9 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { #[macro_export] macro_rules! edn_provide_content { (|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a, E: Output> EdnProvide<'a, Box + 'a>> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + fn get (&'a $self, edn: &'a Atom>) -> Option + 'a>> { Some(match edn.to_ref() { - $(EdnItem::Sym($pat) => $expr),*, + $(Atom::Sym($pat) => $expr),*, _ => return None }) } @@ -84,9 +84,9 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { }; ($Output:ty: |$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, Box + 'a>> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + fn get (&'a $self, edn: &'a Atom>) -> Option + 'a>> { Some(match edn.to_ref() { - $(EdnItem::Sym($pat) => $expr),*, + $(Atom::Sym($pat) => $expr),*, _ => return None }) } diff --git a/edn/src/token.rs b/edn/src/token.rs new file mode 100644 index 00000000..1aa78645 --- /dev/null +++ b/edn/src/token.rs @@ -0,0 +1,299 @@ +use crate::*; +use konst::string::{split_at, str_range, char_indices}; +use self::ParseError::*; +use self::TokenKind::*; +macro_rules! iterate { + ($expr:expr => $arg: pat => $body:expr) => { + let mut iter = $expr; + while let Some(($arg, next)) = iter.next() { + $body; + iter = next; + } + } +} +#[derive(Debug)] pub enum ParseError { Unimplemented, Empty, Incomplete, Unexpected(char), Code(u8), } +impl std::fmt::Display for ParseError { + fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Unimplemented => write!(f, "unimplemented"), + Empty => write!(f, "empty"), + Incomplete => write!(f, "incomplete"), + Unexpected(c) => write!(f, "unexpected '{c}'"), + Code(i) => write!(f, "error #{i}"), + } + } +} +impl std::error::Error for ParseError {} +#[derive(Debug, Copy, Clone, Default, PartialEq)] +pub enum TokenKind { #[default] Nil, Num, Sym, Key, Exp } +#[derive(Debug, Copy, Clone, Default, PartialEq)] +pub struct Token<'a> { + source: &'a str, + kind: TokenKind, + start: usize, + length: usize, + depth: usize, +} +impl<'a> Token<'a> { + pub const fn new ( + source: &'a str, kind: TokenKind, start: usize, length: usize, depth: usize + ) -> Self { + Self { source, kind, start, length, depth } + } + pub const fn end (&self) -> usize { self.start + self.length } + pub const fn slice (&self) -> &str { str_range(self.source, self.start, self.end()) } + pub const fn kind (&self) -> TokenKind { Nil } + pub const fn grow (self) -> Self { + Self { length: self.length + 1, ..self } + } + pub const fn grow_in (self) -> Self { + Self { length: self.length + 1, depth: self.depth + 1, ..self } + } + pub const fn grow_out (self) -> Result { + match self.depth { + 0 => Err(Unexpected(')')), + d => Ok(Self { length: self.length + 1, depth: d - 1, ..self }) + } + } + pub const fn chomp_first (source: &'a str) -> Result { + match Self::chomp(source) { + Ok((token, _)) => match token.kind() { Nil => Err(Empty), _ => Ok(token) }, + Err(e) => Err(e), + } + } + pub const fn chomp (src: &'a str) -> Result<(Self, &'a str), ParseError> { + let mut token: Token<'a> = Token::new(src, Nil, 0, 0, 0); + iterate!(char_indices(src) => (index, c) => token = match token.kind() { + Nil => match c { + '(' => Self::new(src, Exp, index, 1, 1), + ':'|'@' => Self::new(src, Sym, index, 1, 0), + '0'..='9' => Self::new(src, Num, index, 1, 0), + '/'|'a'..='z' => Self::new(src, Key, index, 1, 0), + ' '|'\n'|'\r'|'\t' => token.grow(), + _ => return Err(Unexpected(c)) + }, + Num => match c { + '0'..='9' => token.grow(), + ' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)), + _ => return Err(Unexpected(c)) + }, + Sym => match c { + 'a'..='z'|'0'..='9'|'-' => token.grow(), + ' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)), + _ => return Err(Unexpected(c)), + }, + Key => match c { + 'a'..='z'|'0'..='9'|'-'|'/' => token.grow(), + ' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)), + _ => return Err(Unexpected(c)) + }, + Exp => match token.depth { + 0 => match c { + ' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)), + _ => return Err(Unexpected(c)) + }, + _ => match c { + ')' => match token.grow_out() { + Ok(token) => token, + Err(e) => return Err(e) + }, + '(' => token.grow_in(), + _ => token.grow(), + } + }, + }); + Err(Empty) + } + pub const fn number (digits: &str) -> Result { + let mut value = 0; + iterate!(char_indices(digits) => (_, c) => match Self::digit(c) { + Ok(digit) => value = 10 * value + digit, + Err(e) => return Err(e) + }); + Ok(value) + } + pub const fn digit (c: char) -> Result { + Ok(match c { + '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, + '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, + _ => return Err(Unexpected(c)) + }) + } + pub const fn to_ref_atom (&'a self) -> Result, ParseError> { + Ok(match self.kind { + Nil => return Err(ParseError::Empty), + Num => match Self::number(self.slice()) { + Ok(n) => Atom::Num(n), + Err(e) => return Err(e) + }, + Sym => Atom::Sym(self.slice()), + Key => Atom::Key(self.slice()), + Exp => todo!() + }) + } + pub fn to_arc_atom (&self) -> Result>, ParseError> { + Ok(match self.kind { + Nil => return Err(ParseError::Empty), + Num => match Self::number(self.slice()) { + Ok(n) => Atom::Num(n), + Err(e) => return Err(e) + }, + Sym => Atom::Sym(self.slice().into()), + Key => Atom::Key(self.slice().into()), + Exp => todo!() + }) + } +} +#[derive(Clone, PartialEq)] pub enum Atom { Num(usize), Sym(T), Key(T), Exp(Vec>) } +impl<'a, T: 'a> Atom { + pub fn transform U + Clone> (&'a self, f: F) -> Atom { + use Atom::*; + match self { + Num(n) => Num(*n), + Sym(t) => Sym(f(t)), + Key(t) => Key(f(t)), + Exp(e) => Exp(e.iter().map(|i|i.transform(f.clone())).collect()) + } + } +} +impl<'a, T: AsRef> Atom { + pub fn to_ref (&'a self) -> Atom<&'a str> { + self.transform(|t|t.as_ref()) + } + pub fn to_arc (&'a self) -> Atom> { + self.transform(|t|t.as_ref().into()) + } +} +impl<'a> Atom<&'a str> { + pub const fn read_all_ref (_: &'a str) -> Result, ParseError> { + Err(Unimplemented) + } +} +impl Debug for Atom { + fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { + use Atom::*; + match self { + Num(u) => write!(f, "(num {u})"), + Sym(u) => write!(f, "(sym {u:?})"), + Key(u) => write!(f, "(key {u:?})"), + Exp(e) => write!(f, "(exp {})", + itertools::join(e.iter().map(|i|format!("{:?}", i)), ",")) + } + } +} +impl Display for Atom { + fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { + use Atom::*; + use itertools::join; + match self { + Num(u) => write!(f, "{u}"), + Sym(u) => write!(f, "{u}"), + Key(u) => write!(f, "{u}"), + Exp(e) => write!(f, "({})", join(e.iter().map(|i|format!("{}", i)), " ")) + } + } +} +//impl<'a> Token<'a> { + //pub const fn chomp_one (source: &'a str) -> Result, ParseError> { + //match Self::chomp(source) { + //Ok((_, token)) => Ok(token), + //Err(e) => Err(e) + //} + //} + //pub const fn from_nil (c: char) -> Result<(&'a str, Token<'a>), ParseError> { + //match c { + //' '|'\n'|'\r'|'\t' => Nil, + //'(' => Exp(source, index, 1, 1), + //':'|'@' => Sym(source, index, 1), + //'0'..='9' => Num(source, index, 1), + //'a'..='z' => Key(source, index, 1), + //_ => return Err(Unexpected(c)) + //} + //} + //pub const fn chomp (source: &'a str) -> Result<(&'a str, Token<'a>), ParseError> { + //let mut state = Self::Nil; + //let mut chars = char_indices(source); + //while let Some(((index, c), next)) = chars.next() { + //state = match state { + //// must begin expression + //Nil => Self::from_nil(c), + //Num(_, _, 0) => unreachable!(), + //Sym(_, _, 0) => unreachable!(), + //Key(_, _, 0) => unreachable!(), + //Num(src, idx, len) => match c { + //'0'..='9' => Num(src, idx, len + 1), + //' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Num(src, idx, len))), + //_ => return Err(Unexpected(c)) + //}, + //Sym(src, idx, len) => match c { + //'a'..='z'|'0'..='9'|'-' => Sym(src, idx, len + 1), + //' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Sym(src, idx, len))), + //_ => return Err(Unexpected(c)) + //}, + //Key(src, idx, len) => match c { + //'a'..='z'|'0'..='9'|'-'|'/' => Key(src, idx, len + 1), + //' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Key(src, idx, len))), + //_ => return Err(Unexpected(c)) + //}, + //Exp(src, idx, len, 0) => match c { + //' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Exp(src, idx, len, 0))), + //_ => return Err(Unexpected(c)) + //}, + //Exp(src, idx, len, balance) => match c { + //')' => Exp(src, idx, len + 1, balance - 1), + //'(' => Exp(src, idx, len + 1, balance + 1), + //_ => Exp(src, idx, len + 1, balance) + //}, + //}; + //chars = next + //} + //Ok(("", state)) + //} + //pub fn src (&self) -> &str { + //match self { + //Self::Nil => "", + //Self::Num(src, _, _) => src, + //Self::Sym(src, _, _) => src, + //Self::Key(src, _, _) => src, + //Self::Exp(src, _, _, _) => src, + //} + //} + //pub fn str (&self) -> &str { + //match self { + //Self::Nil => "", + //Self::Num(src, start, len) => &src[*start..start+len], + //Self::Sym(src, start, len) => &src[*start..start+len], + //Self::Key(src, start, len) => &src[*start..start+len], + //Self::Exp(src, start, len, 0) => &src[*start..(start+len)], + //Self::Exp(src, start, len, d) => panic!( + //"unclosed delimiter with depth {d} in:\n{}", + //&src[*start..(start+len)] + //) + //} + //} + //pub fn to_atom_ref (&'a self) -> Result, ParseError> { + //use Atom::*; + //Ok(match self { + //Token::Nil => Nil, + //Token::Num(_, _, _) => Num(Token::number(self.str())), + //Token::Sym(_, _, _) => Sym(self.str().into()), + //Token::Key(_, _, _) => Key(self.str().into()), + //Token::Exp(_, _, _, _) => Exp(match Atom::read_all_ref(self.str()) { + //Ok(exp) => exp, + //Err(e) => return Err(e) + //}), + //}) + //} +//} + +#[cfg(test)] #[test] fn test_edn_token () -> Result<(), Box> { + use Token::*; + assert_eq!(Nil, Token::chomp_one("")?); + assert_eq!(Nil, Token::chomp_one(" \n \r \t ")?); + assert_eq!(Num("8", 0, 1), Token::chomp_one("8")?); + assert_eq!(Num(" 8 ", 3, 1), Token::chomp_one(" 8 ")?); + assert_eq!(Sym(":foo", 0, 4), Token::chomp_one(":foo")?); + assert_eq!(Sym("@bar", 0, 4), Token::chomp_one("@bar")?); + assert_eq!(Key("foo/bar", 0, 7), Token::chomp_one("foo/bar")?); + Ok(()) +} diff --git a/edn/src/try_from_edn.rs b/edn/src/try_from_edn.rs deleted file mode 100644 index d71ba9cb..00000000 --- a/edn/src/try_from_edn.rs +++ /dev/null @@ -1,6 +0,0 @@ -use crate::*; - -pub trait TryFromEdn<'a, T>: Sized { - fn try_from_edn (state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> - Option; -} diff --git a/input/examples/edn-keys.rs b/input/examples/edn-keys.rs deleted file mode 100644 index edc5c930..00000000 --- a/input/examples/edn-keys.rs +++ /dev/null @@ -1 +0,0 @@ -fn main () {} diff --git a/input/src/edn_input.rs b/input/src/keymap.rs similarity index 80% rename from input/src/edn_input.rs rename to input/src/keymap.rs index d43809d6..e56a3f1f 100644 --- a/input/src/edn_input.rs +++ b/input/src/keymap.rs @@ -3,7 +3,7 @@ use std::sync::Arc; pub trait EdnInput: Input { fn matches_edn (&self, token: &str) -> bool; - fn get_event (_: &EdnItem>) -> Option { + fn get_event (_: &Atom>) -> Option { None } } @@ -12,8 +12,8 @@ pub trait EdnInput: Input { pub trait EdnCommand: Command { fn from_edn <'a> ( state: &C, - head: &EdnItem>, - tail: &'a [EdnItem>] + head: &Atom>, + tail: &'a [Atom>] ) -> Option; } @@ -26,7 +26,7 @@ pub trait EdnCommand: Command { $( // argument name $arg:ident - // if type is not provided defaults to EdnItem + // if type is not provided defaults to Atom $( // type:name separator : @@ -43,10 +43,10 @@ pub trait EdnCommand: Command { impl<$T: $Trait> EdnCommand<$T> for $Command { fn from_edn <'a> ( $state: &$T, - head: &EdnItem>, - tail: &'a [EdnItem>] + head: &Atom>, + tail: &'a [Atom>] ) -> Option { - $(if let (EdnItem::Key($key), [ // if the identifier matches + $(if let (Atom::Key($key), [ // if the identifier matches // bind argument ids $($arg),* // bind rest parameters @@ -69,7 +69,7 @@ pub trait EdnCommand: Command { $( // argument name $arg:ident - // if type is not provided defaults to EdnItem + // if type is not provided defaults to Atom $( // type:name separator : @@ -86,10 +86,10 @@ pub trait EdnCommand: Command { impl EdnCommand<$State> for $Command { fn from_edn <'a> ( $state: &$State, - head: &EdnItem>, - tail: &'a [EdnItem>], + head: &Atom>, + tail: &'a [Atom>], ) -> Option { - $(if let (EdnItem::Key($key), [ // if the identifier matches + $(if let (Atom::Key($key), [ // if the identifier matches // bind argument ids $($arg),* // bind rest parameters @@ -113,18 +113,18 @@ pub trait EdnCommand: Command { }; } -pub struct EdnKeyMapToCommand(Vec>>); -impl EdnKeyMapToCommand { +pub struct KeyMap(Vec>>); +impl KeyMap { /// Construct keymap from source text or fail pub fn new (keymap: &str) -> Usually { - Ok(Self(EdnItem::read_all(keymap)?)) + Ok(Self(Atom::read_all(keymap)?)) } /// Try to find a binding matching the currently pressed key - pub fn from (&self, state: &T, input: &impl EdnInput) -> Option + pub fn command (&self, state: &T, input: &impl EdnInput) -> Option where C: Command + EdnCommand { - use EdnItem::*; + use Atom::*; let mut command: Option = None; for item in self.0.iter() { if let Exp(e) = item { @@ -145,6 +145,7 @@ impl EdnKeyMapToCommand { } } -#[cfg(test)] #[test] fn test_edn_keymap () { - let keymap = EdnKeymapToCommand::new("")?; +#[cfg(test)] #[test] fn test_edn_keymap () -> Usually<()> { + let keymap = KeyMap::new("")?; + Ok(()) } diff --git a/input/src/lib.rs b/input/src/lib.rs index 994f635d..edba6774 100644 --- a/input/src/lib.rs +++ b/input/src/lib.rs @@ -1,19 +1,15 @@ #![feature(associated_type_defaults)] - -//mod component; pub use self::component::*; -mod input; pub use self::input::*; -mod command; pub use self::command::*; -mod event_map; pub use self::event_map::*; -mod edn_input; pub use self::edn_input::*; - -pub(crate) use ::tek_edn::EdnItem; +mod input; pub use self::input::*; +mod command; pub use self::command::*; +mod keymap; pub use self::keymap::*; +//mod event_map; pub use self::event_map::*; +pub(crate) use ::tek_edn::Atom; /// Standard error trait. pub(crate) use std::error::Error; /// Standard result type. pub(crate) type Usually = Result>; /// Standard optional result type. pub(crate) type Perhaps = Result, Box>; - #[cfg(test)] #[test] fn test_stub_input () -> Usually<()> { use crate::*; struct TestInput(bool); diff --git a/output/examples/edn-view.rs b/output/examples/edn-view.rs deleted file mode 100644 index ac35f494..00000000 --- a/output/examples/edn-view.rs +++ /dev/null @@ -1,57 +0,0 @@ -use tek_tui::{*, tek_input::*, tek_output::*}; -use tek_edn::*; -use std::sync::{Arc, RwLock}; -use crossterm::event::{*, KeyCode::*}; -use crate::ratatui::style::Color; - -const EDN: &'static [&'static str] = &[ - include_str!("edn01.edn"), - include_str!("edn02.edn"), - include_str!("edn03.edn"), - include_str!("edn04.edn"), - include_str!("edn05.edn"), - include_str!("edn06.edn"), - include_str!("edn07.edn"), - include_str!("edn08.edn"), - include_str!("edn09.edn"), - include_str!("edn10.edn"), - include_str!("edn11.edn"), - include_str!("edn12.edn"), - include_str!("edn13.edn"), -]; -fn main () -> Usually<()> { - let state = Arc::new(RwLock::new(Example(10, Measure::new()))); - Tui::new().unwrap().run(&state)?; - Ok(()) -} -#[derive(Debug)] pub struct Example(usize, Measure); -edn_view!(TuiOut: |self: Example|{ - let title = Tui::bg(Color::Rgb(60,10,10), - Push::y(1, Align::n(format!("Example {}/{} in {:?}", self.0 + 1, EDN.len(), &self.1.wh())))); - let code = Tui::bg(Color::Rgb(10,60,10), - Push::y(2, Align::n(format!("{}", EDN[self.0])))); - let content = Tui::bg(Color::Rgb(10,10,60), - EdnView::from_source(self, EDN[self.0])); - self.1.of(Bsp::s(title, Bsp::n(""/*code*/, content))) -};{ - bool {}; - u16 {}; - usize {}; - Box + 'a> { - ":title" => Tui::bg(Color::Rgb(60,10,10), Push::y(1, Align::n(format!("Example {}/{}:", self.0 + 1, EDN.len())))).boxed(), - ":code" => Tui::bg(Color::Rgb(10,60,10), Push::y(2, Align::n(format!("{}", EDN[self.0])))).boxed(), - ":hello-world" => "Hello world!".boxed(), - ":hello" => Tui::bg(Color::Rgb(10, 100, 10), "Hello").boxed(), - ":world" => Tui::bg(Color::Rgb(100, 10, 10), "world").boxed() - } -}); -impl Handle for Example { - fn handle (&mut self, input: &TuiIn) -> Perhaps { - match input.event() { - kpat!(Right) => self.0 = (self.0 + 1) % EDN.len(), - kpat!(Left) => self.0 = if self.0 > 0 { self.0 - 1 } else { EDN.len() - 1 }, - _ => return Ok(None) - } - Ok(Some(true)) - } -} diff --git a/output/src/lib.rs b/output/src/lib.rs index 54e0bd90..bb62c35d 100644 --- a/output/src/lib.rs +++ b/output/src/lib.rs @@ -12,7 +12,7 @@ mod op_iter; pub use self::op_iter::*; mod op_align; pub use self::op_align::*; mod op_bsp; pub use self::op_bsp::*; mod op_transform; pub use self::op_transform::*; -mod edn_view; pub use self::edn_view::*; +mod view; pub use self::view::*; pub(crate) use std::marker::PhantomData; pub(crate) use std::error::Error; pub(crate) use ::tek_edn::*; diff --git a/output/src/op_align.rs b/output/src/op_align.rs index c4efc29e..d38153b7 100644 --- a/output/src/op_align.rs +++ b/output/src/op_align.rs @@ -47,10 +47,10 @@ impl> Content for Align { impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Align> { fn try_from_edn ( state: &'a T, - head: &EdnItem>, - tail: &'a [EdnItem>] + head: &Atom>, + tail: &'a [Atom>] ) -> Option { - use EdnItem::*; + use Atom::*; Some(match (head.to_ref(), tail) { (Key("align/c"), [a]) => Self::c(state.get_content(a).expect("no content")), (Key("align/x"), [a]) => Self::x(state.get_content(a).expect("no content")), diff --git a/output/src/op_bsp.rs b/output/src/op_bsp.rs index 371b9fbd..22868d49 100644 --- a/output/src/op_bsp.rs +++ b/output/src/op_bsp.rs @@ -93,8 +93,8 @@ impl, B: Content> BspAreas for Bsp fn contents (&self) -> (&A, &B) { (&self.2, &self.3) } } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Bsp, RenderBox<'a, E>> { - fn try_from_edn (s: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> Option { - use EdnItem::*; + fn try_from_edn (s: &'a T, head: &Atom>, tail: &'a [Atom>]) -> Option { + use Atom::*; Some(match (head.to_ref(), tail) { (Key("bsp/n"), [a, b]) => Self::n( s.get_content(a).expect("no south"), diff --git a/output/src/op_cond.rs b/output/src/op_cond.rs index c3c2a4b0..1f6dd186 100644 --- a/output/src/op_cond.rs +++ b/output/src/op_cond.rs @@ -8,9 +8,9 @@ impl When { } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for When> { fn try_from_edn ( - state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] + state: &'a T, head: &Atom>, tail: &'a [Atom>] ) -> Option { - use EdnItem::*; + use Atom::*; if let (Key("when"), [condition, content]) = (head.to_ref(), tail) { Some(Self( Default::default(), @@ -48,8 +48,8 @@ impl Either { } } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Either, RenderBox<'a, E>> { - fn try_from_edn (state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> Option { - use EdnItem::*; + fn try_from_edn (state: &'a T, head: &Atom>, tail: &'a [Atom>]) -> Option { + use Atom::*; if let (Key("either"), [condition, content, alternative]) = (head.to_ref(), tail) { Some(Self::new( state.get_bool(condition).expect("either: no condition"), diff --git a/output/src/op_transform.rs b/output/src/op_transform.rs index 06ff1db6..97d9dea9 100644 --- a/output/src/op_transform.rs +++ b/output/src/op_transform.rs @@ -28,9 +28,9 @@ macro_rules! transform_xy { } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum> { fn try_from_edn ( - state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] + state: &'a T, head: &Atom>, tail: &'a [Atom>] ) -> Option { - use EdnItem::*; + use Atom::*; Some(match (head.to_ref(), tail) { (Key($x), [a]) => Self::x(state.get_content(a).expect("no content")), (Key($y), [a]) => Self::y(state.get_content(a).expect("no content")), @@ -84,9 +84,9 @@ macro_rules! transform_xy_unit { } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum> { fn try_from_edn ( - state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] + state: &'a T, head: &Atom>, tail: &'a [Atom>] ) -> Option { - use EdnItem::*; + use Atom::*; Some(match (head.to_ref(), tail) { (Key($x), [x, a]) => Self::x( state.get_unit(x).expect("no x"), diff --git a/output/src/edn_view.rs b/output/src/view.rs similarity index 83% rename from output/src/edn_view.rs rename to output/src/view.rs index 1ab4768c..d31fb466 100644 --- a/output/src/edn_view.rs +++ b/output/src/view.rs @@ -1,6 +1,6 @@ use crate::*; use std::{sync::Arc, marker::PhantomData}; -use EdnItem::*; +use Atom::*; /// Define an EDN-backed view. /// /// This consists of: @@ -15,8 +15,8 @@ use EdnItem::*; } $( impl<'a> EdnProvide<'a, $type> for $App { - fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { - Some(match edn.to_ref() { $(EdnItem::Sym($sym) => $value,)* _ => return None }) + fn get (&'a $self, edn: &'a Atom>) -> Option<$type> { + Some(match edn.to_ref() { $(Atom::Sym($sym) => $value,)* _ => return None }) } } )* @@ -26,9 +26,9 @@ use EdnItem::*; #[macro_export] macro_rules! edn_provide_content { (|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a, E: Output> EdnProvide<'a, Box + 'a>> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + fn get (&'a $self, edn: &'a Atom>) -> Option + 'a>> { Some(match edn.to_ref() { - $(EdnItem::Sym($pat) => $expr),*, + $(Atom::Sym($pat) => $expr),*, _ => return None }) } @@ -36,9 +36,9 @@ use EdnItem::*; }; ($Output:ty: |$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, Box + 'a>> for $State { - fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + fn get (&'a $self, edn: &'a Atom>) -> Option + 'a>> { Some(match edn.to_ref() { - $(EdnItem::Sym($pat) => $expr),*, + $(Atom::Sym($pat) => $expr),*, _ => return None }) } @@ -48,7 +48,7 @@ use EdnItem::*; /// Renders from EDN source and context. #[derive(Default)] pub enum EdnView<'a, E: Output, T: EdnViewData<'a, E> + std::fmt::Debug> { #[default] Inert, - Ok(T, EdnItem>), + Ok(T, Atom>), //render: BoxBox + Send + Sync + 'a> + Send + Sync + 'a> Err(String), _Unused(PhantomData<&'a E>), @@ -74,13 +74,13 @@ impl<'a, E: Output, T> EdnViewData<'a, E> for T where T: {} impl<'a, E: Output, T: EdnViewData<'a, E> + std::fmt::Debug> EdnView<'a, E, T> { pub fn from_source (state: T, source: &'a str) -> Self { - match EdnItem::read_one(&source) { + match Atom::read_one(&source) { Ok((layout, _)) => Self::Ok(state, layout), Err(error) => Self::Err(format!("{error} in {source}")) } } - pub fn from_items (state: T, items: Vec>>) -> Self { - Self::Ok(state, EdnItem::Exp(items).to_arc()) + pub fn from_items (state: T, items: Vec>>) -> Self { + Self::Ok(state, Atom::Exp(items).to_arc()) } } implEdnViewData<'a, E> + Send + Sync + std::fmt::Debug> Content for EdnView<'_, E, T> { @@ -113,7 +113,7 @@ pub trait EdnViewData<'a, E: Output>: EdnProvide<'a, E::Unit> + EdnProvide<'a, Box + 'a>> { - fn get_bool (&'a self, item: &'a EdnItem>) -> Option { + fn get_bool (&'a self, item: &'a Atom>) -> Option { Some(match &item { Sym(s) => match s.as_ref() { ":false" | ":f" => false, @@ -125,13 +125,13 @@ pub trait EdnViewData<'a, E: Output>: _ => return EdnProvide::get(self, item) }) } - fn get_usize (&'a self, item: &'a EdnItem>) -> Option { + fn get_usize (&'a self, item: &'a Atom>) -> Option { Some(match &item { Num(n) => *n, _ => return EdnProvide::get(self, item) }) } - fn get_unit (&'a self, item: &'a EdnItem>) -> Option { + fn get_unit (&'a self, item: &'a Atom>) -> Option { Some(match &item { Num(n) => (*n as u16).into(), _ => return EdnProvide::get(self, item) }) } - fn get_content (&'a self, item: &'a EdnItem>) -> Option + 'a>> where E: 'a { + fn get_content (&'a self, item: &'a Atom>) -> Option + 'a>> where E: 'a { Some(match item { Nil => Box::new(()), Exp(ref e) => { diff --git a/input/examples/keys00.edn b/tek/examples/arranger.edn similarity index 100% rename from input/examples/keys00.edn rename to tek/examples/arranger.edn diff --git a/input/examples/keys01.edn b/tek/examples/clip.edn similarity index 100% rename from input/examples/keys01.edn rename to tek/examples/clip.edn diff --git a/input/examples/keys02.edn b/tek/examples/sampler.edn similarity index 100% rename from input/examples/keys02.edn rename to tek/examples/sampler.edn diff --git a/tek/src/lib.rs b/tek/src/lib.rs index dbe7a624..b1b907e2 100644 --- a/tek/src/lib.rs +++ b/tek/src/lib.rs @@ -587,8 +587,6 @@ const KEYS_TRACK: &str = include_str!("keys_track.edn"); const KEYS_SCENE: &str = include_str!("keys_scene.edn"); const KEYS_MIX: &str = include_str!("keys_mix.edn"); handle!(TuiIn: |self: Tek, input|Ok({ - use EdnItem::*; - let mut command: Option = None; // If editing, editor keys take priority if self.is_editing() { if self.editor.handle(input)? == Some(true) { @@ -596,17 +594,17 @@ handle!(TuiIn: |self: Tek, input|Ok({ } } // Handle from root keymap - if let Some(command) = EdnKeyMapToCommand::new(KEYS_APP)?.from::<_, TekCommand>(self, input) { + if let Some(command) = KeyMap::new(KEYS_APP)?.command::<_, TekCommand>(self, input) { if let Some(undo) = command.execute(self)? { self.history.push(undo); } return Ok(Some(true)) } // Handle from selection-dependent keymaps - if let Some(command) = EdnKeyMapToCommand::new(match self.selected() { + if let Some(command) = KeyMap::new(match self.selected() { Selection::Clip(t, s) => KEYS_CLIP, Selection::Track(t) => KEYS_TRACK, Selection::Scene(s) => KEYS_SCENE, Selection::Mix => KEYS_MIX, - })?.from::<_, TekCommand>( + })?.command::<_, TekCommand>( self, input ) { if let Some(undo) = command.execute(self)? { self.history.push(undo); } diff --git a/output/examples/demo.rs.old b/tui/examples/demo.rs.old similarity index 100% rename from output/examples/demo.rs.old rename to tui/examples/demo.rs.old diff --git a/output/examples/edn01.edn b/tui/examples/edn01.edn similarity index 100% rename from output/examples/edn01.edn rename to tui/examples/edn01.edn diff --git a/output/examples/edn02.edn b/tui/examples/edn02.edn similarity index 100% rename from output/examples/edn02.edn rename to tui/examples/edn02.edn diff --git a/output/examples/edn03.edn b/tui/examples/edn03.edn similarity index 100% rename from output/examples/edn03.edn rename to tui/examples/edn03.edn diff --git a/output/examples/edn04.edn b/tui/examples/edn04.edn similarity index 100% rename from output/examples/edn04.edn rename to tui/examples/edn04.edn diff --git a/output/examples/edn05.edn b/tui/examples/edn05.edn similarity index 100% rename from output/examples/edn05.edn rename to tui/examples/edn05.edn diff --git a/output/examples/edn06.edn b/tui/examples/edn06.edn similarity index 100% rename from output/examples/edn06.edn rename to tui/examples/edn06.edn diff --git a/output/examples/edn07.edn b/tui/examples/edn07.edn similarity index 100% rename from output/examples/edn07.edn rename to tui/examples/edn07.edn diff --git a/output/examples/edn08.edn b/tui/examples/edn08.edn similarity index 100% rename from output/examples/edn08.edn rename to tui/examples/edn08.edn diff --git a/output/examples/edn09.edn b/tui/examples/edn09.edn similarity index 100% rename from output/examples/edn09.edn rename to tui/examples/edn09.edn diff --git a/output/examples/edn10.edn b/tui/examples/edn10.edn similarity index 100% rename from output/examples/edn10.edn rename to tui/examples/edn10.edn diff --git a/output/examples/edn11.edn b/tui/examples/edn11.edn similarity index 100% rename from output/examples/edn11.edn rename to tui/examples/edn11.edn diff --git a/output/examples/edn12.edn b/tui/examples/edn12.edn similarity index 100% rename from output/examples/edn12.edn rename to tui/examples/edn12.edn diff --git a/output/examples/edn13.edn b/tui/examples/edn13.edn similarity index 100% rename from output/examples/edn13.edn rename to tui/examples/edn13.edn diff --git a/output/examples/edn99.edn b/tui/examples/edn99.edn similarity index 100% rename from output/examples/edn99.edn rename to tui/examples/edn99.edn diff --git a/tui/examples/tui.rs b/tui/examples/tui.rs new file mode 100644 index 00000000..b341f06e --- /dev/null +++ b/tui/examples/tui.rs @@ -0,0 +1,67 @@ +use tek_tui::{*, tek_input::*, tek_output::*}; +use tek_edn::*; +use std::sync::{Arc, RwLock}; +use crossterm::event::{*, KeyCode::*}; +use crate::ratatui::style::Color; +fn main () -> Usually<()> { + let state = Arc::new(RwLock::new(Example(10, Measure::new()))); + Tui::new().unwrap().run(&state)?; + Ok(()) +} +#[derive(Debug)] pub struct Example(usize, Measure); +const KEYMAP: &str = "(:left prev) (:right next)"; +handle!(TuiIn: |self: Example, input|{ + let keymap = KeyMap::new(KEYMAP)?; + let command = keymap.command::<_, ExampleCommand>(self, input); + if let Some(command) = command { + command.execute(self)?; + return Ok(Some(true)) + } + return Ok(None) +}); +enum ExampleCommand { Next, Previous } +edn_command!(ExampleCommand: |app: Example| { + (":prev" [] Self::Previous) + (":next" [] Self::Next) +}); +command!(|self: ExampleCommand, state: Example|match self { + Self::Next => + { state.0 = (state.0 + 1) % EXAMPLES.len(); None }, + Self::Previous => + { state.0 = if state.0 > 0 { state.0 - 1 } else { EXAMPLES.len() - 1 }; None }, +}); +const EXAMPLES: &'static [&'static str] = &[ + include_str!("edn01.edn"), + include_str!("edn02.edn"), + include_str!("edn03.edn"), + include_str!("edn04.edn"), + include_str!("edn05.edn"), + include_str!("edn06.edn"), + include_str!("edn07.edn"), + include_str!("edn08.edn"), + include_str!("edn09.edn"), + include_str!("edn10.edn"), + include_str!("edn11.edn"), + include_str!("edn12.edn"), + include_str!("edn13.edn"), +]; +edn_view!(TuiOut: |self: Example|{ + let title = Tui::bg(Color::Rgb(60,10,10), + Push::y(1, Align::n(format!("Example {}/{} in {:?}", self.0 + 1, EXAMPLES.len(), &self.1.wh())))); + let code = Tui::bg(Color::Rgb(10,60,10), + Push::y(2, Align::n(format!("{}", EXAMPLES[self.0])))); + let content = Tui::bg(Color::Rgb(10,10,60), + EdnView::from_source(self, EXAMPLES[self.0])); + self.1.of(Bsp::s(title, Bsp::n(""/*code*/, content))) +}; { + bool {}; + u16 {}; + usize {}; + Box + 'a> { + ":title" => Tui::bg(Color::Rgb(60,10,10), Push::y(1, Align::n(format!("Example {}/{}:", self.0 + 1, EXAMPLES.len())))).boxed(), + ":code" => Tui::bg(Color::Rgb(10,60,10), Push::y(2, Align::n(format!("{}", EXAMPLES[self.0])))).boxed(), + ":hello" => Tui::bg(Color::Rgb(10, 100, 10), "Hello").boxed(), + ":world" => Tui::bg(Color::Rgb(100, 10, 10), "world").boxed(), + ":hello-world" => "Hello world!".boxed() + } +});