Skip to main content

welly_parser/
valid.rs

1use super::{Location};
2
3/// The error type of [`AST::validate()`].
4///
5/// This can conveniently be returned using the idoim `Err(report(...))?`.
6pub struct Invalid;
7
8impl From<()> for Invalid {
9    fn from(_: ()) -> Self { Self }
10}
11
12/// Represents a valid abstract syntax tree of some valid Welly source code.
13pub trait AST: Sized + std::fmt::Debug {
14    /// The parser type that turns into `Self`.
15    type Generous;
16
17    /// Attempt to construct a `Self` given its parse tree.
18    ///
19    /// If you return `Invalid`, you must first `report()` at least one error.
20    fn validate(report: &mut impl FnMut(Location, &str), tree: &Self::Generous)
21    -> Result<Self, Invalid>;
22}
23
24impl<T: AST> AST for Option<T> {
25    type Generous = Option<T::Generous>;
26
27    fn validate(report: &mut impl FnMut(Location, &str), tree: &Self::Generous)
28    -> Result<Self, Invalid> {
29        Ok(if let Some(tree) = tree {
30            Some(T::validate(report, tree)?)
31        } else {
32            None
33        })
34    }
35}
36
37impl<T: AST> AST for Box<T> {
38    type Generous = Box<T::Generous>;
39
40    fn validate(report: &mut impl FnMut(Location, &str), tree: &Self::Generous)
41    -> Result<Self, Invalid> {
42        Ok(Box::new(T::validate(report, tree)?))
43    }
44}