adam_rs/dependency.rs
1//! Value-free guard dependency analysis for runtime and symbolic cell graphs.
2//!
3//! Register all cell keys, add every authored method direction, then add guard
4//! dependencies in diagnostic priority order. Method-only cycles are legal; a
5//! guard must not depend on a cell it governs. No values or callbacks are needed.
6//! Validate imported references before inserting trusted edges here. Validate
7//! ordinary relationship structure with
8//! [`check_relationship_edges`](crate::template::check_relationship_edges).
9//!
10//! # Examples
11//! ```
12//! use adam_rs::dependency::{DependencyGraph, DependencyHop};
13//!
14//! let mut graph = DependencyGraph::new(["input", "output"]);
15//! graph.add_method("copy", &["input"], &["output"]);
16//! assert_eq!(graph.analyze().unwrap().guard_depth("output"), 0);
17//! graph.add_guard("output", "input");
18//! let path = graph.analyze().unwrap_err();
19//! assert_eq!(path.cells, ["input", "output"]);
20//! assert_eq!(path.hops, [DependencyHop::Method("copy")]);
21//! ```
22
23use std::collections::{HashMap, HashSet, VecDeque};
24use std::hash::Hash;
25
26/// The provenance of one dependency edge.
27///
28/// # Examples
29/// See the [module example](self).
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum DependencyHop<R> {
32 /// A method edge belonging to the identified relationship.
33 Method(R),
34 /// A filter or conditional guard edge.
35 Guard,
36}
37
38/// An ordered governed-cell-to-guard path that witnesses a guard cycle.
39///
40/// Paths returned by [`DependencyGraph::analyze`] contain one more cell than
41/// hop; each hop connects the cells on either side. A self-guard has one cell
42/// and no hops. The offending guard's closing edge is not included.
43///
44/// # Examples
45/// See the [module example](self).
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct DependencyPath<C, R> {
48 /// Cells in traversal order, from the governed cell to its guard.
49 pub cells: Vec<C>,
50 /// Edge provenance in traversal order.
51 pub hops: Vec<DependencyHop<R>>,
52}
53
54/// A shared forest of nonempty boundary paths returned by [`DependencyGraph::project`].
55///
56/// Every edge indexes its terminal step; following predecessors reaches a root.
57/// Predecessors always have smaller indices, so traversal and destruction need
58/// no recursive calls. Paths distinguish ordinary-only and guard-bearing reachability.
59///
60/// # Examples
61/// See [`DependencyGraph::project`].
62#[derive(Debug)]
63pub struct DependencyProjection<C, R> {
64 /// Boundary reachability in supplied boundary order, ordinary before guarded.
65 pub edges: Vec<ProjectedDependency<C>>,
66 /// Shared path prefixes owned by this projection.
67 pub steps: Vec<DependencyStep<C, R>>,
68}
69
70/// One nonempty boundary dependency and its representative path.
71///
72/// # Examples
73/// See [`DependencyGraph::project`].
74#[derive(Debug)]
75pub struct ProjectedDependency<C> {
76 /// The starting boundary cell.
77 pub from: C,
78 /// The ending boundary cell.
79 pub to: C,
80 /// Whether this representative path contains a guard.
81 pub guarded: bool,
82 /// The terminal index in the owning projection's steps.
83 pub path: usize,
84}
85
86/// One cell and its optional incoming edge in a projection's shared path forest.
87///
88/// # Examples
89/// See [`DependencyGraph::project`].
90#[derive(Debug)]
91pub struct DependencyStep<C, R> {
92 /// The cell reached by this step.
93 pub cell: C,
94 /// The preceding step index and incoming hop, or `None` at a path root.
95 pub previous: Option<(usize, DependencyHop<R>)>,
96}
97
98/// An owned snapshot of each cell's longest dependency path measured in guard edges.
99///
100/// Method-only strongly connected components share a depth. Cells unreachable
101/// from guard edges have depth zero. Constant methods add no dependency edges.
102///
103/// # Examples
104/// See [`DependencyOrder::guard_depth`].
105#[derive(Debug)]
106pub struct DependencyOrder<C> {
107 components: HashMap<C, usize>,
108 depths: Vec<usize>,
109}
110
111impl<C: Copy + Eq + Hash> DependencyOrder<C> {
112 /// Returns the cell's longest incoming dependency path measured in guard edges.
113 ///
114 /// - Precondition: `cell` belongs to the graph that produced this order.
115 /// - Complexity: Expected O(1) time, excluding key hashing and equality costs.
116 ///
117 /// # Examples
118 /// ```
119 /// use adam_rs::dependency::DependencyGraph;
120 /// let mut graph = DependencyGraph::<_, ()>::new([0, 1, 2]);
121 /// graph.add_guard(0, 1);
122 /// graph.add_guard(1, 2);
123 /// let order = graph.analyze().unwrap();
124 /// assert_eq!(order.guard_depth(0), 0);
125 /// assert_eq!(order.guard_depth(2), 2);
126 /// ```
127 pub fn guard_depth(&self, cell: C) -> usize {
128 debug_assert!(self.components.contains_key(&cell));
129 self.depths[self.components[&cell]]
130 }
131}
132
133/// One static dependency edge.
134#[derive(Debug, Clone, Copy)]
135struct DependencyEdge<C, R> {
136 to: C,
137 hop: DependencyHop<R>,
138}
139
140/// An owning graph of cell identities, method dependencies, and ordered guards.
141///
142/// Every edge connects registered cells. Relationship keys provide provenance,
143/// not runtime relationships; callers validate relationship structure separately.
144/// An input that also occurs in a method's outputs contributes no outgoing edges.
145/// Repeated edges are retained, and guard insertion order sets diagnostic priority.
146///
147/// # Examples
148/// See the [module example](self).
149pub struct DependencyGraph<C, R> {
150 nodes: Vec<C>,
151 adjacency: HashMap<C, Vec<DependencyEdge<C, R>>>,
152 guard_edges: Vec<(C, C)>,
153}
154
155/// One suspended depth-first-search frame for iterative Tarjan SCC.
156struct TarjanFrame<C> {
157 node: C,
158 next_successor: usize,
159 entered: bool,
160}
161
162impl<C: Copy + Eq + Hash, R: Copy + Eq + Hash> DependencyGraph<C, R> {
163 /// Creates a graph owning the supplied cell identities without dependencies.
164 ///
165 /// Repeated keys identify the same cell; first occurrence determines node order.
166 ///
167 /// - Complexity: Expected O(n) time and O(V) space for n supplied keys and V
168 /// distinct cells, excluding key hashing and equality costs.
169 ///
170 /// # Examples
171 /// ```
172 /// use adam_rs::dependency::DependencyGraph;
173 /// let graph = DependencyGraph::<_, ()>::new([0, 1]);
174 /// assert_eq!(graph.analyze().unwrap().guard_depth(1), 0);
175 /// ```
176 pub fn new(cells: impl IntoIterator<Item = C>) -> Self {
177 let mut nodes = Vec::new();
178 let mut adjacency = HashMap::new();
179 for cell in cells {
180 if let std::collections::hash_map::Entry::Vacant(entry) = adjacency.entry(cell) {
181 entry.insert(Vec::new());
182 nodes.push(cell);
183 }
184 }
185 Self {
186 nodes,
187 adjacency,
188 guard_edges: Vec::new(),
189 }
190 }
191
192 /// Adds one authored method direction with relationship provenance.
193 ///
194 /// Each input outside the output set contributes an edge to every output.
195 /// Empty inputs contribute no edges, as required for constant producers.
196 /// This operation records dependencies without validating relationship groups;
197 /// [`check_relationship_edges`](crate::template::check_relationship_edges)
198 /// remains the ordinary relationship validator.
199 ///
200 /// - Precondition: Every input and output belongs to this graph.
201 /// - Complexity: Expected amortized O(I + O + E) time and O(O) temporary space
202 /// for I inputs, O outputs, and E added edges, excluding key operation costs.
203 /// Stores E additional edges.
204 ///
205 /// # Examples
206 /// See the [module example](self).
207 pub fn add_method(&mut self, relationship: R, inputs: &[C], outputs: &[C]) {
208 debug_assert!(
209 inputs
210 .iter()
211 .chain(outputs)
212 .all(|cell| self.adjacency.contains_key(cell))
213 );
214 let output_set: HashSet<C> = outputs.iter().copied().collect();
215 for &input in inputs {
216 if output_set.contains(&input) {
217 continue;
218 }
219 for &output in outputs {
220 self.adjacency
221 .get_mut(&input)
222 .expect("registered input")
223 .push(DependencyEdge {
224 to: output,
225 hop: DependencyHop::Method(relationship),
226 });
227 }
228 }
229 }
230
231 /// Adds a guard dependency from `input` to the cell it governs.
232 ///
233 /// - Precondition: Both keys belong to this graph.
234 /// - Complexity: Expected amortized O(1) time, excluding key operation costs.
235 ///
236 /// # Examples
237 /// See the [module example](self).
238 pub fn add_guard(&mut self, input: C, governed: C) {
239 self.add_dependency(input, governed, DependencyHop::Guard);
240 }
241
242 /// Adds an already resolved dependency, including an ordinary self-edge.
243 ///
244 /// Unlike [`Self::add_method`], this operation does not apply read/write
245 /// overlap exclusion: callers have already resolved method semantics.
246 ///
247 /// - Precondition: Both keys belong to this graph.
248 /// - Complexity: Expected amortized O(1), excluding key operation costs.
249 ///
250 /// # Examples
251 /// See [`Self::project`].
252 pub fn add_dependency(&mut self, input: C, governed: C, hop: DependencyHop<R>) {
253 debug_assert!(self.adjacency.contains_key(&input));
254 debug_assert!(self.adjacency.contains_key(&governed));
255 self.adjacency
256 .get_mut(&input)
257 .expect("registered input")
258 .push(DependencyEdge { to: governed, hop });
259 if matches!(hop, DependencyHop::Guard) {
260 self.guard_edges.push((input, governed));
261 }
262 }
263
264 /// Projects both kinds of nonempty reachability onto the supplied boundary cells.
265 ///
266 /// Retains one deterministic representative per pair and kind, using outgoing
267 /// edge order to break traversal ties. Ordinary self-reachability requires
268 /// a nonempty cycle; an isolated boundary contributes no path.
269 ///
270 /// - Precondition: Every boundary belongs to this graph.
271 /// - Complexity: Expected O(B(V + E) + B²) time and O(BV + B²) result and
272 /// auxiliary space for B supplied boundaries, V cells and E stored edges,
273 /// excluding key operation costs. Shared prefixes are not expanded.
274 ///
275 /// # Examples
276 /// ```
277 /// use adam_rs::dependency::{DependencyGraph, DependencyHop};
278 /// let mut graph = DependencyGraph::new([0, 1, 2]);
279 /// graph.add_dependency(0, 1, DependencyHop::Method("copy"));
280 /// graph.add_guard(1, 2);
281 /// let projection = graph.project(&[0, 2]);
282 /// assert_eq!(projection.edges.len(), 1);
283 /// assert!(projection.edges[0].guarded);
284 /// assert_eq!(projection.steps[projection.edges[0].path].cell, 2);
285 /// ```
286 pub fn project(&self, boundaries: &[C]) -> DependencyProjection<C, R> {
287 debug_assert!(
288 boundaries
289 .iter()
290 .all(|cell| self.adjacency.contains_key(cell))
291 );
292 let mut projection = DependencyProjection {
293 edges: Vec::new(),
294 steps: Vec::new(),
295 };
296 for &start in boundaries {
297 let root = projection.steps.len();
298 projection.steps.push(DependencyStep {
299 cell: start,
300 previous: None,
301 });
302 let mut reached = HashMap::from([((start, false), root)]);
303 let mut queue = VecDeque::from([(root, false)]);
304 let mut ordinary_cycle = None;
305 while let Some((previous, guarded)) = queue.pop_front() {
306 let cell = projection.steps[previous].cell;
307 for edge in self.successors(cell) {
308 let guarded = guarded || matches!(edge.hop, DependencyHop::Guard);
309 let state = (edge.to, guarded);
310 let cycle = state == (start, false) && ordinary_cycle.is_none();
311 if reached.contains_key(&state) && !cycle {
312 continue;
313 }
314 let next = projection.steps.len();
315 projection.steps.push(DependencyStep {
316 cell: edge.to,
317 previous: Some((previous, edge.hop)),
318 });
319 if cycle {
320 ordinary_cycle = Some(next);
321 } else {
322 reached.insert(state, next);
323 queue.push_back((next, guarded));
324 }
325 }
326 }
327 for &to in boundaries {
328 for guarded in [false, true] {
329 let path = if to == start && !guarded {
330 ordinary_cycle
331 } else {
332 reached.get(&(to, guarded)).copied()
333 };
334 if let Some(path) = path {
335 projection.edges.push(ProjectedDependency {
336 from: start,
337 to,
338 guarded,
339 path,
340 });
341 }
342 }
343 }
344 }
345 projection
346 }
347
348 /// Validates guard independence and returns each cell's guard depth.
349 ///
350 /// Ordinary method-only cycles are legal. Equal-length diagnostic paths
351 /// follow outgoing edge insertion order.
352 ///
353 /// - Complexity: Expected O(V + E) time and auxiliary space for V cells and E
354 /// stored edges, excluding key hashing and equality costs.
355 ///
356 /// # Errors
357 ///
358 /// Returns a shortest governed-cell-to-guard path for the first inserted
359 /// guard that closes a cycle, including self-guards.
360 ///
361 /// # Examples
362 /// See the [module example](self).
363 pub fn analyze(&self) -> Result<DependencyOrder<C>, DependencyPath<C, R>> {
364 let components = self.strongly_connected_components();
365 for &(guard, target) in &self.guard_edges {
366 if guard == target {
367 return Err(DependencyPath {
368 cells: vec![target],
369 hops: Vec::new(),
370 });
371 }
372 if components.get(&guard) == components.get(&target) {
373 return Err(self
374 .shortest_path_within_component(target, guard, &components)
375 .expect("nodes in one component have a connecting path"));
376 }
377 }
378 let depths = self.component_guard_depths(&components);
379 Ok(DependencyOrder { components, depths })
380 }
381
382 /// Returns the outgoing dependency edges for a registered cell.
383 ///
384 /// - Complexity: Expected O(1) time, excluding key operation costs.
385 fn successors(&self, cell: C) -> &[DependencyEdge<C, R>] {
386 debug_assert!(self.adjacency.contains_key(&cell));
387 &self.adjacency[&cell]
388 }
389
390 /// Returns each component's longest incoming path measured in guard edges.
391 ///
392 /// Uses Kahn's topological traversal of the component DAG.
393 ///
394 /// - Precondition: `components` describes every node's strongly connected component.
395 /// - Precondition: No guard edge remains inside one component.
396 /// - Complexity: Expected O(V + E) time and O(V + E) auxiliary space,
397 /// excluding key operation costs.
398 fn component_guard_depths(&self, components: &HashMap<C, usize>) -> Vec<usize> {
399 debug_assert!(self.nodes.iter().all(|node| components.contains_key(node)));
400 let count = components
401 .values()
402 .max()
403 .map_or(0, |component| component + 1);
404 let mut successors = vec![Vec::new(); count];
405 let mut indegrees = vec![0; count];
406 for &node in &self.nodes {
407 let from = components[&node];
408 for edge in self.successors(node) {
409 let to = components[&edge.to];
410 if from == to {
411 debug_assert!(!matches!(edge.hop, DependencyHop::Guard));
412 continue;
413 }
414 successors[from].push((to, usize::from(matches!(edge.hop, DependencyHop::Guard))));
415 indegrees[to] += 1;
416 }
417 }
418 let mut ready: VecDeque<_> = (0..count)
419 .filter(|&component| indegrees[component] == 0)
420 .collect();
421 let mut depths = vec![0; count];
422 let mut visited = 0;
423 while let Some(component) = ready.pop_front() {
424 visited += 1;
425 for &(successor, guard_edges) in &successors[component] {
426 depths[successor] = depths[successor].max(depths[component] + guard_edges);
427 indegrees[successor] -= 1;
428 if indegrees[successor] == 0 {
429 ready.push_back(successor);
430 }
431 }
432 }
433 debug_assert_eq!(visited, count);
434 depths
435 }
436
437 /// Returns the strongly connected component id for each graph node.
438 ///
439 /// Uses iterative Tarjan's algorithm so large graphs do not consume call stack.
440 ///
441 /// - Complexity: Expected O(V + E) time and O(V) auxiliary space,
442 /// excluding key operation costs.
443 fn strongly_connected_components(&self) -> HashMap<C, usize> {
444 let mut next_index = 0usize;
445 let mut next_component = 0usize;
446 let mut indices: HashMap<C, usize> = HashMap::new();
447 let mut lowlinks: HashMap<C, usize> = HashMap::new();
448 let mut stack = Vec::new();
449 let mut on_stack = HashSet::new();
450 let mut components = HashMap::new();
451
452 for &start in &self.nodes {
453 if indices.contains_key(&start) {
454 continue;
455 }
456 let mut frames = vec![TarjanFrame {
457 node: start,
458 next_successor: 0,
459 entered: false,
460 }];
461 while !frames.is_empty() {
462 let frame_index = frames.len() - 1;
463 if !frames[frame_index].entered {
464 let node = frames[frame_index].node;
465 indices.insert(node, next_index);
466 lowlinks.insert(node, next_index);
467 next_index += 1;
468 stack.push(node);
469 on_stack.insert(node);
470 frames[frame_index].entered = true;
471 }
472 let node = frames[frame_index].node;
473 let successors = self.successors(node);
474 if frames[frame_index].next_successor < successors.len() {
475 let successor = successors[frames[frame_index].next_successor].to;
476 frames[frame_index].next_successor += 1;
477 if !indices.contains_key(&successor) {
478 frames.push(TarjanFrame {
479 node: successor,
480 next_successor: 0,
481 entered: false,
482 });
483 } else if on_stack.contains(&successor) {
484 let successor_index = indices[&successor];
485 let lowlink = lowlinks
486 .get_mut(&node)
487 .expect("entered nodes have a lowlink");
488 *lowlink = (*lowlink).min(successor_index);
489 }
490 continue;
491 }
492 let completed = frames.pop().expect("frame exists").node;
493 if lowlinks[&completed] == indices[&completed] {
494 while let Some(member) = stack.pop() {
495 on_stack.remove(&member);
496 components.insert(member, next_component);
497 if member == completed {
498 break;
499 }
500 }
501 next_component += 1;
502 }
503 if let Some(parent) = frames.last() {
504 let child_lowlink = lowlinks[&completed];
505 let parent_lowlink = lowlinks
506 .get_mut(&parent.node)
507 .expect("entered parent nodes have a lowlink");
508 *parent_lowlink = (*parent_lowlink).min(child_lowlink);
509 }
510 }
511 }
512 components
513 }
514
515 /// Returns a shortest path from `start` to `target` inside their shared SCC.
516 ///
517 /// Returns `None` if no path exists, which indicates inconsistent component data.
518 ///
519 /// - Precondition: `components` describes this graph's SCCs and
520 /// `components[start] == components[target]`.
521 /// - Complexity: Expected O(V + E) time and O(V) auxiliary space for V graph
522 /// cells and E stored edges, excluding key operation costs.
523 fn shortest_path_within_component(
524 &self,
525 start: C,
526 target: C,
527 components: &HashMap<C, usize>,
528 ) -> Option<DependencyPath<C, R>> {
529 debug_assert!(components.get(&start) == components.get(&target));
530 let component = components[&start];
531 let mut parent: HashMap<C, Option<(C, DependencyHop<R>)>> = HashMap::new();
532 let mut queue = VecDeque::from([start]);
533 parent.insert(start, None);
534 while let Some(cell) = queue.pop_front() {
535 if cell == target {
536 return Some(Self::rebuild_path(cell, &parent));
537 }
538 for edge in self.successors(cell) {
539 if components.get(&edge.to) != Some(&component) {
540 continue;
541 }
542 if let std::collections::hash_map::Entry::Vacant(e) = parent.entry(edge.to) {
543 e.insert(Some((cell, edge.hop)));
544 queue.push_back(edge.to);
545 }
546 }
547 }
548 None
549 }
550
551 /// Returns the path ending at `end`, following `parent` links back to a root.
552 ///
553 /// - Precondition: `parent` links from `end` terminate at a `None` root.
554 /// - Complexity: Expected O(n) time and result space for n path cells,
555 /// excluding key operation costs.
556 fn rebuild_path(
557 end: C,
558 parent: &HashMap<C, Option<(C, DependencyHop<R>)>>,
559 ) -> DependencyPath<C, R> {
560 debug_assert!(parent.contains_key(&end));
561 let mut cells = vec![end];
562 let mut hops = Vec::new();
563 let mut cursor = end;
564 while let Some(&Some((prev, hop))) = parent.get(&cursor) {
565 cells.push(prev);
566 hops.push(hop);
567 cursor = prev;
568 }
569 cells.reverse();
570 hops.reverse();
571 DependencyPath { cells, hops }
572 }
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578
579 /// Preserves both path kinds, nonempty cycles, and deterministic shared witnesses.
580 #[test]
581 fn projection_retains_ordinary_and_guarded_reachability() {
582 let mut graph = DependencyGraph::new([0, 1, 2, 3]);
583 graph.add_dependency(0, 1, DependencyHop::Method('a'));
584 graph.add_dependency(1, 2, DependencyHop::Method('b'));
585 graph.add_guard(0, 2);
586 graph.add_dependency(2, 0, DependencyHop::Method('c'));
587 graph.add_dependency(3, 3, DependencyHop::Method('d'));
588 let projection = graph.project(&[0, 2, 3]);
589 let facts: Vec<_> = projection
590 .edges
591 .iter()
592 .map(|edge| (edge.from, edge.to, edge.guarded))
593 .collect();
594 assert_eq!(
595 facts,
596 [
597 (0, 0, false),
598 (0, 0, true),
599 (0, 2, false),
600 (0, 2, true),
601 (2, 0, false),
602 (2, 0, true),
603 (2, 2, false),
604 (2, 2, true),
605 (3, 3, false),
606 ]
607 );
608 let ordinary = projection
609 .edges
610 .iter()
611 .find(|edge| (edge.from, edge.to, edge.guarded) == (0, 2, false))
612 .unwrap();
613 let mut cursor = ordinary.path;
614 let mut cells = Vec::new();
615 while let Some(step) = projection.steps.get(cursor) {
616 cells.push(step.cell);
617 let Some((previous, hop)) = step.previous else {
618 break;
619 };
620 assert!(previous < cursor);
621 assert!(matches!(hop, DependencyHop::Method(_)));
622 cursor = previous;
623 }
624 assert_eq!(cells, [2, 1, 0]);
625 let empty = DependencyGraph::<_, ()>::new([0]).project(&[0]);
626 assert!(empty.edges.is_empty());
627 assert!(graph.project(&[]).steps.is_empty());
628 }
629
630 /// Preserves method cycles, overlap exclusion, and deterministic guard-cycle paths.
631 #[test]
632 fn value_free_guard_graph_preserves_cycle_rules_and_paths() {
633 let empty = DependencyGraph::<&str, &str>::new([]);
634 assert!(empty.analyze().is_ok());
635
636 let mut graph = DependencyGraph::new(["a", "b", "c", "isolated", "constant", "isolated"]);
637 graph.add_method("forward", &["a"], &["b"]);
638 graph.add_method("reverse", &["b"], &["a"]);
639 graph.add_method("forward", &["a"], &["b"]);
640 graph.add_method("constant", &[], &["constant"]);
641 let order = graph.analyze().unwrap();
642 for cell in ["a", "b", "c", "isolated", "constant"] {
643 assert_eq!(order.guard_depth(cell), 0);
644 }
645 graph.add_method("downstream", &["b"], &["c"]);
646 graph.add_guard("c", "a");
647 graph.add_guard("isolated", "isolated");
648 let path = graph.analyze().unwrap_err();
649 assert_eq!(path.cells, ["a", "b", "c"]);
650 assert_eq!(
651 path.hops,
652 [
653 DependencyHop::Method("forward"),
654 DependencyHop::Method("downstream")
655 ]
656 );
657
658 let mut self_guard = DependencyGraph::<_, ()>::new([1]);
659 self_guard.add_guard(1, 1);
660 let path = self_guard.analyze().unwrap_err();
661 assert_eq!(path.cells, [1]);
662 assert!(path.hops.is_empty());
663
664 let mut overlap = DependencyGraph::new([0, 1, 2]);
665 overlap.add_method("read-write", &[0, 1], &[1, 2]);
666 overlap.add_guard(2, 1);
667 let order = overlap.analyze().unwrap();
668 assert_eq!(order.guard_depth(0), 0);
669 assert_eq!(order.guard_depth(2), 0);
670 assert_eq!(order.guard_depth(1), 1);
671 }
672
673 /// Retains guard provenance, shortest-path tie order, and repeated guard depths.
674 #[test]
675 fn value_free_guard_graph_orders_guards_and_shortest_paths() {
676 let mut graph = DependencyGraph::new([0, 1, 2, 3, 4, 5, 6, 7]);
677 graph.add_guard(0, 1);
678 graph.add_guard(0, 1);
679 graph.add_method('d', &[1], &[6]);
680 graph.add_method('e', &[6], &[7]);
681 graph.add_method('f', &[7], &[4]);
682 graph.add_method('a', &[1], &[2]);
683 graph.add_method('b', &[1], &[3]);
684 graph.add_guard(2, 4);
685 graph.add_guard(3, 4);
686 graph.add_method('c', &[4], &[5]);
687 let order = graph.analyze().unwrap();
688 for (cell, depth) in [
689 (0, 0),
690 (1, 1),
691 (2, 1),
692 (3, 1),
693 (4, 2),
694 (5, 2),
695 (6, 1),
696 (7, 1),
697 ] {
698 assert_eq!(order.guard_depth(cell), depth);
699 }
700 graph.add_guard(5, 0);
701 let path = graph.analyze().unwrap_err();
702 // The first guard is 0 -> 1; method insertion order chooses 1 -> 2.
703 assert_eq!(path.cells, [1, 2, 4, 5, 0]);
704 assert_eq!(
705 path.hops,
706 [
707 DependencyHop::Method('a'),
708 DependencyHop::Guard,
709 DependencyHop::Method('c'),
710 DependencyHop::Guard
711 ]
712 );
713 }
714}