Skip to main content

datafusion_common/
cse.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Common Subexpression Elimination logic implemented in [`CSE`] can be controlled with
6//! a [`CSEController`], that defines how to eliminate common subtrees from a particular
7//! [`TreeNode`] tree.
8
9use crate::Result;
10use crate::hash_utils::combine_hashes;
11use crate::tree_node::{
12    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
13    TreeNodeVisitor,
14};
15use indexmap::IndexMap;
16use std::collections::{HashMap, HashSet};
17use std::hash::{BuildHasher, Hash, Hasher, RandomState};
18use std::marker::PhantomData;
19use std::sync::Arc;
20
21/// Hashes the direct content of an [`TreeNode`] without recursing into its children.
22///
23/// This method is useful to incrementally compute hashes, such as in [`CSE`] which builds
24/// a deep hash of a node and its descendants during the bottom-up phase of the first
25/// traversal and so avoid computing the hash of the node and then the hash of its
26/// descendants separately.
27///
28/// If a node doesn't have any children then the value returned by `hash_node()` is
29/// similar to '.hash()`, but not necessarily returns the same value.
30pub trait HashNode {
31    fn hash_node<H: Hasher>(&self, state: &mut H);
32}
33
34impl<T: HashNode + ?Sized> HashNode for Arc<T> {
35    fn hash_node<H: Hasher>(&self, state: &mut H) {
36        (**self).hash_node(state);
37    }
38}
39
40/// The `Normalizeable` trait defines a method to determine whether a node can be normalized.
41///
42/// Normalization is the process of converting a node into a canonical form that can be used
43/// to compare nodes for equality. This is useful in optimizations like Common Subexpression Elimination (CSE),
44/// where semantically equivalent nodes (e.g., `a + b` and `b + a`) should be treated as equal.
45pub trait Normalizeable {
46    fn can_normalize(&self) -> bool;
47}
48
49/// The `NormalizeEq` trait extends `Eq` and `Normalizeable` to provide a method for comparing
50/// normalized nodes in optimizations like Common Subexpression Elimination (CSE).
51///
52/// The `normalize_eq` method ensures that two nodes that are semantically equivalent (after normalization)
53/// are considered equal in CSE optimization, even if their original forms differ.
54///
55/// This trait allows for equality comparisons between nodes with equivalent semantics, regardless of their
56/// internal representations.
57pub trait NormalizeEq: Eq + Normalizeable {
58    fn normalize_eq(&self, other: &Self) -> bool;
59}
60
61/// Identifier that represents a [`TreeNode`] tree.
62///
63/// This identifier is designed to be efficient and  "hash", "accumulate", "equal" and
64/// "have no collision (as low as possible)"
65#[derive(Debug, Eq)]
66struct Identifier<'n, N: NormalizeEq> {
67    // Hash of `node` built up incrementally during the first, visiting traversal.
68    // Its value is not necessarily equal to default hash of the node. E.g. it is not
69    // equal to `expr.hash()` if the node is `Expr`.
70    hash: u64,
71    node: &'n N,
72}
73
74impl<N: NormalizeEq> Clone for Identifier<'_, N> {
75    fn clone(&self) -> Self {
76        *self
77    }
78}
79impl<N: NormalizeEq> Copy for Identifier<'_, N> {}
80
81impl<N: NormalizeEq> Hash for Identifier<'_, N> {
82    fn hash<H: Hasher>(&self, state: &mut H) {
83        state.write_u64(self.hash);
84    }
85}
86
87impl<N: NormalizeEq> PartialEq for Identifier<'_, N> {
88    fn eq(&self, other: &Self) -> bool {
89        self.hash == other.hash && self.node.normalize_eq(other.node)
90    }
91}
92
93impl<'n, N> Identifier<'n, N>
94where
95    N: HashNode + NormalizeEq,
96{
97    fn new(node: &'n N, random_state: &RandomState) -> Self {
98        let mut hasher = random_state.build_hasher();
99        node.hash_node(&mut hasher);
100        let hash = hasher.finish();
101        Self { hash, node }
102    }
103
104    fn combine(mut self, other: Option<Self>) -> Self {
105        other.map_or(self, |other_id| {
106            self.hash = combine_hashes(self.hash, other_id.hash);
107            self
108        })
109    }
110}
111
112/// A cache that contains the postorder index and the identifier of [`TreeNode`]s by the
113/// preorder index of the nodes.
114///
115/// This cache is filled by [`CSEVisitor`] during the first traversal and is
116/// used by [`CSERewriter`] during the second traversal.
117///
118/// The purpose of this cache is to quickly find the identifier of a node during the
119/// second traversal.
120///
121/// Elements in this array are added during `f_down` so the indexes represent the preorder
122/// index of nodes and thus element 0 belongs to the root of the tree.
123///
124/// The elements of the array are tuples that contain:
125/// - Postorder index that belongs to the preorder index. Assigned during `f_up`, start
126///   from 0.
127/// - The optional [`Identifier`] of the node. If none the node should not be considered
128///   for CSE.
129///
130/// # Example
131/// An expression tree like `(a + b)` would have the following `IdArray`:
132/// ```text
133/// [
134///   (2, Some(Identifier(hash_of("a + b"), &"a + b"))),
135///   (1, Some(Identifier(hash_of("a"), &"a"))),
136///   (0, Some(Identifier(hash_of("b"), &"b")))
137/// ]
138/// ```
139type IdArray<'n, N> = Vec<(usize, Option<Identifier<'n, N>>)>;
140
141#[derive(PartialEq, Eq)]
142/// How many times a node is evaluated. A node can be considered common if evaluated
143/// surely at least 2 times or surely only once but also conditionally.
144enum NodeEvaluation {
145    SurelyOnce,
146    ConditionallyAtLeastOnce,
147    Common,
148}
149
150/// A map that contains the evaluation stats of [`TreeNode`]s by their identifiers.
151type NodeStats<'n, N> = HashMap<Identifier<'n, N>, NodeEvaluation>;
152
153/// A map that contains the common [`TreeNode`]s and their alias by their identifiers,
154/// extracted during the second, rewriting traversal.
155type CommonNodes<'n, N> = IndexMap<Identifier<'n, N>, (N, String)>;
156
157type ChildrenList<N> = (Vec<N>, Vec<N>);
158
159/// The [`TreeNode`] specific definition of elimination.
160pub trait CSEController {
161    /// The type of the tree nodes.
162    type Node;
163
164    /// Splits the children to normal and conditionally evaluated ones or returns `None`
165    /// if all are always evaluated.
166    ///
167    /// The returned references must point to the children of `node` themselves. The two
168    /// lists can be in any order.
169    fn conditional_children(node: &Self::Node) -> Option<ChildrenList<&Self::Node>>;
170
171    // Returns true if a node is valid. If a node is invalid then it can't be eliminated.
172    // Validity is propagated up which means no subtree can be eliminated that contains
173    // an invalid node.
174    // (E.g. volatile expressions are not valid and subtrees containing such a node can't
175    // be extracted.)
176    fn is_valid(node: &Self::Node) -> bool;
177
178    // Returns true if a node should be ignored during CSE. Contrary to validity of a node,
179    // it is not propagated up.
180    fn is_ignored(&self, node: &Self::Node) -> bool;
181
182    // Generates a new name for the extracted subtree.
183    fn generate_alias(&self) -> String;
184
185    // Replaces a node to the generated alias.
186    fn rewrite(&mut self, node: &Self::Node, alias: &str) -> Self::Node;
187
188    // A helper method called on each node during top-down traversal during the second,
189    // rewriting traversal of CSE.
190    fn rewrite_f_down(&mut self, _node: &Self::Node) {}
191
192    // A helper method called on each node during bottom-up traversal during the second,
193    // rewriting traversal of CSE.
194    fn rewrite_f_up(&mut self, _node: &Self::Node) {}
195}
196
197/// The result of potentially rewriting a list of [`TreeNode`]s to eliminate common
198/// subtrees.
199#[derive(Debug)]
200pub enum FoundCommonNodes<N> {
201    /// No common [`TreeNode`]s were found
202    No { original_nodes_list: Vec<Vec<N>> },
203
204    /// Common [`TreeNode`]s were found
205    Yes {
206        /// extracted common [`TreeNode`]
207        common_nodes: Vec<(N, String)>,
208
209        /// new [`TreeNode`]s with common subtrees replaced
210        new_nodes_list: Vec<Vec<N>>,
211
212        /// original [`TreeNode`]s
213        original_nodes_list: Vec<Vec<N>>,
214    },
215}
216
217/// Go through a [`TreeNode`] tree and generate identifiers for each subtrees.
218///
219/// An identifier contains information of the [`TreeNode`] itself and its subtrees.
220/// This visitor implementation use a stack `visit_stack` to track traversal, which
221/// lets us know when a subtree's visiting is finished. When `pre_visit` is called
222/// (traversing to a new node), an `EnterMark` and an `NodeItem` will be pushed into stack.
223/// And try to pop out a `EnterMark` on leaving a node (`f_up()`). All `NodeItem`
224/// before the first `EnterMark` is considered to be sub-tree of the leaving node.
225///
226/// This visitor also records identifier in `id_array`. Makes the following traverse
227/// pass can get the identifier of a node without recalculate it. We assign each node
228/// in the tree a series number, start from 1, maintained by `series_number`.
229/// Series number represents the order we left (`f_up()`) a node. Has the property
230/// that child node's series number always smaller than parent's. While `id_array` is
231/// organized in the order we enter (`f_down()`) a node. `node_count` helps us to
232/// get the index of `id_array` for each node.
233///
234/// A [`TreeNode`] without any children (column, literal etc.) will not have identifier
235/// because they should not be recognized as common subtree.
236struct CSEVisitor<'a, 'n, N, C>
237where
238    N: NormalizeEq,
239    C: CSEController<Node = N>,
240{
241    /// statistics of [`TreeNode`]s
242    node_stats: &'a mut NodeStats<'n, N>,
243
244    /// cache to speed up second traversal
245    id_array: &'a mut IdArray<'n, N>,
246
247    /// inner states
248    visit_stack: Vec<VisitRecord<'n, N>>,
249
250    /// buffer reused by `pop_enter_mark` to collect the identifiers of children
251    node_ids: Vec<Identifier<'n, N>>,
252
253    /// preorder index, start from 0.
254    down_index: usize,
255
256    /// postorder index, start from 0.
257    up_index: usize,
258
259    /// a [`RandomState`] to generate hashes during the first traversal
260    random_state: &'a RandomState,
261
262    /// a flag to indicate that common [`TreeNode`]s found
263    found_common: bool,
264
265    /// if we are in a conditional branch. A conditional branch means that the [`TreeNode`]
266    /// might not be executed depending on the runtime values of other [`TreeNode`]s, and
267    /// thus can not be extracted as a common [`TreeNode`].
268    conditional: bool,
269
270    controller: &'a C,
271}
272
273/// Record item that used when traversing a [`TreeNode`] tree.
274enum VisitRecord<'n, N>
275where
276    N: NormalizeEq,
277{
278    /// Marks the beginning of [`TreeNode`]. It contains:
279    /// - The post-order index assigned during the first, visiting traversal.
280    EnterMark(usize),
281
282    /// Marks an accumulated subtree. It contains:
283    /// - The accumulated identifier of a subtree.
284    /// - A accumulated boolean flag if the subtree is valid for CSE.
285    ///   The flag is propagated up from children to parent. (E.g. volatile expressions
286    ///   are not valid and can't be extracted, but non-volatile children of volatile
287    ///   expressions can be extracted.)
288    NodeItem(Identifier<'n, N>, bool),
289}
290
291impl<'n, N, C> CSEVisitor<'_, 'n, N, C>
292where
293    N: TreeNode + HashNode + NormalizeEq,
294    C: CSEController<Node = N>,
295{
296    /// Find the first `EnterMark` in the stack, and accumulates every `NodeItem` before
297    /// it. Returns a tuple that contains:
298    /// - The pre-order index of the [`TreeNode`] we marked.
299    /// - The accumulated identifier of the children of the marked [`TreeNode`].
300    /// - An accumulated boolean flag from the children of the marked [`TreeNode`] if all
301    ///   children are valid for CSE (i.e. it is safe to extract the [`TreeNode`] as a
302    ///   common [`TreeNode`] from its children POV).
303    ///   (E.g. if any of the children of the marked expression is not valid (e.g. is
304    ///   volatile) then the expression is also not valid, so we can propagate this
305    ///   information up from children to parents via `visit_stack` during the first,
306    ///   visiting traversal and no need to test the expression's validity beforehand with
307    ///   an extra traversal).
308    fn pop_enter_mark(
309        &mut self,
310        can_normalize: bool,
311    ) -> (usize, Option<Identifier<'n, N>>, bool) {
312        let mut is_valid = true;
313
314        while let Some(item) = self.visit_stack.pop() {
315            match item {
316                VisitRecord::EnterMark(down_index) => {
317                    if can_normalize {
318                        self.node_ids.sort_by_key(|i| i.hash);
319                    }
320                    let node_id = self
321                        .node_ids
322                        .drain(..)
323                        .fold(None, |accum, item| Some(item.combine(accum)));
324                    return (down_index, node_id, is_valid);
325                }
326                VisitRecord::NodeItem(sub_node_id, sub_node_is_valid) => {
327                    self.node_ids.push(sub_node_id);
328                    is_valid &= sub_node_is_valid;
329                }
330            }
331        }
332        unreachable!("EnterMark should paired with NodeItem");
333    }
334}
335
336impl<'n, N, C> TreeNodeVisitor<'n> for CSEVisitor<'_, 'n, N, C>
337where
338    N: TreeNode + HashNode + NormalizeEq,
339    C: CSEController<Node = N>,
340{
341    type Node = N;
342
343    fn f_down(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> {
344        self.id_array.push((0, None));
345        self.visit_stack
346            .push(VisitRecord::EnterMark(self.down_index));
347        self.down_index += 1;
348
349        // If a node can short-circuit then some of its children might not be executed so
350        // count the occurrence either normal or conditional.
351        Ok(if self.conditional {
352            // If we are already in a conditionally evaluated subtree then continue
353            // traversal.
354            TreeNodeRecursion::Continue
355        } else {
356            // If we are already in a node that can short-circuit then start new
357            // traversals on its normal conditional children.
358            match C::conditional_children(node) {
359                Some((_normal, conditional)) => {
360                    // Visit the children in tree order, whatever order the
361                    // controller lists them in. `CSERewriter` reads `id_array` in
362                    // pre-order, so the indexes that this visitor assigns must
363                    // follow the same order.
364                    let conditional = conditional
365                        .into_iter()
366                        .map(std::ptr::from_ref)
367                        .collect::<HashSet<_>>();
368                    node.apply_children(|child| {
369                        self.conditional =
370                            conditional.contains(&std::ptr::from_ref(child));
371                        child.visit(self)?;
372                        Ok(TreeNodeRecursion::Continue)
373                    })?;
374                    self.conditional = false;
375
376                    TreeNodeRecursion::Jump
377                }
378
379                // In case of non-short-circuit node continue the traversal.
380                _ => TreeNodeRecursion::Continue,
381            }
382        })
383    }
384
385    fn f_up(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> {
386        let (down_index, sub_node_id, sub_node_is_valid) =
387            self.pop_enter_mark(node.can_normalize());
388
389        let node_id = Identifier::new(node, self.random_state).combine(sub_node_id);
390        let is_valid = C::is_valid(node) && sub_node_is_valid;
391
392        self.id_array[down_index].0 = self.up_index;
393        if is_valid && !self.controller.is_ignored(node) {
394            self.id_array[down_index].1 = Some(node_id);
395            self.node_stats
396                .entry(node_id)
397                .and_modify(|evaluation| {
398                    if *evaluation == NodeEvaluation::SurelyOnce
399                        || *evaluation == NodeEvaluation::ConditionallyAtLeastOnce
400                            && !self.conditional
401                    {
402                        *evaluation = NodeEvaluation::Common;
403                        self.found_common = true;
404                    }
405                })
406                .or_insert_with(|| {
407                    if self.conditional {
408                        NodeEvaluation::ConditionallyAtLeastOnce
409                    } else {
410                        NodeEvaluation::SurelyOnce
411                    }
412                });
413        }
414        self.visit_stack
415            .push(VisitRecord::NodeItem(node_id, is_valid));
416        self.up_index += 1;
417
418        Ok(TreeNodeRecursion::Continue)
419    }
420}
421
422/// Rewrite a [`TreeNode`] tree by replacing detected common subtrees with the
423/// corresponding temporary [`TreeNode`], that column contains the evaluate result of
424/// replaced [`TreeNode`] tree.
425struct CSERewriter<'a, 'n, N, C>
426where
427    N: NormalizeEq,
428    C: CSEController<Node = N>,
429{
430    /// statistics of [`TreeNode`]s
431    node_stats: &'a NodeStats<'n, N>,
432
433    /// cache to speed up second traversal
434    id_array: &'a IdArray<'n, N>,
435
436    /// common [`TreeNode`]s, that are replaced during the second traversal, are collected
437    /// to this map
438    common_nodes: &'a mut CommonNodes<'n, N>,
439
440    // preorder index, starts from 0.
441    down_index: usize,
442
443    controller: &'a mut C,
444}
445
446impl<N, C> TreeNodeRewriter for CSERewriter<'_, '_, N, C>
447where
448    N: TreeNode + NormalizeEq,
449    C: CSEController<Node = N>,
450{
451    type Node = N;
452
453    fn f_down(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
454        self.controller.rewrite_f_down(&node);
455
456        let (up_index, node_id) = self.id_array[self.down_index];
457        self.down_index += 1;
458
459        // Handle nodes with identifiers only
460        if let Some(node_id) = node_id {
461            let evaluation = self.node_stats.get(&node_id).unwrap();
462            if *evaluation == NodeEvaluation::Common {
463                // step index to skip all sub-node (which has smaller series number).
464                while self.down_index < self.id_array.len()
465                    && self.id_array[self.down_index].0 < up_index
466                {
467                    self.down_index += 1;
468                }
469
470                // We *must* replace all original nodes with same `node_id`, not just the first
471                // node which is inserted into the common_nodes. This is because nodes with the same
472                // `node_id` are semantically equivalent, but not exactly the same.
473                //
474                // For example, `a + 1` and `1 + a` are semantically equivalent but not identical.
475                // In this case, we should replace the common expression `1 + a` with a new variable
476                // (e.g., `__common_cse_1`). So, `a + 1` and `1 + a` would both be replaced by
477                // `__common_cse_1`.
478                //
479                // The final result would be:
480                // - `__common_cse_1 as a + 1`
481                // - `__common_cse_1 as 1 + a`
482                //
483                // This way, we can efficiently handle semantically equivalent expressions without
484                // incorrectly treating them as identical.
485                let rewritten = if let Some((_, alias)) = self.common_nodes.get(&node_id)
486                {
487                    self.controller.rewrite(&node, alias)
488                } else {
489                    let node_alias = self.controller.generate_alias();
490                    let rewritten = self.controller.rewrite(&node, &node_alias);
491                    self.common_nodes.insert(node_id, (node, node_alias));
492                    rewritten
493                };
494
495                return Ok(Transformed::new(rewritten, true, TreeNodeRecursion::Jump));
496            }
497        }
498
499        Ok(Transformed::no(node))
500    }
501
502    fn f_up(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
503        self.controller.rewrite_f_up(&node);
504
505        Ok(Transformed::no(node))
506    }
507}
508
509/// The main entry point of Common Subexpression Elimination.
510///
511/// [`CSE`] requires a [`CSEController`], that defines how common subtrees of a particular
512/// [`TreeNode`] tree can be eliminated. The elimination process can be started with the
513/// [`CSE::extract_common_nodes()`] method.
514pub struct CSE<N, C: CSEController<Node = N>> {
515    random_state: RandomState,
516    phantom_data: PhantomData<N>,
517    controller: C,
518}
519
520impl<N, C> CSE<N, C>
521where
522    N: TreeNode + HashNode + Clone + NormalizeEq,
523    C: CSEController<Node = N>,
524{
525    pub fn new(controller: C) -> Self {
526        Self {
527            random_state: RandomState::new(),
528            phantom_data: PhantomData,
529            controller,
530        }
531    }
532
533    /// Add an identifier to `id_array` for every [`TreeNode`] in this tree.
534    fn node_to_id_array<'n>(
535        &self,
536        node: &'n N,
537        node_stats: &mut NodeStats<'n, N>,
538        id_array: &mut IdArray<'n, N>,
539    ) -> Result<bool> {
540        let mut visitor = CSEVisitor {
541            node_stats,
542            id_array,
543            visit_stack: vec![],
544            node_ids: vec![],
545            down_index: 0,
546            up_index: 0,
547            random_state: &self.random_state,
548            found_common: false,
549            conditional: false,
550            controller: &self.controller,
551        };
552        node.visit(&mut visitor)?;
553
554        Ok(visitor.found_common)
555    }
556
557    /// Returns the identifier list for each element in `nodes` and a flag to indicate if
558    /// rewrite phase of CSE make sense.
559    ///
560    /// Returns and array with 1 element for each input node in `nodes`
561    ///
562    /// Each element is itself the result of [`CSE::node_to_id_array`] for that node
563    /// (e.g. the identifiers for each node in the tree)
564    fn to_arrays<'n>(
565        &self,
566        nodes: &'n [N],
567        node_stats: &mut NodeStats<'n, N>,
568    ) -> Result<(bool, Vec<IdArray<'n, N>>)> {
569        let mut found_common = false;
570        nodes
571            .iter()
572            .map(|n| {
573                let mut id_array = vec![];
574                self.node_to_id_array(n, node_stats, &mut id_array)
575                    .map(|fc| {
576                        found_common |= fc;
577
578                        id_array
579                    })
580            })
581            .collect::<Result<Vec<_>>>()
582            .map(|id_arrays| (found_common, id_arrays))
583    }
584
585    /// Replace common subtrees in `node` with the corresponding temporary
586    /// [`TreeNode`], updating `common_nodes` with any replaced [`TreeNode`]
587    fn replace_common_node<'n>(
588        &mut self,
589        node: N,
590        id_array: &IdArray<'n, N>,
591        node_stats: &NodeStats<'n, N>,
592        common_nodes: &mut CommonNodes<'n, N>,
593    ) -> Result<N> {
594        if id_array.is_empty() {
595            Ok(Transformed::no(node))
596        } else {
597            node.rewrite(&mut CSERewriter {
598                node_stats,
599                id_array,
600                common_nodes,
601                down_index: 0,
602                controller: &mut self.controller,
603            })
604        }
605        .data()
606    }
607
608    /// Replace common subtrees in `nodes_list` with the corresponding temporary
609    /// [`TreeNode`], updating `common_nodes` with any replaced [`TreeNode`].
610    fn rewrite_nodes_list<'n>(
611        &mut self,
612        nodes_list: Vec<Vec<N>>,
613        arrays_list: &[Vec<IdArray<'n, N>>],
614        node_stats: &NodeStats<'n, N>,
615        common_nodes: &mut CommonNodes<'n, N>,
616    ) -> Result<Vec<Vec<N>>> {
617        nodes_list
618            .into_iter()
619            .zip(arrays_list.iter())
620            .map(|(nodes, arrays)| {
621                nodes
622                    .into_iter()
623                    .zip(arrays.iter())
624                    .map(|(node, id_array)| {
625                        self.replace_common_node(node, id_array, node_stats, common_nodes)
626                    })
627                    .collect::<Result<Vec<_>>>()
628            })
629            .collect::<Result<Vec<_>>>()
630    }
631
632    /// Extracts common [`TreeNode`]s and rewrites `nodes_list`.
633    ///
634    /// Returns [`FoundCommonNodes`] recording the result of the extraction.
635    pub fn extract_common_nodes(
636        &mut self,
637        nodes_list: Vec<Vec<N>>,
638    ) -> Result<FoundCommonNodes<N>> {
639        let mut found_common = false;
640        let mut node_stats = NodeStats::new();
641
642        let id_arrays_list = nodes_list
643            .iter()
644            .map(|nodes| {
645                self.to_arrays(nodes, &mut node_stats)
646                    .map(|(fc, id_arrays)| {
647                        found_common |= fc;
648
649                        id_arrays
650                    })
651            })
652            .collect::<Result<Vec<_>>>()?;
653        if found_common {
654            let mut common_nodes = CommonNodes::new();
655            let new_nodes_list = self.rewrite_nodes_list(
656                // Must clone the list of nodes as Identifiers use references to original
657                // nodes so we have to keep them intact.
658                nodes_list.clone(),
659                &id_arrays_list,
660                &node_stats,
661                &mut common_nodes,
662            )?;
663            assert!(!common_nodes.is_empty());
664
665            Ok(FoundCommonNodes::Yes {
666                common_nodes: common_nodes.into_values().collect(),
667                new_nodes_list,
668                original_nodes_list: nodes_list,
669            })
670        } else {
671            Ok(FoundCommonNodes::No {
672                original_nodes_list: nodes_list,
673            })
674        }
675    }
676}
677
678#[cfg(test)]
679mod test {
680    use crate::Result;
681    use crate::alias::AliasGenerator;
682    use crate::cse::{
683        CSE, CSEController, HashNode, IdArray, Identifier, NodeStats, NormalizeEq,
684        Normalizeable,
685    };
686    use crate::tree_node::tests::TestTreeNode;
687    use std::collections::HashSet;
688    use std::hash::{Hash, Hasher};
689
690    const CSE_PREFIX: &str = "__common_node";
691
692    #[derive(Clone, Copy)]
693    pub enum TestTreeNodeMask {
694        Normal,
695        NormalAndAggregates,
696    }
697
698    pub struct TestTreeNodeCSEController<'a> {
699        alias_generator: &'a AliasGenerator,
700        mask: TestTreeNodeMask,
701    }
702
703    impl<'a> TestTreeNodeCSEController<'a> {
704        fn new(alias_generator: &'a AliasGenerator, mask: TestTreeNodeMask) -> Self {
705            Self {
706                alias_generator,
707                mask,
708            }
709        }
710    }
711
712    impl CSEController for TestTreeNodeCSEController<'_> {
713        type Node = TestTreeNode<String>;
714
715        fn conditional_children(
716            _: &Self::Node,
717        ) -> Option<(Vec<&Self::Node>, Vec<&Self::Node>)> {
718            None
719        }
720
721        fn is_valid(_node: &Self::Node) -> bool {
722            true
723        }
724
725        fn is_ignored(&self, node: &Self::Node) -> bool {
726            let is_leaf = node.is_leaf();
727            let is_aggr = node.data == "avg" || node.data == "sum";
728
729            match self.mask {
730                TestTreeNodeMask::Normal => is_leaf || is_aggr,
731                TestTreeNodeMask::NormalAndAggregates => is_leaf,
732            }
733        }
734
735        fn generate_alias(&self) -> String {
736            self.alias_generator.next(CSE_PREFIX)
737        }
738
739        fn rewrite(&mut self, node: &Self::Node, alias: &str) -> Self::Node {
740            TestTreeNode::new_leaf(format!("alias({}, {})", node.data, alias))
741        }
742    }
743
744    impl HashNode for TestTreeNode<String> {
745        fn hash_node<H: Hasher>(&self, state: &mut H) {
746            self.data.hash(state);
747        }
748    }
749
750    impl Normalizeable for TestTreeNode<String> {
751        fn can_normalize(&self) -> bool {
752            false
753        }
754    }
755
756    impl NormalizeEq for TestTreeNode<String> {
757        fn normalize_eq(&self, other: &Self) -> bool {
758            self == other
759        }
760    }
761
762    #[test]
763    fn id_array_visitor() -> Result<()> {
764        let alias_generator = AliasGenerator::new();
765        let eliminator = CSE::new(TestTreeNodeCSEController::new(
766            &alias_generator,
767            TestTreeNodeMask::Normal,
768        ));
769
770        let a_plus_1 = TestTreeNode::new(
771            vec![
772                TestTreeNode::new_leaf("a".to_string()),
773                TestTreeNode::new_leaf("1".to_string()),
774            ],
775            "+".to_string(),
776        );
777        let avg_c = TestTreeNode::new(
778            vec![TestTreeNode::new_leaf("c".to_string())],
779            "avg".to_string(),
780        );
781        let sum_a_plus_1 = TestTreeNode::new(vec![a_plus_1], "sum".to_string());
782        let sum_a_plus_1_minus_avg_c =
783            TestTreeNode::new(vec![sum_a_plus_1, avg_c], "-".to_string());
784        let root = TestTreeNode::new(
785            vec![
786                sum_a_plus_1_minus_avg_c,
787                TestTreeNode::new_leaf("2".to_string()),
788            ],
789            "*".to_string(),
790        );
791
792        let [sum_a_plus_1_minus_avg_c, _] = root.children.as_slice() else {
793            panic!("Cannot extract subtree references")
794        };
795        let [sum_a_plus_1, avg_c] = sum_a_plus_1_minus_avg_c.children.as_slice() else {
796            panic!("Cannot extract subtree references")
797        };
798        let [a_plus_1] = sum_a_plus_1.children.as_slice() else {
799            panic!("Cannot extract subtree references")
800        };
801
802        // skip aggregates
803        let mut id_array = vec![];
804        eliminator.node_to_id_array(&root, &mut NodeStats::new(), &mut id_array)?;
805
806        // Collect distinct hashes and set them to 0 in `id_array`
807        fn collect_hashes(
808            id_array: &mut IdArray<'_, TestTreeNode<String>>,
809        ) -> HashSet<u64> {
810            id_array
811                .iter_mut()
812                .filter_map(|(_, id_option)| {
813                    id_option.as_mut().map(|node_id| {
814                        let hash = node_id.hash;
815                        node_id.hash = 0;
816                        hash
817                    })
818                })
819                .collect::<HashSet<_>>()
820        }
821
822        let hashes = collect_hashes(&mut id_array);
823        assert_eq!(hashes.len(), 3);
824
825        let expected = vec![
826            (
827                8,
828                Some(Identifier {
829                    hash: 0,
830                    node: &root,
831                }),
832            ),
833            (
834                6,
835                Some(Identifier {
836                    hash: 0,
837                    node: sum_a_plus_1_minus_avg_c,
838                }),
839            ),
840            (3, None),
841            (
842                2,
843                Some(Identifier {
844                    hash: 0,
845                    node: a_plus_1,
846                }),
847            ),
848            (0, None),
849            (1, None),
850            (5, None),
851            (4, None),
852            (7, None),
853        ];
854        assert_eq!(expected, id_array);
855
856        // include aggregates
857        let eliminator = CSE::new(TestTreeNodeCSEController::new(
858            &alias_generator,
859            TestTreeNodeMask::NormalAndAggregates,
860        ));
861
862        let mut id_array = vec![];
863        eliminator.node_to_id_array(&root, &mut NodeStats::new(), &mut id_array)?;
864
865        let hashes = collect_hashes(&mut id_array);
866        assert_eq!(hashes.len(), 5);
867
868        let expected = vec![
869            (
870                8,
871                Some(Identifier {
872                    hash: 0,
873                    node: &root,
874                }),
875            ),
876            (
877                6,
878                Some(Identifier {
879                    hash: 0,
880                    node: sum_a_plus_1_minus_avg_c,
881                }),
882            ),
883            (
884                3,
885                Some(Identifier {
886                    hash: 0,
887                    node: sum_a_plus_1,
888                }),
889            ),
890            (
891                2,
892                Some(Identifier {
893                    hash: 0,
894                    node: a_plus_1,
895                }),
896            ),
897            (0, None),
898            (1, None),
899            (
900                5,
901                Some(Identifier {
902                    hash: 0,
903                    node: avg_c,
904                }),
905            ),
906            (4, None),
907            (7, None),
908        ];
909        assert_eq!(expected, id_array);
910
911        Ok(())
912    }
913}