Skip to main content

vortex_array/expr/
display.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Tree rendering shared by bound and unbound expressions.
5
6use std::fmt;
7use std::fmt::Display;
8use std::fmt::Formatter;
9
10use vortex_utils::tree::TreeDisplayAdapter;
11use vortex_utils::tree::write_branch_tree;
12
13use crate::expr::BoundExpression;
14use crate::scalar_fn::ChildName;
15
16/// A node of an expression tree that [`DisplayTreeExpr`] can render.
17pub trait DisplayTreeNode: Sized {
18    /// The children of this node, in argument order.
19    fn tree_children(&self) -> &[Self];
20
21    /// The display name of the child at `index`.
22    fn tree_child_name(&self, index: usize) -> ChildName;
23
24    /// Write this node's own label.
25    fn fmt_tree_node(&self, f: &mut Formatter<'_>) -> fmt::Result;
26}
27
28/// Tree-display label for the scope root.
29pub const ROOT_DISPLAY: &str = "vortex.root()";
30
31impl DisplayTreeNode for BoundExpression {
32    fn tree_children(&self) -> &[Self] {
33        BoundExpression::children(self)
34    }
35
36    fn tree_child_name(&self, index: usize) -> ChildName {
37        match self {
38            BoundExpression::Scalar { scalar_fn, .. } => scalar_fn.signature().child_name(index),
39            BoundExpression::Root { .. } => unreachable!("the scope root has no children"),
40        }
41    }
42
43    fn fmt_tree_node(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        match self {
45            BoundExpression::Scalar { scalar_fn, .. } => Display::fmt(scalar_fn, f),
46            BoundExpression::Root { .. } => write!(f, "{ROOT_DISPLAY}"),
47        }
48    }
49}
50
51/// Renders an expression tree with one node per line.
52pub struct DisplayTreeExpr<'a, T: ?Sized>(pub &'a T);
53
54impl<T: DisplayTreeNode> TreeDisplayAdapter for DisplayTreeExpr<'_, T> {
55    type Context = ();
56    type Node = T;
57
58    fn write_node(
59        &self,
60        node: &Self::Node,
61        _context: &Self::Context,
62        formatter: &mut Formatter<'_>,
63    ) -> fmt::Result {
64        node.fmt_tree_node(formatter)
65    }
66
67    fn visit_children(
68        &self,
69        node: &Self::Node,
70        visit: &mut dyn FnMut(&str, &Self::Node, bool) -> fmt::Result,
71    ) -> fmt::Result {
72        let children = node.tree_children();
73        for (index, child) in children.iter().enumerate() {
74            let child_name = node.tree_child_name(index);
75            visit(child_name.as_ref(), child, index + 1 == children.len())?;
76        }
77        Ok(())
78    }
79}
80
81impl<T: DisplayTreeNode> Display for DisplayTreeExpr<'_, T> {
82    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
83        write_branch_tree(self, self.0, &mut (), f)
84    }
85}