Skip to main content

pddl_core/
visitor.rs

1//! Visitor traits for traversing PDDL structures.
2//!
3//! **Provisional API.** These traits may change between minor releases
4//! until they have settled. They are exposed primarily to let external
5//! code contribute `Visitor<T, RcDoc>` impls for the `pretty` feature.
6
7/// A visitor.
8pub trait Visitor<T, O> {
9    /// Visits `value` and returns the result.
10    fn visit(&self, value: &T) -> O;
11}
12
13/// A mutable visitor.
14pub trait VisitorMut<T, O> {
15    /// Visits `value`, possibly updating the visitor, and returns the result.
16    fn visit_mut(&mut self, value: &T) -> O;
17}
18
19/// Trait to accept immutable visitors.
20pub trait Accept<V: Visitor<T, O>, T, O> {
21    /// Lets the visitor `v` visit `self`.
22    fn accept(&self, v: &V) -> O;
23}
24
25/// Trait to accept mutable visitors.
26pub trait AcceptMut<V: VisitorMut<T, O>, T, O> {
27    /// Lets the mutable visitor `v` visit `self`.
28    fn accept_mut(&self, v: &mut V) -> O;
29}
30
31/// Automatic implementation for accepting immutable visitors
32/// if the visitor recognizes the target type.
33impl<V, T, O> Accept<V, T, O> for T
34where
35    V: Visitor<T, O>,
36{
37    fn accept(&self, v: &V) -> O {
38        v.visit(self)
39    }
40}
41
42/// Automatic implementation for accepting mutable visitors
43/// if the visitor recognizes the target type.
44impl<V, T, O> AcceptMut<V, T, O> for T
45where
46    V: VisitorMut<T, O>,
47{
48    fn accept_mut(&self, v: &mut V) -> O {
49        v.visit_mut(self)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use assert2::check;
57
58    struct Visi(isize);
59    struct Item(i32);
60
61    impl VisitorMut<Item, ()> for Visi {
62        fn visit_mut(&mut self, value: &Item) {
63            self.0 += value.0 as isize;
64        }
65    }
66
67    #[test]
68    fn it_works() {
69        let a = Item(10);
70        let b = Item(7);
71        let mut v = Visi(20);
72
73        a.accept_mut(&mut v);
74        b.accept_mut(&mut v);
75
76        check!(v.0 == 37);
77    }
78}