adam_rs/template/structure.rs
1//! Projects native recipe structure without constructing values or calling factories.
2//!
3//! ```
4//! let template = adam_rs::TemplateBuilder::new().finish().unwrap();
5//! let structure = template.structure();
6//! assert!(structure.definitions[0].cells.is_empty());
7//! ```
8
9use super::*;
10
11/// Owns the distinct definitions of a native recipe DAG; definition zero is the root.
12///
13/// No structure retains a factory or a live sheet. See the [module example](self).
14pub struct Structure {
15 /// Definitions indexed by first discovery in authored relationship order.
16 pub definitions: Vec<DefinitionStructure>,
17}
18
19/// Retains one native definition's local cells, relationships, and policies.
20///
21/// Local ordinals refer only to this definition. See [`Structure`].
22pub struct DefinitionStructure {
23 /// Identifies the immutable native owner.
24 pub id: TemplateId,
25 /// Cells in native declaration order.
26 pub cells: Vec<CellStructure>,
27 /// Relationship groups in native declaration order.
28 pub relationships: Vec<RelationshipStructure>,
29 /// Filters and requirements in attachment order.
30 pub policies: Vec<PolicyStructure>,
31 /// Conditional branch/default group membership in declaration order.
32 pub conditionals: Vec<ConditionalStructure>,
33}
34
35/// Describes a native cell without retaining its initializer.
36///
37/// See [`DefinitionStructure`].
38pub struct CellStructure {
39 /// Identifies the owning local declaration for diagnostic metadata.
40 pub slot: CellSlot,
41 /// The local declaration or parameter name.
42 pub name: String,
43 /// The native cell kind before formal substitution.
44 pub kind: CellKind,
45 /// Whether this cell aliases a caller-owned parameter.
46 pub parameter: bool,
47}
48
49/// Describes an ordinary relationship, output writer, or included definition.
50///
51/// See [`DefinitionStructure`].
52pub enum RelationshipStructure {
53 /// Authored alternatives before whole-method source specialization.
54 Methods(Vec<MethodStructure>),
55 /// A single private output writer.
56 Out(MethodStructure),
57 /// An included definition and its formal-to-actual local cell bindings.
58 Include {
59 /// The child index in the enclosing [`Structure`].
60 definition: usize,
61 /// Child formal/local cell ordinal paired with caller local ordinal.
62 bindings: Vec<(usize, usize)>,
63 },
64}
65
66/// Retains the declared edges of one method without its factory.
67///
68/// See [`RelationshipStructure`].
69pub struct MethodStructure {
70 /// Read cell ordinals in declared order.
71 pub inputs: Vec<usize>,
72 /// Written cell ordinals in declared order.
73 pub outputs: Vec<usize>,
74}
75
76/// Distinguishes guard-producing filters from nonguard requirements.
77///
78/// See [`DefinitionStructure`].
79pub struct PolicyStructure {
80 /// The local governed cell.
81 pub cell: usize,
82 /// Declared dynamic dependencies, excluding the filter candidate.
83 pub inputs: Vec<usize>,
84 /// Whether this policy is a filter.
85 pub is_filter: bool,
86}
87
88/// Retains every conditional branch/default group without evaluating keys.
89///
90/// See [`DefinitionStructure`].
91pub struct ConditionalStructure {
92 /// Local match-input cells.
93 pub inputs: Vec<usize>,
94 /// Branch relationship-group ordinals, preserving branch boundaries.
95 pub branches: Vec<Vec<usize>>,
96 /// Default relationship-group ordinals.
97 pub default: Vec<usize>,
98}
99
100/// Copies method edge ordinals without accessing the factory.
101///
102/// - Complexity: O(i + o) copied input and output ordinals.
103fn method(method: &MethodRecipe) -> MethodStructure {
104 MethodStructure {
105 inputs: method.inputs.iter().map(|slot| slot.index).collect(),
106 outputs: method.outputs.iter().map(|slot| slot.index).collect(),
107 }
108}
109
110impl SheetTemplate {
111 /// Copies the value-free structure of each distinct native definition once.
112 ///
113 /// No initializer, policy, key, method, or conditional factory executes.
114 /// - Complexity: Expected O(n + e log(e + 1) + b) time and O(n + e + b)
115 /// space for distinct recipe declarations n, retained endpoints e, and
116 /// copied name bytes b; include bindings are sorted by formal ordinal.
117 ///
118 /// # Examples
119 /// See the [module example](self).
120 pub fn structure(&self) -> Structure {
121 let mut pending = vec![self];
122 let mut ids = HashMap::from([(self.id(), 0)]);
123 let mut definitions = Vec::new();
124 let mut next = 0;
125 while next < pending.len() {
126 let recipe = pending[next];
127 next += 1;
128 let relationships = recipe
129 .relationships
130 .iter()
131 .map(|relationship| match relationship {
132 RelationshipRecipe::Methods(methods) => {
133 RelationshipStructure::Methods(methods.iter().map(method).collect())
134 }
135 RelationshipRecipe::Out(writer) => RelationshipStructure::Out(method(writer)),
136 RelationshipRecipe::Include { child, bindings } => {
137 let definition = *ids.entry(child.id()).or_insert_with(|| {
138 let id = pending.len();
139 pending.push(child);
140 id
141 });
142 let mut bindings: Vec<_> = bindings
143 .iter()
144 .map(|(formal, actual)| (*formal, actual.index))
145 .collect();
146 bindings.sort_unstable();
147 RelationshipStructure::Include {
148 definition,
149 bindings,
150 }
151 }
152 })
153 .collect();
154 definitions.push(DefinitionStructure {
155 id: recipe.id(),
156 cells: recipe
157 .cells
158 .iter()
159 .enumerate()
160 .map(|(index, cell)| CellStructure {
161 slot: CellSlot {
162 owner: recipe.owner.clone(),
163 index,
164 },
165 name: cell.name.clone(),
166 kind: cell.kind,
167 parameter: cell.make.is_none(),
168 })
169 .collect(),
170 relationships,
171 policies: recipe
172 .items
173 .iter()
174 .filter_map(|item| match item {
175 Item::Policy(policy) => Some(PolicyStructure {
176 cell: policy.cell.index,
177 inputs: policy.inputs.iter().map(|slot| slot.index).collect(),
178 is_filter: policy.is_filter,
179 }),
180 _ => None,
181 })
182 .collect(),
183 conditionals: recipe
184 .items
185 .iter()
186 .filter_map(|item| match item {
187 Item::Conditional(conditional) => Some(ConditionalStructure {
188 inputs: conditional.inputs.iter().map(|slot| slot.index).collect(),
189 branches: conditional
190 .branches
191 .iter()
192 .map(|branch| branch.iter().map(|group| group.index).collect())
193 .collect(),
194 default: conditional
195 .default
196 .iter()
197 .map(|group| group.index)
198 .collect(),
199 }),
200 _ => None,
201 })
202 .collect(),
203 });
204 }
205 Structure { definitions }
206 }
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 /// Preserves policy kinds, branch/default groups and shared DAG owners without factories.
214 #[test]
215 fn snapshot_preserves_structure_without_factories() {
216 let child = Rc::new(TemplateBuilder::new().finish().unwrap());
217 let mut builder = TemplateBuilder::new();
218 let a = builder.parameter::<i32>("a").unwrap();
219 let b = builder.parameter::<i32>("b").unwrap();
220 let private = builder
221 .cell::<i32, _>("private", || panic!("initializer"))
222 .unwrap();
223 builder
224 .filter(&private, std::slice::from_ref(&a), |_, _| panic!("filter"))
225 .unwrap();
226 builder
227 .require(&private, std::slice::from_ref(&b), |_| {
228 panic!("requirement")
229 })
230 .unwrap();
231 let branch = builder
232 .relationship(vec![
233 MethodRecipe::new(
234 std::slice::from_ref(&a),
235 std::slice::from_ref(&b),
236 |_, _| panic!("method"),
237 )
238 .unwrap(),
239 ])
240 .unwrap();
241 let default = builder
242 .relationship(vec![
243 MethodRecipe::new(
244 std::slice::from_ref(&b),
245 std::slice::from_ref(&a),
246 |_, _| panic!("method"),
247 )
248 .unwrap(),
249 ])
250 .unwrap();
251 builder
252 .conditional_factory::<i32, _, _>(
253 std::slice::from_ref(&a),
254 |_| panic!("match"),
255 || panic!("keys"),
256 vec![vec![branch]],
257 vec![default],
258 )
259 .unwrap();
260 builder.include(child.clone(), &[]).unwrap();
261 builder.include(child, &[]).unwrap();
262 let template = builder.finish().unwrap();
263 let snapshot = template.structure();
264 drop(template);
265 assert_eq!(snapshot.definitions.len(), 2);
266 let root = &snapshot.definitions[0];
267 assert_eq!(
268 root.cells
269 .iter()
270 .map(|cell| cell.parameter)
271 .collect::<Vec<_>>(),
272 [true, true, false]
273 );
274 assert!(root.policies[0].is_filter);
275 assert!(!root.policies[1].is_filter);
276 assert_eq!(root.policies[0].inputs, [0]);
277 assert_eq!(root.policies[1].inputs, [1]);
278 assert_eq!(root.conditionals[0].inputs, [0]);
279 assert_eq!(root.conditionals[0].branches, [vec![0]]);
280 assert_eq!(root.conditionals[0].default, [1]);
281 for group in &root.relationships[2..] {
282 assert!(
283 matches!(group, RelationshipStructure::Include { definition: 1, bindings } if bindings.is_empty())
284 );
285 }
286 }
287}