mirror of
https://codeberg.org/unspeaker/tengri.git
synced 2025-12-06 03:36:42 +01:00
This commit is contained in:
parent
91dc77cfea
commit
11f686650f
19 changed files with 964 additions and 918 deletions
|
|
@ -1,31 +1,38 @@
|
|||
//! The abstract syntax tree (AST) can be produced from the CST
|
||||
//! by cloning source slices into owned ([Arc]) string slices.
|
||||
use crate::*;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Ast(pub AstValue);
|
||||
pub struct Ast(pub Arc<VecDeque<DslVal<Arc<str>, Ast>>>);
|
||||
|
||||
/// The abstract syntax tree (AST) can be produced from the CST
|
||||
/// by cloning source slices into owned [Arc] values.
|
||||
pub type AstValue = DslValue<Arc<str>, VecDeque<Ast>>;
|
||||
|
||||
//#[derive(Debug, Clone, Default, PartialEq)]
|
||||
//pub struct AstIter();
|
||||
|
||||
impl<'src> From<Cst<'src>> for Ast {
|
||||
fn from (token: Cst<'src>) -> Self {
|
||||
token.value().into()
|
||||
impl Dsl for Ast {
|
||||
type Str = Arc<str>;
|
||||
type Exp = Ast;
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Self::Str, Self::Exp>> {
|
||||
self.0.get(index).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> From<CstValue<'src>> for Ast {
|
||||
fn from (value: CstValue<'src>) -> Self {
|
||||
Self(match value {
|
||||
DslValue::Nil => DslValue::Nil,
|
||||
DslValue::Err(e) => DslValue::Err(e),
|
||||
DslValue::Num(u) => DslValue::Num(u),
|
||||
DslValue::Sym(s) => DslValue::Sym(s.into()),
|
||||
DslValue::Key(s) => DslValue::Key(s.into()),
|
||||
DslValue::Str(s) => DslValue::Str(s.into()),
|
||||
DslValue::Exp(d, x) => DslValue::Exp(d, x.map(|x|x.into()).collect()),
|
||||
})
|
||||
impl<'s> From<Cst<'s>> for Ast {
|
||||
fn from (cst: Cst<'s>) -> Self {
|
||||
Self(VecDeque::from([dsl_val(cst.val())]).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s> From<CstIter<'s>> for Ast {
|
||||
fn from (cst: CstIter<'s>) -> Self {
|
||||
Self(cst.map(|x|x.value.into()).collect::<VecDeque<_>>().into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s> From<CstVal<'s>> for Ast {
|
||||
fn from (cst: CstVal<'s>) -> Self {
|
||||
Self(VecDeque::from([dsl_val(cst.val())]).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'s> From<DslVal<&'s str, CstIter<'s>>> for DslVal<Arc<str>, Ast> {
|
||||
fn from (cst: DslVal<&'s str, CstIter<'s>>) -> Self {
|
||||
dsl_val(cst)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
447
dsl/src/cst.rs
447
dsl/src/cst.rs
|
|
@ -1,9 +1,219 @@
|
|||
//! The concrete syntax tree (CST) implements zero-copy
|
||||
//! parsing of the DSL from a string reference. CST items
|
||||
//! preserve info about their location in the source.
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// CST stores strings as source references and expressions as [CstIter] instances.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Cst<'src>(pub CstIter<'src>);
|
||||
impl<'src> Dsl for Cst<'src> {
|
||||
type Str = &'src str;
|
||||
type Exp = CstIter<'src>;
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Self::Str, Self::Exp>> {
|
||||
self.0.nth(index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed substring with range and value.
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq)]
|
||||
pub struct CstVal<'src> {
|
||||
/// Meaning of token.
|
||||
pub value: DslVal<&'src str, CstIter<'src>>,
|
||||
/// Reference to source text.
|
||||
pub source: &'src str,
|
||||
/// Index of 1st character of token.
|
||||
pub start: usize,
|
||||
/// Length of token.
|
||||
pub length: usize,
|
||||
}
|
||||
impl<'src> Dsl for CstVal<'src> {
|
||||
type Str = &'src str;
|
||||
type Exp = CstIter<'src>;
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Self::Str, Self::Exp>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> CstVal<'src> {
|
||||
pub const fn new (
|
||||
source: &'src str,
|
||||
start: usize,
|
||||
length: usize,
|
||||
value: DslVal<&'src str, CstIter<'src>>
|
||||
) -> Self {
|
||||
Self { source, start, length, value }
|
||||
}
|
||||
pub const fn end (&self) -> usize {
|
||||
self.start.saturating_add(self.length)
|
||||
}
|
||||
pub const fn slice (&'src self) -> &'src str {
|
||||
self.slice_source(self.source)
|
||||
}
|
||||
pub const fn slice_source <'range> (&'src self, source: &'range str) -> &'range str {
|
||||
str_range(source, self.start, self.end())
|
||||
}
|
||||
pub const fn slice_source_exp <'range> (&'src self, source: &'range str) -> &'range str {
|
||||
str_range(source, self.start.saturating_add(1), self.end())
|
||||
}
|
||||
pub const fn with_value (self, value: DslVal<&'src str, CstIter<'src>>) -> Self {
|
||||
Self { value, ..self }
|
||||
}
|
||||
pub const fn value (&self) -> DslVal<&'src str, CstIter<'src>> {
|
||||
self.value
|
||||
}
|
||||
pub const fn error (self, error: DslErr) -> Self {
|
||||
Self { value: DslVal::Err(error), ..self }
|
||||
}
|
||||
pub const fn grow (self) -> Self {
|
||||
Self { length: self.length.saturating_add(1), ..self }
|
||||
}
|
||||
pub const fn grow_num (self, m: usize, c: char) -> Self {
|
||||
match to_digit(c) {
|
||||
Result::Ok(n) => Self { value: DslVal::Num(10*m+n), ..self.grow() },
|
||||
Result::Err(e) => Self { value: DslVal::Err(e), ..self.grow() },
|
||||
}
|
||||
}
|
||||
pub const fn grow_key (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslVal::Key(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_sym (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslVal::Sym(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_str (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslVal::Str(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_exp (self) -> Self {
|
||||
let token = self.grow();
|
||||
if let DslVal::Exp(depth, _) = token.value() {
|
||||
token.with_value(DslVal::Exp(depth, CstIter::new(token.slice_source_exp(self.source))))
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
pub const fn grow_in (self) -> Self {
|
||||
let token = self.grow_exp();
|
||||
if let DslVal::Exp(depth, source) = token.value() {
|
||||
token.with_value(DslVal::Exp(depth.saturating_add(1), source))
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
pub const fn grow_out (self) -> Self {
|
||||
let token = self.grow_exp();
|
||||
if let DslVal::Exp(depth, source) = token.value() {
|
||||
if depth > 0 {
|
||||
token.with_value(DslVal::Exp(depth - 1, source))
|
||||
} else {
|
||||
return self.error(Unexpected(')'))
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides a native [Iterator] API over [CstConstIter],
|
||||
/// emitting [Cst] items.
|
||||
///
|
||||
/// [Cst::next] returns just the [Cst] and mutates `self`,
|
||||
/// instead of returning an updated version of the struct as [CstConstIter::next] does.
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct CstIter<'src>(pub CstConstIter<'src>);
|
||||
impl<'src> Dsl for CstIter<'src> {
|
||||
type Str = &'src str;
|
||||
type Exp = Self;
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Self::Str, Self::Exp>> {
|
||||
use DslVal::*;
|
||||
self.0.nth(index).map(|x|match x {
|
||||
Nil => Nil,
|
||||
Err(e) => Err(e),
|
||||
Num(u) => Num(u),
|
||||
Sym(s) => Sym(s),
|
||||
Key(s) => Sym(s),
|
||||
Str(s) => Sym(s),
|
||||
Exp(d, x) => DslVal::Exp(d, CstIter(x)),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<'src> CstIter<'src> {
|
||||
pub const fn new (source: &'src str) -> Self {
|
||||
Self(CstConstIter::new(source))
|
||||
}
|
||||
pub const fn peek (&self) -> Option<CstVal<'src>> {
|
||||
self.0.peek()
|
||||
}
|
||||
}
|
||||
impl<'src> Iterator for CstIter<'src> {
|
||||
type Item = CstVal<'src>;
|
||||
fn next (&mut self) -> Option<CstVal<'src>> {
|
||||
self.0.next().map(|(item, rest)|{
|
||||
self.0 = rest;
|
||||
item
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<'src> Into<Vec<CstVal<'src>>> for CstIter<'src> {
|
||||
fn into (self) -> Vec<CstVal<'src>> {
|
||||
self.collect()
|
||||
}
|
||||
}
|
||||
impl<'src> Into<Vec<Ast>> for CstIter<'src> {
|
||||
fn into (self) -> Vec<Ast> {
|
||||
self.map(Into::into).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns a reference to the source text.
|
||||
/// [CstConstIter::next] emits subsequent pairs of:
|
||||
/// * a [Cst] and
|
||||
/// * the source text remaining
|
||||
/// * [ ] TODO: maybe [CstConstIter::next] should wrap the remaining source in `Self` ?
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct CstConstIter<'src>(pub &'src str);
|
||||
impl<'src> Dsl for CstConstIter<'src> {
|
||||
type Str = &'src str;
|
||||
type Exp = Self;
|
||||
fn nth (&self, mut index: usize) -> Option<DslVal<Self::Str, Self::Exp>> {
|
||||
use DslVal::*;
|
||||
let mut iter = self.clone();
|
||||
for i in 0..index {
|
||||
iter = iter.next()?.1
|
||||
}
|
||||
iter.next().map(|(x, _)|match x.value {
|
||||
Nil => Nil,
|
||||
Err(e) => Err(e),
|
||||
Num(u) => Num(u),
|
||||
Sym(s) => Sym(s),
|
||||
Key(s) => Sym(s),
|
||||
Str(s) => Sym(s),
|
||||
Exp(d, x) => DslVal::Exp(d, x.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<'src> CstConstIter<'src> {
|
||||
pub const fn new (source: &'src str) -> Self {
|
||||
Self(source)
|
||||
}
|
||||
pub const fn chomp (&self, index: usize) -> Self {
|
||||
Self(split_at(self.0, index).1)
|
||||
}
|
||||
pub const fn next (mut self) -> Option<(CstVal<'src>, Self)> {
|
||||
Self::next_mut(&mut self)
|
||||
}
|
||||
pub const fn peek (&self) -> Option<CstVal<'src>> {
|
||||
peek_src(self.0)
|
||||
}
|
||||
pub const fn next_mut (&mut self) -> Option<(CstVal<'src>, Self)> {
|
||||
match self.peek() {
|
||||
Some(token) => Some((token, self.chomp(token.end()))),
|
||||
None => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement the const iterator pattern.
|
||||
macro_rules! const_iter {
|
||||
($(<$l:lifetime>)?|$self:ident: $Struct:ty| => $Item:ty => $expr:expr) => {
|
||||
|
|
@ -19,6 +229,10 @@ macro_rules! const_iter {
|
|||
}
|
||||
}
|
||||
|
||||
const_iter!(<'src>|self: CstConstIter<'src>|
|
||||
=> CstVal<'src>
|
||||
=> self.next_mut().map(|(result, _)|result));
|
||||
|
||||
/// Static iteration helper used by [cst].
|
||||
macro_rules! iterate {
|
||||
($expr:expr => $arg: pat => $body:expr) => {
|
||||
|
|
@ -30,140 +244,26 @@ macro_rules! iterate {
|
|||
}
|
||||
}
|
||||
|
||||
/// CST stores strings as source references and expressions as [SourceIter] instances.
|
||||
pub type CstValue<'source> = DslValue<&'source str, SourceIter<'source>>;
|
||||
|
||||
/// Token sharing memory with source reference.
|
||||
#[derive(Debug, Copy, Clone, Default, PartialEq)]
|
||||
pub struct Cst<'src> {
|
||||
/// Reference to source text.
|
||||
pub source: &'src str,
|
||||
/// Index of 1st character of token.
|
||||
pub start: usize,
|
||||
/// Length of token.
|
||||
pub length: usize,
|
||||
/// Meaning of token.
|
||||
pub value: CstValue<'src>,
|
||||
}
|
||||
|
||||
impl<'src> Cst<'src> {
|
||||
pub const fn new (
|
||||
source: &'src str,
|
||||
start: usize,
|
||||
length: usize,
|
||||
value: CstValue<'src>
|
||||
) -> Self {
|
||||
Self { source, start, length, value }
|
||||
}
|
||||
pub const fn end (&self) -> usize {
|
||||
self.start.saturating_add(self.length)
|
||||
}
|
||||
pub const fn slice (&'src self) -> &'src str {
|
||||
self.slice_source(self.source)
|
||||
}
|
||||
pub const fn slice_source <'range> (&'src self, source: &'range str) -> &'range str {
|
||||
str_range(source, self.start, self.end())
|
||||
}
|
||||
pub const fn slice_source_exp <'range> (&'src self, source: &'range str) -> &'range str {
|
||||
str_range(source, self.start.saturating_add(1), self.end())
|
||||
}
|
||||
pub const fn with_value (self, value: CstValue<'src>) -> Self {
|
||||
Self { value, ..self }
|
||||
}
|
||||
pub const fn value (&self) -> CstValue<'src> {
|
||||
self.value
|
||||
}
|
||||
pub const fn error (self, error: DslError) -> Self {
|
||||
Self { value: DslValue::Err(error), ..self }
|
||||
}
|
||||
pub const fn grow (self) -> Self {
|
||||
Self { length: self.length.saturating_add(1), ..self }
|
||||
}
|
||||
pub const fn grow_num (self, m: usize, c: char) -> Self {
|
||||
match to_digit(c) {
|
||||
Result::Ok(n) => Self { value: DslValue::Num(10*m+n), ..self.grow() },
|
||||
Result::Err(e) => Self { value: DslValue::Err(e), ..self.grow() },
|
||||
}
|
||||
}
|
||||
pub const fn grow_key (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslValue::Key(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_sym (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslValue::Sym(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_str (self) -> Self {
|
||||
let token = self.grow();
|
||||
token.with_value(DslValue::Str(token.slice_source(self.source)))
|
||||
}
|
||||
pub const fn grow_exp (self) -> Self {
|
||||
let token = self.grow();
|
||||
if let DslValue::Exp(depth, _) = token.value() {
|
||||
token.with_value(DslValue::Exp(depth, SourceIter::new(token.slice_source_exp(self.source))))
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
pub const fn grow_in (self) -> Self {
|
||||
let token = self.grow_exp();
|
||||
if let DslValue::Exp(depth, source) = token.value() {
|
||||
token.with_value(DslValue::Exp(depth.saturating_add(1), source))
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
pub const fn grow_out (self) -> Self {
|
||||
let token = self.grow_exp();
|
||||
if let DslValue::Exp(depth, source) = token.value() {
|
||||
if depth > 0 {
|
||||
token.with_value(DslValue::Exp(depth - 1, source))
|
||||
} else {
|
||||
return self.error(Unexpected(')'))
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn to_number (digits: &str) -> DslResult<usize> {
|
||||
let mut value = 0;
|
||||
iterate!(char_indices(digits) => (_, c) => match to_digit(c) {
|
||||
Ok(digit) => value = 10 * value + digit,
|
||||
Result::Err(e) => return Result::Err(e)
|
||||
});
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub const fn to_digit (c: char) -> DslResult<usize> {
|
||||
Ok(match c {
|
||||
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
|
||||
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
|
||||
_ => return Result::Err(Unexpected(c))
|
||||
})
|
||||
}
|
||||
|
||||
pub const fn peek_src <'src> (source: &'src str) -> Option<Cst<'src>> {
|
||||
use DslValue::*;
|
||||
let mut token: Cst<'src> = Cst::new(source, 0, 0, Nil);
|
||||
pub const fn peek_src <'src> (source: &'src str) -> Option<CstVal<'src>> {
|
||||
use DslVal::*;
|
||||
let mut token: CstVal<'src> = CstVal::new(source, 0, 0, Nil);
|
||||
iterate!(char_indices(source) => (start, c) => token = match token.value() {
|
||||
Err(_) => return Some(token),
|
||||
Nil => match c {
|
||||
' '|'\n'|'\r'|'\t' =>
|
||||
token.grow(),
|
||||
'(' =>
|
||||
Cst::new(source, start, 1, Exp(1, SourceIter::new(str_range(source, start, start + 1)))),
|
||||
CstVal::new(source, start, 1, Exp(1, CstIter::new(str_range(source, start, start + 1)))),
|
||||
'"' =>
|
||||
Cst::new(source, start, 1, Str(str_range(source, start, start + 1))),
|
||||
CstVal::new(source, start, 1, Str(str_range(source, start, start + 1))),
|
||||
':'|'@' =>
|
||||
Cst::new(source, start, 1, Sym(str_range(source, start, start + 1))),
|
||||
CstVal::new(source, start, 1, Sym(str_range(source, start, start + 1))),
|
||||
'/'|'a'..='z' =>
|
||||
Cst::new(source, start, 1, Key(str_range(source, start, start + 1))),
|
||||
CstVal::new(source, start, 1, Key(str_range(source, start, start + 1))),
|
||||
'0'..='9' =>
|
||||
Cst::new(source, start, 1, match to_digit(c) {
|
||||
Ok(c) => DslValue::Num(c),
|
||||
Result::Err(e) => DslValue::Err(e)
|
||||
CstVal::new(source, start, 1, match to_digit(c) {
|
||||
Ok(c) => DslVal::Num(c),
|
||||
Result::Err(e) => DslVal::Err(e)
|
||||
}),
|
||||
_ => token.error(Unexpected(c))
|
||||
},
|
||||
|
|
@ -201,90 +301,19 @@ pub const fn peek_src <'src> (source: &'src str) -> Option<Cst<'src>> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Owns a reference to the source text.
|
||||
/// [SourceConstIter::next] emits subsequent pairs of:
|
||||
/// * a [Cst] and
|
||||
/// * the source text remaining
|
||||
/// * [ ] TODO: maybe [SourceConstIter::next] should wrap the remaining source in `Self` ?
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct SourceConstIter<'src>(pub &'src str);
|
||||
|
||||
impl<'src> From<SourceConstIter<'src>> for SourceIter<'src> {
|
||||
fn from (source: SourceConstIter<'src>) -> Self{
|
||||
Self(source)
|
||||
}
|
||||
pub const fn to_number (digits: &str) -> DslResult<usize> {
|
||||
let mut value = 0;
|
||||
iterate!(char_indices(digits) => (_, c) => match to_digit(c) {
|
||||
Ok(digit) => value = 10 * value + digit,
|
||||
Result::Err(e) => return Result::Err(e)
|
||||
});
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
impl<'src> From<&'src str> for SourceConstIter<'src> {
|
||||
fn from (source: &'src str) -> Self{
|
||||
Self::new(source)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> SourceConstIter<'src> {
|
||||
pub const fn new (source: &'src str) -> Self {
|
||||
Self(source)
|
||||
}
|
||||
pub const fn chomp (&self, index: usize) -> Self {
|
||||
Self(split_at(self.0, index).1)
|
||||
}
|
||||
pub const fn next (mut self) -> Option<(Cst<'src>, Self)> {
|
||||
Self::next_mut(&mut self)
|
||||
}
|
||||
pub const fn peek (&self) -> Option<Cst<'src>> {
|
||||
peek_src(self.0)
|
||||
}
|
||||
pub const fn next_mut (&mut self) -> Option<(Cst<'src>, Self)> {
|
||||
match self.peek() {
|
||||
Some(token) => Some((token, self.chomp(token.end()))),
|
||||
None => None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const_iter!(<'src>|self: SourceConstIter<'src>| => Cst<'src> => self.next_mut().map(|(result, _)|result));
|
||||
|
||||
/// Provides a native [Iterator] API over [SourceConstIter],
|
||||
/// emitting [Cst] items.
|
||||
///
|
||||
/// [Cst::next] returns just the [Cst] and mutates `self`,
|
||||
/// instead of returning an updated version of the struct as [SourceConstIter::next] does.
|
||||
#[derive(Copy, Clone, Debug, Default, PartialEq)]
|
||||
pub struct SourceIter<'src>(pub SourceConstIter<'src>);
|
||||
|
||||
impl<'src> SourceIter<'src> {
|
||||
pub const fn new (source: &'src str) -> Self {
|
||||
Self(SourceConstIter::new(source))
|
||||
}
|
||||
pub const fn peek (&self) -> Option<Cst<'src>> {
|
||||
self.0.peek()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> Iterator for SourceIter<'src> {
|
||||
type Item = Cst<'src>;
|
||||
fn next (&mut self) -> Option<Cst<'src>> {
|
||||
self.0.next().map(|(item, rest)|{
|
||||
self.0 = rest;
|
||||
item
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> From<&'src str> for SourceIter<'src> {
|
||||
fn from (source: &'src str) -> Self{
|
||||
Self(SourceConstIter(source))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> Into<Vec<Cst<'src>>> for SourceIter<'src> {
|
||||
fn into (self) -> Vec<Cst<'src>> {
|
||||
self.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'src> Into<Vec<Ast>> for SourceIter<'src> {
|
||||
fn into (self) -> Vec<Ast> {
|
||||
self.map(Into::into).collect()
|
||||
}
|
||||
pub const fn to_digit (c: char) -> DslResult<usize> {
|
||||
Ok(match c {
|
||||
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
|
||||
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
|
||||
_ => return Result::Err(Unexpected(c))
|
||||
})
|
||||
}
|
||||
|
|
|
|||
178
dsl/src/dsl.rs
178
dsl/src/dsl.rs
|
|
@ -1,6 +1,11 @@
|
|||
use crate::*;
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(Error, Debug, Copy, Clone, PartialEq)] pub enum DslError {
|
||||
/// Standard result type for DSL-specific operations.
|
||||
pub type DslResult<T> = Result<T, DslErr>;
|
||||
|
||||
/// DSL-specific error codes.
|
||||
#[derive(Error, Debug, Copy, Clone, PartialEq)] pub enum DslErr {
|
||||
#[error("parse failed: not implemented")]
|
||||
Unimplemented,
|
||||
#[error("parse failed: empty")]
|
||||
|
|
@ -13,41 +18,23 @@ use crate::*;
|
|||
Code(u8),
|
||||
}
|
||||
|
||||
/// Thing that may construct itself from `State` and [DslValue].
|
||||
pub trait FromDsl<State>: Sized {
|
||||
fn try_provide (
|
||||
state: &State,
|
||||
value: DslValue<impl DslStr, impl DslExp>
|
||||
) -> Perhaps<Self>;
|
||||
fn provide (
|
||||
state: &State,
|
||||
value: DslValue<impl DslStr, impl DslExp>,
|
||||
error: impl Fn()->Box<dyn std::error::Error>
|
||||
) -> Usually<Self> {
|
||||
match Self::try_provide(state, value)? {
|
||||
Some(value) => Ok(value),
|
||||
_ => Err(error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type DslResult<T> = Result<T, DslError>;
|
||||
|
||||
/// Marker trait for supported string types.
|
||||
pub trait DslStr: PartialEq + Clone + Default + Debug + AsRef<str> {}
|
||||
impl<T: PartialEq + Clone + Default + Debug + AsRef<str>> DslStr for T {}
|
||||
|
||||
/// Marker trait for supported expression types.
|
||||
pub trait DslExp: PartialEq + Clone + Default + Debug {}
|
||||
impl<T: PartialEq + Clone + Default + Debug> DslExp for T {}
|
||||
|
||||
/// A DSL value generic over string and expression types.
|
||||
/// See [CstValue] and [AstValue].
|
||||
/// Enumeration of possible DSL tokens.
|
||||
/// Generic over string and expression storage.
|
||||
///
|
||||
/// * [ ] FIXME: Value may be [Err] which may shadow [Result::Err]
|
||||
/// * [DslVal::Exp] wraps an expression depth and a [CstIter]
|
||||
/// with the remaining part of the expression.
|
||||
/// * expression depth other that 0 mean unclosed parenthesis.
|
||||
/// * closing and unopened parenthesis panics during reading.
|
||||
/// * [ ] TODO: signed depth might be interesting
|
||||
/// * [DslVal::Sym] and [DslVal::Key] are stringish literals
|
||||
/// with slightly different parsing rules.
|
||||
/// * [DslVal::Num] is an unsigned integer literal.
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
pub enum DslValue<Str: DslStr, Exp: DslExp> {
|
||||
pub enum DslVal<Str, Exp> {
|
||||
#[default]
|
||||
Nil,
|
||||
Err(DslError),
|
||||
Err(DslErr),
|
||||
Num(usize),
|
||||
Sym(Str),
|
||||
Key(Str),
|
||||
|
|
@ -55,38 +42,69 @@ pub enum DslValue<Str: DslStr, Exp: DslExp> {
|
|||
Exp(usize, Exp),
|
||||
}
|
||||
|
||||
impl<Str: DslStr, Exp: DslExp> DslValue<Str, Exp> {
|
||||
pub trait Dsl {
|
||||
type Str: PartialEq + Clone + Default + Debug + AsRef<str>;
|
||||
type Exp: PartialEq + Clone + Default + Debug + Dsl;
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Self::Str, Self::Exp>>;
|
||||
fn val (&self) -> DslVal<Self::Str, Self::Exp> {
|
||||
self.nth(0).unwrap_or(DslVal::Nil)
|
||||
}
|
||||
// exp-only nth here?
|
||||
}
|
||||
|
||||
impl<
|
||||
Str: PartialEq + Clone + Default + Debug + AsRef<str>,
|
||||
Exp: PartialEq + Clone + Default + Debug + Dsl,
|
||||
> Dsl for DslVal<Str, Exp> {
|
||||
type Str = Str;
|
||||
type Exp = Exp;
|
||||
fn val (&self) -> DslVal<Str, Exp> {
|
||||
self.clone()
|
||||
}
|
||||
fn nth (&self, index: usize) -> Option<DslVal<Str, Exp>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
/// May construct self from state and DSL.
|
||||
pub trait DslFrom<State>: Sized {
|
||||
fn try_dsl_from (state: &State, value: &impl Dsl) -> Perhaps<Self>;
|
||||
fn dsl_from (
|
||||
state: &State, value: &impl Dsl, error: impl Fn()->Box<dyn Error>
|
||||
) -> Usually<Self> {
|
||||
match Self::try_dsl_from(state, value)? {
|
||||
Some(value) => Ok(value),
|
||||
_ => Err(error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// May construct another from self and DSL.
|
||||
pub trait DslInto<Item> {
|
||||
fn try_dsl_into (&self, dsl: &impl Dsl) -> Perhaps<Item>;
|
||||
fn dsl_into (
|
||||
&self, value: &impl Dsl, error: impl Fn()->Box<dyn Error>
|
||||
) -> Usually<Item> {
|
||||
match Self::try_dsl_into(self, value)? {
|
||||
Some(value) => Ok(value),
|
||||
_ => Err(error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Str, Exp> DslVal<Str, Exp> {
|
||||
pub fn is_nil (&self) -> bool {
|
||||
matches!(self, Self::Nil)
|
||||
}
|
||||
pub fn as_err (&self) -> Option<&DslError> {
|
||||
pub fn as_err (&self) -> Option<&DslErr> {
|
||||
if let Self::Err(e) = self { Some(e) } else { None }
|
||||
}
|
||||
pub fn as_num (&self) -> Option<usize> {
|
||||
if let Self::Num(n) = self { Some(*n) } else { None }
|
||||
}
|
||||
pub fn as_sym (&self) -> Option<&str> {
|
||||
if let Self::Sym(s) = self { Some(s.as_ref()) } else { None }
|
||||
}
|
||||
pub fn as_key (&self) -> Option<&str> {
|
||||
if let Self::Key(k) = self { Some(k.as_ref()) } else { None }
|
||||
}
|
||||
pub fn as_str (&self) -> Option<&str> {
|
||||
if let Self::Str(s) = self { Some(s.as_ref()) } else { None }
|
||||
}
|
||||
pub fn as_exp (&self) -> Option<&Exp> {
|
||||
if let Self::Exp(_, x) = self { Some(x) } else { None }
|
||||
}
|
||||
pub fn exp_match <T, F> (&self, namespace: &str, cb: F) -> Perhaps<T>
|
||||
where F: Fn(&str, &Exp)-> Perhaps<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)
|
||||
}
|
||||
}
|
||||
pub fn exp_depth (&self) -> Option<usize> {
|
||||
todo!()
|
||||
}
|
||||
|
|
@ -107,4 +125,54 @@ impl<Str: DslStr, Exp: DslExp> DslValue<Str, Exp> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<Str: DslStr + Copy, Exp: DslExp + Copy> Copy for DslValue<Str, Exp> {}
|
||||
impl<Str: Copy, Exp: Copy> Copy for DslVal<Str, Exp> {}
|
||||
|
||||
impl<Str: AsRef<str>, Exp> DslVal<Str, Exp> {
|
||||
pub fn as_sym (&self) -> Option<&str> {
|
||||
if let Self::Sym(s) = self { Some(s.as_ref()) } else { None }
|
||||
}
|
||||
pub fn as_key (&self) -> Option<&str> {
|
||||
if let Self::Key(k) = self { Some(k.as_ref()) } else { None }
|
||||
}
|
||||
pub fn as_str (&self) -> Option<&str> {
|
||||
if let Self::Str(s) = self { Some(s.as_ref()) } else { None }
|
||||
}
|
||||
pub fn exp_match <T, F> (&self, namespace: &str, cb: F) -> Perhaps<T>
|
||||
where F: Fn(&str, &Exp)-> Perhaps<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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! from_str {
|
||||
($Struct:ty |$source:ident| $expr:expr) => {
|
||||
impl<'s> From<&'s str> for $Struct {
|
||||
fn from ($source: &'s str) -> Self {
|
||||
$expr
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
from_str!(Ast|source|Self::from(CstIter::from(source)));
|
||||
from_str!(Cst<'s>|source|Self(CstIter(CstConstIter(source))));
|
||||
from_str!(CstIter<'s>|source|Self(CstConstIter(source)));
|
||||
from_str!(CstConstIter<'s>|source|Self::new(source));
|
||||
|
||||
pub fn dsl_val <A: Into<X>, B: Into<Y>, X, Y> (val: DslVal<A, B>) -> DslVal<X, Y> {
|
||||
use DslVal::*;
|
||||
match val {
|
||||
Nil => Nil,
|
||||
Err(e) => Err(e),
|
||||
Num(u) => Num(u),
|
||||
Sym(s) => Sym(s.into()),
|
||||
Key(s) => Key(s.into()),
|
||||
Str(s) => Str(s.into()),
|
||||
Exp(d, x) => Exp(d, x.into()),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
141
dsl/src/lib.rs
141
dsl/src/lib.rs
|
|
@ -1,152 +1,17 @@
|
|||
//! [Token]s are parsed substrings with an associated [Value].
|
||||
//!
|
||||
//! * [ ] FIXME: Value may be [Err] which may shadow [Result::Err]
|
||||
//! * [Value::Exp] wraps an expression depth and a [SourceIter]
|
||||
//! with the remaining part of the expression.
|
||||
//! * expression depth other that 0 mean unclosed parenthesis.
|
||||
//! * closing and unopened parenthesis panics during reading.
|
||||
//! * [ ] TODO: signed depth might be interesting
|
||||
//! * [Value::Sym] and [Value::Key] are stringish literals
|
||||
//! with slightly different parsing rules.
|
||||
//! * [Value::Num] is an unsigned integer literal.
|
||||
//!```
|
||||
//! use tengri_dsl::{*, Value::*};
|
||||
//! let source = include_str!("../test.edn");
|
||||
//! let mut view = TokenIter::new(source);
|
||||
//! assert_eq!(view.peek(), Some(Token {
|
||||
//! source,
|
||||
//! start: 0,
|
||||
//! length: source.len(),
|
||||
//! value: Exp(0, TokenIter::new(&source[1..]))
|
||||
//! }));
|
||||
//!```
|
||||
//! The token iterator [TokenIter] allows you to get the
|
||||
//! general-purpose syntactic [Token]s represented by the source text.
|
||||
//!
|
||||
//! Both iterators are `peek`able:
|
||||
//!
|
||||
//! ```
|
||||
//! let src = include_str!("../test.edn");
|
||||
//! let mut view = tengri_dsl::TokenIter::new(src);
|
||||
//! assert_eq!(view.0.0, src);
|
||||
//! assert_eq!(view.peek(), view.0.peek())
|
||||
//! ```
|
||||
#![feature(adt_const_params)]
|
||||
#![feature(type_alias_impl_trait)]
|
||||
#![feature(impl_trait_in_fn_trait_return)]
|
||||
pub(crate) use ::tengri_core::*;
|
||||
pub(crate) use std::fmt::Debug;//, Display};//, Formatter, Error as FormatError};
|
||||
pub(crate) use std::fmt::Debug;
|
||||
pub(crate) use std::sync::Arc;
|
||||
pub(crate) use std::collections::VecDeque;
|
||||
pub(crate) use konst::iter::{ConstIntoIter, IsIteratorKind};
|
||||
pub(crate) use konst::string::{split_at, str_range, char_indices};
|
||||
pub(crate) use thiserror::Error;
|
||||
pub(crate) use self::DslError::*;
|
||||
pub(crate) use self::DslErr::*;
|
||||
|
||||
mod dsl; pub use self::dsl::*;
|
||||
mod ast; pub use self::ast::*;
|
||||
mod cst; pub use self::cst::*;
|
||||
|
||||
#[cfg(test)] mod test_token_iter {
|
||||
use crate::*;
|
||||
//use proptest::prelude::*;
|
||||
#[test] fn test_iters () {
|
||||
let mut iter = crate::SourceIter::new(&":foo :bar");
|
||||
let _ = iter.next();
|
||||
}
|
||||
#[test] const fn test_const_iters () {
|
||||
let iter = crate::SourceConstIter::new(&":foo :bar");
|
||||
let _ = iter.next();
|
||||
}
|
||||
#[test] fn test_num () {
|
||||
let _digit = to_digit('0');
|
||||
let _digit = to_digit('x');
|
||||
let _number = to_number(&"123");
|
||||
let _number = to_number(&"12asdf3");
|
||||
}
|
||||
//proptest! {
|
||||
//#[test] fn proptest_source_iter (
|
||||
//source in "\\PC*"
|
||||
//) {
|
||||
//let mut iter = crate::SourceIter::new(&source);
|
||||
////let _ = iter.next()
|
||||
//}
|
||||
//#[test] fn proptest_token_iter (
|
||||
//source in "\\PC*"
|
||||
//) {
|
||||
//let mut iter = crate::TokenIter::new(&source);
|
||||
////let _ = iter.next();
|
||||
//}
|
||||
//}
|
||||
}
|
||||
|
||||
//#[cfg(test)] mod test_token_prop {
|
||||
//use crate::{Cst, CstMeta, Value::*};
|
||||
//use proptest::prelude::*;
|
||||
//proptest! {
|
||||
//#[test] fn test_token_prop (
|
||||
//source in "\\PC*",
|
||||
//start in usize::MIN..usize::MAX,
|
||||
//length in usize::MIN..usize::MAX,
|
||||
//) {
|
||||
//let token = Cst(Nil, CstMeta { source: &source, start, length });
|
||||
//let _ = token.slice();
|
||||
//}
|
||||
//}
|
||||
//}
|
||||
|
||||
#[cfg(test)] #[test] fn test_token () -> Result<(), Box<dyn std::error::Error>> {
|
||||
use crate::DslValue::*;
|
||||
let source = ":f00";
|
||||
let mut token = Cst::new(source, 0, 1, Sym(":"));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, Cst::new(source, 0, 2, Sym(":f")));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, Cst::new(source, 0, 3, Sym(":f0")));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, Cst::new(source, 0, 4, Sym(":f00")));
|
||||
|
||||
assert_eq!(None, SourceIter::new("").next());
|
||||
assert_eq!(None, SourceIter::new(" \n \r \t ").next());
|
||||
|
||||
assert_eq!(Err(Unexpected('a')), SourceIter::new(" 9a ").next().unwrap().value());
|
||||
|
||||
assert_eq!(Num(7), SourceIter::new("7").next().unwrap().value());
|
||||
assert_eq!(Num(100), SourceIter::new(" 100 ").next().unwrap().value());
|
||||
|
||||
assert_eq!(Sym(":123foo"), SourceIter::new(" :123foo ").next().unwrap().value());
|
||||
assert_eq!(Sym("@bar456"), SourceIter::new(" \r\r\n\n@bar456\t\t\t").next().unwrap().value());
|
||||
|
||||
assert_eq!(Key("foo123"), SourceIter::new("foo123").next().unwrap().value());
|
||||
assert_eq!(Key("foo/bar"), SourceIter::new("foo/bar").next().unwrap().value());
|
||||
|
||||
assert_eq!(Str("foo/bar"), SourceIter::new("\"foo/bar\"").next().unwrap().value());
|
||||
assert_eq!(Str("foo/bar"), SourceIter::new(" \"foo/bar\" ").next().unwrap().value());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
//#[cfg(test)] #[test] fn test_examples () -> Result<(), DslError> {
|
||||
//// Let's pretend to render some view.
|
||||
//let source = include_str!("../../tek/src/view_arranger.edn");
|
||||
//// The token iterator allows you to get the tokens represented by the source text.
|
||||
//let mut view = TokenIter(source);
|
||||
//// The token iterator wraps a const token+source iterator.
|
||||
//assert_eq!(view.0.0, source);
|
||||
//let mut expr = view.peek();
|
||||
//assert_eq!(view.0.0, source);
|
||||
//assert_eq!(expr, Some(Token {
|
||||
//source, start: 0, length: source.len() - 1, value: Exp(0, SourceIter::new(&source[1..]))
|
||||
//}));
|
||||
////panic!("{view:?}");
|
||||
////panic!("{:#?}", expr);
|
||||
////for example in [
|
||||
////include_str!("../../tui/examples/edn01.edn"),
|
||||
////include_str!("../../tui/examples/edn02.edn"),
|
||||
////] {
|
||||
//////let items = Dsl::read_all(example)?;
|
||||
//////panic!("{layout:?}");
|
||||
//////let content = <dyn ViewContext<::tengri_engine::tui::Tui>>::from(&layout);
|
||||
////}
|
||||
//Ok(())
|
||||
//}
|
||||
#[cfg(test)] mod test;
|
||||
|
|
|
|||
104
dsl/src/test.rs
Normal file
104
dsl/src/test.rs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
use crate::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test] fn test_iters () {
|
||||
let mut iter = crate::CstIter::new(&":foo :bar");
|
||||
let _ = iter.next();
|
||||
}
|
||||
|
||||
#[test] const fn test_const_iters () {
|
||||
let iter = crate::CstConstIter::new(&":foo :bar");
|
||||
let _ = iter.next();
|
||||
}
|
||||
|
||||
#[test] fn test_num () {
|
||||
let _digit = to_digit('0');
|
||||
let _digit = to_digit('x');
|
||||
let _number = to_number(&"123");
|
||||
let _number = to_number(&"12asdf3");
|
||||
}
|
||||
//proptest! {
|
||||
//#[test] fn proptest_source_iter (
|
||||
//source in "\\PC*"
|
||||
//) {
|
||||
//let mut iter = crate::CstIter::new(&source);
|
||||
////let _ = iter.next()
|
||||
//}
|
||||
//#[test] fn proptest_token_iter (
|
||||
//source in "\\PC*"
|
||||
//) {
|
||||
//let mut iter = crate::TokenIter::new(&source);
|
||||
////let _ = iter.next();
|
||||
//}
|
||||
//}
|
||||
|
||||
//#[cfg(test)] mod test_token_prop {
|
||||
//use crate::{Cst, CstMeta, Value::*};
|
||||
//use proptest::prelude::*;
|
||||
//proptest! {
|
||||
//#[test] fn test_token_prop (
|
||||
//source in "\\PC*",
|
||||
//start in usize::MIN..usize::MAX,
|
||||
//length in usize::MIN..usize::MAX,
|
||||
//) {
|
||||
//let token = Cst(Nil, CstMeta { source: &source, start, length });
|
||||
//let _ = token.slice();
|
||||
//}
|
||||
//}
|
||||
//}
|
||||
|
||||
#[test] fn test_token () -> Result<(), Box<dyn std::error::Error>> {
|
||||
use crate::DslVal::*;
|
||||
let source = ":f00";
|
||||
let mut token = CstVal::new(source, 0, 1, Sym(":"));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, CstVal::new(source, 0, 2, Sym(":f")));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, CstVal::new(source, 0, 3, Sym(":f0")));
|
||||
token = token.grow_sym();
|
||||
assert_eq!(token, CstVal::new(source, 0, 4, Sym(":f00")));
|
||||
|
||||
assert_eq!(None, CstIter::new("").next());
|
||||
assert_eq!(None, CstIter::new(" \n \r \t ").next());
|
||||
|
||||
assert_eq!(Err(Unexpected('a')), CstIter::new(" 9a ").next().unwrap().value());
|
||||
|
||||
assert_eq!(Num(7), CstIter::new("7").next().unwrap().value());
|
||||
assert_eq!(Num(100), CstIter::new(" 100 ").next().unwrap().value());
|
||||
|
||||
assert_eq!(Sym(":123foo"), CstIter::new(" :123foo ").next().unwrap().value());
|
||||
assert_eq!(Sym("@bar456"), CstIter::new(" \r\r\n\n@bar456\t\t\t").next().unwrap().value());
|
||||
|
||||
assert_eq!(Key("foo123"), CstIter::new("foo123").next().unwrap().value());
|
||||
assert_eq!(Key("foo/bar"), CstIter::new("foo/bar").next().unwrap().value());
|
||||
|
||||
//assert_eq!(Str("foo/bar"), CstIter::new("\"foo/bar\"").next().unwrap().value());
|
||||
//assert_eq!(Str("foo/bar"), CstIter::new(" \"foo/bar\" ").next().unwrap().value());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
//#[cfg(test)] #[test] fn test_examples () -> Result<(), DslErr> {
|
||||
//// Let's pretend to render some view.
|
||||
//let source = include_str!("../../tek/src/view_arranger.edn");
|
||||
//// The token iterator allows you to get the tokens represented by the source text.
|
||||
//let mut view = TokenIter(source);
|
||||
//// The token iterator wraps a const token+source iterator.
|
||||
//assert_eq!(view.0.0, source);
|
||||
//let mut expr = view.peek();
|
||||
//assert_eq!(view.0.0, source);
|
||||
//assert_eq!(expr, Some(Token {
|
||||
//source, start: 0, length: source.len() - 1, value: Exp(0, CstIter::new(&source[1..]))
|
||||
//}));
|
||||
////panic!("{view:?}");
|
||||
////panic!("{:#?}", expr);
|
||||
////for example in [
|
||||
////include_str!("../../tui/examples/edn01.edn"),
|
||||
////include_str!("../../tui/examples/edn02.edn"),
|
||||
////] {
|
||||
//////let items = Dsl::read_all(example)?;
|
||||
//////panic!("{layout:?}");
|
||||
//////let content = <dyn ViewContext<::tengri_engine::tui::Tui>>::from(&layout);
|
||||
////}
|
||||
//Ok(())
|
||||
//}
|
||||
Loading…
Add table
Add a link
Reference in a new issue