toasty_core/stmt/
node.rs

1use super::{Visit, VisitMut};
2use std::fmt;
3
4/// A node in the statement AST that can be traversed by a visitor.
5///
6/// Every AST type (statements, expressions, values, etc.) implements `Node`
7/// to participate in the visitor pattern defined by [`Visit`] and
8/// [`VisitMut`].
9///
10/// # Examples
11///
12/// ```ignore
13/// use toasty_core::stmt::{Node, Expr, Value, visit};
14///
15/// let expr = Expr::from(Value::from(42_i64));
16/// visit::for_each_expr(&expr, |e| {
17///     println!("{:?}", e);
18/// });
19/// ```
20pub trait Node: fmt::Debug {
21    /// Traverses this node with an immutable visitor.
22    fn visit<V: Visit>(&self, visit: V)
23    where
24        Self: Sized;
25
26    /// Traverses this node with a mutable visitor.
27    fn visit_mut<V: VisitMut>(&mut self, visit: V);
28}
29
30impl<T: Node> Node for Option<T> {
31    fn visit<V: Visit>(&self, visit: V)
32    where
33        Self: Sized,
34    {
35        if let Some(node) = self {
36            node.visit(visit);
37        }
38    }
39
40    fn visit_mut<V: VisitMut>(&mut self, visit: V) {
41        if let Some(node) = self {
42            node.visit_mut(visit);
43        }
44    }
45}
46
47impl<T: Node> Node for &mut T {
48    fn visit<V: Visit>(&self, visit: V)
49    where
50        Self: Sized,
51    {
52        (**self).visit(visit)
53    }
54
55    fn visit_mut<V: VisitMut>(&mut self, visit: V) {
56        (**self).visit_mut(visit)
57    }
58}