Skip to main content

cel_runtime/
prepared_segment.rs

1//! Executes one construction-validated canonical borrowed frame.
2//!
3//! ```
4//! use cel_runtime::{DynSegment, Nil, Leaf, IntoCStackList};
5//! let mut body = DynSegment::new::<()>();
6//! body.just(7i32);
7//! let mut prepared = body.prepare::<Nil, Leaf<i32>>().unwrap();
8//! assert_eq!(prepared.call(&().into_c_stack_list()).unwrap(), 7);
9//! ```
10
11use std::marker::PhantomData;
12
13use crate::container_execution::{ArgumentPlan, ResultPlan};
14use crate::{DynSegment, ValueRepr};
15
16/// Owns the same frozen raw engine as [`PreparedSegment`] with runtime-bound witnesses.
17///
18/// Hosts validate their storage adapters once, then lend exact canonical pointers.
19pub struct PreparedRawSegment {
20    /// Owns the validated independent instruction body.
21    body: DynSegment,
22    /// Binds exact result ownership and extraction.
23    result: ResultPlan,
24    /// Counts the borrowed positional pointers required on each call.
25    arity: usize,
26}
27
28impl PreparedRawSegment {
29    /// Binds every argument read and the complete result before any operation executes.
30    ///
31    /// # Errors
32    /// Rejects dependent bodies, undeclared or mismatched reads, missing cloning,
33    /// and a mismatched result.
34    /// - Complexity: O(n) in descriptor nodes and emitted reads.
35    ///
36    /// # Examples
37    /// ```
38    /// use cel_runtime::{DynSegment, ValueType, prepared_segment::PreparedRawSegment};
39    /// let mut body = DynSegment::new::<()>();
40    /// body.just(7i32);
41    /// let mut body = PreparedRawSegment::new(body, &[], &ValueType::leaf::<i32>())?;
42    /// let result = unsafe { body.call(&[]) }?;
43    /// assert_eq!(result.try_into_typed::<cel_runtime::Leaf<i32>>()?, 7);
44    /// # Ok::<(), anyhow::Error>(())
45    /// ```
46    pub fn new(
47        body: DynSegment,
48        arguments: &[crate::ValueType],
49        result: &crate::ValueType,
50    ) -> anyhow::Result<Self> {
51        body.validate_independent_body()?;
52        for (index, read) in &body.argument_reads {
53            let expected = arguments
54                .get(*index)
55                .ok_or_else(|| anyhow::anyhow!("undeclared argument {index}"))?;
56            anyhow::ensure!(
57                expected.same_shape(read),
58                "argument {index} representation mismatch"
59            );
60            anyhow::ensure!(
61                read.can_clone(),
62                "argument {index} clone capability unavailable"
63            );
64        }
65        anyhow::ensure!(
66            body.result_type()?.same_shape(result),
67            "result representation mismatch"
68        );
69        let result = ResultPlan::new(0, body.result_type()?.clone())?;
70        Ok(Self {
71            body,
72            result,
73            arity: arguments.len(),
74        })
75    }
76
77    /// Executes the bound raw frame without conversions or descriptor comparisons.
78    ///
79    /// # Safety
80    /// `arguments` must have the prepared arity. Each pointer must borrow a live,
81    /// aligned value of its exact preparation descriptor throughout this call.
82    /// No pointer may alias mutable storage accessed by an operation.
83    /// # Errors
84    /// Propagates operation errors after frame cleanup.
85    /// - Complexity: Body execution and emitted clone costs.
86    ///
87    /// # Examples
88    /// See [`Self::new`].
89    pub unsafe fn call(&mut self, arguments: &[*const u8]) -> anyhow::Result<crate::OwnedValue> {
90        debug_assert_eq!(arguments.len(), self.arity);
91        let mut output = unsafe { self.body.execute_raw(arguments)? };
92        Ok(unsafe { self.result.take(&mut output) })
93    }
94}
95
96/// Owns a frozen raw body with exact canonical argument/result witnesses.
97///
98/// Calls borrow arguments, clone only emitted reads, and return independent owners.
99pub struct PreparedSegment<A: ValueRepr, R: ValueRepr> {
100    /// Owns the frozen instruction body.
101    body: DynSegment,
102    /// Binds the canonical borrowed argument tuple layout.
103    arguments: ArgumentPlan,
104    /// Reuses fixed-arity pointer slots, rebound before each call.
105    pointers: Vec<*const u8>,
106    /// Binds exact result ownership and extraction.
107    result: ResultPlan,
108    /// Associates the validated body with its concrete boundary witnesses.
109    witness: PhantomData<fn(A, R)>,
110}
111
112impl<A: ValueRepr, R: ValueRepr> PreparedSegment<A, R> {
113    /// Validates exact read/result identities and borrowed clone capabilities once.
114    ///
115    /// # Errors
116    /// Rejects dependent bodies, non-list arguments, missing/mismatched positional
117    /// reads, missing clone capability, or a result differing at any recursive node.
118    /// - Complexity: O(n) complete descriptor comparisons and frame planning.
119    pub(crate) fn new(body: DynSegment) -> anyhow::Result<Self> {
120        body.validate_independent_body()?;
121        let args = A::value_type();
122        let fields = args
123            .tuple_elements()
124            .ok_or_else(|| anyhow::anyhow!("prepared arguments must be a canonical list"))?;
125        for (index, read) in &body.argument_reads {
126            let expected = fields
127                .get(*index)
128                .ok_or_else(|| anyhow::anyhow!("undeclared argument {index}"))?;
129            anyhow::ensure!(
130                expected.value_type.same_shape(read),
131                "argument {index} representation mismatch"
132            );
133            anyhow::ensure!(
134                read.can_clone(),
135                "argument {index} clone capability unavailable"
136            );
137        }
138        body.result_type()?.validate::<R>()?;
139        let result = ResultPlan::new(0, body.result_type()?.clone())?;
140        let pointers = vec![std::ptr::null(); fields.len()];
141        Ok(Self {
142            body,
143            arguments: ArgumentPlan::borrowed(args)?,
144            pointers,
145            result,
146            witness: PhantomData,
147        })
148    }
149
150    /// Executes without shape comparisons, checked conversions, or `Any` downcasts.
151    ///
152    /// - Postcondition: The input remains borrowed and every returned owner is independent.
153    /// # Errors
154    /// Propagates the original operation error and its context after frame cleanup.
155    /// - Complexity: O(a) pointer setup for a arguments plus body/clone costs.
156    ///
157    /// # Examples
158    /// See the module example.
159    pub fn call(&mut self, args: &A::Value) -> anyhow::Result<R::Value> {
160        let base = std::ptr::from_ref(args).cast::<u8>();
161        // SAFETY: The sealed witnesses, immutable body, and preparation bind all
162        // reads/results to this exact representation for every subsequent call.
163        unsafe {
164            self.arguments.bind_pointers(base, &mut self.pointers);
165            let mut output = self.body.execute_raw(&self.pointers)?;
166            Ok(self.result.take_typed::<R::Value>(&mut output))
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::{Array, ArrayOf, Cons, IntoCStackList, Leaf, Nil, ValueType};
175
176    /// Prepared nested borrowed frames perform no recursive comparisons on repeated calls.
177    #[test]
178    fn trusted_calls_never_compare_descriptors() {
179        type Pair = Cons<Leaf<i32>, Cons<Leaf<f64>, Nil>>;
180        type Argument = ArrayOf<Pair>;
181        type Args = Cons<Argument, Nil>;
182        let mut body = DynSegment::new::<()>();
183        body.push_argument(0, Argument::value_type().with_clone::<Argument>().unwrap())
184            .unwrap();
185        let mut body = body.prepare::<Args, Argument>().unwrap();
186        let input = (Array::from_vec(vec![(1i32, 2f64).into_c_stack_list()]),).into_c_stack_list();
187        crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
188        let first = body.call(&input).unwrap();
189        let second = body.call(&input).unwrap();
190        crate::value_type::SHAPE_COMPARISONS.with(|count| assert_eq!(count.get(), 0));
191        assert_ne!(first.as_slice().as_ptr(), second.as_slice().as_ptr());
192        assert_ne!(input.1.as_slice().as_ptr(), first.as_slice().as_ptr());
193    }
194
195    /// Runtime-bound frames use the identical frozen execution and equality plans.
196    #[test]
197    fn erased_prepared_calls_never_compare_descriptors() {
198        type Pair = Cons<Leaf<i32>, Cons<ArrayOf<Leaf<f64>>, Nil>>;
199        type Argument = ArrayOf<Pair>;
200        let descriptor = Argument::value_type()
201            .with_clone::<Argument>()
202            .unwrap()
203            .with_equality::<Argument>()
204            .unwrap();
205        let mut body = DynSegment::new::<()>();
206        body.push_argument(0, descriptor.clone()).unwrap();
207        let mut body =
208            PreparedRawSegment::new(body, std::slice::from_ref(&descriptor), &descriptor).unwrap();
209        let input = Array::from_vec(vec![(1, Array::from_vec(vec![2.0])).into_c_stack_list()]);
210        let pointer = std::ptr::from_ref(&input).cast::<u8>();
211        crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
212        // SAFETY: Input uses exactly the witness bound at construction.
213        let first = unsafe { body.call(&[pointer]) }.unwrap();
214        let second = unsafe { body.call(&[pointer]) }.unwrap();
215        // SAFETY: Both values come from the same comparable bound result plan.
216        assert!(unsafe { first.eq_bound(&second) });
217        crate::value_type::SHAPE_COMPARISONS.with(|count| assert_eq!(count.get(), 0));
218        let first = first.try_into_typed::<Argument>().unwrap();
219        let second = second.try_into_typed::<Argument>().unwrap();
220        assert_ne!(input.as_slice().as_ptr(), first.as_slice().as_ptr());
221        assert_ne!(first.as_slice().as_ptr(), second.as_slice().as_ptr());
222        assert_ne!(
223            first.as_slice()[0].0.1.as_slice().as_ptr(),
224            second.as_slice()[0].0.1.as_slice().as_ptr()
225        );
226    }
227
228    /// Erased preparation rejects mismatched reads and results before executing effects.
229    #[test]
230    fn erased_preparation_checks_complete_signature_before_effects() {
231        let mut body = DynSegment::new::<()>();
232        body.push_arg::<i32>(0);
233        assert!(
234            PreparedRawSegment::new(body, &[ValueType::leaf::<u32>()], &ValueType::leaf::<i32>())
235                .is_err()
236        );
237        let mut body = DynSegment::new::<()>();
238        body.push_arg::<i32>(0);
239        assert!(PreparedRawSegment::new(body, &[], &ValueType::leaf::<i32>()).is_err());
240        let mut body = DynSegment::new::<()>();
241        body.just(1i32);
242        assert!(PreparedRawSegment::new(body, &[], &ValueType::leaf::<u32>()).is_err());
243        let body = DynSegment::new::<(i32,)>();
244        assert!(PreparedRawSegment::new(body, &[], &ValueType::leaf::<i32>()).is_err());
245    }
246
247    /// Exact argument/result identities, independent origins, and clone plans bind once.
248    #[test]
249    fn preparation_rejects_every_boundary_mismatch() {
250        let mut wrong_result = DynSegment::new::<()>();
251        wrong_result.just(1i32);
252        assert!(wrong_result.prepare::<Nil, Leaf<u32>>().is_err());
253
254        let mut wrong_arg = DynSegment::new::<()>();
255        wrong_arg.push_arg::<i32>(0);
256        assert!(
257            wrong_arg
258                .prepare::<Cons<Leaf<u32>, Nil>, Leaf<i32>>()
259                .is_err()
260        );
261
262        let mut undeclared = DynSegment::new::<()>();
263        undeclared.push_arg::<i32>(1);
264        assert!(
265            undeclared
266                .prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>()
267                .is_err()
268        );
269
270        let mut nonlist = DynSegment::new::<()>();
271        nonlist.just(1i32);
272        assert!(nonlist.prepare::<Leaf<()>, Leaf<i32>>().is_err());
273
274        let preloaded = DynSegment::new::<(i32,)>();
275        assert!(
276            preloaded
277                .prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>()
278                .is_err()
279        );
280
281        let mut nonclone = DynSegment::new::<()>();
282        assert!(
283            nonclone
284                .push_argument(0, ValueType::leaf::<String>())
285                .is_err()
286        );
287        assert!(nonclone.peek_stack_infos(0).is_empty());
288    }
289}