12.2 React to every edge of a depth-first search
You run a depth-first search that reports every edge with the state of its target and lets you follow the edge, skip it or stop.
Problem
Section titled “Problem”You want a depth-first search that decides for each edge whether to follow it. You may also want to notice on the way the edges that close a cycle. A search that reports only nodes cannot do that. You need this for:
- calls followed only within a module, or dependencies only of a certain kind;
- links followed only where a filter accepts them;
- the edges that close a cycle, reported while the search runs.
Example
Section titled “Example”The example graph calls models the calls between the ten methods of a small program. It has an
edge from each method to each method it calls. The array names holds the names of the methods. The
methods belong to packages. The array
packageOfpackage_ofpackageOfpackageOf holds the package of
each method. read and write belong to the package storage, which the gray frame shows. Which
methods does main reach without calling into storage, and which calls
on the way close a cycle? The picture after shows the methods the search reaches, the calls into
storage that the hook skips, and the calls that close a cycle:
- Start node
- Package
- Skipped call into storage
- Reached method
- Call that closes a cycle
Solution
Section titled “Solution”class AvoidingStorage extends DfsEdgeTraverser { final List<String> reached = new ArrayList<>(); final List<String> recursive = new ArrayList<>();
AvoidingStorage(Graph calls) { super(calls); }
@Override protected boolean enterNode(int method) { reached.add(names[method]); return true; }
@Override protected EdgeAction visitEdge( int caller, int callee, int edge, TargetState state) { if (state == TargetState.ON_STACK) { recursive.add(names[caller] + " -> " + names[callee]); // closes a cycle } if (packageOf[callee] == storage) { return EdgeAction.SKIP; // do not follow calls into storage } return super.visitEdge(caller, callee, edge, state); }}var search = new AvoidingStorage(calls);search.run(main);// search.reached: [main, parseArgs, run, load, parse, save, format, show]// search.recursive: [parse -> parse, format -> format]struct AvoidingStorage<'a> { names: &'a [&'static str], package_of: &'a [u32], storage: u32, reached: Vec<&'static str>, recursive: Vec<String>,}
impl DfsEdgeHooks for AvoidingStorage<'_> { fn enter_node(&mut self, method: u32, _control: &mut DfsControl<'_>) -> bool { self.reached.push(self.names[method as usize]); true }
fn visit_edge( &mut self, caller: u32, callee: u32, _edge: u32, state: TargetState, _control: &mut DfsControl<'_>, ) -> EdgeAction { if state == TargetState::OnStack { let (from, to) = (self.names[caller as usize], self.names[callee as usize]); self.recursive.push(format!("{from} -> {to}")); // closes a cycle } if self.package_of[callee as usize] == self.storage { return EdgeAction::Skip; // do not follow calls into storage } EdgeAction::default_for(state) }}let mut search = AvoidingStorage { names, package_of: &package_of, storage, reached: Vec::new(), recursive: Vec::new(),};DfsEdgeTraverser::new(&calls).run_from(main, &mut search);// search.reached: ["main", "parseArgs", "run", "load", "parse", "save", "format",// "show"]// search.recursive: ["parse -> parse", "format -> format"]class AvoidingStorage extends DfsEdgeTraverser { readonly reached: string[] = []; readonly recursive: string[] = [];
protected override enterNode(method: number): boolean { this.reached.push(names[method]); return true; }
protected override visitEdge( caller: number, callee: number, edge: number, state: TargetState, ): EdgeAction { if (state === TargetState.ON_STACK) { this.recursive.push(`${names[caller]} -> ${names[callee]}`); // closes a cycle } if (packageOf[callee] === storage) { return EdgeAction.SKIP; // do not follow calls into storage } return super.visitEdge(caller, callee, edge, state); }}const search = new AvoidingStorage(calls);search.run(main);// search.reached: [main, parseArgs, run, load, parse, save, format, show]// search.recursive: [parse -> parse, format -> format]private sealed class AvoidingStorage( Graph calls, string[] names, int[] packageOf, int storage) : DfsEdgeTraverser(calls){ public List<string> Reached { get; } = [];
public List<string> Recursive { get; } = [];
protected override bool EnterNode(int method) { Reached.Add(names[method]); return true; }
protected override EdgeAction VisitEdge( int caller, int callee, int edge, TargetState state) { if (state == TargetState.OnStack) { Recursive.Add($"{names[caller]} -> {names[callee]}"); // closes a cycle } if (packageOf[callee] == storage) { return EdgeAction.Skip; // do not follow calls into storage } return base.VisitEdge(caller, callee, edge, state); }}
private static WithoutStorageResult WithoutStorage( Graph calls, string[] names, int[] packageOf, int storage, int main){ var search = new AvoidingStorage(calls, names, packageOf, storage); search.Run(main); // search.Reached: [main, parseArgs, run, load, parse, save, format, show] // search.Recursive: [parse -> parse, format -> format] return new WithoutStorageResult(search.Reached, search.Recursive);}reachedreachedreachedReached lists eight methods, in the
order in which the search enters them. read and write are missing because the hook skips the
calls to them. The calls parse -> parse and format -> format lead to a method on the current
path. They close a cycle, and
recursiverecursiverecursiveRecursive lists them.
Good to know
Section titled “Good to know”- The default follows an edge to a target not visited yet and skips any other edge.
super.visitEdge(...)EdgeAction::default_for(state)super.visitEdge(...)base.VisitEdge(...)returns this default, as at the end of the hook in the example. - States.
ON_STACKOnStackTargetState.ON_STACKOnStackmeans that the target is on the current path, so the edge closes a cycle. Such an edge is a back edge.FINISHEDFinishedTargetState.FINISHEDFinishedmeans that the search has left the target already. It does not tell a forward edge from a cross edge. To tell them apart, see Classify the edges of a depth-first search. - Edge data. The edge index comes with every edge, so you can read the data in your arrays.
- As in a depth-first search of nodes. See
Write a depth-first search without recursion for that search.
leaveNodeleave_nodeleaveNodeLeaveNode,isVisitedis_visitedisVisitedIsVisited,isOnStackis_on_stackisOnStackIsOnStackandstopstopstopStopwork the same way here. So do the runs:run(int)run_fromrun(startNode: number)Run(int)from one start node,run(IntList)run_from_nodesrun(startNodes: IntList)Run(ReadOnlySpan<int>)from several andrun()runrun()Run()from every node not visited yet. Where hooks for the nodes suffice,DfsTraverserDfsTraverserDfsTraverserDfsTraverseris faster.
API used
Section titled “API used”DfsEdgeTraverser.visitEdge(int, int, int, DfsEdgeTraverser.TargetState)DfsEdgeHooks::visit_edgeDfsEdgeTraverser.visitEdgeDfsEdgeTraverser.VisitEdgeDfsEdgeTraverser.enterNode(int)DfsEdgeHooks::enter_nodeDfsEdgeTraverser.enterNodeDfsEdgeTraverser.EnterNodeDfsEdgeTraverser.run(int)DfsEdgeTraverser::run_fromDfsEdgeTraverser.run(startNode: number)DfsEdgeTraverser.Run(int)DfsEdgeTraverser.run(IntList)DfsEdgeTraverser::run_from_nodesDfsEdgeTraverser.run(startNodes: IntList)DfsEdgeTraverser.Run(ReadOnlySpan<int>)DfsEdgeTraverser.run()DfsEdgeTraverser::runDfsEdgeTraverser.run()DfsEdgeTraverser.Run()DfsEdgeTraverser.leaveNode(int)DfsEdgeHooks::leave_nodeDfsEdgeTraverser.leaveNodeDfsEdgeTraverser.LeaveNodeDfsEdgeTraverser.isVisited(int)DfsControl::is_visitedDfsEdgeTraverser.isVisitedDfsEdgeTraverser.IsVisitedDfsEdgeTraverser.isOnStack(int)DfsControl::is_on_stackDfsEdgeTraverser.isOnStackDfsEdgeTraverser.IsOnStackDfsEdgeTraverser.stop()DfsControl::stopDfsEdgeTraverser.stopDfsEdgeTraverser.Stop