Skip to main content

adam_rs/template/
builder.rs

1//! Ordered recipe construction and local inclusion remapping.
2
3use std::any::{Any, TypeId};
4use std::collections::{HashMap, HashSet};
5use std::rc::Rc;
6
7use super::{
8    CellFactory, CellRecipe, CellSlot, ConditionalRecipe, Item, MethodRecipe, PolicyRecipe,
9    RelationshipRecipe, RelationshipSlot, SheetTemplate, TemplateError, TemplateInclusion,
10};
11use crate::conditional::MatchSource;
12use crate::{CellId, CellKind, Filter, MatchExpr, Requirement, Sheet};
13
14/// Owns declarations and validates all local references before accepting them.
15///
16/// Private included names do not enter this builder's declaration namespace.
17///
18/// # Examples
19/// See the [module example](super).
20pub struct TemplateBuilder {
21    recipe: SheetTemplate,
22    names: HashSet<String>,
23    /// Tracks local groups already owned by a conditional.
24    conditional_groups: HashSet<usize>,
25    /// Tracks private cells already assigned a filter.
26    filtered: HashSet<usize>,
27}
28
29impl Default for TemplateBuilder {
30    /// Creates an empty builder with a fresh local owner.
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl TemplateBuilder {
37    /// Creates an empty recipe with its own local handle namespace.
38    ///
39    /// # Examples
40    ///
41    /// ```
42    /// # use adam_rs::TemplateBuilder;
43    /// let template = TemplateBuilder::new().finish()?;
44    /// assert!(template.is_relationship_only());
45    /// # Ok::<(), adam_rs::TemplateError>(())
46    /// ```
47    pub fn new() -> Self {
48        Self {
49            recipe: SheetTemplate {
50                owner: Rc::new(()),
51                cells: Vec::new(),
52                relationships: Vec::new(),
53                items: Vec::new(),
54                written_cells: HashSet::new(),
55                relationship_only: true,
56                expanded_size: Some(0),
57                depth: Some(1),
58            },
59            names: HashSet::new(),
60            conditional_groups: HashSet::new(),
61            filtered: HashSet::new(),
62        }
63    }
64
65    /// Declares a typed formal that allocates and writes no destination cell.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`TemplateError::DuplicateParameter`] for a repeated declaration
70    /// name, or [`TemplateError::Capacity`] when storage cannot be reserved.
71    ///
72    /// - Complexity: Amortized O(n) time and space for a name of length n.
73    ///
74    /// # Examples
75    ///
76    /// See the [module example](super).
77    pub fn parameter<T: 'static>(&mut self, name: &str) -> Result<CellSlot, TemplateError> {
78        self.add_cell_recipe(name, TypeId::of::<T>(), CellKind::Cell, None)
79    }
80
81    /// Declares a private cell initialized afresh for every live instance.
82    ///
83    /// The initializer owns its captures and runs only during instantiation.
84    ///
85    /// # Errors
86    ///
87    /// Returns [`TemplateError::DuplicateParameter`] for a repeated declaration
88    /// name, or [`TemplateError::Capacity`] when storage cannot be reserved.
89    ///
90    /// - Complexity: Amortized O(n) time and space for a name of length n.
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// # use adam_rs::{Sheet, TemplateBuilder};
96    /// let mut builder = TemplateBuilder::new();
97    /// builder.cell("count", || Ok(3i32))?;
98    /// let mut sheet = Sheet::new();
99    /// let instance = builder.finish()?.instantiate(&mut sheet, &[])?;
100    /// assert_eq!(*sheet.read::<i32>(instance.cells()[0])?, 3);
101    /// # Ok::<(), Box<dyn std::error::Error>>(())
102    /// ```
103    pub fn cell<T, F>(&mut self, name: &str, initial: F) -> Result<CellSlot, TemplateError>
104    where
105        T: Any + PartialEq + 'static,
106        F: Fn() -> anyhow::Result<T> + 'static,
107    {
108        self.add_cell_recipe(
109            name,
110            TypeId::of::<T>(),
111            CellKind::Cell,
112            Some(Box::new(move |sheet: &mut Sheet| {
113                Ok(sheet.add_cell(initial()?))
114            })),
115        )
116    }
117
118    /// Declares a private source initialized afresh for every live instance.
119    ///
120    /// Specialization removes every whole method that writes a source.
121    ///
122    /// # Errors
123    ///
124    /// Returns [`TemplateError::DuplicateParameter`] for a repeated declaration
125    /// name, or [`TemplateError::Capacity`] when storage cannot be reserved.
126    ///
127    /// - Complexity: Amortized O(n) time and space for a name of length n.
128    ///
129    /// # Examples
130    ///
131    /// ```
132    /// # use adam_rs::{CellKind, Sheet, TemplateBuilder};
133    /// let mut builder = TemplateBuilder::new();
134    /// builder.source("constant", || Ok(7i32))?;
135    /// let mut sheet = Sheet::new();
136    /// let instance = builder.finish()?.instantiate(&mut sheet, &[])?;
137    /// assert_eq!(sheet.cell_kind(instance.cells()[0]), Some(CellKind::Source));
138    /// # Ok::<(), adam_rs::TemplateError>(())
139    /// ```
140    pub fn source<T, F>(&mut self, name: &str, initial: F) -> Result<CellSlot, TemplateError>
141    where
142        T: Any + PartialEq + 'static,
143        F: Fn() -> anyhow::Result<T> + 'static,
144    {
145        self.add_cell_recipe(
146            name,
147            TypeId::of::<T>(),
148            CellKind::Source,
149            Some(Box::new(move |sheet: &mut Sheet| {
150                Ok(sheet.add_source(initial()?))
151            })),
152        )
153    }
154
155    /// Appends a checked local cell declaration and its ordered body item.
156    ///
157    /// - Complexity: Amortized O(n) time and space for a name of length n.
158    fn add_cell_recipe(
159        &mut self,
160        name: &str,
161        type_id: TypeId,
162        kind: CellKind,
163        make: Option<Box<CellFactory>>,
164    ) -> Result<CellSlot, TemplateError> {
165        if self.names.contains(name) {
166            return Err(TemplateError::DuplicateParameter { name: name.into() });
167        }
168        self.recipe
169            .cells
170            .try_reserve(1)
171            .map_err(|_| TemplateError::Capacity)?;
172        self.recipe
173            .items
174            .try_reserve(1)
175            .map_err(|_| TemplateError::Capacity)?;
176        let index = self.recipe.cells.len();
177        self.names.insert(name.into());
178        self.recipe.relationship_only &= make.is_none();
179        self.recipe.cells.push(CellRecipe {
180            name: name.into(),
181            type_id,
182            kind,
183            make,
184        });
185        self.recipe.items.push(Item::Cell(index));
186        Ok(CellSlot {
187            owner: self.recipe.owner.clone(),
188            index,
189        })
190    }
191
192    /// Appends a relationship after validating owners and native edge-set rules.
193    ///
194    /// Methods must reference the same cell set and have distinct, non-nested
195    /// output sets. Source-writing methods remain authored until specialization.
196    ///
197    /// # Errors
198    ///
199    /// Returns [`TemplateError::EmptyRelationship`], [`TemplateError::ForeignHandle`],
200    /// [`TemplateError::InvalidDefinition`], or [`TemplateError::Capacity`].
201    ///
202    /// - Complexity: O(m² × e) time and O(m × e) space for m methods of at most e edges.
203    ///
204    /// # Examples
205    ///
206    /// See the [module example](super).
207    pub fn relationship(
208        &mut self,
209        methods: Vec<MethodRecipe>,
210    ) -> Result<RelationshipSlot, TemplateError> {
211        self.validate_relationship(&methods)?;
212        self.recipe
213            .relationships
214            .try_reserve(1)
215            .map_err(|_| TemplateError::Capacity)?;
216        self.recipe
217            .items
218            .try_reserve(1)
219            .map_err(|_| TemplateError::Capacity)?;
220        let index = self.recipe.relationships.len();
221        self.recipe
222            .written_cells
223            .extend(methods.iter().flat_map(|m| &m.outputs).map(|s| s.index));
224        self.recipe
225            .relationships
226            .push(RelationshipRecipe::Methods(methods));
227        self.recipe.items.push(Item::Relationship(index));
228        Ok(RelationshipSlot {
229            owner: self.recipe.owner.clone(),
230            index,
231        })
232    }
233
234    /// Checks ownership and native relationship invariants without running factories.
235    ///
236    /// - Complexity: O(m² × e) time and O(m × e) space for m methods of at most e edges.
237    fn validate_relationship(&self, methods: &[MethodRecipe]) -> Result<(), TemplateError> {
238        if methods.is_empty() {
239            return Err(TemplateError::EmptyRelationship);
240        }
241        for slot in methods
242            .iter()
243            .flat_map(|m| m.inputs.iter().chain(&m.outputs))
244        {
245            self.check_slot(slot)?;
246        }
247        if let Some(slot) = methods
248            .iter()
249            .flat_map(|m| &m.outputs)
250            .find(|s| self.recipe.cells[s.index].kind == CellKind::Out)
251        {
252            return Err(TemplateError::InvalidDefinition {
253                detail: "an out cell already has its sole writer",
254                slot: Some(slot.clone()),
255            });
256        }
257        let edges: Vec<_> = methods
258            .iter()
259            .map(|method| (method.inputs.as_slice(), method.outputs.as_slice()))
260            .collect();
261        super::check_relationship_edges(&edges).map_err(|detail| TemplateError::InvalidDefinition {
262            detail,
263            slot: Some(methods[0].outputs[0].clone()),
264        })
265    }
266
267    /// Rejects a local reference not owned by this recipe.
268    fn check_slot(&self, slot: &CellSlot) -> Result<(), TemplateError> {
269        if !Rc::ptr_eq(&self.recipe.owner, &slot.owner) || slot.index >= self.recipe.cells.len() {
270            return Err(TemplateError::ForeignHandle { slot: slot.clone() });
271        }
272        Ok(())
273    }
274
275    /// Promotes a private ordinary cell through its sole, single-output writer.
276    ///
277    /// Formal parameters cannot become outputs. Requirements attach separately,
278    /// in declaration order, through [`Self::require`].
279    ///
280    /// # Errors
281    ///
282    /// Returns [`TemplateError::InvalidDefinition`] for a non-private, non-ordinary,
283    /// multiply-written, or non-single output; also returns relationship validation errors.
284    ///
285    /// - Complexity: O(i + r) time and O(i) space for inputs i and prior output summaries r.
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// # use adam_rs::{TemplateBuilder, MethodRecipe, Method};
291    /// let mut b = TemplateBuilder::new();
292    /// let input = b.parameter::<i32>("input")?;
293    /// let output = b.cell("output", || Ok(0i32))?;
294    /// b.out(MethodRecipe::new(&[input], &[output], |i, o| {
295    ///     Ok(Method::from_fn_1_1(i[0], o[0], |x: &i32| Ok(*x)))
296    /// })?)?;
297    /// # Ok::<(), adam_rs::TemplateError>(())
298    /// ```
299    pub fn out(&mut self, writer: MethodRecipe) -> Result<RelationshipSlot, TemplateError> {
300        self.validate_relationship(std::slice::from_ref(&writer))?;
301        let output = &writer.outputs[0];
302        self.check_private(output)?;
303        if writer.outputs.len() != 1
304            || self.recipe.cells[output.index].kind != CellKind::Cell
305            || self.recipe.written_cells.contains(&output.index)
306        {
307            return Err(TemplateError::InvalidDefinition {
308                detail: "out requires one private ordinary cell with no prior writer",
309                slot: Some(output.clone()),
310            });
311        }
312        self.recipe
313            .relationships
314            .try_reserve(1)
315            .map_err(|_| TemplateError::Capacity)?;
316        self.recipe
317            .items
318            .try_reserve(1)
319            .map_err(|_| TemplateError::Capacity)?;
320        let index = self.recipe.relationships.len();
321        self.recipe.cells[output.index].kind = CellKind::Out;
322        self.recipe.written_cells.insert(output.index);
323        self.recipe
324            .relationships
325            .push(RelationshipRecipe::Out(writer));
326        self.recipe.items.push(Item::Relationship(index));
327        self.recipe.relationship_only = false;
328        Ok(RelationshipSlot {
329            owner: self.recipe.owner.clone(),
330            index,
331        })
332    }
333
334    /// Rejects policy targets that are not private declarations of this owner.
335    fn check_private(&self, cell: &CellSlot) -> Result<(), TemplateError> {
336        self.check_slot(cell)?;
337        if self.recipe.cells[cell.index].make.is_none() {
338            return Err(TemplateError::InvalidDefinition {
339                detail: "component policies and out writers require private targets",
340                slot: Some(cell.clone()),
341            });
342        }
343        Ok(())
344    }
345
346    /// Attaches one freshly constructed filter to a private cell.
347    ///
348    /// The factory receives the live target and positional dynamic arguments.
349    /// Its filter must declare those exact arguments and their concrete types.
350    ///
351    /// # Errors
352    ///
353    /// Returns ownership, capacity, or [`TemplateError::InvalidDefinition`] errors
354    /// for a formal target, duplicate filter, or self-dependent filter.
355    ///
356    /// - Complexity: O(i) time and space for i inputs.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// # use adam_rs::{TemplateBuilder, Filter};
362    /// let mut b = TemplateBuilder::new();
363    /// let x = b.cell("x", || Ok(0i32))?;
364    /// b.filter(&x, &[], |_, _| Ok(Filter::from_fn_0(|x: &i32| Ok((*x).max(0)))))?;
365    /// # Ok::<(), adam_rs::TemplateError>(())
366    /// ```
367    pub fn filter<F>(
368        &mut self,
369        cell: &CellSlot,
370        inputs: &[CellSlot],
371        make: F,
372    ) -> Result<(), TemplateError>
373    where
374        F: Fn(CellId, &[CellId]) -> anyhow::Result<Filter> + 'static,
375    {
376        self.check_private(cell)?;
377        if self.filtered.contains(&cell.index) || inputs.contains(cell) {
378            return Err(TemplateError::InvalidDefinition {
379                detail: "duplicate or self-dependent filter",
380                slot: Some(cell.clone()),
381            });
382        }
383        let slot = cell.clone();
384        self.add_policy(
385            cell,
386            inputs,
387            true,
388            Box::new(move |sheet, target, ids| {
389                let filter = make(target, ids).map_err(|source| TemplateError::Factory {
390                    source,
391                    slot: slot.clone(),
392                })?;
393                if filter.0.args != ids
394                    || filter.0.value_type != sheet.cell_type_id(target).unwrap()
395                    || !super::instantiate::signature_matches(sheet, ids, &filter.0.arg_types)
396                {
397                    return Err(TemplateError::InvalidDefinition {
398                        detail: "filter factory signature differs from its recipe",
399                        slot: Some(slot.clone()),
400                    });
401                }
402                sheet
403                    .add_filter(target, filter)
404                    .map_err(TemplateError::Runtime)
405            }),
406        )?;
407        self.filtered.insert(cell.index);
408        Ok(())
409    }
410
411    /// Attaches a freshly constructed requirement to a private cell.
412    ///
413    /// The factory must declare exactly the supplied positional inputs and types.
414    /// Native attachment evaluates ordinary/source requirements immediately;
415    /// output requirements wait until propagation.
416    ///
417    /// # Errors
418    ///
419    /// Returns ownership, capacity, or [`TemplateError::InvalidDefinition`] errors
420    /// for a formal target. Factory and native errors occur during instantiation.
421    ///
422    /// - Complexity: O(i) time and space for i inputs.
423    ///
424    /// # Examples
425    ///
426    /// ```
427    /// # use adam_rs::{TemplateBuilder, Requirement};
428    /// let mut b = TemplateBuilder::new();
429    /// let x = b.cell("x", || Ok(1i32))?;
430    /// b.require(&x, &[x.clone()], |i| Ok(Requirement::from_fn_1(i[0], |x: &i32| Ok(*x > 0))))?;
431    /// # Ok::<(), adam_rs::TemplateError>(())
432    /// ```
433    pub fn require<F>(
434        &mut self,
435        cell: &CellSlot,
436        inputs: &[CellSlot],
437        make: F,
438    ) -> Result<(), TemplateError>
439    where
440        F: Fn(&[CellId]) -> anyhow::Result<Requirement> + 'static,
441    {
442        let slot = cell.clone();
443        self.add_policy(
444            cell,
445            inputs,
446            false,
447            Box::new(move |sheet, target, ids| {
448                let requirement = make(ids).map_err(|source| TemplateError::Factory {
449                    source,
450                    slot: slot.clone(),
451                })?;
452                if requirement.inputs != ids
453                    || !super::instantiate::signature_matches(sheet, ids, &requirement.input_types)
454                {
455                    return Err(TemplateError::InvalidDefinition {
456                        detail: "requirement factory signature differs from its recipe",
457                        slot: Some(slot.clone()),
458                    });
459                }
460                sheet
461                    .add_requirement(target, requirement)
462                    .map(|_| ())
463                    .map_err(TemplateError::Runtime)
464            }),
465        )
466    }
467
468    /// Appends a private policy after validating all local input owners.
469    ///
470    /// - Complexity: O(i) time and space for i inputs.
471    fn add_policy(
472        &mut self,
473        cell: &CellSlot,
474        inputs: &[CellSlot],
475        is_filter: bool,
476        make: Box<super::PolicyFactory>,
477    ) -> Result<(), TemplateError> {
478        self.check_private(cell)?;
479        for input in inputs {
480            self.check_slot(input)?;
481        }
482        self.recipe
483            .items
484            .try_reserve(1)
485            .map_err(|_| TemplateError::Capacity)?;
486        self.recipe.items.push(Item::Policy(PolicyRecipe {
487            cell: cell.clone(),
488            inputs: inputs.to_vec(),
489            is_filter,
490            make,
491        }));
492        self.recipe.relationship_only = false;
493        Ok(())
494    }
495
496    /// Registers native conditional branches over direct relationships or included groups.
497    ///
498    /// Included groups must be transitively relationship-only before specialization.
499    /// Each constituent remains a distinct native relationship; no extra activation
500    /// layer is introduced. Keys follow native first-match semantics.
501    ///
502    /// # Errors
503    ///
504    /// Returns [`TemplateError::ConditionalComponent`] for stateful groups, or
505    /// [`TemplateError::InvalidDefinition`] for foreign, reused, or duplicate groups
506    /// or empty branch keys. Input ownership and capacity errors are also reported.
507    ///
508    /// - Complexity: O(i + g + k) time and space for inputs i, groups g, and keys k.
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// # use adam_rs::{TemplateBuilder, MatchExpr};
514    /// let mut b = TemplateBuilder::new();
515    /// let guard = b.parameter::<bool>("guard")?;
516    /// b.conditional(&[guard], |i| Ok(MatchExpr::cell(i[0])), vec![(vec![true], vec![])], vec![])?;
517    /// # Ok::<(), adam_rs::TemplateError>(())
518    /// ```
519    pub fn conditional<T, F>(
520        &mut self,
521        inputs: &[CellSlot],
522        make: F,
523        branches: Vec<(Vec<T>, Vec<RelationshipSlot>)>,
524        default: Vec<RelationshipSlot>,
525    ) -> Result<(), TemplateError>
526    where
527        T: Clone + Any + PartialEq + 'static,
528        F: Fn(&[CellId]) -> anyhow::Result<MatchExpr> + 'static,
529    {
530        let (keys, groups): (Vec<_>, Vec<_>) = branches.into_iter().unzip();
531        if keys.iter().any(Vec::is_empty) {
532            return Err(TemplateError::InvalidDefinition {
533                detail: "conditional branch requires keys",
534                slot: None,
535            });
536        }
537        self.conditional_factory(inputs, make, move || Ok(keys.clone()), groups, default)
538    }
539
540    /// Registers conditional groups with fresh keys constructed once per instance.
541    ///
542    /// Neither factory executes during preparation. Group ownership, uniqueness and
543    /// relationship-only eligibility are checked before mutation. Keys follow native
544    /// first-match semantics and must have one nonempty vector per declared branch.
545    ///
546    /// # Errors
547    /// Reports invalid inputs/groups before mutation; reports failed factories, invalid
548    /// key counts, empty keys or native conditional errors during construction.
549    /// - Complexity: O(i + b + g) preparation for inputs i, branches b and groups g;
550    ///   construction adds factory costs and O(i + b + k + g + r) for keys k and
551    ///   expanded relationship members r.
552    ///
553    /// # Examples
554    /// ```
555    /// let mut b = adam_rs::TemplateBuilder::new();
556    /// let flag = b.parameter::<bool>("flag")?;
557    /// b.conditional_factory::<bool, _, _>(&[flag],
558    ///     |ids| Ok(adam_rs::MatchExpr::cell(ids[0])),
559    ///     || Ok(vec![vec![true]]), vec![vec![]], vec![])?;
560    /// # Ok::<(), adam_rs::TemplateError>(())
561    /// ```
562    pub fn conditional_factory<T, F, K>(
563        &mut self,
564        inputs: &[CellSlot],
565        make: F,
566        keys: K,
567        branches: Vec<Vec<RelationshipSlot>>,
568        default: Vec<RelationshipSlot>,
569    ) -> Result<(), TemplateError>
570    where
571        T: Any + PartialEq + 'static,
572        F: Fn(&[CellId]) -> anyhow::Result<MatchExpr> + 'static,
573        K: Fn() -> anyhow::Result<Vec<Vec<T>>> + 'static,
574    {
575        for input in inputs {
576            self.check_slot(input)?;
577        }
578        let mut seen = HashSet::new();
579        for group in branches.iter().flatten().chain(&default) {
580            if !Rc::ptr_eq(&self.recipe.owner, &group.owner)
581                || group.index >= self.recipe.relationships.len()
582                || self.conditional_groups.contains(&group.index)
583                || !seen.insert(group.index)
584            {
585                return Err(TemplateError::InvalidDefinition {
586                    detail: "foreign or already conditional relationship group",
587                    slot: None,
588                });
589            }
590            let eligible = match &self.recipe.relationships[group.index] {
591                RelationshipRecipe::Methods(_) => true,
592                RelationshipRecipe::Out(_) => false,
593                RelationshipRecipe::Include { child, .. } => child.relationship_only,
594            };
595            if !eligible {
596                return Err(TemplateError::ConditionalComponent);
597            }
598        }
599        self.recipe
600            .items
601            .try_reserve(1)
602            .map_err(|_| TemplateError::Capacity)?;
603        self.recipe.items.push(Item::Conditional(ConditionalRecipe {
604            inputs: inputs.to_vec(),
605            branches: branches.clone(),
606            default: default.clone(),
607            make: Box::new(move |sheet, ids, groups, relationships| {
608                let source =
609                    make(ids).map_err(|source| TemplateError::ConditionalFactory { source })?;
610                let valid = match &source.0 {
611                    MatchSource::Cell(id) => {
612                        ids == [*id] && sheet.cell_type_id(*id) == Some(TypeId::of::<T>())
613                    }
614                    MatchSource::Expr(expr) => {
615                        expr.inputs == ids
616                            && expr.output_type == TypeId::of::<T>()
617                            && super::instantiate::signature_matches(sheet, ids, &expr.input_types)
618                    }
619                };
620                if !valid {
621                    return Err(TemplateError::InvalidDefinition {
622                        detail: "conditional factory signature differs from its recipe",
623                        slot: None,
624                    });
625                }
626                let mut live_branches = Vec::new();
627                live_branches
628                    .try_reserve(branches.len())
629                    .map_err(|_| TemplateError::Capacity)?;
630                let keys = keys().map_err(|source| TemplateError::ConditionalFactory { source })?;
631                if keys.len() != branches.len() || keys.iter().any(Vec::is_empty) {
632                    return Err(TemplateError::InvalidDefinition {
633                        detail: "conditional key factory differs from its branches",
634                        slot: None,
635                    });
636                }
637                for (live_keys, slots) in keys.into_iter().zip(&branches) {
638                    live_branches.push((
639                        live_keys,
640                        super::instantiate::group_members(slots, groups, relationships)?,
641                    ));
642                }
643                let live_default =
644                    super::instantiate::group_members(&default, groups, relationships)?;
645                sheet
646                    .add_conditional(source, live_branches, live_default)
647                    .map_err(TemplateError::Runtime)
648            }),
649        }));
650        self.conditional_groups.extend(seen);
651        self.recipe.relationship_only = false;
652        Ok(())
653    }
654
655    /// Appends a compact child-DAG edge with checked named bindings.
656    ///
657    /// Binding and structural failures leave the builder unchanged. Immutable
658    /// factories are shared, but every live instantiation creates fresh native methods.
659    /// The returned single group slot represents all transitive relationships;
660    /// only instantiation enumerates its distinct live members in inline order.
661    ///
662    /// # Errors
663    ///
664    /// Returns binding errors for unknown, missing, duplicate, aliased, foreign,
665    /// or wrongly typed arguments; returns [`TemplateError::InvalidDefinition`]
666    /// for a private out argument, or [`TemplateError::Capacity`] on reservation failure.
667    ///
668    /// - Complexity: Expected O(c + b) time and space for the child's own local
669    ///   cells c and bindings b, independent of transitive expansion size.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// # use std::rc::Rc;
675    /// # use adam_rs::TemplateBuilder;
676    /// let child = Rc::new(TemplateBuilder::new().finish()?);
677    /// let mut parent = TemplateBuilder::new();
678    /// let included = parent.include(child, &[])?;
679    /// assert_eq!(included.relationships().len(), 1);
680    /// # Ok::<(), adam_rs::TemplateError>(())
681    /// ```
682    pub fn include(
683        &mut self,
684        child: Rc<SheetTemplate>,
685        bindings: &[(&str, CellSlot)],
686    ) -> Result<TemplateInclusion, TemplateError> {
687        let bound = child.bind(bindings, |_, slot| {
688            self.check_slot(slot)?;
689            Ok(self.recipe.cells[slot.index].type_id)
690        })?;
691        if let Some(slot) = bound
692            .values()
693            .find(|s| self.recipe.cells[s.index].kind == CellKind::Out)
694        {
695            return Err(TemplateError::InvalidDefinition {
696                detail: "an included parameter cannot bind an out cell",
697                slot: Some(slot.clone()),
698            });
699        }
700        self.recipe
701            .relationships
702            .try_reserve(1)
703            .map_err(|_| TemplateError::Capacity)?;
704        self.recipe
705            .items
706            .try_reserve(1)
707            .map_err(|_| TemplateError::Capacity)?;
708        let index = self.recipe.relationships.len();
709        let handles = vec![RelationshipSlot {
710            owner: self.recipe.owner.clone(),
711            index,
712        }];
713        self.recipe.written_cells.extend(
714            child
715                .written_cells
716                .iter()
717                .filter_map(|i| bound.get(i))
718                .map(|s| s.index),
719        );
720        self.recipe.relationship_only &= child.relationship_only;
721        self.recipe.relationships.push(RelationshipRecipe::Include {
722            child,
723            bindings: bound,
724        });
725        self.recipe.items.push(Item::Relationship(index));
726        Ok(TemplateInclusion {
727            relationships: handles,
728        })
729    }
730
731    /// Finalizes the owning immutable recipe without invoking any factory.
732    ///
733    /// # Errors
734    ///
735    /// Rejects included parameters that became private outputs after inclusion.
736    /// Expanded-size overflow is retained for diagnosis before live expansion.
737    ///
738    /// - Complexity: O(n + e) time for local declarations n and edges e; no DAG expansion.
739    ///
740    /// # Examples
741    ///
742    /// See the [module example](super).
743    pub fn finish(mut self) -> Result<SheetTemplate, TemplateError> {
744        let mut size = self
745            .recipe
746            .cells
747            .len()
748            .checked_add(self.recipe.items.len())
749            .and_then(|n| n.checked_add(self.recipe.relationships.len()))
750            // Every occurrence needs a record, even when its recipe is empty.
751            .and_then(|n| n.checked_add(1));
752        let mut depth = Some(1usize);
753        for relationship in &self.recipe.relationships {
754            match relationship {
755                RelationshipRecipe::Include { child, bindings } => {
756                    if let Some(slot) = bindings
757                        .values()
758                        .find(|s| self.recipe.cells[s.index].kind == CellKind::Out)
759                    {
760                        return Err(TemplateError::InvalidDefinition {
761                            detail: "an included parameter cannot bind an out cell",
762                            slot: Some(slot.clone()),
763                        });
764                    }
765                    size = size.and_then(|n| child.expanded_size.and_then(|c| n.checked_add(c)));
766                    depth = depth
767                        .and_then(|d| child.depth.and_then(|c| c.checked_add(1)).map(|c| d.max(c)));
768                }
769                RelationshipRecipe::Methods(methods) => {
770                    for method in methods {
771                        size = size
772                            .and_then(|n| n.checked_add(method.inputs.len()))
773                            .and_then(|n| n.checked_add(method.outputs.len()))
774                            .and_then(|n| n.checked_add(1));
775                    }
776                }
777                RelationshipRecipe::Out(method) => {
778                    size = size
779                        .and_then(|n| n.checked_add(method.inputs.len()))
780                        .and_then(|n| n.checked_add(method.outputs.len()));
781                }
782            }
783        }
784        self.recipe.expanded_size = size;
785        self.recipe.depth = depth;
786        Ok(self.recipe)
787    }
788}
789
790impl SheetTemplate {
791    /// Builds a local-index binding map after checking names, aliases, and concrete types.
792    ///
793    /// - Complexity: Expected O(c + b) time and O(c + b) space for cells c and bindings b.
794    pub(super) fn bind<A, F>(
795        &self,
796        bindings: &[(&str, A)],
797        type_of: F,
798    ) -> Result<HashMap<usize, A>, TemplateError>
799    where
800        A: Clone + Eq + std::hash::Hash,
801        F: Fn(&str, &A) -> Result<TypeId, TemplateError>,
802    {
803        let parameters: HashMap<&str, usize> = self
804            .cells
805            .iter()
806            .enumerate()
807            .filter(|(_, c)| c.make.is_none())
808            .map(|(i, c)| (c.name.as_str(), i))
809            .collect();
810        let mut result = HashMap::with_capacity(bindings.len());
811        let mut actuals = HashMap::with_capacity(bindings.len());
812        for (name, actual) in bindings {
813            let &index = parameters
814                .get(name)
815                .ok_or_else(|| TemplateError::UnknownParameter {
816                    name: (*name).into(),
817                })?;
818            if result.contains_key(&index) {
819                return Err(TemplateError::DuplicateParameter {
820                    name: (*name).into(),
821                });
822            }
823            if let Some(first) = actuals.insert(actual.clone(), *name) {
824                return Err(TemplateError::AliasedArgument {
825                    first: first.into(),
826                    second: (*name).into(),
827                });
828            }
829            let found = type_of(name, actual)?;
830            let expected = self.cells[index].type_id;
831            if expected != found {
832                return Err(TemplateError::TypeMismatch {
833                    name: (*name).into(),
834                    expected,
835                    found,
836                });
837            }
838            result.insert(index, actual.clone());
839        }
840        for (index, cell) in self
841            .cells
842            .iter()
843            .enumerate()
844            .filter(|(_, c)| c.make.is_none())
845        {
846            if !result.contains_key(&index) {
847                return Err(TemplateError::MissingParameter {
848                    name: cell.name.clone(),
849                });
850            }
851        }
852        Ok(result)
853    }
854}
855
856impl std::hash::Hash for CellSlot {
857    /// Hashes the immutable owner identity and local index consistently with equality.
858    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
859        std::hash::Hash::hash(&Rc::as_ptr(&self.owner), state);
860        std::hash::Hash::hash(&self.index, state);
861    }
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    /// Starts fresh namespaces and keeps the builder usable after a rejected declaration.
869    #[test]
870    fn defaults_and_rejected_declarations_preserve_builder_contract() {
871        let mut builder = TemplateBuilder::default();
872        let slot = builder.parameter::<i32>("input").unwrap();
873        assert!(matches!(
874            builder.parameter::<bool>("input"),
875            Err(TemplateError::DuplicateParameter { .. })
876        ));
877        let foreign = TemplateBuilder::new().parameter::<i32>("input").unwrap();
878        assert_ne!(slot, foreign);
879        assert_eq!(HashSet::from([slot.clone(), slot, foreign]).len(), 2);
880        builder.cell("private", || Ok(9_i32)).unwrap();
881        let template = builder.finish().unwrap();
882        assert_eq!(template.parameter_names().collect::<Vec<_>>(), ["input"]);
883        assert!(!template.is_relationship_only());
884        let mut sheet = Sheet::new();
885        let actual = sheet.add_cell(3_i32);
886        let instance = template
887            .instantiate(&mut sheet, &[("input", actual)])
888            .unwrap();
889        assert_eq!(instance.cells().len(), 2);
890        assert_eq!(*sheet.read::<i32>(instance.cells()[1]).unwrap(), 9);
891        assert!(
892            TemplateBuilder::default()
893                .finish()
894                .unwrap()
895                .is_relationship_only()
896        );
897    }
898}