lwb_parser/parser/ast/
mod.rs

1use crate::codegen_prelude::{GenerateAstInfo, ParsePairSort};
2use crate::parser::ast::from_pairs::FromPairs;
3use crate::sources::span::Span;
4use serde::{Deserialize, Serialize};
5use std::fmt::Debug;
6
7pub mod from_pairs;
8pub mod generate_ast;
9
10pub trait SpannedAstInfo: AstInfo {
11    fn span(&self) -> &Span;
12
13    fn as_str(&self) -> &str {
14        self.span().as_str()
15    }
16}
17
18#[derive(Hash, Eq, PartialEq, Copy, Clone, Serialize, Deserialize, Debug)]
19pub struct NodeId(u64);
20
21impl NodeId {
22    pub(crate) fn new(value: u64) -> NodeId {
23        Self(value)
24    }
25}
26
27pub trait AstInfo: Debug + PartialEq {
28    fn node_id(&self) -> NodeId;
29}
30
31pub trait AstNode<M: AstInfo>: FromPairs<M> {
32    fn as_str<'a>(&'a self) -> &'a str
33    where
34        M: SpannedAstInfo + 'a,
35    {
36        self.ast_info().as_str()
37    }
38
39    fn ast_info(&self) -> &M;
40    fn sort(&self) -> &'static str;
41    fn constructor(&self) -> &'static str;
42
43    fn traverse<F>(&self, _f: F)
44    where
45        Self: Sized,
46        F: FnMut(&dyn AstNode<M>),
47    {
48        todo!()
49    }
50}
51
52impl<M: AstInfo, T> FromPairs<M> for Box<T>
53where
54    T: AstNode<M>,
55{
56    fn from_pairs<G: GenerateAstInfo<Result = M>>(pair: &ParsePairSort, generator: &mut G) -> Self
57    where
58        Self: Sized,
59    {
60        Box::new(T::from_pairs(pair, generator))
61    }
62}
63
64impl<M: AstInfo, T> AstNode<M> for Box<T>
65where
66    T: AstNode<M>,
67{
68    fn ast_info(&self) -> &M {
69        T::ast_info(self)
70    }
71
72    fn sort(&self) -> &'static str {
73        T::sort(self)
74    }
75
76    fn constructor(&self) -> &'static str {
77        T::constructor(self)
78    }
79}