mirror of
https://codeberg.org/unspeaker/tengri.git
synced 2025-12-06 11:46:42 +01:00
dsl: modularize
This commit is contained in:
parent
4fc0db5777
commit
cf253c28f9
6 changed files with 224 additions and 397 deletions
|
|
@ -22,6 +22,7 @@ version = "0.13.0"
|
|||
edition = "2024"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = { version = "1.0" }
|
||||
atomic_float = { version = "1" }
|
||||
better-panic = { version = "0.3.0" }
|
||||
const_panic = { version = "0.2.12", features = [ "derive" ] }
|
||||
|
|
|
|||
334
dsl/src/dsl.rs
334
dsl/src/dsl.rs
|
|
@ -16,331 +16,27 @@ pub(crate) use ::{
|
|||
};
|
||||
pub(crate) use self::DslError::*;
|
||||
mod dsl_conv; pub use self::dsl_conv::*;
|
||||
mod dsl_type;
|
||||
mod dsl_ns; pub use self::dsl_ns::*;
|
||||
mod dsl_src; pub use self::dsl_src::*;
|
||||
mod dsl_type; pub use self::dsl_type::*;
|
||||
#[cfg(test)] mod dsl_test;
|
||||
/// DSL-specific result type.
|
||||
pub type DslResult<T> = Result<T, DslError>;
|
||||
/// DSL-specific optional result type.
|
||||
pub type DslPerhaps<T> = Result<Option<T>, DslError>;
|
||||
/// Namespace mapping.
|
||||
pub struct DslNsMap<'t, T: 't>(pub &'t [(&'t str, T)]);
|
||||
impl<'t, T: 't> DslNsMap<'t, T> {
|
||||
/// Populate a namespace.
|
||||
pub const fn new (data: &'t [(&'t str, T)]) -> Self {
|
||||
Self(data) // TODO build search index
|
||||
}
|
||||
}
|
||||
pub trait DslNs<'t, T: 't>: 't {
|
||||
/// Known symbols.
|
||||
const SYMS: DslNsMap<'t, fn (&'t Self)->Perhaps<T>> = DslNsMap::new(&[]);
|
||||
/// Known expressions.
|
||||
const EXPS: DslNsMap<'t, fn (&'t Self, &str)->Perhaps<T>> = DslNsMap::new(&[]);
|
||||
/// Resolve a symbol if known.
|
||||
fn from_sym <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Some(dsl) = dsl.sym()? {
|
||||
for (sym, get) in Self::SYMS.0 { if dsl == *sym { return get(self) } }
|
||||
}
|
||||
return Ok(None)
|
||||
}
|
||||
/// Resolve an expression if known.
|
||||
fn from_exp <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Some(exp) = dsl.exp()? {
|
||||
for (key, value) in Self::EXPS.0.iter() {
|
||||
if exp.head() == Ok(Some(key)) { return value(self, exp.tail()?.unwrap_or("")) }
|
||||
}
|
||||
}
|
||||
return Ok(None)
|
||||
}
|
||||
/// Resolve an expression or symbol.
|
||||
fn from <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Ok(Some(src)) = dsl.src() {
|
||||
if let Ok(Some(src)) = src.sym() {
|
||||
self.from_sym(src)
|
||||
} else {
|
||||
self.from_exp(src)
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Define a namespace:
|
||||
#[macro_export] macro_rules! dsl_ns (
|
||||
(|$state:ident : $State: ty| $($Type:ty $(=> { $($pat:tt => $body:expr),* $(,)? })?;)+) => {
|
||||
$(dsl_ns!(|$state: $State| -> $Type { $( $($pat => $body),* )? });)+
|
||||
};
|
||||
(|$state:ident : $State: ty| -> $Type:ty { $($pat:tt => $body:expr),* $(,)? }) => {
|
||||
impl<'t> DslNs<'t, $Type> for $State {
|
||||
const SYMS: DslNsMap<'t, fn (&'t $State)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@sym ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
const EXPS: DslNsMap<'t, fn (&'t $State, &str)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@exp ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
}
|
||||
};
|
||||
(@sym ($state:ident: $State:ty) -> $Type:ty { $sym:literal => $body:expr }) => {
|
||||
($sym, |$state|Ok(Some($body)))
|
||||
};
|
||||
(@exp ($state:ident: $State:ty) -> $Type:ty {
|
||||
($head:literal $(,$arg:ident:$ty:ty)* $(,)*) => $body:expr
|
||||
}) => { ($head, |$state, tail: &str|{
|
||||
$(
|
||||
let head = tail.head()?.unwrap_or_default();
|
||||
let $arg: $ty = if let Some(arg) = $state.from(&head)? {
|
||||
arg
|
||||
} else {
|
||||
return Err(format!("missing argument: {}", stringify!($arg)).into())
|
||||
};
|
||||
let tail = tail.tail()?.unwrap_or_default();
|
||||
)*
|
||||
Ok(Some($body))
|
||||
}) };
|
||||
(@sym ($state:ident: $State:ty) -> $Type:ty { $pat:tt => $body:expr }) => {
|
||||
("", |_|Ok(None))
|
||||
};
|
||||
(@exp ($state:ident: $State:ty) -> $Type:ty { $pat:tt => $body:expr }) => {
|
||||
("", |_, _|Ok(None))
|
||||
};
|
||||
);
|
||||
// Some things that can be DSL source:
|
||||
impl Dsl for String { fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) } }
|
||||
impl Dsl for Arc<str> { fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) } }
|
||||
impl<'s> Dsl for &'s str { fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) } }
|
||||
|
||||
// Designates a string as parsable DSL.
|
||||
flex_trait!(Dsl: Debug + Send + Sync + Sized { fn src (&self) -> DslPerhaps<&str> { unreachable!("Dsl::src default impl") } });
|
||||
impl<D: Dsl> Dsl for Option<D> {
|
||||
fn src (&self) -> DslPerhaps<&str> {Ok(if let Some(dsl) = self { dsl.src()? } else { None })}
|
||||
}
|
||||
impl<D: Dsl> Dsl for Result<D, DslError> {
|
||||
fn src (&self) -> DslPerhaps<&str> {match self {Ok(dsl) => Ok(dsl.src()?), Err(e) => Err(*e)}}
|
||||
}
|
||||
|
||||
/// DSL-specific error codes.
|
||||
#[derive(Error, Debug, Copy, Clone, PartialEq, PanicFmt)]
|
||||
pub enum DslError {
|
||||
#[error("parse failed: not implemented")] Unimplemented,
|
||||
#[error("parse failed: empty")] Empty,
|
||||
#[error("parse failed: incomplete")] Incomplete,
|
||||
#[error("parse failed: unexpected character '{0}'")] Unexpected(char, Option<usize>, Option<&'static str>),
|
||||
#[error("parse failed: error #{0}")] Code(u8),
|
||||
#[error("end reached")] End
|
||||
}
|
||||
|
||||
fn ok_flat <T> (x: Option<DslPerhaps<T>>) -> DslPerhaps<T> { Ok(x.transpose()?.flatten()) }
|
||||
pub const fn is_space (c: char) -> bool {
|
||||
matches!(c, ' '|'\n'|'\r'|'\t')
|
||||
}
|
||||
pub const fn no_trailing_non_space (src: &str, offset: usize, context: Option<&'static str>) -> DslResult<()> {
|
||||
Ok(for_each!((i, c) in char_indices(str_range(src, offset, src.len())) => if !is_space(c) {
|
||||
return Err(Unexpected(c, Some(offset + i), if let Some(context) = context {
|
||||
Some(context)
|
||||
} else {
|
||||
Some("trailing non-space")
|
||||
}))
|
||||
}))
|
||||
}
|
||||
|
||||
pub const fn peek (src: &str) -> DslPerhaps<&str> {
|
||||
Ok(Some(if let Ok(Some(exp)) = exp_peek(src) { exp } else
|
||||
if let Ok(Some(sym)) = sym_peek(src) { sym } else
|
||||
if let Ok(Some(key)) = key_peek(src) { key } else
|
||||
if let Ok(Some(num)) = num_peek(src) { num } else
|
||||
if let Ok(Some(text)) = text_peek(src) { text } else
|
||||
if let Err(e) = no_trailing_non_space(src, 0, Some("peek")) { return Err(e) }
|
||||
else { return Ok(None) }))
|
||||
}
|
||||
pub const fn seek (src: &str) -> DslPerhaps<(usize, usize)> {
|
||||
Ok(Some(if let Ok(Some(exp)) = exp_seek(src) { exp } else
|
||||
if let Ok(Some(sym)) = sym_seek(src) { sym } else
|
||||
if let Ok(Some(key)) = key_seek(src) { key } else
|
||||
if let Ok(Some(num)) = num_seek(src) { num } else
|
||||
if let Ok(Some(text)) = text_seek(src) { text } else
|
||||
if let Err(e) = no_trailing_non_space(src, 0, Some("seek")) { return Err(e) }
|
||||
else { return Ok(None) }))
|
||||
}
|
||||
pub const fn peek_tail (src: &str) -> DslPerhaps<&str> {
|
||||
match seek(src) {
|
||||
Err(e) => Err(e),
|
||||
Ok(None) => Ok(None),
|
||||
Ok(Some((start, length))) => {
|
||||
let tail = str_range(src, start + length, src.len());
|
||||
for_each!((_i, c) in char_indices(tail) => if !is_space(c) { return Ok(Some(tail)) });
|
||||
Ok(None)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_exp_start (c: char) -> bool { c == '(' }
|
||||
pub const fn is_exp_end (c: char) -> bool { c == ')' }
|
||||
dsl_type!(DslExp {
|
||||
fn exp (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(exp_peek_inner_only))}
|
||||
fn head (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(peek))}
|
||||
fn tail (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(peek_tail))}
|
||||
/// my other car is a cdr :<
|
||||
fn each (&self, mut cb: impl FnMut(&str)->Usually<()>) -> Usually<()> {
|
||||
Ok(if let Some(head) = self.head()? {
|
||||
cb(head)?;
|
||||
if let Some(tail) = self.tail()? {
|
||||
tail.each(cb)?;
|
||||
}
|
||||
})
|
||||
}
|
||||
} {
|
||||
pub const fn exp_peek [generated];
|
||||
pub const fn exp_peek_only [generated];
|
||||
pub const fn exp_seek [generated];
|
||||
pub const fn exp_seek_start (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_exp_start(c) { return Ok(Some(i)) } else
|
||||
if !is_space(c) { return Err(Unexpected(c, Some(i), Some("expected expression start"))) });
|
||||
Ok(None)
|
||||
}
|
||||
pub const fn exp_seek_length (src) {
|
||||
let mut depth = 0;
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_exp_start(c) { depth += 1; } else
|
||||
if is_exp_end(c) {
|
||||
if depth == 0 {
|
||||
return Err(Unexpected(c, Some(i), Some("expected expression end")))
|
||||
} else if depth == 1 {
|
||||
return Ok(Some(i + 1))
|
||||
} else {
|
||||
depth -= 1;
|
||||
}
|
||||
});
|
||||
Err(Incomplete)
|
||||
}
|
||||
});
|
||||
|
||||
pub const fn exp_peek_inner (src: &str) -> DslPerhaps<&str> {
|
||||
match exp_peek(src) {
|
||||
Ok(Some(peeked)) => {
|
||||
let len = peeked.len();
|
||||
let start = if len > 0 { 1 } else { 0 };
|
||||
Ok(Some(str_range(src, start, start + len.saturating_sub(2))))
|
||||
},
|
||||
e => e
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn exp_peek_inner_only (src: &str) -> DslPerhaps<&str> {
|
||||
match exp_seek(src) {
|
||||
Err(e) => Err(e),
|
||||
Ok(None) => Ok(None),
|
||||
Ok(Some((start, length))) => {
|
||||
if let Err(e) = no_trailing_non_space(src, start + length, Some("exp_peek_inner_only")) { return Err(e) }
|
||||
let peeked = str_range(src, start, start + length);
|
||||
let len = peeked.len();
|
||||
let start = if len > 0 { 1 } else { 0 };
|
||||
Ok(Some(str_range(peeked, start, start + len.saturating_sub(2))))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_sym_start (c: char) -> bool { matches!(c, ':'|'@') }
|
||||
pub const fn is_sym_char (c: char) -> bool { is_sym_start(c) || matches!(c, 'a'..='z'|'A'..='Z'|'0'..='9'|'-'|'/') }
|
||||
pub const fn is_sym_end (c: char) -> bool { is_space(c) || matches!(c, ')') }
|
||||
dsl_type!(DslSym {
|
||||
fn sym (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(sym_peek_only))}
|
||||
} {
|
||||
pub const fn sym_peek [generated];
|
||||
pub const fn sym_peek_only [generated];
|
||||
pub const fn sym_seek [generated];
|
||||
pub const fn sym_seek_start (src) {
|
||||
for_each!((i, c) in char_indices(src) => if
|
||||
is_sym_start(c) { return Ok(Some(i)) } else
|
||||
if !is_space(c) { return Err(Unexpected(c, Some(i), Some("sym_seek_start"))) });
|
||||
Ok(None)
|
||||
}
|
||||
pub const fn sym_seek_length (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_sym_end(c) { return Ok(Some(i)) } else
|
||||
if !is_sym_char(c) { return Err(Unexpected(c, Some(i), Some("sym_seek_length"))) });
|
||||
Ok(Some(src.len()))
|
||||
}
|
||||
});
|
||||
|
||||
pub const fn is_text_start (c: char) -> bool { matches!(c, '"') }
|
||||
pub const fn is_text_end (c: char) -> bool { matches!(c, '"') }
|
||||
dsl_type!(DslText {
|
||||
fn text (&self) -> DslPerhaps<&str> { ok_flat(self.src()?.map(text_peek_only)) }
|
||||
} {
|
||||
pub const fn text_peek [generated];
|
||||
pub const fn text_peek_only [generated];
|
||||
pub const fn text_seek [generated];
|
||||
pub const fn text_seek_start (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_text_start(c) { return Ok(Some(i)) } else
|
||||
if !is_space(c) { return Err(Unexpected(c, Some(i), None)) });
|
||||
Ok(None)
|
||||
}
|
||||
pub const fn text_seek_length (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_text_end(c) { return Ok(Some(i)) });
|
||||
Ok(None)
|
||||
}
|
||||
});
|
||||
|
||||
pub const fn is_key_start (c: char) -> bool { matches!(c, '/'|('a'..='z')) }
|
||||
pub const fn is_key_char (c: char) -> bool { is_key_start(c) || matches!(c, '0'..='9'|'-') }
|
||||
pub const fn is_key_end (c: char) -> bool { !is_key_char(c) }
|
||||
dsl_type!(DslKey {
|
||||
fn key (&self) -> DslPerhaps<&str> { ok_flat(self.src()?.map(key_peek_only)) }
|
||||
} {
|
||||
pub const fn key_peek [generated];
|
||||
pub const fn key_peek_only [generated];
|
||||
pub const fn key_seek [generated];
|
||||
pub const fn key_seek_start (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_key_start(c) { return Ok(Some(i)) } else
|
||||
if !is_space(c) { return Err(Unexpected(c, Some(i), None)) });
|
||||
Ok(None)
|
||||
}
|
||||
pub const fn key_seek_length (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_key_end(c) { return Ok(Some(i)) } else
|
||||
if !is_key_char(c) { return Err(Unexpected(c, Some(i), None)) });
|
||||
Ok(Some(src.len()))
|
||||
}
|
||||
});
|
||||
|
||||
dsl_type!(DslNum {
|
||||
fn num (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(num_peek_only))}
|
||||
} {
|
||||
pub const fn num_peek [generated];
|
||||
pub const fn num_peek_only [generated];
|
||||
pub const fn num_seek [generated];
|
||||
pub const fn num_seek_start (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_digit(c) { return Ok(Some(i)); } else
|
||||
if !is_space(c) { return Err(Unexpected(c, Some(i), None)) });
|
||||
Ok(None)
|
||||
}
|
||||
pub const fn num_seek_length (src) {
|
||||
for_each!((i, c) in char_indices(src) =>
|
||||
if is_num_end(c) { return Ok(Some(i)) } else
|
||||
if !is_digit(c) { return Err(Unexpected(c, Some(i), None)) });
|
||||
Ok(None)
|
||||
}
|
||||
});
|
||||
pub const fn is_digit (c: char) -> bool { matches!(c, '0'..='9') }
|
||||
pub const fn is_num_end (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t'|')') }
|
||||
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;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
pub const fn to_digit (c: char) -> Result<usize, DslError> {
|
||||
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, None, Some("parse digit")))
|
||||
})
|
||||
#[error("parse failed: not implemented")]
|
||||
Unimplemented,
|
||||
#[error("parse failed: empty")]
|
||||
Empty,
|
||||
#[error("parse failed: incomplete")]
|
||||
Incomplete,
|
||||
#[error("parse failed: unexpected character '{0}'")]
|
||||
Unexpected(char, Option<usize>, Option<&'static str>),
|
||||
#[error("parse failed: error #{0}")]
|
||||
Code(u8),
|
||||
#[error("end reached")]
|
||||
End
|
||||
}
|
||||
|
|
|
|||
118
dsl/src/dsl_ns.rs
Normal file
118
dsl/src/dsl_ns.rs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
use crate::*;
|
||||
/// Define a namespace:
|
||||
#[macro_export] macro_rules! dsl_ns (
|
||||
// Special form for numeric types
|
||||
(num |$state:ident : $State: ty| $($($num:lifetime)? $Type:ty $(=> { $(
|
||||
$pat:tt => $body:expr
|
||||
),* $(,)? })?;)+) => {
|
||||
$(dsl_ns!(num |$state: $State| -> $($num)? $Type { $( $($pat => $body),* )? });)+
|
||||
};
|
||||
// Special form for numeric types
|
||||
(num |$state:ident : $State: ty| -> $Type:ty { $( $pat:tt => $body:expr ),* $(,)? }) => {
|
||||
impl<'t> DslNs<'t, $Type> for $State {
|
||||
const SYMS: DslNsMap<'t, fn (&'t $State)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@sym ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
const EXPS: DslNsMap<'t, fn (&'t $State, &str)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@exp ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
fn from <D: Dsl> (&'t self, dsl: D) -> Perhaps<$Type> {
|
||||
if let Ok(Some(src)) = dsl.src() {
|
||||
if let Ok(Some(num)) = src.num() {
|
||||
Ok(Some(to_number(num)? as $Type))
|
||||
} else if let Ok(Some(src)) = src.sym() {
|
||||
self.from_sym(src)
|
||||
} else {
|
||||
self.from_exp(src)
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// A namespace may resolve one or more types.
|
||||
(|$state:ident : $State: ty| $($Type:ty $(=> { $( $pat:tt => $body:expr ),* $(,)? })? ;)+) => {
|
||||
$(dsl_ns!(|$state: $State| -> $Type { $( $($pat => $body),* )? });)+
|
||||
};
|
||||
// Regular form for single type
|
||||
(|$state:ident : $State: ty| -> $Type:ty { $( $pat:tt => $body:expr ),* $(,)? }) => {
|
||||
impl<'t> DslNs<'t, $Type> for $State {
|
||||
const SYMS: DslNsMap<'t, fn (&'t $State)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@sym ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
const EXPS: DslNsMap<'t, fn (&'t $State, &str)->Perhaps<$Type>> =
|
||||
DslNsMap::new(&[$(dsl_ns!{@exp ($state: $State) -> $Type { $pat => $body }}),*]);
|
||||
}
|
||||
};
|
||||
// Symbols only.
|
||||
(@sym ($state:ident: $State:ty) -> $Type:ty {
|
||||
$sym:literal => $body:expr
|
||||
}) => {
|
||||
($sym, |$state|Ok(Some($body)))
|
||||
};
|
||||
// Expression handlers only.
|
||||
(@exp ($state:ident: $State:ty) -> $Type:ty {
|
||||
($head:literal $(,$arg:ident:$ty:ty)* $(,)*) => $body:expr
|
||||
}) => { ($head, |$state, tail: &str|{
|
||||
$(
|
||||
let head = tail.head()?.unwrap_or_default();
|
||||
let $arg: $ty = if let Some(arg) = $state.from(&head)? {
|
||||
arg
|
||||
} else {
|
||||
return Err(format!("missing argument: {}", stringify!($arg)).into())
|
||||
};
|
||||
let tail = tail.tail()?.unwrap_or_default();
|
||||
)*
|
||||
Ok(Some($body))
|
||||
}) };
|
||||
// Nothing else in symbols.
|
||||
(@sym ($state:ident: $State:ty) -> $Type:ty { $pat:tt => $body:expr }) => {
|
||||
("", |_|Ok(None)) // FIXME don't emit at all
|
||||
};
|
||||
// Nothing else in expression handlers.
|
||||
(@exp ($state:ident: $State:ty) -> $Type:ty { $pat:tt => $body:expr }) => {
|
||||
("", |_, _|Ok(None)) // FIXME don't emit at all
|
||||
};
|
||||
|
||||
);
|
||||
|
||||
pub trait DslNs<'t, T: 't>: 't {
|
||||
/// Known symbols.
|
||||
const SYMS: DslNsMap<'t, fn (&'t Self)->Perhaps<T>> = DslNsMap::new(&[]);
|
||||
/// Known expressions.
|
||||
const EXPS: DslNsMap<'t, fn (&'t Self, &str)->Perhaps<T>> = DslNsMap::new(&[]);
|
||||
/// Resolve a symbol if known.
|
||||
fn from_sym <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Some(dsl) = dsl.sym()? {
|
||||
for (sym, get) in Self::SYMS.0 { if dsl == *sym { return get(self) } }
|
||||
}
|
||||
return Ok(None)
|
||||
}
|
||||
/// Resolve an expression if known.
|
||||
fn from_exp <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Some(exp) = dsl.exp()? {
|
||||
for (key, value) in Self::EXPS.0.iter() {
|
||||
if exp.head() == Ok(Some(key)) { return value(self, exp.tail()?.unwrap_or("")) }
|
||||
}
|
||||
}
|
||||
return Ok(None)
|
||||
}
|
||||
/// Resolve an expression or symbol.
|
||||
fn from <D: Dsl> (&'t self, dsl: D) -> Perhaps<T> {
|
||||
if let Ok(Some(src)) = dsl.src() {
|
||||
if let Ok(Some(src)) = src.sym() {
|
||||
self.from_sym(src)
|
||||
} else {
|
||||
self.from_exp(src)
|
||||
}
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Namespace mapping.
|
||||
pub struct DslNsMap<'t, T: 't>(pub &'t [(&'t str, T)]);
|
||||
impl<'t, T: 't> DslNsMap<'t, T> {
|
||||
/// Populate a namespace.
|
||||
pub const fn new (data: &'t [(&'t str, T)]) -> Self {
|
||||
Self(data) // TODO build search index
|
||||
}
|
||||
}
|
||||
21
dsl/src/dsl_src.rs
Normal file
21
dsl/src/dsl_src.rs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
use crate::*;
|
||||
// Designates a string as parsable DSL.
|
||||
flex_trait!(Dsl: Debug + Send + Sync + Sized {
|
||||
fn src (&self) -> DslPerhaps<&str> { unreachable!("Dsl::src default impl") }
|
||||
});
|
||||
// Some things that can be DSL source:
|
||||
impl Dsl for String {
|
||||
fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) }
|
||||
}
|
||||
impl Dsl for Arc<str> {
|
||||
fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) }
|
||||
}
|
||||
impl<'s> Dsl for &'s str {
|
||||
fn src (&self) -> DslPerhaps<&str> { Ok(Some(self.as_ref())) }
|
||||
}
|
||||
impl<D: Dsl> Dsl for Option<D> {
|
||||
fn src (&self) -> DslPerhaps<&str> {Ok(if let Some(dsl) = self { dsl.src()? } else { None })}
|
||||
}
|
||||
impl<D: Dsl> Dsl for Result<D, DslError> {
|
||||
fn src (&self) -> DslPerhaps<&str> {match self {Ok(dsl) => Ok(dsl.src()?), Err(e) => Err(*e)}}
|
||||
}
|
||||
|
|
@ -1,5 +1,50 @@
|
|||
use crate::*;
|
||||
|
||||
fn ok_flat <T> (x: Option<DslPerhaps<T>>) -> DslPerhaps<T> {
|
||||
Ok(x.transpose()?.flatten())
|
||||
}
|
||||
pub const fn is_space (c: char) -> bool {
|
||||
matches!(c, ' '|'\n'|'\r'|'\t')
|
||||
}
|
||||
pub const fn no_trailing_non_space (
|
||||
src: &str, offset: usize, context: Option<&'static str>
|
||||
) -> DslResult<()> {
|
||||
Ok(for_each!((i, c) in char_indices(str_range(src, offset, src.len())) => if !is_space(c) {
|
||||
return Err(Unexpected(c, Some(offset + i), if let Some(context) = context {
|
||||
Some(context)
|
||||
} else {
|
||||
Some("trailing non-space")
|
||||
}))
|
||||
}))
|
||||
}
|
||||
pub const fn peek (src: &str) -> DslPerhaps<&str> {
|
||||
Ok(Some(if let Ok(Some(exp)) = exp_peek(src) { exp } else
|
||||
if let Ok(Some(sym)) = sym_peek(src) { sym } else
|
||||
if let Ok(Some(num)) = num_peek(src) { num } else
|
||||
if let Ok(Some(text)) = text_peek(src) { text } else
|
||||
if let Err(e) = no_trailing_non_space(src, 0, Some("peek")) { return Err(e) }
|
||||
else { return Ok(None) }))
|
||||
}
|
||||
pub const fn seek (src: &str) -> DslPerhaps<(usize, usize)> {
|
||||
Ok(Some(if let Ok(Some(exp)) = exp_seek(src) { exp } else
|
||||
if let Ok(Some(sym)) = sym_seek(src) { sym } else
|
||||
if let Ok(Some(num)) = num_seek(src) { num } else
|
||||
if let Ok(Some(text)) = text_seek(src) { text } else
|
||||
if let Err(e) = no_trailing_non_space(src, 0, Some("seek")) { return Err(e) }
|
||||
else { return Ok(None) }))
|
||||
}
|
||||
pub const fn peek_tail (src: &str) -> DslPerhaps<&str> {
|
||||
match seek(src) {
|
||||
Err(e) => Err(e),
|
||||
Ok(None) => Ok(None),
|
||||
Ok(Some((start, length))) => {
|
||||
let tail = str_range(src, start + length, src.len());
|
||||
for_each!((_i, c) in char_indices(tail) => if !is_space(c) { return Ok(Some(tail)) });
|
||||
Ok(None)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! dsl_type (($T:ident { $($trait:tt)* } {
|
||||
pub const fn $peek:ident $($_1:tt)?;
|
||||
pub const fn $peek_only:ident $($_2:tt)?;
|
||||
|
|
@ -113,9 +158,9 @@ pub const fn exp_peek_inner_only (src: &str) -> DslPerhaps<&str> {
|
|||
}
|
||||
}
|
||||
|
||||
pub const fn is_sym_start (c: char) -> bool { matches!(c, ':'|'@') }
|
||||
pub const fn is_sym_char (c: char) -> bool { is_sym_start(c) || matches!(c, 'a'..='z'|'A'..='Z'|'0'..='9'|'-'|'/') }
|
||||
pub const fn is_sym_end (c: char) -> bool { is_space(c) || matches!(c, ')') }
|
||||
pub const fn is_sym_start (c: char) -> bool { is_sym_char(c) }
|
||||
pub const fn is_sym_char (c: char) -> bool { matches!(c, 'a'..='z'|'A'..='Z'|'0'..='9'|'-'|'/'|'@'|':') }
|
||||
pub const fn is_sym_end (c: char) -> bool { is_space(c) || is_exp_end(c) }
|
||||
dsl_type!(DslSym {
|
||||
fn sym (&self) -> DslPerhaps<&str> {ok_flat(self.src()?.map(sym_peek_only))}
|
||||
} {
|
||||
|
|
@ -201,7 +246,7 @@ dsl_type!(DslNum {
|
|||
});
|
||||
pub const fn is_digit (c: char) -> bool { matches!(c, '0'..='9') }
|
||||
pub const fn is_num_end (c: char) -> bool { matches!(c, ' '|'\n'|'\r'|'\t'|')') }
|
||||
pub const fn to_number <D: Dsl> (digits: &str) -> Result<usize, DslError> {
|
||||
pub const fn to_number (digits: &str) -> Result<usize, DslError> {
|
||||
let mut iter = char_indices(digits);
|
||||
let mut value = 0;
|
||||
while let Some(((_, c), next)) = iter.next() {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,5 @@
|
|||
use crate::*;
|
||||
use std::{sync::Arc, collections::BTreeMap, path::{Path, PathBuf}, fs::{exists, read_to_string}};
|
||||
/// Map of each event (e.g. key combination) to
|
||||
/// all command expressions bound to it by
|
||||
/// all loaded input layers.
|
||||
type EventMapImpl<E, C> = BTreeMap<E, Vec<Binding<C>>>;
|
||||
/// A collection of input bindings.
|
||||
///
|
||||
/// Each contained layer defines a mapping from input event to command invocation
|
||||
|
|
@ -14,15 +10,33 @@ type EventMapImpl<E, C> = BTreeMap<E, Vec<Binding<C>>>;
|
|||
/// When the first non-conditional or true conditional binding is executed,
|
||||
/// that .event()binding's value is returned.
|
||||
#[derive(Debug)]
|
||||
pub struct EventMap<E, C>(pub EventMapImpl<E, C>);
|
||||
pub struct EventMap<E, C>(
|
||||
/// Map of each event (e.g. key combination) to
|
||||
/// all command expressions bound to it by
|
||||
/// all loaded input layers.
|
||||
pub BTreeMap<E, Vec<Binding<C>>>
|
||||
);
|
||||
/// An input binding.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Binding<C> {
|
||||
pub command: C,
|
||||
pub commands: Arc<[C]>,
|
||||
pub condition: Option<Condition>,
|
||||
pub description: Option<Arc<str>>,
|
||||
pub source: Option<Arc<PathBuf>>,
|
||||
}
|
||||
impl<C> Binding<C> {
|
||||
pub fn from_dsl (dsl: impl Dsl) -> Usually<Self> {
|
||||
let command: Option<C> = None;
|
||||
let condition: Option<Condition> = None;
|
||||
let description: Option<Arc<str>> = None;
|
||||
let source: Option<Arc<PathBuf>> = None;
|
||||
if let Some(command) = command {
|
||||
Ok(Self { commands: [command].into(), condition, description, source })
|
||||
} else {
|
||||
Err(format!("no command in {dsl:?}").into())
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Input bindings are only returned if this evaluates to true
|
||||
#[derive(Clone)]
|
||||
pub struct Condition(Arc<Box<dyn Fn()->bool + Send + Sync>>);
|
||||
|
|
@ -59,72 +73,4 @@ impl<E: Clone + Ord, C> EventMap<E, C> {
|
|||
.map(|bb|bb.iter().filter(|b|b.condition.as_ref().map(|c|(c.0)()).unwrap_or(true)).next())
|
||||
.flatten()
|
||||
}
|
||||
/// Create event map from path to text file.
|
||||
pub fn load_from_path <'s> (
|
||||
&'s mut self, path: impl AsRef<Path>
|
||||
) -> Usually<&'s mut Self> where Self: DslInto<C> + DslInto<E> {
|
||||
if exists(path.as_ref())? {
|
||||
let source = read_to_string(&path)?;
|
||||
let path: Arc<PathBuf> = Arc::new(path.as_ref().into());
|
||||
self.load_from_source(&source, &Some(&path))
|
||||
} else {
|
||||
return Err(format!("(e5) not found: {:?}", path.as_ref()).into())
|
||||
}
|
||||
}
|
||||
/// Create event map from DSL tokenizer.
|
||||
pub fn load_from_source (
|
||||
&mut self, dsl: impl Dsl, path: &Option<&Arc<PathBuf>>
|
||||
) -> Usually<&mut Self> where Self: DslInto<C> + DslInto<E> {
|
||||
dsl.each(|dsl|self.load_from_source_one(&dsl, path).map(move|_|()))?;
|
||||
Ok(self)
|
||||
}
|
||||
/// Load one event binding into the event map.
|
||||
pub fn load_from_source_one <'s> (
|
||||
&'s mut self, dsl: impl Dsl, path: &Option<&Arc<PathBuf>>
|
||||
) -> Usually<&'s mut Self> where Self: DslInto<C> + DslInto<E> {
|
||||
if let Some(exp) = dsl.head()?.exp()?
|
||||
&& let Some(sym) = exp.head()?.sym()?
|
||||
&& let Some(tail) = exp.tail()?
|
||||
{
|
||||
let event = self.dsl_into_or_else(&sym, ||panic!())?;
|
||||
let command = self.dsl_into_or_else(&tail, ||panic!())?;
|
||||
Ok(self.add(event, Binding {
|
||||
command, condition: None, description: None, source: path.cloned()
|
||||
}))
|
||||
} else {
|
||||
Err(format!("unexpected: {:?}", dsl.head()?).into())
|
||||
}
|
||||
}
|
||||
//})Ok(if let Some(sym) = dsl.head()?.exp()?.head()?.sym()? {
|
||||
//if let Some(tail) = dsl.head()?.exp()?.tail()? {
|
||||
//let event: E = sym.into();
|
||||
//let binding: Binding<C> = Binding { command: tail.into(), condition: None, description: None, source: None };
|
||||
//if let Some(bindings) = map.0.get_mut(&event) {
|
||||
//bindings.push(binding);
|
||||
//} else {
|
||||
//map.0.insert(event, vec![binding]);
|
||||
//}
|
||||
//} else {
|
||||
//panic!("empty binding: {}", dsl.head()?.exp()?.unwrap_or_default())
|
||||
//}
|
||||
//} else if let Some(ref text) = dsl.text()? {
|
||||
//map.0.extend(Self::from_path(PathBuf::from(text))?.0);
|
||||
//} else {
|
||||
//return Err(format!("unexpected: {dsl:?}").into())
|
||||
//}));
|
||||
//Ok(map)
|
||||
//}
|
||||
}
|
||||
impl<C> Binding<C> {
|
||||
pub fn from_dsl (dsl: impl Dsl) -> Usually<Self> {
|
||||
let command: Option<C> = None;
|
||||
let condition: Option<Condition> = None;
|
||||
let description: Option<Arc<str>> = None;
|
||||
let source: Option<Arc<PathBuf>> = None;
|
||||
if let Some(command) = command {
|
||||
Ok(Self { command, condition, description, source })
|
||||
} else {
|
||||
Err(format!("no command in {dsl:?}").into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue