-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
tree_node.rs
1673 lines (1554 loc) · 62.2 KB
/
tree_node.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! This module provides common traits for visiting or rewriting tree
//! data structures easily.
use std::sync::Arc;
use crate::Result;
/// This macro is used to control continuation behaviors during tree traversals
/// based on the specified direction. Depending on `$DIRECTION` and the value of
/// the given expression (`$EXPR`), which should be a variant of [`TreeNodeRecursion`],
/// the macro results in the following behavior:
///
/// - If the expression returns [`TreeNodeRecursion::Continue`], normal execution
/// continues.
/// - If it returns [`TreeNodeRecursion::Stop`], recursion halts and propagates
/// [`TreeNodeRecursion::Stop`].
/// - If it returns [`TreeNodeRecursion::Jump`], the continuation behavior depends
/// on the traversal direction:
/// - For `UP` direction, the function returns with [`TreeNodeRecursion::Jump`],
/// bypassing further bottom-up closures until the next top-down closure.
/// - For `DOWN` direction, the function returns with [`TreeNodeRecursion::Continue`],
/// skipping further exploration.
/// - If no direction is specified, `Jump` is treated like `Continue`.
#[macro_export]
macro_rules! handle_visit_recursion {
// Internal helper macro for handling the `Jump` case based on the direction:
(@handle_jump UP) => {
return Ok(TreeNodeRecursion::Jump)
};
(@handle_jump DOWN) => {
return Ok(TreeNodeRecursion::Continue)
};
(@handle_jump) => {
{} // Treat `Jump` like `Continue`, do nothing and continue execution.
};
// Main macro logic with variables to handle directionality.
($EXPR:expr $(, $DIRECTION:ident)?) => {
match $EXPR {
TreeNodeRecursion::Continue => {}
TreeNodeRecursion::Jump => handle_visit_recursion!(@handle_jump $($DIRECTION)?),
TreeNodeRecursion::Stop => return Ok(TreeNodeRecursion::Stop),
}
};
}
/// This macro is used to determine continuation during combined transforming
/// traversals.
///
/// Depending on the [`TreeNodeRecursion`] the bottom-up closure returns,
/// [`Transformed::try_transform_node_with()`] decides recursion continuation
/// and if state propagation is necessary. Then, the same procedure recursively
/// applies to the children of the node in question.
macro_rules! handle_transform_recursion {
($F_DOWN:expr, $F_SELF:expr, $F_UP:expr) => {{
let pre_visited = $F_DOWN?;
match pre_visited.tnr {
TreeNodeRecursion::Continue => pre_visited
.data
.map_children($F_SELF)?
.try_transform_node_with($F_UP, TreeNodeRecursion::Jump),
#[allow(clippy::redundant_closure_call)]
TreeNodeRecursion::Jump => $F_UP(pre_visited.data),
TreeNodeRecursion::Stop => return Ok(pre_visited),
}
.map(|mut post_visited| {
post_visited.transformed |= pre_visited.transformed;
post_visited
})
}};
}
/// Defines a visitable and rewriteable tree node. This trait is implemented
/// for plans ([`ExecutionPlan`] and [`LogicalPlan`]) as well as expression
/// trees ([`PhysicalExpr`], [`Expr`]) in DataFusion.
///
/// <!-- Since these are in the datafusion-common crate, can't use intra doc links) -->
/// [`ExecutionPlan`]: https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.ExecutionPlan.html
/// [`PhysicalExpr`]: https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.PhysicalExpr.html
/// [`LogicalPlan`]: https://docs.rs/datafusion-expr/latest/datafusion_expr/logical_plan/enum.LogicalPlan.html
/// [`Expr`]: https://docs.rs/datafusion-expr/latest/datafusion_expr/expr/enum.Expr.html
pub trait TreeNode: Sized {
/// Visit the tree node using the given [`TreeNodeVisitor`], performing a
/// depth-first walk of the node and its children.
///
/// Consider the following tree structure:
/// ```text
/// ParentNode
/// left: ChildNode1
/// right: ChildNode2
/// ```
///
/// Here, the nodes would be visited using the following order:
/// ```text
/// TreeNodeVisitor::f_down(ParentNode)
/// TreeNodeVisitor::f_down(ChildNode1)
/// TreeNodeVisitor::f_up(ChildNode1)
/// TreeNodeVisitor::f_down(ChildNode2)
/// TreeNodeVisitor::f_up(ChildNode2)
/// TreeNodeVisitor::f_up(ParentNode)
/// ```
///
/// See [`TreeNodeRecursion`] for more details on controlling the traversal.
///
/// If [`TreeNodeVisitor::f_down()`] or [`TreeNodeVisitor::f_up()`] returns [`Err`],
/// the recursion stops immediately.
///
/// If using the default [`TreeNodeVisitor::f_up`] that does nothing, consider using
/// [`Self::apply`].
fn visit<V: TreeNodeVisitor<Node = Self>>(
&self,
visitor: &mut V,
) -> Result<TreeNodeRecursion> {
match visitor.f_down(self)? {
TreeNodeRecursion::Continue => {
handle_visit_recursion!(
self.apply_children(&mut |n| n.visit(visitor))?,
UP
);
visitor.f_up(self)
}
TreeNodeRecursion::Jump => visitor.f_up(self),
TreeNodeRecursion::Stop => Ok(TreeNodeRecursion::Stop),
}
}
/// Implements the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern) for
/// recursively transforming [`TreeNode`]s.
///
/// Consider the following tree structure:
/// ```text
/// ParentNode
/// left: ChildNode1
/// right: ChildNode2
/// ```
///
/// Here, the nodes would be visited using the following order:
/// ```text
/// TreeNodeRewriter::f_down(ParentNode)
/// TreeNodeRewriter::f_down(ChildNode1)
/// TreeNodeRewriter::f_up(ChildNode1)
/// TreeNodeRewriter::f_down(ChildNode2)
/// TreeNodeRewriter::f_up(ChildNode2)
/// TreeNodeRewriter::f_up(ParentNode)
/// ```
///
/// See [`TreeNodeRecursion`] for more details on controlling the traversal.
///
/// If [`TreeNodeVisitor::f_down()`] or [`TreeNodeVisitor::f_up()`] returns [`Err`],
/// the recursion stops immediately.
fn rewrite<R: TreeNodeRewriter<Node = Self>>(
self,
rewriter: &mut R,
) -> Result<Transformed<Self>> {
handle_transform_recursion!(rewriter.f_down(self), |c| c.rewrite(rewriter), |n| {
rewriter.f_up(n)
})
}
/// Applies `f` to the node and its children. `f` is applied in a pre-order
/// way, and it is controlled by [`TreeNodeRecursion`], which means result
/// of the `f` on a node can cause an early return.
///
/// The `f` closure can be used to collect some information from tree nodes
/// or run a check on the tree.
fn apply<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
&self,
f: &mut F,
) -> Result<TreeNodeRecursion> {
handle_visit_recursion!(f(self)?, DOWN);
self.apply_children(&mut |n| n.apply(f))
}
/// Convenience utility for writing optimizer rules: Recursively apply the
/// given function `f` to the tree in a bottom-up (post-order) fashion. When
/// `f` does not apply to a given node, it is left unchanged.
fn transform<F: Fn(Self) -> Result<Transformed<Self>>>(
self,
f: &F,
) -> Result<Transformed<Self>> {
self.transform_up(f)
}
/// Convenience utility for writing optimizer rules: Recursively apply the
/// given function `f` to a node and then to its children (pre-order traversal).
/// When `f` does not apply to a given node, it is left unchanged.
fn transform_down<F: Fn(Self) -> Result<Transformed<Self>>>(
self,
f: &F,
) -> Result<Transformed<Self>> {
f(self)?.try_transform_node_with(
|n| n.map_children(|c| c.transform_down(f)),
TreeNodeRecursion::Continue,
)
}
/// Convenience utility for writing optimizer rules: Recursively apply the
/// given mutable function `f` to a node and then to its children (pre-order
/// traversal). When `f` does not apply to a given node, it is left unchanged.
fn transform_down_mut<F: FnMut(Self) -> Result<Transformed<Self>>>(
self,
f: &mut F,
) -> Result<Transformed<Self>> {
f(self)?.try_transform_node_with(
|n| n.map_children(|c| c.transform_down_mut(f)),
TreeNodeRecursion::Continue,
)
}
/// Convenience utility for writing optimizer rules: Recursively apply the
/// given function `f` to all children of a node, and then to the node itself
/// (post-order traversal). When `f` does not apply to a given node, it is
/// left unchanged.
fn transform_up<F: Fn(Self) -> Result<Transformed<Self>>>(
self,
f: &F,
) -> Result<Transformed<Self>> {
self.map_children(|c| c.transform_up(f))?
.try_transform_node_with(f, TreeNodeRecursion::Jump)
}
/// Convenience utility for writing optimizer rules: Recursively apply the
/// given mutable function `f` to all children of a node, and then to the
/// node itself (post-order traversal). When `f` does not apply to a given
/// node, it is left unchanged.
fn transform_up_mut<F: FnMut(Self) -> Result<Transformed<Self>>>(
self,
f: &mut F,
) -> Result<Transformed<Self>> {
self.map_children(|c| c.transform_up_mut(f))?
.try_transform_node_with(f, TreeNodeRecursion::Jump)
}
/// Transforms the tree using `f_down` while traversing the tree top-down
/// (pre-order), and using `f_up` while traversing the tree bottom-up
/// (post-order).
///
/// Use this method if you want to start the `f_up` process right where `f_down` jumps.
/// This can make the whole process faster by reducing the number of `f_up` steps.
/// If you don't need this, it's just like using `transform_down_mut` followed by
/// `transform_up_mut` on the same tree.
///
/// Consider the following tree structure:
/// ```text
/// ParentNode
/// left: ChildNode1
/// right: ChildNode2
/// ```
///
/// The nodes are visited using the following order:
/// ```text
/// f_down(ParentNode)
/// f_down(ChildNode1)
/// f_up(ChildNode1)
/// f_down(ChildNode2)
/// f_up(ChildNode2)
/// f_up(ParentNode)
/// ```
///
/// See [`TreeNodeRecursion`] for more details on controlling the traversal.
///
/// If `f_down` or `f_up` returns [`Err`], the recursion stops immediately.
///
/// Example:
/// ```text
/// | +---+
/// | | J |
/// | +---+
/// | |
/// | +---+
/// TreeNodeRecursion::Continue | | I |
/// | +---+
/// | |
/// | +---+
/// \|/ | F |
/// ' +---+
/// / \ ___________________
/// When `f_down` is +---+ \ ---+
/// applied on node "E", | E | | G |
/// it returns with "Jump". +---+ +---+
/// | |
/// +---+ +---+
/// | C | | H |
/// +---+ +---+
/// / \
/// +---+ +---+
/// | B | | D |
/// +---+ +---+
/// |
/// +---+
/// | A |
/// +---+
///
/// Instead of starting from leaf nodes, `f_up` starts from the node "E".
/// +---+
/// | | J |
/// | +---+
/// | |
/// | +---+
/// | | I |
/// | +---+
/// | |
/// / +---+
/// / | F |
/// / +---+
/// / / \ ______________________
/// | +---+ . \ ---+
/// | | E | /|\ After `f_down` jumps | G |
/// | +---+ | on node E, `f_up` +---+
/// \------| ---/ if applied on node E. |
/// +---+ +---+
/// | C | | H |
/// +---+ +---+
/// / \
/// +---+ +---+
/// | B | | D |
/// +---+ +---+
/// |
/// +---+
/// | A |
/// +---+
/// ```
fn transform_down_up<
FD: FnMut(Self) -> Result<Transformed<Self>>,
FU: FnMut(Self) -> Result<Transformed<Self>>,
>(
self,
f_down: &mut FD,
f_up: &mut FU,
) -> Result<Transformed<Self>> {
handle_transform_recursion!(
f_down(self),
|c| c.transform_down_up(f_down, f_up),
f_up
)
}
/// Apply the closure `F` to the node's children.
fn apply_children<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
&self,
f: &mut F,
) -> Result<TreeNodeRecursion>;
/// Apply transform `F` to the node's children. Note that the transform `F`
/// might have a direction (pre-order or post-order).
fn map_children<F: FnMut(Self) -> Result<Transformed<Self>>>(
self,
f: F,
) -> Result<Transformed<Self>>;
}
/// Implements the [visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern)
/// for recursively walking [`TreeNode`]s.
///
/// A [`TreeNodeVisitor`] allows one to express algorithms separately from the
/// code traversing the structure of the `TreeNode` tree, making it easier to
/// add new types of tree nodes and algorithms.
///
/// When passed to [`TreeNode::visit`], [`TreeNodeVisitor::f_down`] and
/// [`TreeNodeVisitor::f_up`] are invoked recursively on the tree.
/// See [`TreeNodeRecursion`] for more details on controlling the traversal.
pub trait TreeNodeVisitor: Sized {
/// The node type which is visitable.
type Node: TreeNode;
/// Invoked before any children of `node` are visited.
/// Default implementation simply continues the recursion.
fn f_down(&mut self, _node: &Self::Node) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
/// Invoked after all children of `node` are visited.
/// Default implementation simply continues the recursion.
fn f_up(&mut self, _node: &Self::Node) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
}
/// Trait for potentially recursively transforming a tree of [`TreeNode`]s.
pub trait TreeNodeRewriter: Sized {
/// The node type which is rewritable.
type Node: TreeNode;
/// Invoked while traversing down the tree before any children are rewritten.
/// Default implementation returns the node as is and continues recursion.
fn f_down(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
Ok(Transformed::no(node))
}
/// Invoked while traversing up the tree after all children have been rewritten.
/// Default implementation returns the node as is and continues recursion.
fn f_up(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
Ok(Transformed::no(node))
}
}
/// Controls how [`TreeNode`] recursions should proceed.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum TreeNodeRecursion {
/// Continue recursion with the next node.
Continue,
/// In top-down traversals, skip recursing into children but continue with
/// the next node, which actually means pruning of the subtree.
///
/// In bottom-up traversals, bypass calling bottom-up closures till the next
/// leaf node.
///
/// In combined traversals, if it is the `f_down` (pre-order) phase, execution
/// "jumps" to the next `f_up` (post-order) phase by shortcutting its children.
/// If it is the `f_up` (post-order) phase, execution "jumps" to the next `f_down`
/// (pre-order) phase by shortcutting its parent nodes until the first parent node
/// having unvisited children path.
Jump,
/// Stop recursion.
Stop,
}
/// This struct is used by tree transformation APIs such as
/// - [`TreeNode::rewrite`],
/// - [`TreeNode::transform_down`],
/// - [`TreeNode::transform_down_mut`],
/// - [`TreeNode::transform_up`],
/// - [`TreeNode::transform_up_mut`],
/// - [`TreeNode::transform_down_up`]
///
/// to control the transformation and return the transformed result.
///
/// Specifically, API users can provide transformation closures or [`TreeNodeRewriter`]
/// implementations to control the transformation by returning:
/// - The resulting (possibly transformed) node,
/// - A flag indicating whether any change was made to the node, and
/// - A flag specifying how to proceed with the recursion.
///
/// At the end of the transformation, the return value will contain:
/// - The final (possibly transformed) tree,
/// - A flag indicating whether any change was made to the tree, and
/// - A flag specifying how the recursion ended.
#[derive(PartialEq, Debug)]
pub struct Transformed<T> {
pub data: T,
pub transformed: bool,
pub tnr: TreeNodeRecursion,
}
impl<T> Transformed<T> {
/// Create a new `Transformed` object with the given information.
pub fn new(data: T, transformed: bool, tnr: TreeNodeRecursion) -> Self {
Self {
data,
transformed,
tnr,
}
}
/// Wrapper for transformed data with [`TreeNodeRecursion::Continue`] statement.
pub fn yes(data: T) -> Self {
Self::new(data, true, TreeNodeRecursion::Continue)
}
/// Wrapper for unchanged data with [`TreeNodeRecursion::Continue`] statement.
pub fn no(data: T) -> Self {
Self::new(data, false, TreeNodeRecursion::Continue)
}
/// Applies the given `f` to the data of this [`Transformed`] object.
pub fn update_data<U, F: FnOnce(T) -> U>(self, f: F) -> Transformed<U> {
Transformed::new(f(self.data), self.transformed, self.tnr)
}
/// Maps the data of [`Transformed`] object to the result of the given `f`.
pub fn map_data<U, F: FnOnce(T) -> Result<U>>(self, f: F) -> Result<Transformed<U>> {
f(self.data).map(|data| Transformed::new(data, self.transformed, self.tnr))
}
/// Handling [`TreeNodeRecursion::Continue`] and [`TreeNodeRecursion::Stop`]
/// is straightforward, but [`TreeNodeRecursion::Jump`] can behave differently
/// when we are traversing down or up on a tree. If [`TreeNodeRecursion`] of
/// the node is [`TreeNodeRecursion::Jump`], recursion stops with the given
/// `return_if_jump` value.
fn try_transform_node_with<F: FnOnce(T) -> Result<Transformed<T>>>(
mut self,
f: F,
return_if_jump: TreeNodeRecursion,
) -> Result<Transformed<T>> {
match self.tnr {
TreeNodeRecursion::Continue => {
return f(self.data).map(|mut t| {
t.transformed |= self.transformed;
t
});
}
TreeNodeRecursion::Jump => {
self.tnr = return_if_jump;
}
TreeNodeRecursion::Stop => {}
}
Ok(self)
}
/// If [`TreeNodeRecursion`] of the node is [`TreeNodeRecursion::Continue`] or
/// [`TreeNodeRecursion::Jump`], transformation is applied to the node.
/// Otherwise, it remains as it is.
pub fn try_transform_node<F: FnOnce(T) -> Result<Transformed<T>>>(
self,
f: F,
) -> Result<Transformed<T>> {
if self.tnr == TreeNodeRecursion::Stop {
Ok(self)
} else {
f(self.data).map(|mut t| {
t.transformed |= self.transformed;
t
})
}
}
}
/// Transformation helper to process tree nodes that are siblings.
pub trait TransformedIterator: Iterator {
fn map_until_stop_and_collect<
F: FnMut(Self::Item) -> Result<Transformed<Self::Item>>,
>(
self,
f: F,
) -> Result<Transformed<Vec<Self::Item>>>;
}
impl<I: Iterator> TransformedIterator for I {
fn map_until_stop_and_collect<
F: FnMut(Self::Item) -> Result<Transformed<Self::Item>>,
>(
self,
mut f: F,
) -> Result<Transformed<Vec<Self::Item>>> {
let mut tnr = TreeNodeRecursion::Continue;
let mut transformed = false;
let data = self
.map(|item| match tnr {
TreeNodeRecursion::Continue | TreeNodeRecursion::Jump => {
f(item).map(|result| {
tnr = result.tnr;
transformed |= result.transformed;
result.data
})
}
TreeNodeRecursion::Stop => Ok(item),
})
.collect::<Result<Vec<_>>>()?;
Ok(Transformed::new(data, transformed, tnr))
}
}
/// Transformation helper to access [`Transformed`] fields in a [`Result`] easily.
pub trait TransformedResult<T> {
fn data(self) -> Result<T>;
fn transformed(self) -> Result<bool>;
fn tnr(self) -> Result<TreeNodeRecursion>;
}
impl<T> TransformedResult<T> for Result<Transformed<T>> {
fn data(self) -> Result<T> {
self.map(|t| t.data)
}
fn transformed(self) -> Result<bool> {
self.map(|t| t.transformed)
}
fn tnr(self) -> Result<TreeNodeRecursion> {
self.map(|t| t.tnr)
}
}
/// Helper trait for implementing [`TreeNode`] that have children stored as
/// `Arc`s. If some trait object, such as `dyn T`, implements this trait,
/// its related `Arc<dyn T>` will automatically implement [`TreeNode`].
pub trait DynTreeNode {
/// Returns all children of the specified `TreeNode`.
fn arc_children(&self) -> Vec<Arc<Self>>;
/// Constructs a new node with the specified children.
fn with_new_arc_children(
&self,
arc_self: Arc<Self>,
new_children: Vec<Arc<Self>>,
) -> Result<Arc<Self>>;
}
/// Blanket implementation for any `Arc<T>` where `T` implements [`DynTreeNode`]
/// (such as [`Arc<dyn PhysicalExpr>`]).
impl<T: DynTreeNode + ?Sized> TreeNode for Arc<T> {
fn apply_children<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
&self,
f: &mut F,
) -> Result<TreeNodeRecursion> {
let mut tnr = TreeNodeRecursion::Continue;
for child in self.arc_children() {
tnr = f(&child)?;
handle_visit_recursion!(tnr)
}
Ok(tnr)
}
fn map_children<F: FnMut(Self) -> Result<Transformed<Self>>>(
self,
f: F,
) -> Result<Transformed<Self>> {
let children = self.arc_children();
if !children.is_empty() {
let new_children = children.into_iter().map_until_stop_and_collect(f)?;
// Propagate up `new_children.transformed` and `new_children.tnr`
// along with the node containing transformed children.
if new_children.transformed {
let arc_self = Arc::clone(&self);
new_children.map_data(|new_children| {
self.with_new_arc_children(arc_self, new_children)
})
} else {
Ok(Transformed::new(self, false, new_children.tnr))
}
} else {
Ok(Transformed::no(self))
}
}
}
/// Instead of implementing [`TreeNode`], it's recommended to implement a [`ConcreteTreeNode`] for
/// trees that contain nodes with payloads. This approach ensures safe execution of algorithms
/// involving payloads, by enforcing rules for detaching and reattaching child nodes.
pub trait ConcreteTreeNode: Sized {
/// Provides read-only access to child nodes.
fn children(&self) -> Vec<&Self>;
/// Detaches the node from its children, returning the node itself and its detached children.
fn take_children(self) -> (Self, Vec<Self>);
/// Reattaches updated child nodes to the node, returning the updated node.
fn with_new_children(self, children: Vec<Self>) -> Result<Self>;
}
impl<T: ConcreteTreeNode> TreeNode for T {
fn apply_children<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
&self,
f: &mut F,
) -> Result<TreeNodeRecursion> {
let mut tnr = TreeNodeRecursion::Continue;
for child in self.children() {
tnr = f(child)?;
handle_visit_recursion!(tnr)
}
Ok(tnr)
}
fn map_children<F: FnMut(Self) -> Result<Transformed<Self>>>(
self,
f: F,
) -> Result<Transformed<Self>> {
let (new_self, children) = self.take_children();
if !children.is_empty() {
let new_children = children.into_iter().map_until_stop_and_collect(f)?;
// Propagate up `new_children.transformed` and `new_children.tnr` along with
// the node containing transformed children.
new_children.map_data(|new_children| new_self.with_new_children(new_children))
} else {
Ok(Transformed::no(new_self))
}
}
}
#[cfg(test)]
mod tests {
use std::fmt::Display;
use crate::tree_node::{
Transformed, TransformedIterator, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
TreeNodeVisitor,
};
use crate::Result;
#[derive(PartialEq, Debug)]
struct TestTreeNode<T> {
children: Vec<TestTreeNode<T>>,
data: T,
}
impl<T> TestTreeNode<T> {
fn new(children: Vec<TestTreeNode<T>>, data: T) -> Self {
Self { children, data }
}
}
impl<T> TreeNode for TestTreeNode<T> {
fn apply_children<F>(&self, f: &mut F) -> Result<TreeNodeRecursion>
where
F: FnMut(&Self) -> Result<TreeNodeRecursion>,
{
let mut tnr = TreeNodeRecursion::Continue;
for child in &self.children {
tnr = f(child)?;
handle_visit_recursion!(tnr);
}
Ok(tnr)
}
fn map_children<F>(self, f: F) -> Result<Transformed<Self>>
where
F: FnMut(Self) -> Result<Transformed<Self>>,
{
Ok(self
.children
.into_iter()
.map_until_stop_and_collect(f)?
.update_data(|new_children| Self {
children: new_children,
..self
}))
}
}
// J
// |
// I
// |
// F
// / \
// E G
// | |
// C H
// / \
// B D
// |
// A
fn test_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "a".to_string());
let node_b = TestTreeNode::new(vec![], "b".to_string());
let node_d = TestTreeNode::new(vec![node_a], "d".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "c".to_string());
let node_e = TestTreeNode::new(vec![node_c], "e".to_string());
let node_h = TestTreeNode::new(vec![], "h".to_string());
let node_g = TestTreeNode::new(vec![node_h], "g".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f".to_string());
let node_i = TestTreeNode::new(vec![node_f], "i".to_string());
TestTreeNode::new(vec![node_i], "j".to_string())
}
// Continue on all nodes
// Expected visits in a combined traversal
fn all_visits() -> Vec<String> {
vec![
"f_down(j)",
"f_down(i)",
"f_down(f)",
"f_down(e)",
"f_down(c)",
"f_down(b)",
"f_up(b)",
"f_down(d)",
"f_down(a)",
"f_up(a)",
"f_up(d)",
"f_up(c)",
"f_up(e)",
"f_down(g)",
"f_down(h)",
"f_up(h)",
"f_up(g)",
"f_up(f)",
"f_up(i)",
"f_up(j)",
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
// Expected transformed tree after a combined traversal
fn transformed_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_up(f_down(a))".to_string());
let node_b = TestTreeNode::new(vec![], "f_up(f_down(b))".to_string());
let node_d = TestTreeNode::new(vec![node_a], "f_up(f_down(d))".to_string());
let node_c =
TestTreeNode::new(vec![node_b, node_d], "f_up(f_down(c))".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_up(f_down(e))".to_string());
let node_h = TestTreeNode::new(vec![], "f_up(f_down(h))".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_up(f_down(g))".to_string());
let node_f =
TestTreeNode::new(vec![node_e, node_g], "f_up(f_down(f))".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_up(f_down(i))".to_string());
TestTreeNode::new(vec![node_i], "f_up(f_down(j))".to_string())
}
// Expected transformed tree after a top-down traversal
fn transformed_down_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_down(a)".to_string());
let node_b = TestTreeNode::new(vec![], "f_down(b)".to_string());
let node_d = TestTreeNode::new(vec![node_a], "f_down(d)".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "f_down(c)".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_down(e)".to_string());
let node_h = TestTreeNode::new(vec![], "f_down(h)".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_down(g)".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f_down(f)".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_down(i)".to_string());
TestTreeNode::new(vec![node_i], "f_down(j)".to_string())
}
// Expected transformed tree after a bottom-up traversal
fn transformed_up_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_up(a)".to_string());
let node_b = TestTreeNode::new(vec![], "f_up(b)".to_string());
let node_d = TestTreeNode::new(vec![node_a], "f_up(d)".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "f_up(c)".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_up(e)".to_string());
let node_h = TestTreeNode::new(vec![], "f_up(h)".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_up(g)".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f_up(f)".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_up(i)".to_string());
TestTreeNode::new(vec![node_i], "f_up(j)".to_string())
}
// f_down Jump on A node
fn f_down_jump_on_a_visits() -> Vec<String> {
vec![
"f_down(j)",
"f_down(i)",
"f_down(f)",
"f_down(e)",
"f_down(c)",
"f_down(b)",
"f_up(b)",
"f_down(d)",
"f_down(a)",
"f_up(a)",
"f_up(d)",
"f_up(c)",
"f_up(e)",
"f_down(g)",
"f_down(h)",
"f_up(h)",
"f_up(g)",
"f_up(f)",
"f_up(i)",
"f_up(j)",
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
fn f_down_jump_on_a_transformed_down_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_down(a)".to_string());
let node_b = TestTreeNode::new(vec![], "f_down(b)".to_string());
let node_d = TestTreeNode::new(vec![node_a], "f_down(d)".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "f_down(c)".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_down(e)".to_string());
let node_h = TestTreeNode::new(vec![], "f_down(h)".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_down(g)".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f_down(f)".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_down(i)".to_string());
TestTreeNode::new(vec![node_i], "f_down(j)".to_string())
}
// f_down Jump on E node
fn f_down_jump_on_e_visits() -> Vec<String> {
vec![
"f_down(j)",
"f_down(i)",
"f_down(f)",
"f_down(e)",
"f_up(e)",
"f_down(g)",
"f_down(h)",
"f_up(h)",
"f_up(g)",
"f_up(f)",
"f_up(i)",
"f_up(j)",
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
fn f_down_jump_on_e_transformed_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "a".to_string());
let node_b = TestTreeNode::new(vec![], "b".to_string());
let node_d = TestTreeNode::new(vec![node_a], "d".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "c".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_up(f_down(e))".to_string());
let node_h = TestTreeNode::new(vec![], "f_up(f_down(h))".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_up(f_down(g))".to_string());
let node_f =
TestTreeNode::new(vec![node_e, node_g], "f_up(f_down(f))".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_up(f_down(i))".to_string());
TestTreeNode::new(vec![node_i], "f_up(f_down(j))".to_string())
}
fn f_down_jump_on_e_transformed_down_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "a".to_string());
let node_b = TestTreeNode::new(vec![], "b".to_string());
let node_d = TestTreeNode::new(vec![node_a], "d".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "c".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_down(e)".to_string());
let node_h = TestTreeNode::new(vec![], "f_down(h)".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_down(g)".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f_down(f)".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_down(i)".to_string());
TestTreeNode::new(vec![node_i], "f_down(j)".to_string())
}
// f_up Jump on A node
fn f_up_jump_on_a_visits() -> Vec<String> {
vec![
"f_down(j)",
"f_down(i)",
"f_down(f)",
"f_down(e)",
"f_down(c)",
"f_down(b)",
"f_up(b)",
"f_down(d)",
"f_down(a)",
"f_up(a)",
"f_down(g)",
"f_down(h)",
"f_up(h)",
"f_up(g)",
"f_up(f)",
"f_up(i)",
"f_up(j)",
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
fn f_up_jump_on_a_transformed_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_up(f_down(a))".to_string());
let node_b = TestTreeNode::new(vec![], "f_up(f_down(b))".to_string());
let node_d = TestTreeNode::new(vec![node_a], "f_down(d)".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "f_down(c)".to_string());
let node_e = TestTreeNode::new(vec![node_c], "f_down(e)".to_string());
let node_h = TestTreeNode::new(vec![], "f_up(f_down(h))".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_up(f_down(g))".to_string());
let node_f =
TestTreeNode::new(vec![node_e, node_g], "f_up(f_down(f))".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_up(f_down(i))".to_string());
TestTreeNode::new(vec![node_i], "f_up(f_down(j))".to_string())
}
fn f_up_jump_on_a_transformed_up_tree() -> TestTreeNode<String> {
let node_a = TestTreeNode::new(vec![], "f_up(a)".to_string());
let node_b = TestTreeNode::new(vec![], "f_up(b)".to_string());
let node_d = TestTreeNode::new(vec![node_a], "d".to_string());
let node_c = TestTreeNode::new(vec![node_b, node_d], "c".to_string());
let node_e = TestTreeNode::new(vec![node_c], "e".to_string());
let node_h = TestTreeNode::new(vec![], "f_up(h)".to_string());
let node_g = TestTreeNode::new(vec![node_h], "f_up(g)".to_string());
let node_f = TestTreeNode::new(vec![node_e, node_g], "f_up(f)".to_string());
let node_i = TestTreeNode::new(vec![node_f], "f_up(i)".to_string());
TestTreeNode::new(vec![node_i], "f_up(j)".to_string())
}
// f_up Jump on E node
fn f_up_jump_on_e_visits() -> Vec<String> {
vec![
"f_down(j)",
"f_down(i)",
"f_down(f)",
"f_down(e)",
"f_down(c)",
"f_down(b)",
"f_up(b)",
"f_down(d)",
"f_down(a)",
"f_up(a)",
"f_up(d)",
"f_up(c)",
"f_up(e)",
"f_down(g)",
"f_down(h)",
"f_up(h)",