This commit is contained in:
2024-10-07 19:05:33 -04:00
parent ca52443f81
commit bb3a0ad113
12 changed files with 173 additions and 218 deletions
+16 -50
View File
@@ -3,39 +3,29 @@ use std::{
ops::{Deref, DerefMut},
};
use super::{FileSpan, ParserError, TokenCursor};
use super::{FileSpan, ParserError, ParserErrors, TokenCursor};
#[derive(Clone)]
pub struct Node<T> {
pub inner: Result<T, ParserError>,
pub inner: Result<T, ()>,
pub span: FileSpan,
}
pub trait Parsable: Sized {
fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError>;
fn parse(cursor: &mut TokenCursor, errors: &mut ParserErrors) -> Result<Self, ParserError>;
}
pub trait MaybeParsable: Sized {
fn maybe_parse(cursor: &mut TokenCursor) -> Result<Option<Self>, ParserError>;
}
pub trait NodeContainer {
fn children(&self) -> Vec<Node<Box<dyn NodeContainer>>>;
}
impl<T: NodeContainer + ?Sized> NodeContainer for Node<Box<T>> {
fn children(&self) -> Vec<Node<Box<dyn NodeContainer>>> {
match &self.inner {
Ok(v) => v.children(),
Err(_) => Vec::new(),
}
}
fn maybe_parse(
cursor: &mut TokenCursor,
errors: &mut ParserErrors,
) -> Result<Option<Self>, ParserError>;
}
impl<T: Parsable> Node<T> {
pub fn parse(cursor: &mut TokenCursor) -> Self {
pub fn parse(cursor: &mut TokenCursor, errors: &mut ParserErrors) -> Self {
let start = cursor.next_pos();
let inner = T::parse(cursor);
let inner = T::parse(cursor, errors).map_err(|e| errors.add(e));
let end = cursor.prev_end();
Self {
inner,
@@ -45,11 +35,14 @@ impl<T: Parsable> Node<T> {
}
impl<T: MaybeParsable> Node<T> {
pub fn maybe_parse(cursor: &mut TokenCursor) -> Option<Self> {
pub fn maybe_parse(cursor: &mut TokenCursor, errors: &mut ParserErrors) -> Option<Self> {
let start = cursor.next_pos();
let inner = match T::maybe_parse(cursor) {
let inner = match T::maybe_parse(cursor, errors) {
Ok(v) => Ok(v?),
Err(e) => Err(e),
Err(e) => {
errors.add(e);
Err(())
}
};
let end = cursor.prev_end();
Some(Self {
@@ -66,15 +59,6 @@ impl<T> Node<T> {
span,
}
}
pub fn err(inner: ParserError, span: FileSpan) -> Self {
Self {
inner: Err(inner),
span,
}
}
pub fn take(self) -> Result<T, ParserError> {
self.inner
}
pub fn bx(self) -> Node<Box<T>> {
Node {
inner: self.inner.map(|v| Box::new(v)),
@@ -83,15 +67,6 @@ impl<T> Node<T> {
}
}
impl<T: NodeContainer + Clone + 'static> Node<T> {
pub fn containerr(&self) -> Node<Box<dyn NodeContainer>> {
Node {
inner: self.clone().inner.map(|v| Box::new(v) as Box<dyn NodeContainer>),
span: self.span,
}
}
}
impl<T> Node<Box<T>> {
pub fn unbx(self) -> Node<T> {
Node {
@@ -100,17 +75,8 @@ impl<T> Node<Box<T>> {
}
}
}
impl<T: NodeContainer + Clone + 'static> Node<Box<T>> {
pub fn container(&self) -> Node<Box<dyn NodeContainer>> {
Node {
inner: self.clone().inner.map(|v| v as Box<dyn NodeContainer>),
span: self.span,
}
}
}
impl<T> Deref for Node<T> {
type Target = Result<T, ParserError>;
type Target = Result<T, ()>;
fn deref(&self) -> &Self::Target {
&self.inner
}