Compare commits

...

2 commits

Author SHA1 Message Date
a145e332de 1 file, 300 lines, many worries
Some checks are pending
/ build (push) Waiting to run
2025-07-17 21:45:59 +03:00
d99b20c99d wip: fix(dsl): kinda patch it up 2025-07-17 19:29:14 +03:00
3 changed files with 295 additions and 285 deletions

View file

@ -14,50 +14,35 @@ pub(crate) use konst::string::{split_at, str_range, char_indices};
pub(crate) use thiserror::Error; pub(crate) use thiserror::Error;
pub(crate) use self::DslError::*; pub(crate) use self::DslError::*;
#[cfg(test)] mod test; #[cfg(test)] mod test;
/// Enumeration of values that may figure in an expression.
pub type DslUsually<T> = Result<T, DslError>;
pub type DslPerhaps<T> = Result<Option<T>, DslError>;
/// Pronounced dizzle.
pub trait Dsl: Clone + Debug {
/// The string representation for a dizzle.
type Str: DslStr;
/// The expression representation for a dizzle.
type Exp: DslExp;
/// Return a token iterator for this dizzle.
fn dsl (&self) -> DslUsually<&Val<Self>>;
}
/// Enumeration of values representable by a DSL [Token]s.
/// Generic over string and expression storage. /// Generic over string and expression storage.
#[derive(Clone, Debug, PartialEq, Default)] #[derive(Clone, Debug, PartialEq, Default)]
pub enum Val<D: Dsl> { pub enum Val<Str, Exp> {
#[default] /// Empty expression
Nil, #[default] Nil,
/// Unsigned integer literal /// Unsigned integer literal
Num(usize), Num(usize),
/// Tokens that start with `:` /// An identifier that starts with `.`
Sym(D::Str), Sym(Str),
/// Tokens that don't start with `:` /// An identifier that doesn't start with `:`
Key(D::Str), Key(Str),
/// Quoted string literals /// A quoted string literal
Str(D::Str), Str(Str),
/// Expressions. /// A DSL expression.
Exp( Exp(
/// Expression depth checksum. Must be 0, otherwise you have an unclosed delimiter. /// Number of unclosed parentheses. Must be 0 to be valid.
usize, isize,
/// Expression content. /// Expression content.
D::Exp Exp
), ),
/// An error.
Error(DslError), Error(DslError),
} }
impl<Str: Copy, Exp: Copy> Copy for Val<Str, Exp> {}
impl<Str: Copy, Exp: Copy, D: Dsl<Str=Str,Exp=Exp>> Copy for Val<D> {} impl<Str: DslStr, Exp: DslExp> Val<Str, Exp> {
pub fn convert <T: Dsl> (&self) -> Val<T::Str, T::Exp> where
impl<D: Dsl> Val<D> { T::Str: for<'a> From<&'a Str>,
pub fn convert <T: Dsl> (&self) -> Val<T> where T::Exp: for<'a> From<&'a Exp>
B::Str: for<'a> From<&'a D::Str>,
B::Exp: for<'a> From<&'a D::Exp>
{ {
match self { Val::Nil => Val::Nil, match self { Val::Nil => Val::Nil,
Val::Num(u) => Val::Num(*u), Val::Num(u) => Val::Num(*u),
@ -66,87 +51,122 @@ impl<D: Dsl> Val<D> {
Val::Str(s) => Val::Str(s.into()), Val::Str(s) => Val::Str(s.into()),
Val::Exp(d, x) => Val::Exp(*d, x.into()), Val::Exp(d, x) => Val::Exp(*d, x.into()),
Val::Error(e) => Val::Error(*e) } } Val::Error(e) => Val::Error(*e) } }
pub fn is_nil (&self) -> bool { matches!(self, Self::Nil) }
pub fn as_error (&self) -> Option<&DslError> { if let Self::Error(e) = self { Some(e) } else { None } }
pub fn as_num (&self) -> Option<usize> {match self{Self::Num(n)=>Some(*n),_=>None}}
pub fn as_sym (&self) -> Option<&str> {match self{Self::Sym(s )=>Some(s.as_ref()),_=>None}}
pub fn as_key (&self) -> Option<&str> {match self{Self::Key(k )=>Some(k.as_ref()),_=>None}}
pub fn as_str (&self) -> Option<&str> {match self{Self::Str(s )=>Some(s.as_ref()),_=>None}}
pub fn as_exp (&self) -> Option<&D::Exp> {match self{Self::Exp(_, x)=>Some(x),_=>None}}
pub fn exp_depth (&self) -> Option<usize> { todo!() }
pub fn exp_head_tail (&self) -> (Option<&Self>, Option<&D::Exp>) { (self.exp_head(), self.exp_tail()) }
pub fn exp_head (&self) -> Option<&Self> { todo!() } // TODO
pub fn exp_tail (&self) -> Option<&D::Exp> { todo!() }
pub fn peek (&self) -> Option<Self> { todo!() }
pub fn next (&mut self) -> Option<Self> { todo!() }
pub fn rest (self) -> Vec<Self> { todo!() }
//pub fn exp_match <T, F> (&self, namespace: &str, cb: F) -> DslPerhaps<T>
//where F: Fn(&str, &Exp)-> DslPerhaps<T> {
//if let Some(Self::Key(key)) = self.exp_head()
//&& key.as_ref().starts_with(namespace)
//&& let Some(tail) = self.exp_tail() {
//cb(key.as_ref().split_at(namespace.len()).1, tail)
//} else {
//Ok(None)
//}
//}
} }
/// The expression representation for a [Dsl] implementation.
/// [Cst] uses [CstIter]. [Ast] uses [VecDeque].
pub trait DslExp: PartialEq + Clone + Default + Debug + Dsl {}
impl<T: PartialEq + Clone + Default + Debug + Dsl> DslExp for T {}
/// The string representation for a [Dsl] implementation. /// The string representation for a [Dsl] implementation.
/// [Cst] uses `&'s str`. [Ast] uses `Arc<str>`. /// [Cst] uses `&'s str`. [Ast] uses `Arc<str>`.
pub trait DslStr: PartialEq + Clone + Default + Debug + AsRef<str> + std::ops::Deref<Target = str> {} pub trait DslStr: PartialEq + Clone + Default + Debug + AsRef<str> + std::ops::Deref<Target = str> {}
impl<T: PartialEq + Clone + Default + Debug + AsRef<str> + std::ops::Deref<Target = str>> DslStr for T {} impl<T: PartialEq + Clone + Default + Debug + AsRef<str> + std::ops::Deref<Target = str>> DslStr for T {}
impl<Str: DslStr, Exp: DslExp + Dsl<Str=Str, Exp=Exp>> Val<Str, Exp> {
/// The expression representation for a [Dsl] implementation. pub const fn err (&self) -> Option<DslError> {match self{Val::Error(e)=>Some(*e), _=>None}}
/// [Cst] uses [CstIter]. [Ast] uses [VecDeque]. pub const fn nil (&self) -> bool {match self{Val::Nil=>true, _=>false}}
pub trait DslExp: PartialEq + Clone + Default + Debug {} pub const fn num (&self) -> Option<usize> {match self{Val::Num(n)=>Some(*n), _=>None}}
impl <T: PartialEq + Clone + Default + Debug> DslExp for T {} pub const fn sym (&self) -> Option<&Str> {match self{Val::Sym(s)=>Some(s), _=>None}}
pub const fn key (&self) -> Option<&Str> {match self{Val::Key(k)=>Some(k), _=>None}}
pub const fn str (&self) -> Option<&Str> {match self{Val::Str(s)=>Some(s), _=>None}}
pub const fn exp (&self) -> Option<&Exp> {match self{Val::Exp(_, x)=>Some(x),_=>None}}
pub const fn exp_depth (&self) -> Option<isize> {match self{Val::Exp(d, _)=>Some(*d), _=>None}}
}
/// Parsed substring with range and value.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Token<Str, Exp> {
/// Meaning of token.
pub value: Val<Str, Exp>,
/// Reference to source text.
pub source: Str,
/// Index of 1st character of span.
pub start: usize,
/// Length of span.
pub length: usize,
}
impl<Str: Copy, Exp: Copy> Copy for Token<Str, Exp> {}
impl<Str, Exp> Token<Str, Exp> {
pub const fn end (&self) -> usize {
self.start.saturating_add(self.length) }
pub const fn value (&self)
-> &Val<Str, Exp> { &self.value }
pub const fn err (&self)
-> Option<DslError> { if let Val::Error(e) = self.value { Some(e) } else { None } }
pub const fn new (source: Str, start: usize, length: usize, value: Val<Str, Exp>)
-> Self { Self { value, start, length, source } }
pub const fn copy (&self) -> Self where Val<Str, Exp>: Copy, Str: Copy, Exp: Copy {
Self { value: self.value, ..*self }
}
}
impl<'s> CstToken<'s> {
pub const fn slice (&self) -> &str {
str_range(self.source, self.start, self.end()) }
pub const fn slice_exp (&self) -> &str {
str_range(self.source, self.start.saturating_add(1), self.end()) }
pub const fn grow (&mut self) -> &mut Self {
let max_length = self.source.len().saturating_sub(self.start);
self.length = self.length + 1;
if self.length > max_length { self.length = max_length }
self
}
pub const fn grow_exp (&'s mut self, depth: isize, source: &'s str) -> &mut Self {
self.value = Val::Exp(depth, Cst(CstConstIter(source)));
self
}
}
/// To the [Dsl], a token is equivalent to its `value` field.
impl<Str: DslStr, Exp: DslExp> Dsl for Token<Str, Exp> {
type Str = Str; type Exp = Exp;
fn dsl (&self) -> Val<Str, Exp> { self.value.clone() }
}
/// Coerce to [Val] for predefined [Self::Str] and [Self::Exp].
pub trait Dsl: Clone + Debug {
/// The string representation for a dizzle.
type Str: DslStr;
/// The expression representation for a dizzle.
type Exp: DslExp;
/// Request the top-level DSL [Val]ue.
/// May perform cloning or parsing.
fn dsl (&self) -> Val<Self::Str, Self::Exp>;
fn err (&self) -> Option<DslError> {self.dsl().err()}
fn nil (&self) -> bool {self.dsl().nil()}
fn num (&self) -> Option<usize> {self.dsl().num()}
fn sym (&self) -> Option<Self::Str> {self.dsl().sym()}
fn key (&self) -> Option<Self::Str> {self.dsl().key()}
fn str (&self) -> Option<Self::Str> {self.dsl().str()}
fn exp (&self) -> Option<Self::Exp> {self.dsl().exp()}
fn exp_depth (&self) -> Option<isize> {self.dsl().exp_depth()}
fn exp_head (&self) -> Val<Self::Str, Self::Exp> {self.dsl().exp_head()}
fn exp_tail (&self) -> Val<Self::Str, Self::Exp> {self.dsl().exp_tail()}
}
/// The most basic implementor of the [Dsl] trait.
impl<Str: DslStr, Exp: DslExp> Dsl for Val<Str, Exp> {
type Str = Str; type Exp = Exp;
fn dsl (&self) -> Val<Str, Exp> { self.clone() }
}
/// The abstract syntax tree (AST) can be produced from the CST /// The abstract syntax tree (AST) can be produced from the CST
/// by cloning source slices into owned ([Arc]) string slices. /// by cloning source slices into owned ([Arc]) string slices.
#[derive(Debug, Clone, Default, PartialEq)] #[derive(Debug, Clone, Default, PartialEq)]
pub struct Ast(Token<Ast>); pub struct Ast(Arc<VecDeque<Arc<Token<Arc<str>, Ast>>>>);
impl Dsl for Ast { impl Dsl for Ast {
type Str = Arc<str>; type Str = Arc<str>; type Exp = Ast;
type Exp = VecDeque<Arc<Token<Ast>>>; fn dsl (&self) -> Val<Arc<str>, Ast> { Val::Exp(0, Ast(self.0.clone())) }
fn dsl (&self) -> DslUsually<&Val<Self>> {
Ok(self.0.value())
} }
}
/// The concrete syntax tree (CST) implements zero-copy /// The concrete syntax tree (CST) implements zero-copy
/// parsing of the DSL from a string reference. CST items /// parsing of the DSL from a string reference. CST items
/// preserve info about their location in the source. /// preserve info about their location in the source.
/// CST stores strings as source references and expressions as [CstIter] instances. /// CST stores strings as source references and expressions as [CstIter] instances.
#[derive(Debug, Clone, Default, PartialEq)] #[derive(Debug, Copy, Clone, Default, PartialEq)]
pub struct Cst<'s>(Token<Cst<'s>>); pub struct Cst<'s>(pub CstConstIter<'s>);
pub type CstVal<'s> = Val<&'s str, Cst<'s>>;
pub type CstToken<'s> = Token<&'s str, Cst<'s>>;
impl<'s> Dsl for Cst<'s> { impl<'s> Dsl for Cst<'s> {
type Str = &'s str; type Str = &'s str; type Exp = Cst<'s>;
type Exp = CstConstIter<'s>; fn dsl (&self) -> Val<Self::Str, Self::Exp> { Val::Exp(0, Cst(self.0)) }
fn dsl (&self) -> DslUsually<&Val<Self>> { }
Ok(self.0.value()) impl<'s> From<&'s str> for Cst<'s> {
fn from (source: &'s str) -> Self {
Self(CstConstIter(source))
} }
} }
/// `State` + [Dsl] -> `Self`.
pub trait FromDsl<State>: Sized {
fn try_from_dsl (state: &State, dsl: &impl Dsl) -> Perhaps<Self>;
fn from_dsl (state: &State, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<Self> {
match Self::try_from_dsl(state, dsl)? { Some(dsl) => Ok(dsl), _ => Err(err()) } } }
/// `self` + `Options` -> [Dsl]
pub trait IntoDsl { /*TODO*/ }
/// `self` + [Dsl] -> `Item`
pub trait DslInto<Item> {
fn try_dsl_into (&self, dsl: &impl Dsl) -> Perhaps<Item>;
fn dsl_into (&self, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<Item> {
match Self::try_dsl_into(self, dsl)? { Some(dsl) => Ok(dsl), _ => Err(err()) } } }
/// `self` + `Item` -> [Dsl]
pub trait DslFrom { /*TODO*/ }
/// Standard result type for DSL-specific operations.
pub type DslResult<T> = Result<T, DslError>;
/// DSL-specific error codes. /// DSL-specific error codes.
#[derive(Error, Debug, Copy, Clone, PartialEq, PanicFmt)] pub enum DslError { #[derive(Error, Debug, Copy, Clone, PartialEq, PanicFmt)] pub enum DslError {
#[error("parse failed: not implemented")] #[error("parse failed: not implemented")]
@ -167,17 +187,16 @@ pub type DslResult<T> = Result<T, DslError>;
/// [Cst::next] returns just the [Cst] and mutates `self`, /// [Cst::next] returns just the [Cst] and mutates `self`,
/// instead of returning an updated version of the struct as [CstConstIter::next] does. /// instead of returning an updated version of the struct as [CstConstIter::next] does.
#[derive(Copy, Clone, Debug, Default, PartialEq)] #[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct CstIter<'s>(CstConstIter<'s>); pub struct CstIter<'s>(pub CstConstIter<'s>);
impl<'s> CstIter<'s> { impl<'s> CstIter<'s> {
pub const fn new (source: &'s str) -> Self { Self(CstConstIter::new(source)) } pub const fn new (source: &'s str) -> Self { Self(CstConstIter::new(source)) }
} }
impl<'s> Iterator for CstIter<'s> { impl<'s> Iterator for CstIter<'s> {
type Item = Token<Cst<'s>>; type Item = CstToken<'s>;
fn next (&mut self) -> Option<Self::Item> { fn next (&mut self) -> Option<Self::Item> {
match self.0.advance() { match self.0.advance() {
Ok(Some((item, rest))) => { self.0 = rest; item.into() }, Some((item, rest)) => { self.0 = rest; Some(item.into()) },
Ok(None) => None, None => None,
Err(e) => panic!("{e:?}")
} }
} }
} }
@ -192,8 +211,8 @@ impl<'s> From <&'s str> for CstConstIter<'s> {
fn from (src: &'s str) -> Self { Self(src) } fn from (src: &'s str) -> Self { Self(src) }
} }
impl<'s> Iterator for CstConstIter<'s> { impl<'s> Iterator for CstConstIter<'s> {
type Item = Token<Cst<'s>>; type Item = CstToken<'s>;
fn next (&mut self) -> Option<Token<Cst<'s>>> { self.advance().unwrap().map(|x|x.0) } fn next (&mut self) -> Option<CstToken<'s>> { self.advance().map(|x|x.0) }
} }
impl<'s> ConstIntoIter for CstConstIter<'s> { impl<'s> ConstIntoIter for CstConstIter<'s> {
type Kind = IsIteratorKind; type Kind = IsIteratorKind;
@ -203,150 +222,147 @@ impl<'s> ConstIntoIter for CstConstIter<'s> {
impl<'s> CstConstIter<'s> { impl<'s> CstConstIter<'s> {
pub const fn new (source: &'s str) -> Self { Self(source) } pub const fn new (source: &'s str) -> Self { Self(source) }
pub const fn chomp (&self, index: usize) -> Self { Self(split_at(self.0, index).1) } pub const fn chomp (&self, index: usize) -> Self { Self(split_at(self.0, index).1) }
pub const fn peek (&self) -> DslPerhaps<Token<Cst<'s>>> { Token::peek(self.0) } pub const fn advance (&mut self) -> Option<(CstToken<'s>, Self)> {
//pub const fn next (mut self) -> Option<(Token<Cst<'s>>, Self)> { match peek(Val::Nil, self.0) {
//Self::advance(&mut self).unwrap() } Token { value: Val::Nil, .. } => None,
pub const fn advance (&mut self) -> DslPerhaps<(Token<Cst<'s>>, Self)> { token => {
match self.peek() { let end = self.chomp(token.end());
Ok(Some(token)) => { Some((token.copy(), end))
let end = self.chomp(token.span.end());
Ok(Some((token.copy(), end)))
}, },
Ok(None) => Ok(None),
Err(e) => Err(e)
} }
} }
} }
#[derive(Debug, Copy, Clone, Default, PartialEq)] pub const fn peek <'s> (mut value: CstVal<'s>, source: &'s str) -> CstToken<'s> {
pub struct Span<D: Dsl> {
/// Reference to source text.
pub source: D::Str,
/// Index of 1st character of span.
pub start: usize,
/// Length of span.
pub length: usize,
}
impl<'s, D: Dsl> Span<D> {
pub const fn end (&self) -> usize { self.start.saturating_add(self.length) }
}
impl<'s, D: Dsl<Str=&'s str>> Span<D> {
pub const fn slice (&self) -> &'s str {
str_range(self.source, self.start, self.end()) }
pub const fn slice_exp (&self) -> &'s str {
str_range(self.source, self.start.saturating_add(1), self.end()) }
pub const fn grow (&mut self) -> DslUsually<&mut Self> {
if self.length + self.start >= self.source.len() { return Err(End) }
self.length = self.length.saturating_add(1);
Ok(self) }
}
/// Parsed substring with range and value.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Token<D: Dsl> {
/// Source span of token.
span: Span<D>,
/// Meaning of token.
value: Val<D>,
}
impl<D: Dsl> Token<D> {
pub const fn value (&self) -> &Val<D> { &self.value }
pub const fn span (&self) -> &Span<D> { &self.span }
pub const fn err (&self) -> Option<DslError> {
if let Val::Error(e) = self.value { Some(e) } else { None } }
pub const fn new (source: D::Str, start: usize, length: usize, value: Val<D>) -> Self {
Self { value, span: Span { source, start, length } } }
pub const fn copy (&self) -> Self where D::Str: Copy, D::Exp: Copy {
Self { span: Span { ..self.span }, value: self.value } }
}
const fn or_panic <T> (result: DslUsually<T>) -> T {
match result { Ok(t) => t, Err(e) => const_panic::concat_panic!(e) }
}
impl<'s, D: Dsl<Str = &'s str>> Token<D> {
pub const fn peek (src: D::Str) -> DslPerhaps<Self> where D::Exp: From<&'s str> {
use Val::*; use Val::*;
let mut t = Self::new(src, 0, 0, Nil); let mut start = 0;
let mut iter = char_indices(src); let mut length = 0;
while let Some(((i, c), next)) = iter.next() { let mut source = source;
t = match (t.value(), c) { loop {
(Error(_), _) => if let Some(((i, c), next)) = char_indices(source).next() {
return Ok(Some(t)), if matches!(value, Error(_)) {
(Nil, ' '|'\n'|'\r'|'\t') => break
*or_panic(t.grow()), } else if matches!(value, Nil) {
(Nil, '(') => if is_whitespace(c) {
Self::new(src, i, 1, Exp(1, D::Exp::from(str_range(src, i, i + 1)))), length += 1;
(Nil, '"') => continue
Self::new(src, i, 1, Str(str_range(src, i, i + 1))), }
(Nil, ':'|'@') => start = i;
Self::new(src, i, 1, Sym(str_range(src, i, i + 1))), length = 1;
(Nil, '/'|'a'..='z') => if is_exp_start(c) {
Self::new(src, i, 1, Key(str_range(src, i, i + 1))), value = Exp(1, Cst(CstConstIter(str_range(source, i, i+1))));
(Nil, '0'..='9') => } else if is_str_start(c) {
Self::new(src, i, 1, match to_digit(c) { Ok(c) => Num(c), Err(e) => Error(e) }), value = Str(str_range(source, i, i+1));
(Nil, _) => } else if is_sym_start(c) {
{ t.value = Val::Error(Unexpected(c)); t }, value = Sym(str_range(source, i, i+1));
(Str(_), '"') => } else if is_key_start(c) {
return Ok(Some(t)), value = Key(str_range(source, i, i+1));
(Str(_), _) => } else if is_digit(c) {
{ or_panic(t.grow()); t.value = Str(t.span.slice()); t }, value = match to_digit(c) { Ok(c) => Num(c), Err(e) => Error(e) };
(Num(m), ' '|'\n'|'\r'|'\t'|')') => } else {
return Ok(Some(t)), value = Error(Unexpected(c));
(Num(m), _) => match to_digit(c) { break
Ok(n) => { t.grow()?; t.value = Num(10*m+n); t }, }
Err(e) => { t.grow()?; t.value = Error(e); t } }, } else if matches!(value, Str(_)) {
(Sym(_), ' '|'\n'|'\r'|'\t'|')') => if is_str_end(c) {
return Ok(Some(t)), break
(Sym(_), 'a'..='z'|'A'..='Z'|'0'..='9'|'-') => { } else {
t.grow()?; t.value = Sym(t.span.slice()); t }, value = Str(str_range(source, start, start + length + 1));
(Sym(_), _) => }
{ t.value = Error(Unexpected(c)); t }, } else if matches!(value, Sym(_)) {
(Key(_), ' '|'\n'|'\r'|'\t'|')') => if is_sym_end(c) {
return Ok(Some(t)), break
(Key(_), 'a'..='z'|'0'..='9'|'-'|'/') => } else if is_sym_char(c) {
{ t.grow()?; t.value = Key(t.span.slice()); t }, value = Sym(str_range(source, start, start + length + 1));
(Key(_), _ ) => } else {
{ t.value = Error(Unexpected(c)); t }, value = Error(Unexpected(c));
(Exp(0, _), _) => }
{ t.grow()?; t.value = Exp(0, D::Exp::from(t.span.slice_exp())); return Ok(Some(t)) }, } else if matches!(value, Key(_)) {
(Exp(d, _), ')') => if is_key_end(c) {
{ t.grow()?; t.value = Exp(d-1, D::Exp::from(t.span.slice_exp())); t }, break
(Exp(d, _), '(') => }
{ t.grow()?; t.value = Exp(d+1, D::Exp::from(t.span.slice_exp())); t }, length += 1;
(Exp(d, _), _ ) => if is_key_char(c) {
{ t.grow()?; t.value = Exp(*d, D::Exp::from(t.span.slice_exp())); t }, value = Key(str_range(source, start, start + length + 1));
}; } else {
value = Error(Unexpected(c));
}
} else if let Exp(depth, exp) = value {
if depth == 0 {
value = Exp(0, Cst(CstConstIter(str_range(source, start, start + length))));
break
}
length += 1;
if c == ')' {
value = Exp(depth-1, Cst(CstConstIter(str_range(source, start, start + length))));
} else if c == '(' {
value = Exp(depth+1, Cst(CstConstIter(str_range(source, start, start + length))));
} else {
value = Exp(depth, Cst(CstConstIter(str_range(source, start, start + length))));
}
} else if let Num(m) = value {
if is_num_end(c) {
break
}
length += 1;
match to_digit(c) {
Ok(n) => { value = Num(n+10*m); },
Err(e) => { value = Error(e); }
}
}
} else {
break
}
}
return Token { value, source, start, length }
}
const fn is_whitespace (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t') }
const fn is_digit (c: char) -> bool { matches!(c, '0'..='9') }
const fn is_num_end (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t'|')') }
const fn is_key_start (c: char) -> bool { matches!(c, '/'|'a'..='z') }
const fn is_key_char (c: char) -> bool { matches!(c, 'a'..='z'|'0'..='9'|'-'|'/') }
const fn is_key_end (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t'|')') }
const fn is_sym_start (c: char) -> bool { matches!(c, ':'|'@') }
const fn is_sym_char (c: char) -> bool { matches!(c, 'a'..='z'|'A'..='Z'|'0'..='9'|'-') }
const fn is_sym_end (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t'|')') }
const fn is_str_start (c: char) -> bool { matches!(c, '"') }
const fn is_str_end (c: char) -> bool { matches!(c, '"') }
const fn is_exp_start (c: char) -> bool { matches!(c, '(') }
pub const fn to_number <D: Dsl> (digits: &str) -> Result<usize, DslError> {
let mut iter = char_indices(digits);
let mut value = 0;
while let Some(((_, c), next)) = iter.next() {
match to_digit(c) {
Ok(digit) => value = 10 * value + digit,
Err(e) => return Err(e),
}
iter = next; iter = next;
} }
Ok(match t.value() { Ok(value)
Nil => None,
_ => Some(t)
})
} }
pub const fn grow (&mut self) -> DslUsually<&mut Self> { self.span.grow()?; Ok(self) } pub const fn to_digit (c: char) -> Result<usize, DslError> {
pub const fn grow_exp (&mut self, d: isize) -> &mut Self where D::Exp: From<&'s str> {
if let Val::Exp(depth, _) = self.value() {
self.value = Val::Exp((*depth as isize + d) as usize, D::Exp::from(self.span.slice_exp()));
self
} else {
unreachable!()
}
}
}
pub const fn to_digit (c: char) -> DslResult<usize> {
Ok(match c { Ok(match c {
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
_ => return Result::Err(Unexpected(c)) }) } _ => return Err(Unexpected(c))
})
macro_rules! iterate(($expr:expr => $arg: pat => $body:expr) => { }
let mut iter = $expr; while let Some(($arg, next)) = iter.next() { $body; iter = next; } }); /// `State` + [Dsl] -> `Self`.
pub const fn to_number (digits: &str) -> DslResult<usize> { pub trait FromDsl<State>: Sized {
let mut value = 0; fn try_from_dsl (state: &State, dsl: &impl Dsl) -> Perhaps<Self>;
iterate!(char_indices(digits) => (_, c) => match to_digit(c) { fn from_dsl (state: &State, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<Self> {
Ok(digit) => value = 10 * value + digit, match Self::try_from_dsl(state, dsl)? { Some(dsl) => Ok(dsl), _ => Err(err()) } }
Result::Err(e) => return Result::Err(e) }); }
Ok(value) } /// `self` + `Options` -> [Dsl]
pub trait IntoDsl { /*TODO*/ }
/// `self` + [Dsl] -> `Item`
pub trait DslInto<Item> {
fn try_dsl_into (&self, dsl: &impl Dsl) -> Perhaps<Item>;
fn dsl_into (&self, dsl: &impl Dsl, err: impl Fn()->Box<dyn Error>) -> Usually<Item> {
match Self::try_dsl_into(self, dsl)? { Some(dsl) => Ok(dsl), _ => Err(err()) } }
}
/// `self` + `Item` -> [Dsl]
pub trait DslFrom { /*TODO*/ }
/// Implement type conversions. /// Implement type conversions.
macro_rules! from(($($Struct:ty { $( macro_rules! from(($($Struct:ty { $(

View file

@ -4,24 +4,24 @@ use crate::*;
/// Each contained layer defines a mapping from input event to command invocation /// Each contained layer defines a mapping from input event to command invocation
/// over a given state. Furthermore, each layer may have an associated cond, /// over a given state. Furthermore, each layer may have an associated cond,
/// so that only certain layers are active at a given time depending on state. /// so that only certain layers are active at a given time depending on state.
#[derive(Debug)] pub struct InputMap<I, T: Dsl>( #[derive(Debug)] pub struct InputMap<I, D: Dsl>(
/// Map of input event (key combination) to /// Map of input event (key combination) to
/// all command expressions bound to it by /// all command expressions bound to it by
/// all loaded input layers. /// all loaded input layers.
pub BTreeMap<I, Vec<InputBinding<T>>> pub BTreeMap<I, Vec<InputBinding<D>>>
); );
impl<I, T: Dsl> Default for InputMap<I, T> { impl<I, D: Dsl> Default for InputMap<I, D> {
fn default () -> Self { fn default () -> Self {
Self(Default::default()) Self(Default::default())
} }
} }
#[derive(Debug, Default)] pub struct InputBinding<T: Dsl> { #[derive(Debug, Default)] pub struct InputBinding<D: Dsl> {
condition: Option<T>, condition: Option<D>,
command: T, command: D,
description: Option<Arc<str>>, description: Option<Arc<str>>,
source: Option<Arc<PathBuf>>, source: Option<Arc<PathBuf>>,
} }
impl<I: Debug + Ord, T: Dsl> InputMap<I, T> { impl<'s, I: Debug + Ord, D: Dsl + From<Cst<'s>>> InputMap<I, D> {
/// Create input layer collection from path to text file. /// Create input layer collection from path to text file.
pub fn from_path <P: Debug + AsRef<Path>> (path: P) -> Usually<Self> { pub fn from_path <P: Debug + AsRef<Path>> (path: P) -> Usually<Self> {
if !exists(path.as_ref())? { if !exists(path.as_ref())? {
@ -30,40 +30,34 @@ impl<I: Debug + Ord, T: Dsl> InputMap<I, T> {
Self::from_source(read_and_leak(path)?) Self::from_source(read_and_leak(path)?)
} }
/// Create input layer collection from string. /// Create input layer collection from string.
pub fn from_source <S: AsRef<str>> (source: S) -> Usually<Self> { pub fn from_source (source: &'s str) -> Usually<Self> {
Self::from_dsl(CstIter::from(source.as_ref())) Self::from_dsl(D::from(Cst(CstConstIter(source))))
} }
/// Create input layer collection from DSL. /// Create input layer collection from DSL.
pub fn from_dsl <D: Dsl> (dsl: D) -> Usually<Self> { pub fn from_dsl (dsl: D) -> Usually<Self> {
use DslVal::*; use Val::*;
let mut input_map: BTreeMap<I, Vec<InputBinding<T>>> = Default::default(); let mut input_map: BTreeMap<I, Vec<InputBinding<D>>> = Default::default();
let mut index = 0; match dsl.exp_head() {
while let Some(Exp(_, mut exp)) = dsl.nth(index) { Str(path) => {
let val = exp.nth(0).map(|x|x.val());
match val {
Some(Str(path)) => {
let path = PathBuf::from(path.as_ref()); let path = PathBuf::from(path.as_ref());
let module = InputMap::<I, T>::from_path(&path)?; for (key, val) in InputMap::<I, D>::from_path(&path)?.0.into_iter() {
for (key, val) in module.0.into_iter() { todo!("import {path:?} {key:?} {val:?}");
todo!("import {exp:?} {key:?} {val:?} {path:?}");
if !input_map.contains_key(&key) { if !input_map.contains_key(&key) {
input_map.insert(key, vec![]); input_map.insert(key, vec![]);
} }
} }
}, },
Some(Sym(sym)) => { Sym(sym) => {
//let key: I = sym.into(); //let key: I = sym.into();
//if !input_map.contains_key(&key) { //if !input_map.contains_key(&key) {
//input_map.insert(key, vec![]); //input_map.insert(key, vec![]);
//} //}
todo!("binding {exp:?} {sym:?}"); todo!("binding {sym:?} {:?}", dsl.exp_tail());
}, },
Some(Key(key)) if key.as_ref() == "if" => { Key(s) if s.as_ref() == "if" => {
todo!("conditional binding {exp:?} {key:?}"); todo!("conditional binding {:?}", dsl.exp_tail());
}, },
_ => return Result::Err(format!("invalid token in keymap: {val:?}").into()), _ => return Err(format!("invalid form in keymap: {dsl:?}").into())
}
index += 1;
} }
Ok(Self(input_map)) Ok(Self(input_map))
} }
@ -92,23 +86,23 @@ impl<I: Debug + Ord, T: Dsl> InputMap<I, T> {
/* /*
/// Create an input map with a single non-condal layer. /// Create an input map with a single non-condal layer.
/// (Use [Default::default] to get an empty map.) /// (Use [Default::default] to get an empty map.)
pub fn new (layer: DslVal<T::Str, T::Exp>) -> Self { pub fn new (layer: Val<T::Str, T::Exp>) -> Self {
Self::default().layer(layer) Self::default().layer(layer)
} }
/// Add layer, return `Self`. /// Add layer, return `Self`.
pub fn layer (mut self, layer: DslVal<T::Str, T::Exp>) -> Self { pub fn layer (mut self, layer: Val<T::Str, T::Exp>) -> Self {
self.add_layer(layer); self self.add_layer(layer); self
} }
/// Add condal layer, return `Self`. /// Add condal layer, return `Self`.
pub fn layer_if (mut self, cond: DslVal<T::Str, T::Exp>, layer: DslVal<T::Str, T::Exp>) -> Self { pub fn layer_if (mut self, cond: Val<T::Str, T::Exp>, layer: Val<T::Str, T::Exp>) -> Self {
self.add_layer_if(Some(cond), layer); self self.add_layer_if(Some(cond), layer); self
} }
/// Add layer, return `&mut Self`. /// Add layer, return `&mut Self`.
pub fn add_layer (&mut self, layer: DslVal<T::Str, T::Exp>) -> &mut Self { pub fn add_layer (&mut self, layer: Val<T::Str, T::Exp>) -> &mut Self {
self.add_layer_if(None, layer.into()); self self.add_layer_if(None, layer.into()); self
} }
/// Add condal layer, return `&mut Self`. /// Add condal layer, return `&mut Self`.
pub fn add_layer_if (&mut self, cond: Option<DslVal<T::Str, T::Exp>>, bind: DslVal<T::Str, T::Exp>) -> &mut Self { pub fn add_layer_if (&mut self, cond: Option<Val<T::Str, T::Exp>>, bind: Val<T::Str, T::Exp>) -> &mut Self {
self.0.push(InputLayer { cond, bind }); self.0.push(InputLayer { cond, bind });
self self
} }
@ -182,7 +176,7 @@ impl<I: Debug + Ord, T: Dsl> InputMap<I, T> {
//} //}
//fn from (source: &'s str) -> Self { //fn from (source: &'s str) -> Self {
//// this should be for single layer: //// this should be for single layer:
//use DslVal::*; //use Val::*;
//let mut layers = vec![]; //let mut layers = vec![];
//let mut source = CstIter::from(source); //let mut source = CstIter::from(source);
//while let Some(Exp(_, mut iter)) = source.next().map(|x|x.value) { //while let Some(Exp(_, mut iter)) = source.next().map(|x|x.value) {

View file

@ -392,7 +392,7 @@ transform_xy_unit!("padding/x" "padding/y" "padding/xy"|self: Padding, area|{
//)*) => { //)*) => {
//$( //$(
//impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? { //impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? {
//fn try_dsl_from ( //fn try_from_dsl (
//state: &S, dsl: &impl Dsl //state: &S, dsl: &impl Dsl
//) -> Perhaps<Self> { //) -> Perhaps<Self> {
//todo!() //todo!()
@ -408,7 +408,7 @@ transform_xy_unit!("padding/x" "padding/y" "padding/xy"|self: Padding, area|{
$op:literal $(/)? [$head: ident, $tail: ident] $expr:expr $op:literal $(/)? [$head: ident, $tail: ident] $expr:expr
) => { ) => {
impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? { impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? {
fn try_dsl_from ( fn try_from_dsl (
_state: &S, _dsl: &impl Dsl _state: &S, _dsl: &impl Dsl
) -> Perhaps<Self> { ) -> Perhaps<Self> {
todo!() todo!()
@ -423,7 +423,7 @@ transform_xy_unit!("padding/x" "padding/y" "padding/xy"|self: Padding, area|{
$op:literal $(/)? [$head: ident, $tail: ident] $expr:expr $op:literal $(/)? [$head: ident, $tail: ident] $expr:expr
) => { ) => {
impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? { impl<S,$($($A),+)?> FromDsl<S> for $Struct$(<$($A),+>)? {
fn try_dsl_from ( fn try_from_dsl (
_state: &S, _dsl: &impl Dsl _state: &S, _dsl: &impl Dsl
) -> Perhaps<Self> { ) -> Perhaps<Self> {
todo!() todo!()