Skip to main content

vortex_expr/traversal/
fold.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5
6use crate::traversal::Node;
7
8/// Use to indicate the control flow of the fold on the downwards pass.
9/// In the case of Continue, the context is passed on to the children nodes.
10/// `Stop` ends the fold with a result, while `Skip` skips the current node's children.
11#[derive(Debug)]
12pub enum FoldDownContext<C, R> {
13    Continue(C),
14    Stop(R),
15    Skip(R),
16}
17
18/// Use to indicate the control flow of the fold on the upwards pass.
19/// `Stop` indicates that the fold should stop at the current position and return the result.
20#[derive(Debug)]
21pub enum FoldUp<R> {
22    Continue(R),
23    Stop(R),
24}
25
26impl<R> FoldUp<R> {
27    pub fn value(self) -> R {
28        match self {
29            Self::Continue(r) => r,
30            Self::Stop(r) => r,
31        }
32    }
33}
34
35/// Use to implement the folding a tree like structure in a pre-order traversal.
36///
37/// At each point on the way down, the `visit_down` method is called. If it returns `Skip`,
38/// the children of the current node are skipped. If it returns `Stop`, the fold is stopped.
39/// If it returns `Continue`, the children of the current node are visited.
40///
41/// At each point on the way up, the `visit_up` method is called. If it returns `Stop`,
42/// the fold stops.
43///
44/// On the way up the folded children are passed to the `visit_up` method along with the current node.
45///
46/// Note: this trait is not safe to use for graphs with a cycle.
47pub trait NodeFolderContext {
48    type NodeTy: Node;
49    type Result;
50    type Context;
51
52    /// visit_down is called when a node is first encountered, in a pre-order traversal.
53    /// If the node's children are to be skipped, return Skip.
54    /// If the node should stop traversal, return Stop.
55    /// Otherwise, return Continue.
56    fn visit_down(
57        &mut self,
58        _ctx: &Self::Context,
59        _node: &Self::NodeTy,
60    ) -> VortexResult<FoldDownContext<Self::Context, Self::Result>>;
61
62    /// visit_up is called when a node is last encountered, in a pre-order traversal.
63    /// If the node should stop traversal, return Stop.
64    /// Otherwise, return Continue.
65    fn visit_up(
66        &mut self,
67        _node: Self::NodeTy,
68        _context: &Self::Context,
69        _children: Vec<Self::Result>,
70    ) -> VortexResult<FoldUp<Self::Result>>;
71}
72
73#[cfg(test)]
74mod tests {
75    use vortex_array::scalar::NumericOperator;
76    use vortex_array::scalar_fn::builtin::boolean::Boolean;
77    use vortex_array::scalar_fn::builtin::compare::Compare;
78    use vortex_array::scalar_fn::builtin::literal::Literal;
79    use vortex_array::scalar_fn::builtin::numeric::Numeric;
80    use vortex_array::scalar_fn::builtin::operators::CompareOperator;
81    use vortex_error::VortexExpect;
82    use vortex_error::vortex_bail;
83
84    use super::*;
85    use crate::Expression;
86    use crate::checked_add;
87    use crate::gt;
88    use crate::lit;
89    use crate::traversal::NodeExt;
90
91    struct AddFold;
92    impl NodeFolderContext for AddFold {
93        type NodeTy = Expression;
94        type Result = i32;
95        type Context = ();
96
97        fn visit_down(
98            &mut self,
99            _ctx: &Self::Context,
100            node: &Self::NodeTy,
101        ) -> VortexResult<FoldDownContext<Self::Context, Self::Result>> {
102            if let Some(scalar) = node.as_opt::<Literal>() {
103                let v = scalar
104                    .as_primitive()
105                    .typed_value::<i32>()
106                    .vortex_expect("i32");
107
108                if v == 5 {
109                    return Ok(FoldDownContext::Stop(5));
110                }
111            }
112
113            if let Some(operator) = node.as_opt::<Compare>()
114                && *operator == CompareOperator::Gt
115            {
116                return Ok(FoldDownContext::Skip(0));
117            }
118
119            Ok(FoldDownContext::Continue(()))
120        }
121
122        fn visit_up(
123            &mut self,
124            node: Self::NodeTy,
125            _context: &Self::Context,
126            children: Vec<Self::Result>,
127        ) -> VortexResult<FoldUp<Self::Result>> {
128            if let Some(scalar) = node.as_opt::<Literal>() {
129                let v = scalar
130                    .as_primitive()
131                    .typed_value::<i32>()
132                    .vortex_expect("i32");
133                Ok(FoldUp::Continue(v))
134            } else if let Some(operator) = node.as_opt::<Numeric>() {
135                if *operator == NumericOperator::Add {
136                    Ok(FoldUp::Continue(children[0] + children[1]))
137                } else {
138                    vortex_bail!("not a valid operator")
139                }
140            } else if node.is::<Compare>() || node.is::<Boolean>() {
141                vortex_bail!("not a valid operator")
142            } else {
143                vortex_bail!("not a valid type")
144            }
145        }
146    }
147
148    #[test]
149    fn test_fold() {
150        let expr = checked_add(checked_add(lit(1), lit(2)), lit(3));
151
152        let mut folder = AddFold;
153        let result = expr.fold_context(&(), &mut folder).unwrap().value();
154        assert_eq!(result, 6);
155    }
156
157    #[test]
158    fn test_stop_value() {
159        let expr = checked_add(checked_add(lit(1), lit(5)), lit(3));
160
161        let mut folder = AddFold;
162        let result = expr.fold_context(&(), &mut folder).unwrap().value();
163        assert_eq!(result, 5);
164    }
165
166    #[test]
167    fn test_skip_value() {
168        let expr = checked_add(gt(lit(1), lit(2)), lit(3));
169
170        let mut folder = AddFold;
171        let result = expr.fold_context(&(), &mut folder).unwrap().value();
172        assert_eq!(result, 3);
173    }
174
175    #[test]
176    fn test_control_flow_value() {
177        let expr = checked_add(gt(lit(1), lit(5)), lit(3));
178
179        let mut folder = AddFold;
180        let result = expr.fold_context(&(), &mut folder).unwrap().value();
181        assert_eq!(result, 3);
182    }
183}