1use std::any::TypeId;
4use std::collections::{HashMap, HashSet};
5use std::ops::Range;
6use std::rc::Rc;
7
8use super::provenance::RelationshipOrigin;
9use super::{
10 CellSlot, Instance, InstanceOccurrence, Item, MethodRecipe, OccurrenceId, RelationshipRecipe,
11 RelationshipSlot, SheetTemplate, TemplateError,
12};
13use crate::{CellId, CellKind, Method, RelationshipId, Sheet};
14
15#[cfg(test)]
16thread_local! {
17 static SOURCE_PREFLIGHT_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19}
20
21fn storage<T: Clone>(count: usize, value: T) -> Result<Vec<T>, TemplateError> {
25 let mut result = Vec::new();
26 result
27 .try_reserve(count)
28 .map_err(|_| TemplateError::Capacity)?;
29 result.resize(count, value);
30 Ok(result)
31}
32
33fn edges(slots: &[CellSlot], cells: &[CellId]) -> Result<Vec<CellId>, TemplateError> {
38 debug_assert!(slots.iter().all(|slot| slot.index < cells.len()));
39 let mut result = Vec::new();
40 result
41 .try_reserve(slots.len())
42 .map_err(|_| TemplateError::Capacity)?;
43 result.extend(slots.iter().map(|s| cells[s.index]));
44 Ok(result)
45}
46
47pub(super) fn signature_matches(sheet: &Sheet, ids: &[CellId], types: &[TypeId]) -> bool {
51 ids.len() == types.len()
52 && ids
53 .iter()
54 .zip(types)
55 .all(|(id, ty)| sheet.cell_type_id(*id) == Some(*ty))
56}
57
58pub(super) fn group_members(
64 slots: &[RelationshipSlot],
65 groups: &[Range<usize>],
66 all: &[RelationshipId],
67) -> Result<Vec<RelationshipId>, TemplateError> {
68 debug_assert!(slots.iter().all(|slot| {
69 groups
70 .get(slot.index)
71 .is_some_and(|group| group.start <= group.end && group.end <= all.len())
72 }));
73 let count = slots
74 .iter()
75 .try_fold(0usize, |n, slot| n.checked_add(groups[slot.index].len()))
76 .ok_or(TemplateError::Capacity)?;
77 let mut result = Vec::new();
78 result
79 .try_reserve(count)
80 .map_err(|_| TemplateError::Capacity)?;
81 for slot in slots {
82 result.extend_from_slice(&all[groups[slot.index].clone()]);
83 }
84 Ok(result)
85}
86
87struct SourceFrame<'a> {
89 recipe: &'a SheetTemplate,
90 sources: Vec<bool>,
91 next: usize,
92 incoming: Option<RelationshipSlot>,
93}
94
95struct LiveFrame<'a> {
102 recipe: &'a SheetTemplate,
103 cells: Vec<CellId>,
104 groups: Vec<Range<usize>>,
105 next: usize,
106 incoming: Option<usize>,
107 occurrence: usize,
108}
109
110impl<'a> LiveFrame<'a> {
111 fn new(
115 recipe: &'a SheetTemplate,
116 incoming: Option<usize>,
117 occurrence: usize,
118 ) -> Result<Self, TemplateError> {
119 Ok(Self {
120 recipe,
121 cells: storage(recipe.cells.len(), CellId::default())?,
122 groups: storage(recipe.relationships.len(), 0..0)?,
123 next: 0,
124 incoming,
125 occurrence,
126 })
127 }
128
129 fn conditional_error(&self, source: TemplateError, instance: &Instance) -> TemplateError {
134 debug_assert!(matches!(
135 self.recipe.items.get(self.next - 1),
136 Some(Item::Conditional(_))
137 ));
138 let conditional = self.recipe.items[..self.next - 1]
139 .iter()
140 .filter(|item| matches!(item, Item::Conditional(_)))
141 .count();
142 TemplateError::ConditionalConstruction {
143 template: self.recipe.id(),
144 conditional,
145 inclusions: self.inclusions(instance),
146 source: Box::new(source),
147 }
148 }
149
150 fn inclusions(&self, instance: &Instance) -> Vec<RelationshipSlot> {
154 let mut inclusions = std::iter::successors(Some(self.occurrence), |&index| {
155 instance.occurrences[index]
156 .parent
157 .as_ref()
158 .map(|parent| parent.index)
159 })
160 .filter_map(|index| instance.occurrences[index].inclusion_site.clone())
161 .collect::<Vec<_>>();
162 inclusions.reverse();
163 inclusions
164 }
165
166 fn construction_error(
170 &self,
171 source: TemplateError,
172 site: super::ConstructionSite,
173 instance: &Instance,
174 ) -> TemplateError {
175 TemplateError::Construction {
176 template: self.recipe.id(),
177 site,
178 inclusions: self.inclusions(instance),
179 source: Box::new(source),
180 }
181 }
182}
183
184impl SheetTemplate {
185 pub fn instantiate(
221 &self,
222 destination: &mut Sheet,
223 bindings: &[(&str, CellId)],
224 ) -> Result<Instance, TemplateError> {
225 let bound = self.bind(bindings, |name, actual| {
226 let type_id =
227 destination
228 .cell_type_id(*actual)
229 .ok_or_else(|| TemplateError::InvalidActual {
230 name: name.into(),
231 actual: *actual,
232 })?;
233 if destination.cell_kind(*actual) == Some(CellKind::Out) {
234 return Err(TemplateError::OutArgument {
235 name: name.into(),
236 actual: *actual,
237 });
238 }
239 Ok(type_id)
240 })?;
241 let size = self.expanded_size.ok_or(TemplateError::Capacity)?;
242 let mut instance = Instance {
243 _identity: Rc::new(()),
244 cells: Vec::new(),
245 relationships: Vec::new(),
246 occurrences: Vec::new(),
247 local_cells: Vec::new(),
248 local_groups: Vec::new(),
249 relationship_origins: Vec::new(),
250 authored_methods: Vec::new(),
251 };
252 instance
253 .cells
254 .try_reserve(size)
255 .map_err(|_| TemplateError::Capacity)?;
256 instance
257 .relationships
258 .try_reserve(size)
259 .map_err(|_| TemplateError::Capacity)?;
260 instance
261 .occurrences
262 .try_reserve(size)
263 .map_err(|_| TemplateError::Capacity)?;
264 instance
265 .local_cells
266 .try_reserve(size)
267 .map_err(|_| TemplateError::Capacity)?;
268 instance
269 .local_groups
270 .try_reserve(size)
271 .map_err(|_| TemplateError::Capacity)?;
272 instance
273 .relationship_origins
274 .try_reserve(size)
275 .map_err(|_| TemplateError::Capacity)?;
276 instance
277 .authored_methods
278 .try_reserve(size)
279 .map_err(|_| TemplateError::Capacity)?;
280 self.preflight_sources(destination, &bound)?;
281 self.expand(destination, &bound, &mut instance)?;
282 Ok(instance)
283 }
284
285 fn preflight_sources(
296 &self,
297 destination: &Sheet,
298 bound: &HashMap<usize, CellId>,
299 ) -> Result<(), TemplateError> {
300 let mut sources = storage(self.cells.len(), false)?;
301 for (i, cell) in self.cells.iter().enumerate() {
302 sources[i] = cell.kind == CellKind::Source
303 || bound
304 .get(&i)
305 .is_some_and(|id| destination.cell_kind(*id) == Some(CellKind::Source));
306 }
307 self.preflight_source_mask(sources)
308 }
309
310 pub fn check_source_bindings(&self, bindings: &[(&str, bool)]) -> Result<(), TemplateError> {
331 self.expanded_size.ok_or(TemplateError::Capacity)?;
332 let mut sources = storage(self.cells.len(), false)?;
333 let mut seen = HashSet::new();
334 for &(name, source) in bindings {
335 let Some(index) = self
336 .cells
337 .iter()
338 .position(|cell| cell.make.is_none() && cell.name == name)
339 else {
340 return Err(TemplateError::InvalidDefinition {
341 detail: "unknown source-binding parameter",
342 slot: None,
343 });
344 };
345 if !seen.insert(index) {
346 return Err(TemplateError::InvalidDefinition {
347 detail: "repeated source-binding parameter",
348 slot: None,
349 });
350 }
351 sources[index] = source;
352 }
353 if seen.len() != self.parameter_names().count() {
354 return Err(TemplateError::InvalidDefinition {
355 detail: "missing source-binding parameter",
356 slot: None,
357 });
358 }
359 for (index, cell) in self.cells.iter().enumerate() {
360 sources[index] |= cell.kind == CellKind::Source;
361 }
362 self.preflight_source_mask(sources)
363 }
364
365 fn preflight_source_mask(&self, sources: Vec<bool>) -> Result<(), TemplateError> {
379 debug_assert_eq!(sources.len(), self.cells.len());
380 let mut complete = HashSet::new();
381 let mut stack = Vec::new();
382 stack
383 .try_reserve(self.depth.ok_or(TemplateError::Capacity)?)
384 .map_err(|_| TemplateError::Capacity)?;
385 stack.push(SourceFrame {
386 recipe: self,
387 sources,
388 next: 0,
389 incoming: None,
390 });
391 while let Some(frame) = stack.last_mut() {
392 #[cfg(test)]
393 if frame.next == 0 {
394 SOURCE_PREFLIGHT_VISITS.with(|visits| visits.set(visits.get() + 1));
395 }
396 let Some(relationship) = frame.recipe.relationships.get(frame.next) else {
397 let frame = stack.pop().expect("active source frame");
398 complete
399 .try_reserve(1)
400 .map_err(|_| TemplateError::Capacity)?;
401 complete.insert((frame.recipe.id(), frame.sources));
402 continue;
403 };
404 frame.next += 1;
405 match relationship {
406 RelationshipRecipe::Methods(methods) => {
407 if !methods.iter().any(|m| {
408 super::method_survives_sources(&m.outputs, |s| frame.sources[s.index])
409 }) {
410 let template = frame.recipe.id();
411 let site = super::ConstructionSite::Relationship(RelationshipSlot {
412 owner: frame.recipe.owner.clone(),
413 index: frame.next - 1,
414 });
415 return Err(TemplateError::Construction {
416 template,
417 site,
418 inclusions: stack
419 .iter()
420 .filter_map(|frame| frame.incoming.clone())
421 .collect(),
422 source: Box::new(TemplateError::EmptyRelationship),
423 });
424 }
425 }
426 RelationshipRecipe::Out(_) => {}
427 RelationshipRecipe::Include { child, bindings } => {
428 let mut sources = storage(child.cells.len(), false)?;
429 for (i, cell) in child.cells.iter().enumerate() {
430 sources[i] = cell.kind == CellKind::Source
431 || bindings.get(&i).is_some_and(|s| frame.sources[s.index]);
432 }
433 let key = (child.id(), sources);
434 if complete.contains(&key) {
435 continue;
436 }
437 let incoming = Some(RelationshipSlot {
438 owner: frame.recipe.owner.clone(),
439 index: frame.next - 1,
440 });
441 stack.push(SourceFrame {
442 recipe: child,
443 sources: key.1,
444 next: 0,
445 incoming,
446 });
447 }
448 }
449 }
450 Ok(())
451 }
452
453 fn expand(
460 &self,
461 destination: &mut Sheet,
462 bound: &HashMap<usize, CellId>,
463 instance: &mut Instance,
464 ) -> Result<(), TemplateError> {
465 let mut root = LiveFrame::new(self, None, 0)?;
466 for (&index, &actual) in bound {
467 root.cells[index] = actual;
468 }
469 instance.cells.resize(self.cells.len(), CellId::default());
470 let mut stack = Vec::new();
471 stack
472 .try_reserve(self.depth.ok_or(TemplateError::Capacity)?)
473 .map_err(|_| TemplateError::Capacity)?;
474 instance.occurrences.push(InstanceOccurrence {
475 id: OccurrenceId {
476 owner: instance._identity.clone(),
477 index: 0,
478 },
479 template: self.id(),
480 parent: None,
481 inclusion_site: None,
482 cells: 0..0,
483 groups: 0..0,
484 conditionals: Vec::new(),
485 });
486 stack.push(root);
487 while let Some(frame) = stack.last_mut() {
488 let Some(item) = frame.recipe.items.get(frame.next) else {
489 let finished = stack.pop().unwrap();
490 let cells_start = instance.local_cells.len();
491 instance.local_cells.extend_from_slice(&finished.cells);
492 let groups_start = instance.local_groups.len();
493 instance.local_groups.extend_from_slice(&finished.groups);
494 let record = &mut instance.occurrences[finished.occurrence];
495 record.cells = cells_start..instance.local_cells.len();
496 record.groups = groups_start..instance.local_groups.len();
497 if let Some(index) = finished.incoming {
498 stack.last_mut().unwrap().groups[index].end = instance.relationships.len();
499 } else {
500 instance.cells[..finished.cells.len()].copy_from_slice(&finished.cells);
501 }
502 continue;
503 };
504 frame.next += 1;
505 match item {
506 Item::Cell(index) => {
507 if let Some(make) = &frame.recipe.cells[*index].make {
508 frame.cells[*index] = make(destination)
509 .map_err(|source| TemplateError::Factory {
510 source,
511 slot: CellSlot {
512 owner: frame.recipe.owner.clone(),
513 index: *index,
514 },
515 })
516 .map_err(|error| {
517 frame.construction_error(
518 error,
519 super::ConstructionSite::Cell(CellSlot {
520 owner: frame.recipe.owner.clone(),
521 index: *index,
522 }),
523 instance,
524 )
525 })?;
526 if frame.incoming.is_some() {
527 instance.cells.push(frame.cells[*index]);
528 }
529 }
530 }
531 Item::Policy(policy) => {
532 let ids = edges(&policy.inputs, &frame.cells)?;
533 (policy.make)(destination, frame.cells[policy.cell.index], &ids).map_err(
534 |error| {
535 frame.construction_error(
536 error,
537 super::ConstructionSite::Policy {
538 cell: policy.cell.clone(),
539 index: frame.recipe.items[..frame.next - 1]
540 .iter()
541 .filter(|item| {
542 matches!(item, Item::Policy(previous)
543 if previous.cell == policy.cell)
544 })
545 .count(),
546 },
547 instance,
548 )
549 },
550 )?;
551 }
552 Item::Conditional(conditional) => {
553 let ids = edges(&conditional.inputs, &frame.cells)?;
554 instance.occurrences[frame.occurrence]
555 .conditionals
556 .try_reserve(1)
557 .map_err(|_| TemplateError::Capacity)?;
558 let id = (conditional.make)(
559 destination,
560 &ids,
561 &frame.groups,
562 &instance.relationships,
563 )
564 .map_err(|error| frame.conditional_error(error, instance))?;
565 instance.occurrences[frame.occurrence].conditionals.push(id);
566 }
567 Item::Relationship(index) => {
568 let start = instance.relationships.len();
569 frame.groups[*index] = start..start;
570 match &frame.recipe.relationships[*index] {
571 RelationshipRecipe::Methods(recipes) => {
572 let methods_start = instance.authored_methods.len();
573 let mut methods = Vec::new();
574 methods
575 .try_reserve(recipes.len())
576 .map_err(|_| TemplateError::Capacity)?;
577 for (method_index, recipe) in recipes.iter().enumerate() {
579 methods.push(
580 recipe.instantiate(destination, &frame.cells).map_err(
581 |error| {
582 frame.construction_error(
583 error,
584 super::ConstructionSite::Method {
585 relationship: RelationshipSlot {
586 owner: frame.recipe.owner.clone(),
587 index: *index,
588 },
589 index: method_index,
590 },
591 instance,
592 )
593 },
594 )?,
595 );
596 }
597 let mut authored_index = 0;
598 methods.retain(|method| {
599 let survives =
600 super::method_survives_sources(&method.outputs, |id| {
601 destination.cell_kind(*id) == Some(CellKind::Source)
602 });
603 if survives {
604 instance.authored_methods.push(authored_index);
605 }
606 authored_index += 1;
607 survives
608 });
609 debug_assert!(!methods.is_empty());
610 instance.relationships.push(
611 destination.add_relationship(methods).map_err(|error| {
612 frame.construction_error(
613 TemplateError::Runtime(error),
614 super::ConstructionSite::Relationship(RelationshipSlot {
615 owner: frame.recipe.owner.clone(),
616 index: *index,
617 }),
618 instance,
619 )
620 })?,
621 );
622 instance.relationship_origins.push(RelationshipOrigin {
623 occurrence: frame.occurrence,
624 slot: *index,
625 methods: methods_start..instance.authored_methods.len(),
626 });
627 frame.groups[*index].end = instance.relationships.len();
628 }
629 RelationshipRecipe::Out(writer) => {
630 let method =
631 writer
632 .instantiate(destination, &frame.cells)
633 .map_err(|error| {
634 frame.construction_error(
635 error,
636 super::ConstructionSite::Method {
637 relationship: RelationshipSlot {
638 owner: frame.recipe.owner.clone(),
639 index: *index,
640 },
641 index: 0,
642 },
643 instance,
644 )
645 })?;
646 let relationship =
647 destination.add_out_writer(method).map_err(|error| {
648 frame.construction_error(
649 TemplateError::Runtime(error),
650 super::ConstructionSite::Relationship(RelationshipSlot {
651 owner: frame.recipe.owner.clone(),
652 index: *index,
653 }),
654 instance,
655 )
656 })?;
657 instance.relationships.push(relationship);
658 let methods_start = instance.authored_methods.len();
659 instance.authored_methods.push(0);
660 instance.relationship_origins.push(RelationshipOrigin {
661 occurrence: frame.occurrence,
662 slot: *index,
663 methods: methods_start..instance.authored_methods.len(),
664 });
665 frame.groups[*index].end = instance.relationships.len();
666 }
667 RelationshipRecipe::Include { child, bindings } => {
668 let occurrence = instance.occurrences.len();
669 let mut next = LiveFrame::new(child, Some(*index), occurrence)?;
670 for (i, slot) in bindings {
671 next.cells[*i] = frame.cells[slot.index];
672 }
673 instance.occurrences.push(InstanceOccurrence {
674 id: OccurrenceId {
675 owner: instance._identity.clone(),
676 index: occurrence,
677 },
678 template: child.id(),
679 parent: Some(instance.occurrences[frame.occurrence].id.clone()),
680 inclusion_site: Some(RelationshipSlot {
681 owner: frame.recipe.owner.clone(),
682 index: *index,
683 }),
684 cells: 0..0,
685 groups: 0..0,
686 conditionals: Vec::new(),
687 });
688 stack.push(next);
689 }
690 }
691 }
692 }
693 }
694 Ok(())
695 }
696}
697
698impl MethodRecipe {
699 fn instantiate(&self, sheet: &Sheet, cells: &[CellId]) -> Result<Method, TemplateError> {
704 debug_assert!(
705 self.inputs
706 .iter()
707 .chain(&self.outputs)
708 .all(|s| s.index < cells.len())
709 );
710 let inputs = edges(&self.inputs, cells)?;
711 let outputs = edges(&self.outputs, cells)?;
712 let method = (self.make)(&inputs, &outputs).map_err(|source| TemplateError::Factory {
713 source,
714 slot: self.outputs[0].clone(),
715 })?;
716 if method.inputs != inputs
717 || method.outputs != outputs
718 || !signature_matches(sheet, &inputs, &method.input_types)
719 || !signature_matches(sheet, &outputs, &method.output_types)
720 {
721 return Err(TemplateError::InvalidDefinition {
722 detail: "method factory edges or concrete types differ from its recipe",
723 slot: Some(self.outputs[0].clone()),
724 });
725 }
726 Ok(method)
727 }
728}
729
730#[cfg(test)]
731mod tests {
732 use super::SOURCE_PREFLIGHT_VISITS;
733 use crate::TemplateBuilder;
734 use std::rc::Rc;
735
736 #[test]
738 fn signatures_check_arity_liveness_and_concrete_types() {
739 use super::{CellId, Sheet, TypeId, signature_matches};
740 let mut sheet = Sheet::new();
741 let number = sheet.add_cell(3_i32);
742 let flag = sheet.add_cell(true);
743 assert!(signature_matches(&sheet, &[], &[]));
744 assert!(signature_matches(
745 &sheet,
746 &[number, flag],
747 &[TypeId::of::<i32>(), TypeId::of::<bool>()]
748 ));
749 assert!(!signature_matches(&sheet, &[number], &[]));
750 assert!(!signature_matches(&sheet, &[], &[TypeId::of::<i32>()]));
751 assert!(!signature_matches(
752 &sheet,
753 &[number],
754 &[TypeId::of::<bool>()]
755 ));
756 assert!(!signature_matches(
757 &sheet,
758 &[CellId::default()],
759 &[TypeId::of::<i32>()]
760 ));
761 }
762
763 #[test]
765 fn local_storage_and_positional_mapping_preserve_order() {
766 use super::{
767 CellId, LiveFrame, Method, MethodRecipe, Sheet, TemplateError, edges, group_members,
768 storage,
769 };
770 assert_eq!(storage(0, 7_u8).unwrap(), []);
771 assert_eq!(storage(2, 7_u8).unwrap(), [7, 7]);
772 assert!(matches!(
773 storage(usize::MAX, 0_u8),
774 Err(TemplateError::Capacity)
775 ));
776 let mut builder = TemplateBuilder::new();
777 let a = builder.parameter::<i32>("a").unwrap();
778 let b = builder.parameter::<i32>("b").unwrap();
779 let group = builder
780 .relationship(vec![
781 MethodRecipe::new(
782 std::slice::from_ref(&a),
783 std::slice::from_ref(&b),
784 |i, o| Ok(Method::from_fn_1_1(i[0], o[0], |v: &i32| Ok(*v))),
785 )
786 .unwrap(),
787 ])
788 .unwrap();
789 let template = builder.finish().unwrap();
790 let frame = LiveFrame::new(&template, None, 0).unwrap();
791 assert_eq!(frame.cells, [CellId::default(); 2]);
792 assert_eq!(frame.groups.as_slice(), std::slice::from_ref(&(0..0)));
793 assert_eq!(frame.next, 0);
794 let mut sheet = Sheet::new();
795 let live_a = sheet.add_cell(3_i32);
796 let live_b = sheet.add_cell(0_i32);
797 let instance = template
798 .instantiate(&mut sheet, &[("a", live_a), ("b", live_b)])
799 .unwrap();
800 assert_eq!(edges(&[b, a], &[live_a, live_b]).unwrap(), [live_b, live_a]);
801 assert_eq!(
802 group_members(
803 &[group],
804 std::slice::from_ref(&(0..1)),
805 instance.relationships()
806 )
807 .unwrap(),
808 instance.relationships()
809 );
810 assert!(group_members(&[], &[], &[]).unwrap().is_empty());
811 }
812
813 #[test]
815 fn source_preflight_checks_shared_dag_specializations_once() {
816 let depth = 12;
817 let mut template = Rc::new(TemplateBuilder::new().finish().unwrap());
818 for _ in 0..depth {
819 let mut builder = TemplateBuilder::new();
820 builder.include(template.clone(), &[]).unwrap();
821 builder.include(template, &[]).unwrap();
822 template = Rc::new(builder.finish().unwrap());
823 }
824 SOURCE_PREFLIGHT_VISITS.with(|visits| visits.set(0));
825 template.check_source_bindings(&[]).unwrap();
826 SOURCE_PREFLIGHT_VISITS.with(|visits| {
827 assert!(
828 visits.get() <= 2 * (depth + 1),
829 "visited {} frames",
830 visits.get()
831 );
832 });
833 }
834}