Skip to main content

vortex_expr/analysis/
annotation.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5
6use vortex_array::expr::BoundExpression;
7use vortex_array::expr::ExactBoundExpr;
8use vortex_array::expr::traversal::NodeExt;
9use vortex_array::expr::traversal::NodeVisitor;
10use vortex_array::expr::traversal::TraversalOrder;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_utils::aliases::hash_map::HashMap;
14use vortex_utils::aliases::hash_set::HashSet;
15
16/// A value that can annotate an expression node.
17pub trait Annotation: Clone + Hash + Eq {}
18
19impl<A> Annotation for A where A: Clone + Hash + Eq {}
20
21/// Computes annotations for an expression node, defaulting to bound expressions.
22pub trait AnnotationFn<N = BoundExpression>: Fn(&N) -> Vec<Self::Annotation> {
23    /// The annotation attached to a node.
24    type Annotation: Annotation;
25}
26
27impl<N, A, F> AnnotationFn<N> for F
28where
29    A: Annotation,
30    F: Fn(&N) -> Vec<A>,
31{
32    type Annotation = A;
33}
34
35/// Annotations keyed by bound-tree identity.
36///
37/// Identity keys avoid structurally hashing every node's dtype. That matters when a bound root
38/// carries a lazy schema whose structural hash would deserialize every field.
39pub type BoundAnnotations<A> = HashMap<ExactBoundExpr, HashSet<A>>;
40
41/// Annotate a bound expression and propagate each annotation to its ancestors.
42///
43/// This uses [`ExactBoundExpr`] keys to preserve the cheap identity semantics of a bound tree.
44pub fn descendent_bound_annotations<A>(
45    expr: &BoundExpression,
46    annotate: A,
47) -> BoundAnnotations<A::Annotation>
48where
49    A: AnnotationFn<BoundExpression>,
50{
51    bound_annotations(expr, annotate, true)
52}
53
54/// Annotate each bound-expression node without propagating annotations to its ancestors.
55///
56/// The returned map uses [`ExactBoundExpr`] keys so lookups do not structurally hash node dtypes.
57pub fn direct_bound_annotations<A>(
58    expr: &BoundExpression,
59    annotate: A,
60) -> BoundAnnotations<A::Annotation>
61where
62    A: AnnotationFn<BoundExpression>,
63{
64    bound_annotations(expr, annotate, false)
65}
66
67fn bound_annotations<A>(
68    expr: &BoundExpression,
69    annotate: A,
70    propagate_up: bool,
71) -> BoundAnnotations<A::Annotation>
72where
73    A: AnnotationFn<BoundExpression>,
74{
75    let mut visitor = BoundAnnotationVisitor {
76        annotations: Default::default(),
77        annotate,
78        propagate_up,
79    };
80    expr.accept(&mut visitor).vortex_expect("Infallible");
81    visitor.annotations
82}
83
84struct BoundAnnotationVisitor<A>
85where
86    A: AnnotationFn<BoundExpression>,
87{
88    annotations: BoundAnnotations<A::Annotation>,
89    annotate: A,
90    propagate_up: bool,
91}
92
93impl<'a, A> NodeVisitor<'a> for BoundAnnotationVisitor<A>
94where
95    A: AnnotationFn<BoundExpression>,
96{
97    type NodeTy = BoundExpression;
98
99    fn visit_down(&mut self, node: &'a Self::NodeTy) -> VortexResult<TraversalOrder> {
100        let annotations = (self.annotate)(node);
101        if annotations.is_empty() {
102            return Ok(TraversalOrder::Continue);
103        }
104
105        self.annotations
106            .entry(ExactBoundExpr(node.clone()))
107            .or_default()
108            .extend(annotations);
109        Ok(TraversalOrder::Skip)
110    }
111
112    fn visit_up(&mut self, node: &'a Self::NodeTy) -> VortexResult<TraversalOrder> {
113        if !self.propagate_up {
114            return Ok(TraversalOrder::Continue);
115        }
116
117        let child_annotations = node
118            .children()
119            .iter()
120            .filter_map(|child| {
121                self.annotations
122                    .get(&ExactBoundExpr(child.clone()))
123                    .cloned()
124            })
125            .collect::<Vec<_>>();
126        let annotations = self
127            .annotations
128            .entry(ExactBoundExpr(node.clone()))
129            .or_default();
130        child_annotations
131            .into_iter()
132            .for_each(|child| annotations.extend(child));
133
134        Ok(TraversalOrder::Continue)
135    }
136}