1use 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
14pub struct TemplateBuilder {
21 recipe: SheetTemplate,
22 names: HashSet<String>,
23 conditional_groups: HashSet<usize>,
25 filtered: HashSet<usize>,
27}
28
29impl Default for TemplateBuilder {
30 fn default() -> Self {
32 Self::new()
33 }
34}
35
36impl TemplateBuilder {
37 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 .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 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 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 #[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}