adam_lang/cell_value.rs
1//! Private canonical cell storage and construction-time frozen Adam/CEL adapters.
2//!
3//! Primitive cells remain concrete Rust values. Compound access passes through
4//! `ParsedSheet`'s checked representation-witness boundary.
5use std::any::{Any, TypeId};
6use std::cell::RefCell;
7
8use adam_rs::{CellId, Requirement};
9
10use cel_runtime::{DynSegment, OwnedValue, ValueType, prepared_segment::PreparedRawSegment};
11
12use crate::{TypeRegistry, type_registry::TypeShape};
13
14/// Formats a canonical compound cell at the checked host boundary.
15///
16/// This also supports hosts that retain the underlying `adam_rs::Sheet`.
17/// # Errors
18/// Rejects an unknown cell, concrete leaf storage, or absent debug capability.
19/// - Complexity: O(v + s) for v contained values and s output bytes.
20///
21/// # Examples
22/// ```
23/// let parsed = adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
24/// .parse_str("sheet s { cell point: (i32, i32) = (3, 4); }").unwrap();
25/// assert_eq!(adam_lang::debug_compound_cell(&parsed.sheet, parsed.cell_names["point"].0).unwrap(), "(3, 4)");
26/// ```
27pub fn debug_compound_cell(sheet: &adam_rs::Sheet, id: adam_rs::CellId) -> anyhow::Result<String> {
28 sheet.read::<CellValue>(id)?.0.try_debug()
29}
30
31/// Prepares canonical compound-cell formatting from the cell owner's debug capability.
32///
33/// The returned closure reads the current value, checks its complete shape, and
34/// formats through the retained capability. It does not consume or clone values.
35///
36/// # Errors
37/// Rejects an unknown cell, noncompound storage, or unavailable debug capability.
38/// The closure also rejects a different shape or missing cell in its input sheet.
39/// - Complexity: Preparation O(1); each call O(n + v + s) for n type nodes,
40/// v contained values and s output bytes, excluding leaf formatter costs.
41///
42/// # Examples
43/// ```
44/// let parsed = adam_lang::AdamParser::new(adam_lang::TypeRegistry::new(), cel_parser::OpLookup::new())
45/// .parse_str("sheet s { cell xs: [i32]; }").unwrap();
46/// let format = adam_lang::prepare_compound_cell_formatter(&parsed, parsed.cell_names["xs"].0).unwrap();
47/// assert_eq!(format(&parsed).unwrap(), "[]");
48/// ```
49pub fn prepare_compound_cell_formatter(
50 sheet: &adam_rs::Sheet,
51 id: adam_rs::CellId,
52) -> anyhow::Result<impl Fn(&adam_rs::Sheet) -> anyhow::Result<String> + use<>> {
53 let formatter = sheet.read::<CellValue>(id)?.0.prepare_debug()?;
54 Ok(move |sheet: &adam_rs::Sheet| formatter.format(&sheet.read::<CellValue>(id)?.0))
55}
56
57/// Owns a compound value whose cloning and equality capabilities are bound.
58///
59/// Only checked host writes and frozen output adapters construct this private type.
60pub(crate) struct CellValue(pub(crate) OwnedValue);
61
62impl CellValue {
63 /// Rejects missing cell capabilities before sheet insertion.
64 ///
65 /// # Errors
66 /// Returns a diagnostic for missing cloning or equality.
67 pub(crate) fn validate(ty: &ValueType) -> anyhow::Result<()> {
68 validate_cell_capabilities(ty.can_clone_for_argument(), ty.can_compare()).map_err(
69 |capability| {
70 anyhow::anyhow!(
71 "Adam cell {capability} capability unavailable for `{}`",
72 ty.type_name()
73 )
74 },
75 )
76 }
77}
78
79/// Rejects cell storage types without cloning or value equality.
80pub(crate) fn validate_cell_capabilities(
81 cloneable: bool,
82 comparable: bool,
83) -> Result<(), &'static str> {
84 if !cloneable {
85 Err("clone")
86 } else if !comparable {
87 Err("equality")
88 } else {
89 Ok(())
90 }
91}
92
93impl Clone for CellValue {
94 /// Clones through the previously validated frozen ownership plan.
95 ///
96 /// - Complexity: O(v) for v contained values, excluding leaf clone costs.
97 fn clone(&self) -> Self {
98 Self(self.0.try_clone().expect("validated cell clone capability"))
99 }
100}
101
102impl PartialEq for CellValue {
103 /// Compares values at a shape-validated cell boundary without repeating type checks.
104 ///
105 /// - Complexity: O(v) for v contained values, excluding leaf equality costs.
106 fn eq(&self, other: &Self) -> bool {
107 // SAFETY: This type is private; host writes and all prepared outputs bind
108 // the complete cell shape before entering Adam's type-erased storage.
109 unsafe { self.0.eq_bound(&other.0) }
110 }
111}
112
113impl std::fmt::Debug for CellValue {
114 /// Formats a value through its optional canonical debug capability.
115 ///
116 /// - Complexity: O(v + s) for v contained values and s formatted bytes.
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 match self.0.try_debug() {
119 Ok(value) => f.write_str(&value),
120 Err(_) => f.write_str("<compound value>"),
121 }
122 }
123}
124
125/// Describes a construction-time validated move from canonical result to Adam storage.
126enum Output {
127 /// A registered primitive or foreign concrete Rust leaf.
128 Leaf(unsafe fn(OwnedValue) -> Box<dyn Any>),
129 /// Private whole-value ownership of a recursive compound.
130 Compound,
131}
132
133impl Output {
134 /// Moves one already-bound canonical result into its Adam storage carrier.
135 fn store(&self, value: OwnedValue) -> Box<dyn Any> {
136 match self {
137 // SAFETY: The result identity was bound during construction.
138 Self::Leaf(box_value) => unsafe { box_value(value) },
139 Self::Compound => Box::new(CellValue(value)),
140 }
141 }
142}
143
144/// Executes a frozen canonical raw frame behind Adam's existing host callback boundary.
145pub(crate) struct Frame {
146 body: RawFrame,
147 outputs: Vec<Output>,
148 split: bool,
149}
150
151/// Binds Adam storage addresses to the canonical runtime's one raw execution engine.
152pub(crate) struct RawFrame {
153 body: PreparedRawSegment,
154 inputs: Vec<Input>,
155 pointers: Vec<*const u8>,
156}
157
158/// Retains the complete storage identity required at an erased host boundary.
159enum Input {
160 /// A concrete registered Rust leaf.
161 Leaf(TypeId),
162 /// A private carrier with an exact recursive canonical shape.
163 Compound(ValueType),
164}
165
166impl Input {
167 /// Checks storage identity and complete shape without binding or reading raw pointers.
168 ///
169 /// # Errors
170 /// Rejects a different concrete type, compound carrier, or recursive shape.
171 /// - Complexity: O(n) for n compound descriptor nodes; O(1) for leaves.
172 fn validate(&self, input: &dyn Any) -> anyhow::Result<()> {
173 let matches = match self {
174 Self::Leaf(id) => input.type_id() == *id,
175 Self::Compound(expected) => input
176 .downcast_ref::<CellValue>()
177 .is_some_and(|value| value.0.value_type().same_shape(expected)),
178 };
179 anyhow::ensure!(matches, "Adam argument storage or shape mismatch");
180 Ok(())
181 }
182}
183
184impl Frame {
185 /// Validates complete reads, outputs, and cell capabilities before execution.
186 ///
187 /// # Errors
188 /// Rejects mismatched recursive representations or missing required capabilities.
189 /// - Complexity: O(n) in signature nodes and emitted reads.
190 pub(crate) fn new(
191 body: DynSegment,
192 inputs: &[TypeShape],
193 outputs: &[TypeShape],
194 split: bool,
195 types: &TypeRegistry,
196 ) -> anyhow::Result<Self> {
197 let result = if split {
198 types.value_type(&TypeShape::Tuple(outputs.to_vec()))
199 } else {
200 types.value_type(&outputs[0])
201 };
202 let mut adapters = Vec::with_capacity(outputs.len());
203 for shape in outputs {
204 match shape {
205 TypeShape::Named(id) => adapters.push(Output::Leaf(
206 types
207 .entry_by_type_id(*id)
208 .expect("resolved leaf")
209 .box_owned,
210 )),
211 _ => {
212 CellValue::validate(&types.value_type(shape))?;
213 adapters.push(Output::Compound);
214 }
215 }
216 }
217 Ok(Self {
218 body: RawFrame::new(body, inputs, &result, types)?,
219 outputs: adapters,
220 split,
221 })
222 }
223
224 /// Executes raw borrowed inputs already type-checked by Adam's callback boundary.
225 ///
226 /// - Precondition: Input storage matches the exact shapes supplied to construction.
227 /// # Errors
228 /// Propagates CEL operation failures after canonical cleanup.
229 /// - Complexity: O(a) pointer binding plus body costs and output moves.
230 pub(crate) fn call(&mut self, inputs: &[&dyn Any]) -> anyhow::Result<Vec<Box<dyn Any>>> {
231 let result = self.body.call(inputs)?;
232 self.store(result)
233 }
234
235 /// Executes a filter frame without allocating a merged host argument list.
236 ///
237 /// - Precondition: The candidate and dependencies match the prepared storage types.
238 /// # Errors
239 /// Propagates operation failures.
240 /// - Complexity: O(a) pointer binding plus body costs and output moves.
241 pub(crate) fn call_with_prefix(
242 &mut self,
243 value: &dyn Any,
244 inputs: &[&dyn Any],
245 ) -> anyhow::Result<Vec<Box<dyn Any>>> {
246 let result = self.body.call_with_prefix(value, inputs)?;
247 self.store(result)
248 }
249
250 /// Moves a whole result or its bound fields into the requested output cells.
251 ///
252 /// # Errors
253 /// Returns an error if a destructuring result is not a tuple.
254 /// - Complexity: O(n + s) for n output fields and s representation bytes.
255 fn store(&self, result: OwnedValue) -> anyhow::Result<Vec<Box<dyn Any>>> {
256 if self.split {
257 Ok(result
258 .into_fields()?
259 .into_iter()
260 .zip(&self.outputs)
261 .map(|(value, output)| output.store(value))
262 .collect())
263 } else {
264 Ok(vec![self.outputs[0].store(result)])
265 }
266 }
267}
268
269impl RawFrame {
270 /// Validates every positional read and binds the result's capabilities before execution.
271 ///
272 /// # Errors
273 /// Rejects a mismatched signature or missing borrowed cloning.
274 /// - Complexity: O(n) in descriptor nodes and emitted reads.
275 pub(crate) fn new(
276 mut body: DynSegment,
277 inputs: &[TypeShape],
278 result: &ValueType,
279 types: &TypeRegistry,
280 ) -> anyhow::Result<Self> {
281 let input_types: Vec<_> = inputs.iter().map(|shape| types.value_type(shape)).collect();
282 body.annotate_top(result.clone())?;
283 Ok(Self {
284 body: PreparedRawSegment::new(body, &input_types, result)?,
285 inputs: inputs
286 .iter()
287 .zip(input_types)
288 .map(|(shape, value_type)| match shape {
289 TypeShape::Named(id) => Input::Leaf(*id),
290 _ => Input::Compound(value_type),
291 })
292 .collect(),
293 pointers: vec![std::ptr::null(); inputs.len()],
294 })
295 }
296
297 /// Executes an Adam-validated host frame without recursive checks or conversions.
298 ///
299 /// - Precondition: Every input matches its preparation-time storage adapter.
300 /// # Errors
301 /// Propagates operation failures after cleanup.
302 /// - Complexity: O(a) pointer binding plus body costs.
303 pub(crate) fn call(&mut self, inputs: &[&dyn Any]) -> anyhow::Result<OwnedValue> {
304 self.call_arguments(inputs.iter().copied(), inputs.len())
305 }
306
307 /// Prepends a filter candidate without allocating a merged host argument list.
308 ///
309 /// - Precondition: The candidate and dependencies match their prepared storage types.
310 /// # Errors
311 /// Propagates operation failures.
312 /// - Complexity: O(a) pointer binding plus body costs.
313 pub(crate) fn call_with_prefix(
314 &mut self,
315 value: &dyn Any,
316 inputs: &[&dyn Any],
317 ) -> anyhow::Result<OwnedValue> {
318 self.call_arguments(
319 std::iter::once(value).chain(inputs.iter().copied()),
320 inputs.len() + 1,
321 )
322 }
323
324 /// Checks every erased input before binding any address or executing the prefixed frame.
325 ///
326 /// # Errors
327 /// Rejects missing or extra inputs, wrong scalar identities, compound carriers, or
328 /// recursive shapes on every invocation; propagates operation failures after cleanup.
329 /// Rejection leaves previously bound pointers unused and permits later valid calls.
330 /// - Complexity: O(a + n) validation for a inputs and n compound descriptor nodes,
331 /// plus pointer binding and body costs.
332 pub(crate) fn call_checked_with_prefix(
333 &mut self,
334 value: &dyn Any,
335 inputs: &[&dyn Any],
336 ) -> anyhow::Result<OwnedValue> {
337 anyhow::ensure!(
338 inputs.len().checked_add(1) == Some(self.inputs.len()),
339 "Adam argument count mismatch"
340 );
341 for (input, expected) in std::iter::once(value)
342 .chain(inputs.iter().copied())
343 .zip(&self.inputs)
344 {
345 expected.validate(input)?;
346 }
347 self.call_with_prefix(value, inputs)
348 }
349
350 /// Binds borrowed host addresses into the reusable canonical pointer slots.
351 ///
352 /// - Precondition: Input count and types match preparation.
353 /// # Errors
354 /// Propagates operation failures after raw frame cleanup.
355 /// - Complexity: O(a) pointer binding plus body costs.
356 fn call_arguments<'a>(
357 &mut self,
358 inputs: impl Iterator<Item = &'a dyn Any>,
359 arity: usize,
360 ) -> anyhow::Result<OwnedValue> {
361 debug_assert_eq!(arity, self.pointers.len());
362 for ((input, adapter), pointer) in inputs.zip(&self.inputs).zip(&mut self.pointers) {
363 let data = std::ptr::from_ref(input).cast::<()>();
364 *pointer = match adapter {
365 Input::Compound(_) => {
366 // SAFETY: Adam's internal boundary or the checked public
367 // adapter verifies the private carrier and complete shape.
368 unsafe { &*data.cast::<CellValue>() }.0.as_ptr()
369 }
370 Input::Leaf(_) => data.cast(),
371 };
372 }
373 // SAFETY: Construction validates every read. The internal callback boundary
374 // or checked entry point guarantees storage types and complete compound shapes.
375 unsafe { self.body.call(&self.pointers) }
376 }
377}
378
379/// Flattens a declared cell's `TypeShape` to the single `TypeId` `adam_rs` itself needs for its
380/// own (CEL-agnostic) storage bookkeeping. Compound shape identity remains separate from
381/// the private common storage carrier and is validated before constructing any adapter.
382pub(crate) fn cell_type_id(shape: &TypeShape) -> TypeId {
383 match shape {
384 TypeShape::Named(type_id) => *type_id,
385 _ => TypeId::of::<CellValue>(),
386 }
387}
388
389/// Prepares a numeric range filter shared by parsed and native builders.
390///
391/// - Precondition: All named shapes are registered.
392/// # Errors
393/// Rejects missing/mismatched numeric ranges, unavailable defaults or invalid frames.
394/// - Complexity: O(n + e + i) descriptor nodes, reads and inputs.
395pub(crate) fn build_range_filter(
396 body: DynSegment,
397 ids: Vec<CellId>,
398 inputs: &[TypeShape],
399 output: &TypeShape,
400 types: &TypeRegistry,
401) -> anyhow::Result<adam_rs::Filter> {
402 let id = body
403 .peek_output_type_id()
404 .ok_or_else(|| anyhow::anyhow!("filter has no result"))?;
405 let range = types
406 .range_entry(id)
407 .ok_or_else(|| anyhow::anyhow!("expected numeric range filter"))?;
408 let value_type = cell_type_id(output);
409 anyhow::ensure!(
410 range.element_type_id == value_type,
411 "filter range element mismatch"
412 );
413 let default = types
414 .entry_by_type_id(value_type)
415 .and_then(|entry| entry.default_fn)
416 .ok_or_else(|| anyhow::anyhow!("numeric range filter requires a default"))?;
417 let placeholder = default();
418 let result = body.peek_stack_infos(1)[0].value_type.clone();
419 let shapes: Vec<_> = std::iter::once(output.clone())
420 .chain(inputs.iter().cloned())
421 .collect();
422 let frame = std::rc::Rc::new(RefCell::new(RawFrame::new(body, &shapes, &result, types)?));
423 let clamp = frame.clone();
424 let clamp_fn = range.clamp_fn;
425 let bounds_fn = range.bounds_fn;
426 Ok(adam_rs::Filter::range(
427 value_type,
428 ids,
429 inputs.iter().map(cell_type_id).collect(),
430 move |value, args| clamp_fn(clamp.borrow_mut().call_with_prefix(value, args)?, value),
431 move |args| {
432 bounds_fn(
433 frame
434 .borrow_mut()
435 .call_checked_with_prefix(placeholder.as_ref(), args)
436 .ok()?,
437 )
438 .ok()
439 },
440 ))
441}
442
443/// Prepares the common value-returning filter frame for parsed and native builders.
444///
445/// - Precondition: All named shapes are registered.
446/// # Errors
447/// Rejects incompatible emitted signatures or missing required cell capabilities.
448/// - Complexity: O(n + e + i) descriptor nodes, reads and inputs.
449pub(crate) fn build_value_filter(
450 body: DynSegment,
451 ids: Vec<CellId>,
452 inputs: &[TypeShape],
453 output: &TypeShape,
454 types: &TypeRegistry,
455) -> anyhow::Result<adam_rs::Filter> {
456 let shapes: Vec<_> = std::iter::once(output.clone())
457 .chain(inputs.iter().cloned())
458 .collect();
459 let frame = RefCell::new(Frame::new(
460 body,
461 &shapes,
462 std::slice::from_ref(output),
463 false,
464 types,
465 )?);
466 Ok(adam_rs::Filter::new(
467 cell_type_id(output),
468 ids,
469 inputs.iter().map(cell_type_id).collect(),
470 move |value, args| Ok(frame.borrow_mut().call_with_prefix(value, args)?.remove(0)),
471 ))
472}
473
474/// Prepares the common bool-returning requirement frame for both builder paths.
475///
476/// - Precondition: All named shapes are registered.
477/// # Errors
478/// Rejects incompatible signatures or unavailable borrowed cloning.
479/// - Complexity: O(n + e + i) descriptor nodes, reads and inputs.
480pub(crate) fn build_requirement(
481 body: DynSegment,
482 ids: Vec<CellId>,
483 inputs: &[TypeShape],
484 types: &TypeRegistry,
485) -> anyhow::Result<Requirement> {
486 let frame = RefCell::new(RawFrame::new(
487 body,
488 inputs,
489 &cel_runtime::ValueType::leaf::<bool>(),
490 types,
491 )?);
492 Ok(Requirement::new(
493 ids,
494 inputs.iter().map(cell_type_id).collect(),
495 move |args| {
496 let value = frame.borrow_mut().call(args)?;
497 // SAFETY: RawFrame bound the result to the complete concrete bool descriptor.
498 Ok(unsafe { value.into_typed_bound::<cel_runtime::Leaf<bool>>() })
499 },
500 ))
501}