Skip to main content

uqa_execution/scalar/
state.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Function state belongs to immutable expressions prepared for one execution.
8
9use uqa_sql::{
10    ast::{BinaryOp, FunctionBinding, FunctionDispatch},
11    expr::enums::EnumComparisonState,
12    ScalarExpr,
13};
14
15#[cfg(test)]
16thread_local! {
17    static COMPARISON_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
18}
19
20/// Read-only lookup into the function state owned by a prepared expression set.
21/// The state has one fixed-size entry per logical ordering comparison, never per input row.
22#[derive(Debug, Default)]
23pub struct FunctionCallStates {
24    enums: Vec<((usize, u8), EnumComparisonState)>,
25}
26
27impl FunctionCallStates {
28    fn register(&mut self, expression: &ScalarExpr) {
29        expression.visit(&mut |expression| match expression {
30            ScalarExpr::Func { name, binding, args, .. } => {
31                self.add(args.as_ptr() as usize, function_slots(name, binding.as_ref(), args));
32            }
33            ScalarExpr::Binary {
34                op: BinaryOp::Less | BinaryOp::LessEqual | BinaryOp::Greater | BinaryOp::GreaterEqual,
35                lhs, ..
36            } => self.add(std::ptr::from_ref(lhs.as_ref()) as usize, 1),
37            ScalarExpr::Between { low, high, .. } => {
38                self.add(std::ptr::from_ref(low.as_ref()) as usize, 1);
39                self.add(std::ptr::from_ref(high.as_ref()) as usize, 1);
40            }
41            _ => {},
42        });
43    }
44
45    fn add(&mut self, address: usize, slots: u8) {
46        for slot in 0..slots {
47            self.enums
48                .push(((address, slot), EnumComparisonState::default()));
49        }
50    }
51
52    pub(crate) fn enum_comparisons(
53        &self,
54        arguments: &[ScalarExpr],
55    ) -> [Option<&EnumComparisonState>; 4] {
56        let address = arguments.as_ptr() as usize;
57        let Ok(first) = self
58            .enums
59            .binary_search_by_key(&(address, 0), |(key, _)| *key)
60        else {
61            return [None; 4];
62        };
63        std::array::from_fn(|slot| {
64            self.enums
65                .get(first + slot)
66                .filter(|(key, _)| *key == (address, slot as u8))
67                .map(|(_, state)| state)
68        })
69    }
70
71    pub(crate) fn enum_binary_comparison(&self, left: &ScalarExpr) -> Option<&EnumComparisonState> {
72        #[cfg(test)]
73        COMPARISON_LOOKUPS.with(|count| count.set(count.get() + 1));
74        self.enums
75            .binary_search_by_key(&(std::ptr::from_ref(left) as usize, 0), |(key, _)| *key)
76            .ok()
77            .map(|index| &self.enums[index].1)
78    }
79}
80
81fn function_slots(name: &str, binding: Option<&FunctionBinding>, args: &[ScalarExpr]) -> u8 {
82    if binding.is_some_and(|binding| !binding.builtin) {
83        return 0;
84    }
85    match binding.and_then(|binding| binding.dispatch) {
86        Some(FunctionDispatch::Enum { operation, .. }) => {
87            u8::from(args.len() == 2 && operation.uses_comparison_state())
88        }
89        Some(FunctionDispatch::AnyOperator | FunctionDispatch::AllOperator) => u8::from(
90            args.len() == 3
91                && matches!(args.last(),
92                Some(ScalarExpr::Literal(uqa_core::Value::Str(op)))
93                    if matches!(op.as_str(), "<" | "<=" | ">" | ">=")),
94        ),
95        Some(FunctionDispatch::BetweenSymmetric) if args.len() == 3 => 4,
96        None => u8::from(
97            args.len() >= 2
98                && (name.eq_ignore_ascii_case("greatest") || name.eq_ignore_ascii_case("least")),
99        ),
100        _ => 0,
101    }
102}
103
104type VisitRoots<T> = fn(&T, &mut dyn FnMut(&ScalarExpr));
105
106/// Retains both the immutable source and its call state. Argument vectors and
107/// comparison operands are heap allocations, so their identity survives moves. They cannot
108/// be changed or freed while the state is usable; addresses are only lookup keys
109/// and are never dereferenced. Cloning prepares independent, initially empty state.
110pub(crate) struct PreparedExpressions<T> {
111    expressions: T,
112    calls: Option<Box<PreparedCallStates<T>>>,
113}
114
115struct PreparedCallStates<T> {
116    calls: FunctionCallStates,
117    visit_roots: VisitRoots<T>,
118}
119
120static EMPTY_CALL_STATES: FunctionCallStates = FunctionCallStates { enums: Vec::new() };
121
122impl<T> PreparedExpressions<T> {
123    pub(crate) fn new(expressions: T, visit_roots: VisitRoots<T>) -> Self {
124        let mut calls = FunctionCallStates::default();
125        visit_roots(&expressions, &mut |expression| calls.register(expression));
126        calls.enums.sort_unstable_by_key(|(address, _)| *address);
127        calls.enums.dedup_by_key(|(address, _)| *address);
128        Self {
129            expressions,
130            calls: (!calls.enums.is_empty())
131                .then(|| Box::new(PreparedCallStates { calls, visit_roots })),
132        }
133    }
134
135    pub(crate) fn calls(&self) -> &FunctionCallStates {
136        self.calls
137            .as_ref()
138            .map_or(&EMPTY_CALL_STATES, |calls| &calls.calls)
139    }
140}
141
142impl PreparedExpressions<ScalarExpr> {
143    pub(crate) fn scalar(expression: ScalarExpr) -> Self {
144        Self::new(expression, |expression, visit| visit(expression))
145    }
146}
147
148impl PreparedExpressions<Vec<ScalarExpr>> {
149    pub(crate) fn scalars(expressions: Vec<ScalarExpr>) -> Self {
150        Self::new(expressions, |expressions, visit| {
151            expressions.iter().for_each(visit);
152        })
153    }
154}
155
156impl PreparedExpressions<Vec<crate::SortKey>> {
157    pub(crate) fn sort_keys(keys: Vec<crate::SortKey>) -> Self {
158        Self::new(keys, |keys, visit| {
159            for key in keys {
160                visit(&key.expr);
161            }
162        })
163    }
164}
165
166impl<T> std::ops::Deref for PreparedExpressions<T> {
167    type Target = T;
168
169    fn deref(&self) -> &T {
170        &self.expressions
171    }
172}
173
174impl<T: Clone> Clone for PreparedExpressions<T> {
175    fn clone(&self) -> Self {
176        match self.calls.as_ref() {
177            Some(calls) => Self::new(self.expressions.clone(), calls.visit_roots),
178            None => Self {
179                expressions: self.expressions.clone(),
180                calls: None,
181            },
182        }
183    }
184}
185
186#[cfg(test)]
187mod tests;