vortex_expr/traversal/
visitor.rs

1use std::marker::PhantomData;
2
3use vortex_error::VortexResult;
4
5use crate::traversal::{Node, NodeVisitor, TraversalOrder};
6
7struct FnVisitor<'a, F, T: 'a>
8where
9    F: FnMut(&'a T) -> VortexResult<TraversalOrder>,
10{
11    f_down: Option<F>,
12    f_up: Option<F>,
13    _data: PhantomData<&'a T>,
14}
15
16impl<'a, T, F> NodeVisitor<'a> for FnVisitor<'a, F, T>
17where
18    F: FnMut(&'a T) -> VortexResult<TraversalOrder>,
19    T: Node,
20{
21    type NodeTy = T;
22
23    fn visit_down(&mut self, node: &'a T) -> VortexResult<TraversalOrder> {
24        if let Some(f) = self.f_down.as_mut() {
25            f(node)
26        } else {
27            Ok(TraversalOrder::Continue)
28        }
29    }
30
31    fn visit_up(&mut self, node: &'a T) -> VortexResult<TraversalOrder> {
32        if let Some(f) = self.f_up.as_mut() {
33            f(node)
34        } else {
35            Ok(TraversalOrder::Continue)
36        }
37    }
38}
39
40pub fn pre_order_visit_up<'a, T: 'a + Node>(
41    f: impl FnMut(&'a T) -> VortexResult<TraversalOrder>,
42) -> impl NodeVisitor<'a, NodeTy = T> {
43    FnVisitor {
44        f_down: None,
45        f_up: Some(f),
46        _data: Default::default(),
47    }
48}
49
50pub fn pre_order_visit_down<'a, T: 'a + Node>(
51    f: impl FnMut(&'a T) -> VortexResult<TraversalOrder>,
52) -> impl NodeVisitor<'a, NodeTy = T> {
53    FnVisitor {
54        f_down: Some(f),
55        f_up: None,
56        _data: Default::default(),
57    }
58}