wip: ast/cst
Some checks are pending
/ build (push) Waiting to run

This commit is contained in:
🪞👃🪞 2025-05-25 22:48:29 +03:00
parent 31e84bf5b3
commit f1b24d436a
20 changed files with 1081 additions and 1103 deletions

70
dsl/src/dsl_ast.rs Normal file
View file

@ -0,0 +1,70 @@
use crate::*;
use std::sync::Arc;
use std::fmt::{Debug, Display, Formatter};
/// Emits tokens.
pub trait Ast: Debug {
fn peek (&self) -> Option<AstValue>;
fn next (&mut self) -> Option<AstValue>;
fn rest (self) -> Option<Box<dyn Ast>>;
}
/// A [Cst] can be used as an [Ast].
impl<'source: 'static> Ast for Cst<'source> {
fn peek (&self) -> Option<AstValue> {
Cst::peek(self).map(|token|token.value.into())
}
fn next (&mut self) -> Option<AstValue> {
Iterator::next(self).map(|token|token.value.into())
}
fn rest (self) -> Option<Box<dyn Ast>> {
self.peek().is_some().then(||Box::new(self) as Box<dyn Ast>)
}
}
#[derive(Clone, Default, Debug)]
pub enum AstValue {
#[default] Nil,
Err(DslError),
Num(usize),
Sym(Arc<str>),
Key(Arc<str>),
Str(Arc<str>),
Exp(Arc<Box<dyn Ast>>),
}
impl std::fmt::Display for AstValue {
fn fmt (&self, out: &mut Formatter) -> Result<(), std::fmt::Error> {
use AstValue::*;
write!(out, "{}", match self {
Nil => String::new(),
Err(e) => format!("[error: {e}]"),
Num(n) => format!("{n}"),
Sym(s) => format!("{s}"),
Key(s) => format!("{s}"),
Str(s) => format!("{s}"),
Exp(e) => format!("{e:?}"),
})
}
}
impl<'source: 'static> From<CstValue<'source>> for AstValue {
fn from (other: CstValue<'source>) -> Self {
use CstValue::*;
match other {
Nil => Self::Nil,
Err(e) => Self::Err(e),
Num(u) => Self::Num(u),
Sym(s) => Self::Sym(s.into()),
Key(s) => Self::Key(s.into()),
Str(s) => Self::Str(s.into()),
Exp(_, s) => Self::Exp(Arc::new(s.into())),
}
}
}
impl<'source: 'static> Into<Box<dyn Ast>> for Cst<'source> {
fn into (self) -> Box<dyn Ast> {
Box::new(self)
}
}