adam_rs/template.rs
1//! Owning, source-free recipes for composition in one native [`Sheet`].
2//!
3//! Parameters alias caller-owned cells; private declarations allocate fresh cells
4//! in declaration order. Factories run at instantiation, never propagation.
5//! Each factory must create fresh execution state and satisfy [`Method`]'s contract.
6//!
7//! ```
8//! use adam_rs::{Method, MethodRecipe, Sheet, TemplateBuilder};
9//!
10//! let mut builder = TemplateBuilder::new();
11//! let input = builder.parameter::<i32>("input")?;
12//! let output = builder.parameter::<i32>("output")?;
13//! let method = MethodRecipe::new(&[input], &[output], |ins, outs| {
14//! Ok(Method::from_fn_1_1(ins[0], outs[0], |x: &i32| Ok(*x)))
15//! })?;
16//! builder.relationship(vec![method])?;
17//! let template = builder.finish()?;
18//! let mut sheet = Sheet::new();
19//! let input = sheet.add_source(7i32);
20//! let output = sheet.add_cell(0i32);
21//! let instance = template.instantiate(&mut sheet, &[("output", output), ("input", input)])?;
22//! sheet.propagate()?;
23//! assert_eq!(*sheet.read::<i32>(output)?, 7);
24//! assert_eq!(instance.cells(), &[input, output]);
25//! # Ok::<(), Box<dyn std::error::Error>>(())
26//! ```
27//!
28//! This path constructs native methods directly: it needs no CEL text, lexer,
29//! parser or operation lookup. For checked multiplication with a source-bound
30//! factor, run `cargo run -p adam-lang --example templates` in the workspace.
31//! That example's native path uses only this crate's recipe and sheet APIs.
32//!
33//! Named actuals must cover each parameter once, use distinct live cells from
34//! the destination sheet, and match the declared concrete types. Fixed sources
35//! specialize away every method that would write them. An empty specialized
36//! relationship fails before factories run. `out` cells cannot be actuals.
37//! Parameters keep caller-owned filters, requirements, strength and aspirations;
38//! component-owned policies may govern only private cells.
39//!
40//! Finished templates own their factories; each factory creates fresh execution
41//! state. Immutable captures may be shared. Live methods survive dropping both
42//! the template and its returned instance metadata. Instantiation runs factories
43//! but never propagates. On error, the destination remains safely discardable;
44//! instantiation does not promise rollback. [`TemplateError::Construction`]
45//! retains the actual native site and original cause without invented source spans.
46//! Conditional inclusion requires a transitively relationship-only component.
47//! Private state remains available to unconditional inclusions.
48
49mod builder;
50mod error;
51mod instantiate;
52mod provenance;
53pub mod structure;
54
55use std::any::TypeId;
56use std::collections::{HashMap, HashSet};
57use std::rc::Rc;
58
59use crate::{CellId, CellKind, Method, RelationshipId, Sheet};
60
61pub use builder::TemplateBuilder;
62pub use error::{ConstructionSite, TemplateError};
63pub use provenance::{InstanceOccurrence, MethodOrigin, OccurrenceId, TemplateId};
64
65/// Identifies a cell declaration within exactly one owning builder/template.
66///
67/// Clones retain identity, not ownership of a live cell.
68///
69/// # Examples
70/// See the [module example](self).
71#[derive(Clone, Debug)]
72pub struct CellSlot {
73 owner: Rc<()>,
74 index: usize,
75}
76
77impl PartialEq for CellSlot {
78 /// Compares the owning recipe and local declaration index.
79 fn eq(&self, other: &Self) -> bool {
80 Rc::ptr_eq(&self.owner, &other.owner) && self.index == other.index
81 }
82}
83
84impl Eq for CellSlot {}
85
86/// Identifies a relationship declaration or inclusion group within one owning recipe.
87///
88/// A group expands to zero or more distinct live relationships, never a merged
89/// runtime relationship. Inclusion returns one group in the including namespace.
90///
91/// # Examples
92/// See [`TemplateBuilder::include`].
93#[derive(Clone, Debug)]
94pub struct RelationshipSlot {
95 owner: Rc<()>,
96 index: usize,
97}
98
99impl PartialEq for RelationshipSlot {
100 /// Compares the owning recipe and local relationship index.
101 fn eq(&self, other: &Self) -> bool {
102 Rc::ptr_eq(&self.owner, &other.owner) && self.index == other.index
103 }
104}
105
106impl Eq for RelationshipSlot {}
107
108/// Creates a fresh native method for the supplied positional edge handles.
109type MethodFactory = dyn Fn(&[CellId], &[CellId]) -> anyhow::Result<Method>;
110
111/// Stores declared local edges and a repeatable, owning native method factory.
112///
113/// Factories must create fresh execution state satisfying [`Method`]'s contract.
114/// Their returned method's positional edges and types must match the declarations.
115/// Immutable captured configuration may be shared.
116///
117/// # Examples
118/// See the [module example](self).
119pub struct MethodRecipe {
120 inputs: Vec<CellSlot>,
121 outputs: Vec<CellSlot>,
122 make: Box<MethodFactory>,
123}
124
125impl MethodRecipe {
126 /// Creates a recipe whose local edges all belong to one owner.
127 ///
128 /// # Errors
129 ///
130 /// Returns [`TemplateError::ForeignHandle`] for mixed owners, or
131 /// [`TemplateError::InvalidDefinition`] for empty or repeated outputs.
132 ///
133 /// - Complexity: O(i + o²) time and O(i + o) space for edge counts i and o.
134 ///
135 /// # Examples
136 ///
137 /// See the [module example](self).
138 pub fn new<F>(inputs: &[CellSlot], outputs: &[CellSlot], make: F) -> Result<Self, TemplateError>
139 where
140 F: Fn(&[CellId], &[CellId]) -> anyhow::Result<Method> + 'static,
141 {
142 let Some(first) = outputs.first() else {
143 return Err(TemplateError::InvalidDefinition {
144 detail: "a method requires an output",
145 slot: None,
146 });
147 };
148 for slot in inputs.iter().chain(outputs) {
149 if !Rc::ptr_eq(&first.owner, &slot.owner) {
150 return Err(TemplateError::ForeignHandle { slot: slot.clone() });
151 }
152 }
153 if outputs
154 .iter()
155 .enumerate()
156 .any(|(i, slot)| outputs[..i].contains(slot))
157 {
158 return Err(TemplateError::InvalidDefinition {
159 detail: "a method repeats an output",
160 slot: Some(first.clone()),
161 });
162 }
163 Ok(Self {
164 inputs: inputs.to_vec(),
165 outputs: outputs.to_vec(),
166 make: Box::new(make),
167 })
168 }
169}
170
171/// Adds a freshly initialized private cell through the ordinary sheet mutators.
172type CellFactory = dyn Fn(&mut Sheet) -> anyhow::Result<CellId>;
173
174/// Describes one typed local cell; parameters have no allocating factory.
175struct CellRecipe {
176 name: String,
177 type_id: TypeId,
178 kind: CellKind,
179 make: Option<Box<CellFactory>>,
180}
181
182/// Preserves inline declaration order independently of local handle numbering.
183enum Item {
184 Cell(usize),
185 Relationship(usize),
186 Policy(PolicyRecipe),
187 Conditional(ConditionalRecipe),
188}
189
190/// Registers one checked private-cell policy with fresh execution state.
191type PolicyFactory = dyn Fn(&mut Sheet, CellId, &[CellId]) -> Result<(), TemplateError>;
192
193/// Retains the private target and declared inputs of an ordered filter or requirement.
194struct PolicyRecipe {
195 cell: CellSlot,
196 inputs: Vec<CellSlot>,
197 is_filter: bool,
198 make: Box<PolicyFactory>,
199}
200
201/// Registers a conditional using the expanded live members of its local groups.
202type ConditionalFactory = dyn Fn(
203 &mut Sheet,
204 &[CellId],
205 &[std::ops::Range<usize>],
206 &[RelationshipId],
207) -> Result<crate::ConditionalId, TemplateError>;
208
209/// Retains declared match inputs and a type-erased native conditional constructor.
210struct ConditionalRecipe {
211 inputs: Vec<CellSlot>,
212 branches: Vec<Vec<RelationshipSlot>>,
213 default: Vec<RelationshipSlot>,
214 make: Box<ConditionalFactory>,
215}
216
217/// Owns one relationship or a compact child-DAG edge with local formal bindings.
218enum RelationshipRecipe {
219 Methods(Vec<MethodRecipe>),
220 Out(MethodRecipe),
221 Include {
222 child: Rc<SheetTemplate>,
223 bindings: HashMap<usize, CellSlot>,
224 },
225}
226
227/// Owns an immutable ordered graph recipe, independent of any live sheet.
228///
229/// Parameters alias bindings; private cells and methods are fresh per instance.
230/// Destruction releases last-owned inclusion edges iteratively; shared children
231/// and their factories remain alive until their last strong owner releases them.
232///
233/// # Examples
234/// See the [module example](self).
235pub struct SheetTemplate {
236 owner: Rc<()>,
237 cells: Vec<CellRecipe>,
238 relationships: Vec<RelationshipRecipe>,
239 items: Vec<Item>,
240 /// Summarizes local outputs without enumerating transitive descendants.
241 written_cells: HashSet<usize>,
242 /// Caches the transitive relationship-only classification.
243 relationship_only: bool,
244 /// Memoizes checked expanded storage/work, with `None` denoting overflow.
245 expanded_size: Option<usize>,
246 /// Bounds the explicit traversal stack without traversing descendants.
247 depth: Option<usize>,
248}
249
250impl Drop for SheetTemplate {
251 /// Releases uniquely owned inclusion descendants without recursive destruction.
252 ///
253 /// Shared children retain their recipes unchanged. Detaching a uniquely owned
254 /// child's edges before dropping it bounds destructor call depth independently
255 /// of inclusion nesting.
256 ///
257 /// - Complexity: O(n) time for released recipe storage n, excluding captured-value
258 /// destructors; O(w) additional space for the maximum pending relationship edges w.
259 fn drop(&mut self) {
260 let mut pending = std::mem::take(&mut self.relationships);
261 while let Some(relationship) = pending.pop() {
262 if let RelationshipRecipe::Include { child, .. } = relationship
263 && let Ok(mut child) = Rc::try_unwrap(child)
264 {
265 pending.append(&mut child.relationships);
266 }
267 }
268 }
269}
270
271impl SheetTemplate {
272 /// Borrows formal names in declaration order, excluding private cells.
273 ///
274 /// - Complexity: O(c) traversal for c local declarations.
275 ///
276 /// # Examples
277 /// ```
278 /// let mut builder = adam_rs::TemplateBuilder::new();
279 /// builder.parameter::<i32>("value")?;
280 /// assert_eq!(builder.finish()?.parameter_names().collect::<Vec<_>>(), ["value"]);
281 /// # Ok::<(), adam_rs::TemplateError>(())
282 /// ```
283 pub fn parameter_names(&self) -> impl Iterator<Item = &str> {
284 self.cells
285 .iter()
286 .filter(|cell| cell.make.is_none())
287 .map(|cell| cell.name.as_str())
288 }
289
290 /// Returns this recipe's immutable identity without retaining its factories or children.
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// let template = adam_rs::TemplateBuilder::new().finish()?;
296 /// assert_eq!(template.id(), template.id());
297 /// # Ok::<(), adam_rs::TemplateError>(())
298 /// ```
299 pub fn id(&self) -> TemplateId {
300 TemplateId(self.owner.clone())
301 }
302}
303
304/// Checks ordinary relationship edge structure without constructing methods or a live sheet.
305///
306/// Every method must have distinct, nonempty outputs and reference the same union of
307/// input/output cells. Output sets of different methods cannot be equal or nested.
308/// Inputs may overlap outputs. This check neither specializes sources nor plans a graph.
309///
310/// # Errors
311/// Returns the violated structural rule.
312/// - Complexity: O(m²e) time and O(me) space for m methods of at most e edges.
313///
314/// # Examples
315/// ```
316/// use adam_rs::template::check_relationship_edges;
317/// assert!(check_relationship_edges(&[(&[0usize][..], &[1usize][..]),
318/// (&[1usize][..], &[0usize][..])]).is_ok());
319/// ```
320pub fn check_relationship_edges<C: Eq + std::hash::Hash>(
321 methods: &[(&[C], &[C])],
322) -> Result<(), &'static str> {
323 if methods.is_empty() {
324 return Err("empty relationship");
325 }
326 let mut cells = Vec::with_capacity(methods.len());
327 let mut outputs = Vec::with_capacity(methods.len());
328 for (input, output) in methods {
329 let output_set: HashSet<_> = output.iter().collect();
330 if output.is_empty() || output_set.len() != output.len() {
331 return Err("a method requires distinct nonempty outputs");
332 }
333 let cell_set: HashSet<_> = input.iter().chain(output.iter()).collect();
334 if cells.first().is_some_and(|first| first != &cell_set) {
335 return Err("relationship methods reference different cell sets");
336 }
337 if outputs.iter().any(|previous: &HashSet<&C>| {
338 previous.is_subset(&output_set) || output_set.is_subset(previous)
339 }) {
340 return Err("relationship output sets are equal or nested");
341 }
342 cells.push(cell_set);
343 outputs.push(output_set);
344 }
345 Ok(())
346}
347
348/// Returns whether a complete method survives fixed-source specialization.
349///
350/// A method survives only when none of its outputs is fixed; partial methods
351/// are never retained.
352/// - Complexity: O(o) source queries for o outputs, excluding query costs.
353///
354/// # Examples
355/// ```
356/// assert!(!adam_rs::template::method_survives_sources(&[0, 1], |id| *id == 1));
357/// ```
358pub fn method_survives_sources<C>(outputs: &[C], is_source: impl Fn(&C) -> bool) -> bool {
359 !outputs.iter().any(is_source)
360}
361
362impl SheetTemplate {
363 /// Returns whether expansion contains only relationships and parameter declarations.
364 ///
365 /// Private cells, policies, outputs and conditionals disqualify a recipe transitively.
366 /// An empty recipe qualifies, independently of source specialization.
367 ///
368 /// # Examples
369 ///
370 /// ```
371 /// # use adam_rs::TemplateBuilder;
372 /// assert!(TemplateBuilder::new().finish()?.is_relationship_only());
373 /// # Ok::<(), adam_rs::TemplateError>(())
374 /// ```
375 pub fn is_relationship_only(&self) -> bool {
376 self.relationship_only
377 }
378}
379
380/// Returns one owner-checked relationship-group handle in the including namespace.
381///
382/// The group represents the entire compact include, including transitive children.
383/// It contains no live handles and does not enumerate its members before expansion.
384///
385/// # Examples
386/// See [`TemplateBuilder::include`].
387pub struct TemplateInclusion {
388 relationships: Vec<RelationshipSlot>,
389}
390
391impl TemplateInclusion {
392 /// Borrows the single inclusion-group handle without enumerating descendants.
393 ///
394 /// # Examples
395 ///
396 /// See [`TemplateBuilder::include`].
397 pub fn relationships(&self) -> &[RelationshipSlot] {
398 &self.relationships
399 }
400}
401
402/// Owns an opaque instance identity and its mapped live handles.
403///
404/// Dropping this object does not remove graph structure from the destination.
405/// Cells begin with root parameters/private cells in local declaration order, then
406/// included private cells in inline expansion order. Bound child formals introduce
407/// no duplicate cell entries. Relationships follow inline expansion order and
408/// remain distinct even when their recipe belongs to a group.
409/// Occurrence records retain local mappings and immutable identity tokens, not
410/// template factories or recursively owned inclusion edges.
411///
412/// # Examples
413/// See the [module example](self).
414#[derive(Debug)]
415pub struct Instance {
416 _identity: Rc<()>,
417 cells: Vec<CellId>,
418 relationships: Vec<RelationshipId>,
419 occurrences: Vec<InstanceOccurrence>,
420 local_cells: Vec<CellId>,
421 local_groups: Vec<std::ops::Range<usize>>,
422 relationship_origins: Vec<provenance::RelationshipOrigin>,
423 authored_methods: Vec<usize>,
424}
425
426impl Instance {
427 /// Borrows live relationship handles in inline declaration order.
428 ///
429 /// # Examples
430 ///
431 /// See the [module example](self).
432 pub fn relationships(&self) -> &[RelationshipId] {
433 &self.relationships
434 }
435
436 /// Borrows all mapped cells, including unchanged parameter identities.
437 ///
438 /// # Examples
439 ///
440 /// See the [module example](self).
441 pub fn cells(&self) -> &[CellId] {
442 &self.cells
443 }
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 /// Preserves slot identity through cloning and distinguishes owners and indices.
451 #[test]
452 fn local_handle_identity_laws() {
453 let mut a = TemplateBuilder::new();
454 let x = a.parameter::<i32>("x").unwrap();
455 let y = a.parameter::<i32>("y").unwrap();
456 let foreign = TemplateBuilder::new().parameter::<i32>("x").unwrap();
457 assert_eq!(x, x.clone());
458 assert_eq!(x.clone(), x);
459 assert_ne!(x, y);
460 assert_ne!(x, foreign);
461 let group = RelationshipSlot {
462 owner: x.owner.clone(),
463 index: 0,
464 };
465 assert_eq!(group, group.clone());
466 assert_ne!(
467 group,
468 RelationshipSlot {
469 owner: y.owner.clone(),
470 index: 1
471 }
472 );
473 assert_ne!(
474 group,
475 RelationshipSlot {
476 owner: foreign.owner.clone(),
477 index: 0
478 }
479 );
480 }
481
482 /// Rejects each malformed relationship boundary and accepts overlapping non-nested outputs.
483 #[test]
484 fn relationship_edges_obey_structural_contract() {
485 assert!(check_relationship_edges::<usize>(&[]).is_err());
486 assert!(check_relationship_edges(&[(&[0][..], &[][..])]).is_err());
487 assert!(check_relationship_edges(&[(&[0][..], &[1, 1][..])]).is_err());
488 assert!(check_relationship_edges(&[(&[0][..], &[1][..]), (&[1][..], &[2][..])]).is_err());
489 assert!(check_relationship_edges(&[(&[0][..], &[1][..]), (&[0][..], &[1][..])]).is_err());
490 assert!(
491 check_relationship_edges(&[(&[0, 2][..], &[1][..]), (&[0][..], &[1, 2][..])]).is_err()
492 );
493 assert!(
494 check_relationship_edges(&[(&[2][..], &[0, 1][..]), (&[0][..], &[1, 2][..])]).is_ok()
495 );
496 }
497
498 /// Retains empty-template summaries and the inclusion's single borrowed group.
499 #[test]
500 fn empty_template_and_inclusion_accessors() {
501 let child = Rc::new(TemplateBuilder::new().finish().unwrap());
502 assert_eq!(child.parameter_names().count(), 0);
503 assert!(child.is_relationship_only());
504 let mut builder = TemplateBuilder::new();
505 let inclusion = builder.include(child, &[]).unwrap();
506 assert_eq!(inclusion.relationships().len(), 1);
507 let instance = builder
508 .finish()
509 .unwrap()
510 .instantiate(&mut Sheet::new(), &[])
511 .unwrap();
512 assert!(instance.cells().is_empty());
513 assert!(instance.relationships().is_empty());
514 assert_eq!(
515 instance.relationship_group(
516 instance.occurrences()[0].id(),
517 &inclusion.relationships()[0]
518 ),
519 Some(&[][..])
520 );
521 }
522}