Skip to main content

uqa_sql/plan/scalar/owned/
replacement.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Address-stable scalar edits keep read-only selection separate from paired payload/owner replacement.
8
9use super::{children, OwnedScalarExpr, ScalarExpr, ScalarMemory};
10use crate::SQLError;
11use std::ptr::NonNull;
12use uqa_core::memory::ProductionControl;
13
14pub type ScalarNodeTransform<'a> =
15    dyn FnMut(NonNull<ScalarExpr>, OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError> + 'a;
16
17pub(crate) type Replacement<'a> =
18    dyn FnMut(&ScalarExpr) -> Result<Option<OwnedScalarExpr>, SQLError> + 'a;
19
20impl OwnedScalarExpr {
21    /// Transform children before their parent, retaining the original address as an opaque selection identity. The callback owns all surviving children and may move them into an admitted wrapper.
22    pub fn transform_nodes(
23        mut self,
24        control: &ProductionControl<'_>,
25        transform: &mut ScalarNodeTransform<'_>,
26    ) -> Result<Self, SQLError> {
27        self.assert_owner(control);
28        Self::transform_nodes_in_place(
29            &mut self.expression,
30            self.memory.as_mut(),
31            control,
32            transform,
33        )?;
34        Ok(self)
35    }
36
37    /// Internal analysis buffers retain each expression's address until this paired in-place transform finishes. Failure leaves the private owner valid for destruction; callers do not publish it.
38    pub(crate) fn transform_retained_nodes(
39        &mut self,
40        control: &ProductionControl<'_>,
41        transform: &mut ScalarNodeTransform<'_>,
42    ) -> Result<(), SQLError> {
43        self.assert_owner(control);
44        Self::transform_nodes_in_place(
45            &mut self.expression,
46            self.memory.as_mut(),
47            control,
48            transform,
49        )
50    }
51
52    pub(crate) fn transform_nodes_in_place(
53        expression: &mut ScalarExpr,
54        mut memory: Option<&mut ScalarMemory>,
55        control: &ProductionControl<'_>,
56        transform: &mut ScalarNodeTransform<'_>,
57    ) -> Result<(), SQLError> {
58        control.check()?;
59        let count = children::count(expression);
60        for ordinal in 0..count {
61            let index = visit_index(expression, ordinal, count);
62            let child = children::get_mut(expression, index).expect("scalar child");
63            let owner = memory
64                .as_mut()
65                .map(|memory| memory.children[index].as_mut().expect("scalar child owner"));
66            Self::transform_nodes_in_place(child, owner, control, transform)?;
67        }
68        let identity = NonNull::from(&*expression);
69        let owner = memory.as_mut().map(|owner| {
70            let direct = control.empty_reservation().expect("controlled scalar slot");
71            let empty = ScalarMemory {
72                children: Vec::new(),
73                direct,
74            };
75            std::mem::replace(*owner, empty)
76        });
77        let input = Self::from_rewrite_parts(
78            std::mem::replace(expression, ScalarExpr::Literal(uqa_core::Value::Null)),
79            owner,
80        );
81        let output = transform(identity, input)?;
82        output.assert_owner(control);
83        control.check()?;
84        let (output, owner) = output.into_rewrite_parts();
85        *expression = output;
86        if let Some(memory) = memory {
87            *memory = owner.expect("controlled scalar transformation");
88        }
89        Ok(())
90    }
91
92    /// Replace selected nodes in pre-order. The observer receives no mutable syntax; every returned node carries its own complete constructor owner.
93    pub fn replace_nodes(
94        mut self,
95        control: &ProductionControl<'_>,
96        replacement: &mut Replacement<'_>,
97    ) -> Result<Self, SQLError> {
98        self.assert_owner(control);
99        Self::replace_nodes_in_place(
100            &mut self.expression,
101            self.memory.as_mut(),
102            control,
103            replacement,
104        )?;
105        Ok(self)
106    }
107
108    pub(crate) fn replace_nodes_in_place(
109        expression: &mut ScalarExpr,
110        mut memory: Option<&mut ScalarMemory>,
111        control: &ProductionControl<'_>,
112        replacement: &mut Replacement<'_>,
113    ) -> Result<(), SQLError> {
114        control.check()?;
115        if let Some(output) = replacement(expression)? {
116            output.assert_owner(control);
117            let (output, owner) = output.into_rewrite_parts();
118            *expression = output;
119            if let Some(memory) = &mut memory {
120                **memory = owner.expect("replacement has its own scalar constructor");
121            }
122        }
123        let count = children::count(expression);
124        for ordinal in 0..count {
125            let index = visit_index(expression, ordinal, count);
126            let child = children::get_mut(expression, index).expect("scalar child");
127            let owner = memory
128                .as_mut()
129                .map(|memory| memory.children[index].as_mut().expect("scalar child owner"));
130            Self::replace_nodes_in_place(child, owner, control, replacement)?;
131        }
132        control.check()?;
133        Ok(())
134    }
135}
136
137fn visit_index(expression: &ScalarExpr, ordinal: usize, count: usize) -> usize {
138    // Read-only/mutable syntax visitation places the window FILTER before its specification; constructor ownership stores it last.
139    if let ScalarExpr::WindowCall {
140        args,
141        filter: Some(_),
142        ..
143    } = expression
144    {
145        if ordinal == args.len() {
146            return count - 1;
147        }
148        if ordinal > args.len() {
149            return ordinal - 1;
150        }
151    }
152    ordinal
153}