cel_runtime/dyn_closure.rs
1//! A first-class, callable CEL value: a compiled body plus its declared signature.
2//!
3//! See `docs/superpowers/specs/2026-08-21-cel-closures-design.md` for the full design rationale
4//! (why `Rc`, why `RefCell`, why no captured environment).
5//!
6//! # Examples
7//!
8//! Build a closure that adds two `i32` values, then call it with different arguments:
9//!
10//! ```rust
11//! use cel_runtime::{DynClosure, DynSegment};
12//! use std::any::TypeId;
13//!
14//! // Compile a body that takes two i32 arguments and returns their sum.
15//! let mut body = DynSegment::new::<()>();
16//! body.push_arg::<i32>(0);
17//! body.push_arg::<i32>(1);
18//! body.op2r(|a: i32, b: i32| {
19//! a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
20//! }).unwrap();
21//!
22//! // Wrap it as a callable closure with its declared signature.
23//! let closure = DynClosure::new(
24//! vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
25//! TypeId::of::<i32>(),
26//! body,
27//! );
28//!
29//! // Call the closure multiple times with different arguments.
30//! let (a, b) = (2i32, 3i32);
31//! assert_eq!(closure.call::<i32>(&[&a, &b]).unwrap(), 5);
32//!
33//! let (c, d) = (10i32, 20i32);
34//! assert_eq!(closure.call::<i32>(&[&c, &d]).unwrap(), 30);
35//! ```
36
37use std::any::{Any, TypeId};
38use std::cell::{Cell, RefCell};
39use std::rc::Rc;
40
41use crate::ValueType;
42use crate::dyn_segment::DynSegment;
43
44/// An exact compile-time callable shape, including nested aggregate and callable results.
45#[derive(Clone, Debug)]
46pub(crate) struct ClosureSignature {
47 /// Retains complete parameter shapes in source order.
48 pub(crate) parameters: Vec<ValueType>,
49 /// Retains the complete result shape.
50 pub(crate) result: ValueType,
51}
52
53impl ClosureSignature {
54 /// Converts known recursive metadata without changing canonical storage.
55 ///
56 /// # Errors
57 /// Returns an error for missing or mismatched leaf factories, unknown nested
58 /// callable signatures, or an unrepresentable canonical tuple layout.
59 /// - Complexity: O(n) traversal time and output space for n signature nodes,
60 /// excluding leaf factory costs.
61 fn complete(
62 &self,
63 leaf: &mut impl FnMut(TypeId) -> Option<crate::value_type::ValueType>,
64 ) -> anyhow::Result<crate::value_type::ValueType> {
65 let parameters = self
66 .parameters
67 .iter()
68 .map(|parameter| enrich_value_type(parameter, leaf))
69 .collect::<anyhow::Result<Vec<_>>>()?;
70 Ok(crate::value_type::ValueType::callable(
71 parameters,
72 enrich_value_type(&self.result, leaf)?,
73 ))
74 }
75}
76
77/// Resolves one concrete registered leaf through a previously monomorphized factory.
78///
79/// # Errors
80/// Returns an error if the factory is missing, structural, or describes another
81/// concrete type or layout. A closure marker without a signature is rejected.
82fn complete_leaf(
83 id: TypeId,
84 size: usize,
85 align: usize,
86 leaf: &mut impl FnMut(TypeId) -> Option<crate::value_type::ValueType>,
87) -> anyhow::Result<crate::value_type::ValueType> {
88 anyhow::ensure!(
89 id != TypeId::of::<DynClosure>(),
90 "closure signature metadata is unavailable"
91 );
92 let complete =
93 leaf(id).ok_or_else(|| anyhow::anyhow!("complete leaf factory is unavailable"))?;
94 complete.validate_opaque_leaf(id)?;
95 anyhow::ensure!(
96 complete.layout().size() == size && complete.layout().align() == align,
97 "complete leaf factory layout mismatch"
98 );
99 Ok(complete)
100}
101
102/// Enriches canonical signature leaves through explicitly supplied factories.
103///
104/// # Errors
105/// Returns an error for unavailable signatures/factories or invalid tuple layout.
106/// - Complexity: O(n) time and output space for n recursive descriptor nodes.
107fn enrich_value_type(
108 value: &ValueType,
109 leaf: &mut impl FnMut(TypeId) -> Option<crate::value_type::ValueType>,
110) -> anyhow::Result<crate::value_type::ValueType> {
111 use crate::value_type::{AssociatedType, ValueType as Complete};
112 match value.kind() {
113 crate::ValueKind::Tuple(fields) => Complete::tuple(
114 fields
115 .iter()
116 .map(|field| {
117 Ok(AssociatedType {
118 offset: 0,
119 value_type: enrich_value_type(&field.value_type, leaf)?,
120 })
121 })
122 .collect::<anyhow::Result<Vec<_>>>()?,
123 ),
124 crate::ValueKind::Array(element) => Ok(Complete::array(enrich_value_type(element, leaf)?)),
125 crate::ValueKind::Callable { parameters, result } => Ok(Complete::callable(
126 parameters
127 .iter()
128 .map(|parameter| enrich_value_type(parameter, leaf))
129 .collect::<anyhow::Result<_>>()?,
130 enrich_value_type(result, leaf)?,
131 )),
132 crate::ValueKind::Leaf(id) => complete_leaf(*id, value.size(), value.align(), leaf),
133 }
134}
135
136/// Compares complete known signatures without relying on the erased closure marker.
137///
138/// - Complexity: O(number of recursive type nodes).
139#[cfg(test)]
140pub(crate) fn same_signature(
141 left: Option<&ClosureSignature>,
142 right: Option<&ClosureSignature>,
143) -> bool {
144 match (left, right) {
145 (None, None) => true,
146 (Some(a), Some(b)) => {
147 a.parameters.len() == b.parameters.len()
148 && a.parameters
149 .iter()
150 .zip(&b.parameters)
151 .all(|(a, b)| a.same_shape(b))
152 && a.result.same_shape(&b.result)
153 }
154 _ => false,
155 }
156}
157
158/// A monomorphized dispatcher for [`DynClosure::call_boxed`]: runs a closure's body via
159/// `DynSegment::call_dyn::<R>` for some concrete `R` the dispatcher itself already knows, boxing
160/// the result so the caller (which only knows `R` dynamically, as a `TypeId`) doesn't need to.
161pub type CallDynFn = fn(&mut DynSegment, &[&dyn Any]) -> anyhow::Result<Box<dyn Any>>;
162
163/// Invokes an exact construction-bound payload and initializes output on success only.
164///
165/// Both frame pointers and the payload must match the dispatcher's concrete types.
166pub(crate) type FrameDispatch = unsafe fn(*mut (), *const u8, *mut u8) -> anyhow::Result<()>;
167
168/// Owns either a compiler-facing body or a private type-bound frame dispatcher.
169enum ClosureBody {
170 /// Owns a compiler-facing instruction stream.
171 Interpreted(DynSegment),
172 /// Owns a concrete native or prepared payload with its exact dispatcher.
173 Framed {
174 /// Owns the dispatcher-bound concrete payload.
175 payload: Box<dyn Any>,
176 /// Invokes that payload through its validated contiguous frame.
177 dispatch: FrameDispatch,
178 },
179}
180
181impl ClosureBody {
182 /// Returns the compiler-facing body, rejecting immutable typed facade bodies.
183 ///
184 /// # Errors
185 /// Rejects framed native and prepared bodies.
186 fn segment(&mut self) -> anyhow::Result<&mut DynSegment> {
187 match self {
188 Self::Interpreted(body) => Ok(body),
189 Self::Framed { .. } => anyhow::bail!("typed callable has no mutable compiler body"),
190 }
191 }
192}
193
194/// Binds a canonical contiguous argument frame and a raw interpreted result once.
195struct FramePlan {
196 /// Binds the canonical argument tuple's field positions.
197 arguments: crate::container_execution::ArgumentPlan,
198 /// Retains fixed-arity pointer slots, rebound before every interpreted call.
199 pointers: Vec<*const u8>,
200 /// Binds owned extraction of the single interpreted result.
201 result: crate::container_execution::ResultPlan,
202}
203
204/// Exclusively borrows a body and its reusable argument-pointer storage together.
205///
206/// Only typed interpreted bodies carry a frame plan. Its pointer slots borrow
207/// the current call's arguments only while that body executes.
208struct ClosureState {
209 /// Owns the currently executing or mutable compiler body.
210 body: ClosureBody,
211 /// Retains reusable frame storage only for a typed interpreted body.
212 frame: Option<FramePlan>,
213}
214
215impl ClosureState {
216 /// Returns the mutable interpreted body without exposing its frame storage.
217 ///
218 /// # Errors
219 /// Rejects native and prepared bodies.
220 fn segment(&mut self) -> anyhow::Result<&mut DynSegment> {
221 self.body.segment()
222 }
223}
224
225/// Shares one body and counts live trusted-binding leases across all carrier aliases.
226struct ClosureData {
227 /// Retains the source-ordered compatibility identities of parameters.
228 param_types: Vec<TypeId>,
229 /// Retains the compatibility identity of the result.
230 return_type: TypeId,
231 /// Serializes execution and compiler mutation across all carrier aliases.
232 body: RefCell<ClosureState>,
233 /// Retains full recursive metadata for typed carriers.
234 signature: Option<std::sync::Arc<ClosureSignature>>,
235 /// Counts independent live leases that forbid compiler mutation.
236 trusted_bindings: Cell<usize>,
237}
238
239/// Prevents arbitrary mutable body dispatch until this independent lease is dropped.
240///
241/// Holds the shared carrier alive; moving the lease preserves the freeze, and
242/// dropping it releases exactly one binding even during unwinding. Carrier clones
243/// share the counter but neither acquire nor release leases themselves.
244pub(crate) struct TrustedBindingLease {
245 /// Keeps the shared body alive until this independent lease releases.
246 closure: DynClosure,
247}
248
249impl Drop for TrustedBindingLease {
250 /// Decrements the lease count without borrowing the body, before releasing the carrier.
251 fn drop(&mut self) {
252 let bindings = &self.closure.0.trusted_bindings;
253 debug_assert!(bindings.get() > 0);
254 bindings.set(bindings.get() - 1);
255 }
256}
257
258/// `Debug` implementation that formats the closure's signature but deliberately omits `body` from the output
259/// (via `finish_non_exhaustive`), since `DynSegment` is not easily debuggable and the signature alone
260/// is typically what callers need to see.
261impl std::fmt::Debug for ClosureData {
262 /// Formats the declared signature without borrowing or evaluating the body.
263 ///
264 /// - Complexity: O(p) formatting for p parameters.
265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266 f.debug_struct("ClosureData")
267 .field("param_types", &self.param_types)
268 .field("return_type", &self.return_type)
269 .finish_non_exhaustive()
270 }
271}
272
273/// A first-class, callable CEL value: a compiled body plus its declared parameter/return types.
274///
275/// Holds no captured environment — only its own parameters resolve inside `body`. Calling it
276/// twice with different `args` is exactly as fresh each time as calling any other `DynSegment`.
277/// `Rc`-wrapped so `Clone` never requires `DynSegment` itself to implement `Clone` (it doesn't —
278/// see the design spec); `RefCell` because callers only ever reach a `DynClosure` through `&self`
279/// (matching `adam_rs::Filter`/`Method`'s `Fn`, not `FnMut`, storage), while `DynSegment`'s own
280/// call methods need `&mut self`.
281#[derive(Clone, Debug)]
282pub struct DynClosure(Rc<ClosureData>, Option<Rc<TrustedBindingLease>>);
283
284impl std::fmt::Debug for TrustedBindingLease {
285 /// Formats the lease without recursively traversing its retained carrier.
286 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
287 f.write_str("TrustedBindingLease")
288 }
289}
290
291impl DynClosure {
292 /// Shares a construction-bound frame dispatcher without exposing its payload.
293 ///
294 /// A prepared payload owns its immutable body and all nested trusted leases.
295 ///
296 /// # Safety
297 /// `dispatch` must match `payload` and the facade's exact Rust signature.
298 /// On success it must initialize exactly one result; on error or unwind it
299 /// must leave output uninitialized. If supplied, metadata must describe that
300 /// exact signature.
301 /// - Complexity: O(p) parameter metadata storage for p declared parameters.
302 pub(crate) unsafe fn from_frame_body(
303 payload: Box<dyn Any>,
304 dispatch: FrameDispatch,
305 signature: Option<ClosureSignature>,
306 ) -> Self {
307 let param_types = signature
308 .as_ref()
309 .map(|s| s.parameters.iter().map(ValueType::type_id).collect())
310 .unwrap_or_default();
311 let return_type = signature
312 .as_ref()
313 .map(|s| s.result.type_id())
314 .unwrap_or(TypeId::of::<()>());
315 Self(
316 Rc::new(ClosureData {
317 param_types,
318 return_type,
319 body: RefCell::new(ClosureState {
320 body: ClosureBody::Framed { payload, dispatch },
321 frame: None,
322 }),
323 signature: signature.map(std::sync::Arc::new),
324 trusted_bindings: Cell::new(0),
325 }),
326 None,
327 )
328 }
329
330 /// Dispatches a complete preparation-validated contiguous borrowed argument frame.
331 ///
332 /// # Safety
333 /// Both frame pointers must match this exact carrier's validated signature.
334 /// Output is aligned uninitialized result storage. A compiler-facing interpreted body
335 /// must be protected by a trusted lease for the duration of the call.
336 /// # Errors
337 /// Returns reentrant entry or original body errors without initializing output.
338 /// - Complexity: Body-dependent plus O(a) pointer binding for a arguments.
339 /// Binding reuses construction-time storage without allocating.
340 pub(crate) unsafe fn call_frame_trusted(
341 &self,
342 args: *const u8,
343 result: *mut u8,
344 ) -> anyhow::Result<()> {
345 let mut body = self
346 .0
347 .body
348 .try_borrow_mut()
349 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
350 let ClosureState { body, frame } = &mut *body;
351 match body {
352 ClosureBody::Framed { payload, dispatch } => {
353 // Erasing an Any pointer preserves the boxed concrete data
354 // address; construction binds its monomorphized dispatcher.
355 let pointer = std::ptr::from_mut(payload.as_mut()).cast::<()>();
356 unsafe { dispatch(pointer, args, result) }
357 }
358 ClosureBody::Interpreted(body) => {
359 let frame = frame.as_mut().expect("validated canonical body");
360 unsafe { frame.arguments.bind_pointers(args, &mut frame.pointers) };
361 let mut stack = unsafe { body.execute_raw(&frame.pointers)? };
362 let mut output = unsafe { frame.result.take(&mut stack) };
363 unsafe { output.move_into(result) };
364 Ok(())
365 }
366 }
367 }
368
369 /// Returns the complete canonical callable descriptor after validating its current body.
370 ///
371 /// # Errors
372 /// Rejects untyped closures, executing bodies, or bodies changed incompatibly
373 /// through an unfrozen mutable dispatcher.
374 /// - Complexity: O(n) complete comparisons for n signature/body descriptor nodes.
375 ///
376 /// # Examples
377 /// ```
378 /// let mut body = cel_runtime::DynSegment::new::<()>(); body.just(7i32);
379 /// let closure = cel_runtime::DynClosure::typed(vec![], body).unwrap();
380 /// assert!(matches!(closure.value_type().unwrap().kind(), cel_runtime::ValueKind::Callable { .. }));
381 /// ```
382 pub fn value_type(&self) -> anyhow::Result<ValueType> {
383 self.validate_body_signature()?;
384 let signature = self
385 .0
386 .signature
387 .as_ref()
388 .expect("validated typed signature");
389 Ok(ValueType::callable(
390 signature.parameters.clone(),
391 signature.result.clone(),
392 ))
393 }
394
395 /// Wraps `body` as a closure value declaring `param_types` (in order) and `return_type`.
396 ///
397 /// - Precondition: `body` was compiled expecting exactly `param_types.len()` positional
398 /// arguments (via `push_arg`/`push_argument`), in that order, and
399 /// produces exactly one result of `return_type`.
400 ///
401 /// # Examples
402 ///
403 /// ```rust
404 /// use cel_runtime::{DynClosure, DynSegment};
405 /// use std::any::TypeId;
406 ///
407 /// let mut body = DynSegment::new::<()>();
408 /// body.push_arg::<i32>(0);
409 /// body.push_arg::<i32>(1);
410 /// body.op2r(|a: i32, b: i32| {
411 /// a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
412 /// }).unwrap();
413 ///
414 /// let closure = DynClosure::new(
415 /// vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
416 /// TypeId::of::<i32>(),
417 /// body,
418 /// );
419 /// assert_eq!(closure.param_types().len(), 2);
420 /// ```
421 #[must_use]
422 pub fn new(param_types: Vec<TypeId>, return_type: TypeId, body: DynSegment) -> Self {
423 DynClosure(
424 Rc::new(ClosureData {
425 param_types,
426 return_type,
427 body: RefCell::new(ClosureState {
428 body: ClosureBody::Interpreted(body),
429 frame: None,
430 }),
431 signature: None,
432 trusted_bindings: Cell::new(0),
433 }),
434 None,
435 )
436 }
437
438 /// Wraps a checked CEL body while retaining its full callable shape.
439 ///
440 /// # Errors
441 /// Returns an error if the body does not produce exactly one value, requires preloaded
442 /// arguments or a nonzero ambient stack origin, reads an undeclared or differently shaped
443 /// argument, or reads a tuple whose leaves lack clone adapters. A zero-origin fragment is
444 /// valid because its operations can access only its local operands and declared arguments.
445 ///
446 /// - Complexity: O(number of parameters plus recursive nodes in body argument reads/result).
447 ///
448 /// # Examples
449 /// ```
450 /// use cel_runtime::{DynClosure, DynSegment, ValueType};
451 /// let mut body = DynSegment::new::<()>();
452 /// body.just(42i32);
453 /// let closure = DynClosure::typed(vec![], body).unwrap();
454 /// assert_eq!(closure.call::<i32>(&[]).unwrap(), 42);
455 /// ```
456 pub fn typed(parameters: Vec<ValueType>, body: DynSegment) -> anyhow::Result<Self> {
457 let result = Self::validate_body(¶meters, &body)?;
458 let tuple = ValueType::tuple(
459 parameters
460 .iter()
461 .map(|value_type| crate::AssociatedType {
462 offset: 0,
463 value_type: value_type.clone(),
464 })
465 .collect(),
466 )?;
467 let frame = FramePlan {
468 arguments: crate::container_execution::ArgumentPlan::borrowed(tuple)?,
469 pointers: vec![std::ptr::null(); parameters.len()],
470 result: crate::container_execution::ResultPlan::new(0, result.clone())?,
471 };
472 let param_types = parameters.iter().map(ValueType::type_id).collect();
473 Ok(Self(
474 Rc::new(ClosureData {
475 param_types,
476 return_type: result.type_id(),
477 signature: Some(std::sync::Arc::new(ClosureSignature { parameters, result })),
478 body: RefCell::new(ClosureState {
479 body: ClosureBody::Interpreted(body),
480 frame: Some(frame),
481 }),
482 trusted_bindings: Cell::new(0),
483 }),
484 None,
485 ))
486 }
487
488 /// Returns a carrier whose clones retain a trusted freeze for their own lifetime.
489 ///
490 /// # Errors
491 /// Rejects an executing body or an unrepresentable additional lease.
492 pub(crate) fn bind_canonical(mut self) -> anyhow::Result<Self> {
493 if self.1.is_none() {
494 self.1 = Some(Rc::new(self.freeze_trusted_binding()?));
495 }
496 Ok(self)
497 }
498
499 /// Freezes arbitrary mutable body access across all aliases until the returned lease drops.
500 ///
501 /// This does not validate the signature; preparation must do so before binding.
502 /// Existing nonmutating execution paths remain available while leased.
503 ///
504 /// # Errors
505 /// Rejects a mutably borrowed body (including an active mutable dispatcher)
506 /// or an unrepresentable additional lease count without changing the counter.
507 pub(crate) fn freeze_trusted_binding(&self) -> anyhow::Result<TrustedBindingLease> {
508 let _body = self
509 .0
510 .body
511 .try_borrow()
512 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
513 let count = self
514 .0
515 .trusted_bindings
516 .get()
517 .checked_add(1)
518 .ok_or_else(|| anyhow::anyhow!("too many trusted bindings"))?;
519 let lease = TrustedBindingLease {
520 closure: self.clone(),
521 };
522 self.0.trusted_bindings.set(count);
523 Ok(lease)
524 }
525
526 /// Validates independent execution and declared argument reads, returning the actual result.
527 ///
528 /// # Errors
529 /// Rejects non-single results, dependent bodies, undeclared or mismatched reads,
530 /// and tuple reads without clone adapters.
531 /// - Complexity: O(recursive nodes in body argument reads and result).
532 fn validate_body(parameters: &[ValueType], body: &DynSegment) -> anyhow::Result<ValueType> {
533 anyhow::ensure!(
534 body.stack_ids.len() == 1,
535 "closure body must produce exactly one value"
536 );
537 body.validate_independent_body()?;
538 for (index, read_type) in &body.argument_reads {
539 anyhow::ensure!(
540 parameters
541 .get(*index)
542 .is_some_and(|expected| expected.same_shape(read_type)),
543 "closure body argument {index} differs from its declared signature"
544 );
545 read_type.validate_clone()?;
546 }
547 Ok(body.peek_stack_infos(1)[0].value_type.clone())
548 }
549
550 /// Checks the current mutable body against its retained typed signature during preparation.
551 ///
552 /// An external mutable dispatcher may have replaced the body without updating its metadata.
553 ///
554 /// # Errors
555 /// Rejects unavailable signatures, an executing body, invalid independent bodies
556 /// or argument reads, and a result differing from the retained signature.
557 /// - Complexity: O(recursive nodes in body argument reads and result).
558 pub(crate) fn validate_body_signature(&self) -> anyhow::Result<()> {
559 let signature = self
560 .0
561 .signature
562 .as_ref()
563 .ok_or_else(|| anyhow::anyhow!("closure signature metadata is unavailable"))?;
564 let body = self
565 .0
566 .body
567 .try_borrow()
568 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
569 let ClosureBody::Interpreted(body) = &body.body else {
570 return Ok(());
571 };
572 let result = Self::validate_body(&signature.parameters, body)?;
573 anyhow::ensure!(
574 signature.result.same_shape(&result),
575 "closure body result differs from its declared signature"
576 );
577 Ok(())
578 }
579
580 /// Returns the metadata retained for a typed CEL closure.
581 pub(crate) fn signature(&self) -> Option<std::sync::Arc<ClosureSignature>> {
582 self.0.signature.clone()
583 }
584
585 /// Enriches a complete canonical signature with explicitly supplied leaf factories.
586 ///
587 /// `leaf` looks up descriptors built while each concrete Rust type was
588 /// known; a `TypeId` never synthesizes a Rust monomorphization.
589 /// Factory capabilities remain independent of identity. This changes metadata
590 /// only; [`Self::value_type`] needs no factories for the existing complete signature.
591 ///
592 /// # Errors
593 ///
594 /// Returns an error for an untyped closure (including [`Self::new`]), an
595 /// unknown nested callable signature, a missing or mismatched concrete leaf
596 /// factory, or an unrepresentable canonical tuple layout.
597 ///
598 /// - Complexity: O(n) traversal time and output space for n signature nodes,
599 /// excluding leaf factory costs.
600 ///
601 /// # Examples
602 ///
603 /// ```
604 /// use cel_runtime::{DynClosure, DynSegment, value_type::{ValueKind, ValueType}};
605 /// use std::any::TypeId;
606 /// let mut body = DynSegment::new::<()>();
607 /// body.just(42i32);
608 /// let closure = DynClosure::typed(vec![], body).unwrap();
609 /// let complete = closure.complete_value_type(|id| {
610 /// (id == TypeId::of::<i32>()).then(ValueType::cloneable_leaf::<i32>)
611 /// }).unwrap();
612 /// assert!(matches!(complete.kind(), ValueKind::Callable { .. }));
613 /// ```
614 pub fn complete_value_type(
615 &self,
616 mut leaf: impl FnMut(TypeId) -> Option<crate::value_type::ValueType>,
617 ) -> anyhow::Result<crate::value_type::ValueType> {
618 self.0
619 .signature
620 .as_ref()
621 .ok_or_else(|| anyhow::anyhow!("closure signature metadata is unavailable"))?
622 .complete(&mut leaf)
623 }
624
625 /// Evaluates a previously checked borrowed raw argument frame into an independent stack.
626 ///
627 /// # Safety
628 /// Every pointer must reference a live value matching `expected.parameters`, in order,
629 /// until execution returns. No pointer may be retained by an operation.
630 ///
631 /// # Errors
632 /// Returns signature mismatch, reentrant body borrow, or body evaluation errors.
633 /// - Complexity: body-dependent.
634 #[cfg(test)]
635 pub(crate) unsafe fn call_raw(
636 &self,
637 expected: &ClosureSignature,
638 arguments: &[*const u8],
639 ) -> anyhow::Result<crate::raw_stack::RawStack> {
640 debug_assert_eq!(expected.parameters.len(), arguments.len());
641 anyhow::ensure!(
642 same_signature(self.0.signature.as_deref(), Some(expected)),
643 "closure signature mismatch"
644 );
645 let mut body = self
646 .0
647 .body
648 .try_borrow_mut()
649 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
650 unsafe { body.segment()?.execute_raw(arguments) }
651 }
652
653 /// Executes this carrier with a construction-validated, representation-matched frame.
654 ///
655 /// This path deliberately omits the external signature check. The prepared
656 /// invocation owns a clone of this exact carrier, preventing substitution.
657 ///
658 /// # Safety
659 ///
660 /// Preparation must validate the actual body's independent origin, argument reads,
661 /// and result against this closure's full signature and its canonical physical
662 /// frame. Every pointer must remain a live matching borrowed value
663 /// until execution returns; operations must not retain argument pointers.
664 /// A trusted-binding lease must protect the validated body from modification
665 /// throughout preparation and execution.
666 ///
667 /// # Errors
668 ///
669 /// Returns reentrant body borrow or body evaluation errors.
670 /// - Complexity: Body-dependent time and independent evaluation stack storage.
671 #[cfg(test)]
672 pub(crate) unsafe fn call_raw_trusted(
673 &self,
674 arguments: &[*const u8],
675 ) -> anyhow::Result<crate::raw_stack::RawStack> {
676 debug_assert_eq!(arguments.len(), self.0.param_types.len());
677 debug_assert!(self.0.signature.is_some());
678 let mut body = self
679 .0
680 .body
681 .try_borrow_mut()
682 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
683 unsafe { body.segment()?.execute_raw(arguments) }
684 }
685
686 /// Returns this closure's declared parameter types, in order.
687 ///
688 /// # Examples
689 ///
690 /// ```rust
691 /// use cel_runtime::{DynClosure, DynSegment};
692 /// use std::any::TypeId;
693 ///
694 /// let mut body = DynSegment::new::<()>();
695 /// body.push_arg::<i32>(0);
696 /// body.push_arg::<i32>(1);
697 /// body.op2r(|a: i32, b: i32| {
698 /// a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
699 /// }).unwrap();
700 ///
701 /// let closure = DynClosure::new(
702 /// vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
703 /// TypeId::of::<i32>(),
704 /// body,
705 /// );
706 /// assert_eq!(closure.param_types(), &[TypeId::of::<i32>(), TypeId::of::<i32>()]);
707 /// ```
708 #[must_use]
709 pub fn param_types(&self) -> &[TypeId] {
710 &self.0.param_types
711 }
712
713 /// Returns this closure's declared return type.
714 ///
715 /// # Examples
716 ///
717 /// ```rust
718 /// use cel_runtime::{DynClosure, DynSegment};
719 /// use std::any::TypeId;
720 ///
721 /// let mut body = DynSegment::new::<()>();
722 /// body.push_arg::<i32>(0);
723 /// body.push_arg::<i32>(1);
724 /// body.op2r(|a: i32, b: i32| {
725 /// a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
726 /// }).unwrap();
727 ///
728 /// let closure = DynClosure::new(
729 /// vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
730 /// TypeId::of::<i32>(),
731 /// body,
732 /// );
733 /// assert_eq!(closure.return_type(), TypeId::of::<i32>());
734 /// ```
735 #[must_use]
736 pub fn return_type(&self) -> TypeId {
737 self.0.return_type
738 }
739
740 /// Invokes the closure's body with `args`, positionally matched against `param_types`.
741 ///
742 /// - Precondition: `args.len() == self.param_types().len()` and each `args[i]`'s runtime type
743 /// matches `param_types()[i]` — the caller (adam-lang's generated `Filter` wrapper, or any
744 /// future caller) must guarantee this ahead of time; a violation is a caller bug, not user
745 /// error (matches `DynSegment::push_arg`'s own existing precondition, which this delegates
746 /// to unchanged).
747 /// - Precondition: `TypeId::of::<R>() == self.return_type()`.
748 /// - Complexity: whatever the body's own evaluation complexity is.
749 ///
750 /// # Examples
751 ///
752 /// ```rust
753 /// use cel_runtime::{DynClosure, DynSegment};
754 /// use std::any::TypeId;
755 ///
756 /// let mut body = DynSegment::new::<()>();
757 /// body.push_arg::<i32>(0);
758 /// body.push_arg::<i32>(1);
759 /// body.op2r(|a: i32, b: i32| {
760 /// a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
761 /// }).unwrap();
762 ///
763 /// let closure = DynClosure::new(
764 /// vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
765 /// TypeId::of::<i32>(),
766 /// body,
767 /// );
768 /// let (a, b) = (2i32, 3i32);
769 /// let result: i32 = closure.call(&[&a, &b]).unwrap();
770 /// assert_eq!(result, 5);
771 /// ```
772 pub fn call<R: 'static>(&self, args: &[&dyn Any]) -> anyhow::Result<R> {
773 debug_assert_eq!(args.len(), self.0.param_types.len());
774 self.0
775 .body
776 .try_borrow_mut()
777 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?
778 .segment()?
779 .call_dyn::<R>(args)
780 }
781
782 /// Invokes the closure's body with `args`, like [`call`](Self::call), for a caller that only
783 /// knows the return type dynamically (as a `TypeId`) rather than as a static Rust generic —
784 /// `call_dyn_fn` is a monomorphized dispatcher the caller already has for that type (e.g.
785 /// `adam-lang`'s per-type `TypeRegistry::TypeEntry::call_dyn_fn`).
786 ///
787 /// - Precondition: `args.len() == self.param_types().len()` and each `args[i]`'s runtime type
788 /// matches `param_types()[i]`, exactly as for [`call`](Self::call).
789 /// - Precondition: `call_dyn_fn` is a dispatcher for `self.return_type()` (i.e. it calls
790 /// `DynSegment::call_dyn::<R>` for the same concrete `R` that `TypeId` names).
791 /// - Complexity: whatever the body's own evaluation complexity is.
792 ///
793 /// # Errors
794 ///
795 /// Returns an error without invoking `call_dyn_fn` while any trusted binding
796 /// leases this shared body, including through another clone. Mutable dispatch
797 /// resumes after the last lease drops. Otherwise propagates dispatcher errors.
798 ///
799 /// # Examples
800 ///
801 /// ```rust
802 /// use cel_runtime::{DynClosure, DynSegment};
803 /// use std::any::{Any, TypeId};
804 ///
805 /// let mut body = DynSegment::new::<()>();
806 /// body.push_arg::<i32>(0);
807 /// body.push_arg::<i32>(1);
808 /// body.op2r(|a: i32, b: i32| {
809 /// a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
810 /// }).unwrap();
811 ///
812 /// let closure = DynClosure::new(
813 /// vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
814 /// TypeId::of::<i32>(),
815 /// body,
816 /// );
817 ///
818 /// fn dispatch_i32(seg: &mut DynSegment, inputs: &[&dyn Any]) -> anyhow::Result<Box<dyn Any>> {
819 /// let result: i32 = seg.call_dyn(inputs)?;
820 /// Ok(Box::new(result))
821 /// }
822 ///
823 /// let (a, b) = (4i32, 5i32);
824 /// let result = closure.call_boxed(&[&a, &b], dispatch_i32).unwrap();
825 /// assert_eq!(*result.downcast_ref::<i32>().unwrap(), 9);
826 /// ```
827 pub fn call_boxed(
828 &self,
829 args: &[&dyn Any],
830 call_dyn_fn: CallDynFn,
831 ) -> anyhow::Result<Box<dyn Any>> {
832 debug_assert_eq!(args.len(), self.0.param_types.len());
833 anyhow::ensure!(
834 self.0.trusted_bindings.get() == 0,
835 "closure body is frozen by a trusted binding"
836 );
837 let mut body = self
838 .0
839 .body
840 .try_borrow_mut()
841 .map_err(|_| anyhow::anyhow!("closure body is already executing"))?;
842 call_dyn_fn(body.segment()?, args)
843 }
844}
845
846#[cfg(test)]
847mod tests {
848 use super::*;
849 use crate::dyn_segment::DynSegment;
850
851 /// Clones and drops the existing shared carrier without erasing its signature.
852 #[test]
853 fn complete_factory_callable_owns_shared_carrier() {
854 use crate::value_type::ValueType as Complete;
855 use std::mem::{ManuallyDrop, MaybeUninit};
856 let mut body = DynSegment::new::<()>();
857 body.just(42i32);
858 let closure = DynClosure::typed(vec![], body).unwrap();
859 let weak = Rc::downgrade(&closure.0);
860 let descriptor = Complete::callable(vec![], Complete::leaf::<i32>());
861 assert_eq!(descriptor.layout(), std::alloc::Layout::new::<DynClosure>());
862 assert!(descriptor.can_clone());
863 assert!(descriptor.can_debug());
864 assert!(!descriptor.can_compare());
865 let mut source = ManuallyDrop::new(closure);
866 let source_ptr = (&mut *source as *mut DynClosure).cast::<u8>();
867 let mut destination = MaybeUninit::<DynClosure>::uninit();
868 // SAFETY: Both locations have the statically known carrier layout and
869 // the descriptor describes this closure's signature.
870 unsafe {
871 crate::owned_value::clone_raw(&descriptor, source_ptr, destination.as_mut_ptr().cast());
872 crate::owned_value::drop_raw(&descriptor, source_ptr);
873 assert!(weak.upgrade().is_some());
874 assert_eq!(destination.assume_init_ref().call::<i32>(&[]).unwrap(), 42);
875 crate::owned_value::drop_raw(&descriptor, destination.as_mut_ptr().cast());
876 }
877 assert!(weak.upgrade().is_none());
878 }
879
880 /// Keeps tuple and array identities in migrated signatures.
881 #[test]
882 fn complete_factory_preserves_structural_callable_signatures() {
883 use crate::value_type::{ValueKind, ValueType as Complete};
884 let mut body = DynSegment::new::<()>();
885 body.just(1i32);
886 body.make_tuple(1, 0).unwrap();
887 let parameter = ValueType::array(ValueType::cloneable_leaf::<i32>());
888 let closure = DynClosure::typed(vec![parameter], body).unwrap();
889 let descriptor = closure
890 .complete_value_type(|id| {
891 (id == TypeId::of::<i32>()).then(Complete::cloneable_leaf::<i32>)
892 })
893 .unwrap();
894 let ValueKind::Callable { parameters, result } = descriptor.kind() else {
895 panic!("expected complete callable metadata");
896 };
897 assert!(parameters[0].same_shape(&Complete::array(Complete::leaf::<i32>())));
898 assert!(!parameters[0].same_shape(&Complete::array(Complete::leaf::<u32>())));
899 assert!(matches!(result.kind(), ValueKind::Tuple(fields) if fields.len() == 1));
900 assert!(!result.same_shape(&Complete::leaf::<i32>()));
901 assert!(!descriptor.same_shape(&Complete::callable(
902 vec![Complete::array(Complete::leaf::<u32>())],
903 (**result).clone()
904 )));
905 assert!(!descriptor.same_shape(&Complete::callable(
906 parameters.clone(),
907 Complete::leaf::<i32>()
908 )));
909 }
910
911 /// Retains known nested callable results and distinguishes canonical source unit.
912 #[test]
913 fn complete_factory_preserves_nested_callable_and_unit() {
914 use crate::value_type::{Nil, ValueKind, ValueRepr, ValueType as Complete};
915 let mut inner_body = DynSegment::new::<()>();
916 inner_body.make_tuple(0, 0).unwrap();
917 let inner = DynClosure::typed(vec![ValueType::leaf::<()>()], inner_body).unwrap();
918 let mut body = DynSegment::new::<()>();
919 body.push_closure(inner).unwrap();
920 let outer = DynClosure::typed(vec![], body).unwrap();
921 let complete = outer
922 .complete_value_type(|id| (id == TypeId::of::<()>()).then(Complete::leaf::<()>))
923 .unwrap();
924 let ValueKind::Callable { result, .. } = complete.kind() else {
925 panic!("expected callable");
926 };
927 let ValueKind::Callable { parameters, result } = result.kind() else {
928 panic!("expected nested callable");
929 };
930 assert!(parameters[0].same_shape(&Complete::leaf::<()>()));
931 assert!(!parameters[0].same_shape(&Nil::value_type()));
932 assert!(result.same_shape(&Nil::value_type()));
933 assert!(!result.same_shape(&Complete::leaf::<()>()));
934 }
935
936 /// Rejects unavailable signatures and missing or incorrectly keyed leaf factories.
937 #[test]
938 fn complete_factory_rejects_unknown_callable_metadata() {
939 use crate::value_type::ValueType as Complete;
940 assert!(
941 adder_closure()
942 .complete_value_type(|_| Some(Complete::leaf::<i32>()))
943 .is_err()
944 );
945 let mut body = DynSegment::new::<()>();
946 body.just(1i32);
947 let closure = DynClosure::typed(vec![], body).unwrap();
948 assert!(closure.complete_value_type(|_| None).is_err());
949 assert!(
950 closure
951 .complete_value_type(|_| Some(Complete::leaf::<u32>()))
952 .is_err()
953 );
954 assert!(
955 closure
956 .complete_value_type(|_| Some(Complete::array(Complete::leaf::<i32>())))
957 .is_err()
958 );
959
960 let mut body = DynSegment::new::<()>();
961 body.just(adder_closure());
962 let closure = DynClosure::typed(vec![], body).unwrap();
963 assert!(
964 closure
965 .complete_value_type(|_| Some(Complete::leaf::<DynClosure>()))
966 .is_err()
967 );
968 }
969
970 /// Builds a signed adder that reports overflow through the runtime error channel.
971 fn adder_closure() -> DynClosure {
972 let mut body = DynSegment::new::<()>();
973 body.push_arg::<i32>(0);
974 body.push_arg::<i32>(1);
975 body.op2r(|a: i32, b: i32| {
976 a.checked_add(b)
977 .ok_or_else(|| anyhow::anyhow!("addition overflow"))
978 })
979 .unwrap();
980 DynClosure::new(
981 vec![TypeId::of::<i32>(), TypeId::of::<i32>()],
982 TypeId::of::<i32>(),
983 body,
984 )
985 }
986
987 /// Calls the body repeatedly with distinct positional arguments.
988 #[test]
989 fn call_is_repeatable_with_different_args() {
990 let closure = adder_closure();
991 let (a1, b1) = (2i32, 3i32);
992 assert_eq!(closure.call::<i32>(&[&a1, &b1]).unwrap(), 5);
993 let (a2, b2) = (10i32, 20i32);
994 assert_eq!(closure.call::<i32>(&[&a2, &b2]).unwrap(), 30);
995 }
996
997 /// Reports arithmetic overflow and leaves the shared body callable afterward.
998 #[test]
999 fn checked_adder_recovers_after_overflow() {
1000 let closure = adder_closure();
1001 assert!(closure.call::<i32>(&[&i32::MAX, &1i32]).is_err());
1002 assert_eq!(closure.call::<i32>(&[&2i32, &3i32]).unwrap(), 5);
1003 }
1004
1005 /// Keeps both carrier aliases callable after cloning.
1006 #[test]
1007 fn clone_shares_the_same_body_and_both_remain_callable() {
1008 let closure = adder_closure();
1009 let cloned = closure.clone();
1010 let (a, b) = (1i32, 1i32);
1011 assert_eq!(closure.call::<i32>(&[&a, &b]).unwrap(), 2);
1012 assert_eq!(cloned.call::<i32>(&[&a, &b]).unwrap(), 2);
1013 }
1014
1015 /// Invokes the supplied monomorphized dispatcher and returns its boxed result.
1016 #[test]
1017 fn call_boxed_dispatches_through_a_supplied_call_dyn_fn() {
1018 let closure = adder_closure();
1019 /// Evaluates and boxes the exact signed result.
1020 fn call_dyn_fn(seg: &mut DynSegment, inputs: &[&dyn Any]) -> anyhow::Result<Box<dyn Any>> {
1021 let v: i32 = seg.call_dyn(inputs)?;
1022 Ok(Box::new(v))
1023 }
1024 let (a, b) = (4i32, 5i32);
1025 let result = closure.call_boxed(&[&a, &b], call_dyn_fn).unwrap();
1026 assert_eq!(*result.downcast_ref::<i32>().unwrap(), 9);
1027 }
1028
1029 /// Returns the declared source-ordered parameter and result identities.
1030 #[test]
1031 fn param_types_and_return_type_are_queryable() {
1032 let closure = adder_closure();
1033 assert_eq!(
1034 closure.param_types(),
1035 &[TypeId::of::<i32>(), TypeId::of::<i32>()]
1036 );
1037 assert_eq!(closure.return_type(), TypeId::of::<i32>());
1038 }
1039
1040 /// A typed body cannot reinterpret an argument through a different Rust representation.
1041 #[test]
1042 fn typed_rejects_incompatible_body_argument_reads() {
1043 let mut body = DynSegment::new::<()>();
1044 body.push_arg::<String>(0);
1045 assert!(DynClosure::typed(vec![ValueType::leaf::<i32>()], body).is_err());
1046 }
1047
1048 /// An undeclared positional argument cannot enter a typed raw call frame.
1049 #[test]
1050 fn typed_rejects_undeclared_body_argument_reads() {
1051 let mut body = DynSegment::new::<()>();
1052 body.push_arg::<i32>(1);
1053 assert!(DynClosure::typed(vec![ValueType::leaf::<i32>()], body).is_err());
1054 }
1055
1056 /// A shifted fragment cannot become a body evaluated on an empty stack.
1057 #[test]
1058 fn typed_rejects_ambient_dependent_body_without_execution() {
1059 let mut inner = DynSegment::new::<()>();
1060 inner.just(42i32);
1061 let closure = DynClosure::typed(vec![], inner).unwrap();
1062 let mut parent = DynSegment::new::<()>();
1063 parent.just(7u64);
1064 parent.just(true);
1065 let mut fragment = parent.new_fragment();
1066 fragment.push_closure(closure).unwrap();
1067 fragment.invoke_closure(0).unwrap();
1068
1069 assert!(DynClosure::typed(vec![], fragment).is_err());
1070 }
1071
1072 /// A zero-origin fragment contains only its local operands, even above ambient unit values.
1073 #[test]
1074 fn typed_accepts_zero_origin_body_with_nested_invocation() {
1075 let mut inner = DynSegment::new::<()>();
1076 inner.just(42i32);
1077 let closure = DynClosure::typed(vec![], inner).unwrap();
1078 let mut parent = DynSegment::new::<()>();
1079 parent.just(());
1080 parent.just(true);
1081 let mut fragment = parent.new_fragment();
1082 fragment.push_closure(closure).unwrap();
1083 fragment.invoke_closure(0).unwrap();
1084
1085 let closure = DynClosure::typed(vec![], fragment).unwrap();
1086 assert_eq!(closure.call::<i32>(&[]).unwrap(), 42);
1087 let mut caller = DynSegment::new::<()>();
1088 caller.push_closure(closure).unwrap();
1089 caller.invoke_closure(0).unwrap();
1090 assert_eq!(caller.call0::<i32>().unwrap(), 42);
1091 }
1092
1093 /// A root body cannot hide a shifted fragment behind a conditional join.
1094 #[test]
1095 fn typed_body_join_rejects_mismatched_fragment_origins_without_execution() {
1096 for shifted_first in [true, false] {
1097 let mut parent = DynSegment::new::<()>();
1098 parent.just(7u64);
1099 parent.just(true);
1100 let mut shifted = parent.new_fragment();
1101 shifted.just(42i32);
1102 let mut body = DynSegment::new::<()>();
1103 body.just(true);
1104 let mut alternate = body.new_fragment();
1105 alternate.just(0i32);
1106
1107 let result = if shifted_first {
1108 body.join2(shifted, alternate)
1109 } else {
1110 body.join2(alternate, shifted)
1111 };
1112 assert!(result.is_err());
1113 }
1114 }
1115
1116 /// A runtime closure value cannot masquerade as another known callable signature.
1117 #[test]
1118 fn invocation_checks_runtime_signature_before_body_execution() {
1119 let mut expected_body = DynSegment::new::<()>();
1120 expected_body.just(1i32);
1121 let expected = DynClosure::typed(vec![], expected_body).unwrap();
1122 let executed = Rc::new(std::cell::Cell::new(false));
1123 let observed = executed.clone();
1124 let mut actual_body = DynSegment::new::<()>();
1125 actual_body.op0(move || {
1126 observed.set(true);
1127 true
1128 });
1129 let actual = DynClosure::typed(vec![], actual_body).unwrap();
1130 // Both signatures have no parameters, so the borrowed argument frame is valid.
1131 let error = unsafe { actual.call_raw(&expected.signature().unwrap(), &[]) }.unwrap_err();
1132 assert!(error.to_string().contains("signature mismatch"));
1133 assert!(!executed.get());
1134 }
1135
1136 /// Argument reads inside alternate fragments participate in signature validation.
1137 #[test]
1138 fn typed_checks_conditional_argument_reads() {
1139 let mut body = DynSegment::new::<()>();
1140 body.just(true);
1141 let mut then_branch = body.new_fragment();
1142 then_branch.push_arg::<String>(0);
1143 let mut else_branch = body.new_fragment();
1144 else_branch.just(String::new());
1145 body.join2(then_branch, else_branch).unwrap();
1146 assert!(DynClosure::typed(vec![ValueType::leaf::<i32>()], body).is_err());
1147 }
1148
1149 /// Rejected invocation leaves the evaluated operand descriptors and operations unchanged.
1150 #[test]
1151 fn wrong_argument_type_is_rejected_before_emitting() {
1152 let mut body = DynSegment::new::<()>();
1153 body.push_arg::<i32>(0);
1154 let closure = DynClosure::typed(vec![ValueType::leaf::<i32>()], body).unwrap();
1155 let mut caller = DynSegment::new::<()>();
1156 caller.push_closure(closure).unwrap();
1157 caller.just(false);
1158 assert!(caller.invoke_closure(1).is_err());
1159 assert_eq!(caller.peek_stack_infos(2).len(), 2);
1160 caller.op1(|_: bool| 8i32).unwrap();
1161 caller.invoke_closure(1).unwrap();
1162 assert_eq!(caller.call0::<i32>().unwrap(), 8);
1163 }
1164
1165 /// Preloaded Rust argument layouts cannot enter the positional CEL invocation adapter.
1166 #[test]
1167 fn preloaded_arguments_fail_explicitly() {
1168 let mut body = DynSegment::new::<()>();
1169 body.just(1i32);
1170 let mut caller = DynSegment::new::<(i32,)>();
1171 caller
1172 .push_closure(DynClosure::typed(vec![], body).unwrap())
1173 .unwrap();
1174 assert!(caller.invoke_closure(0).is_err());
1175 }
1176}