componentCycles function

List<List<String>> componentCycles(
  1. Map<String, Set<String>> calls
)

Every cycle in the call graph calls (type → the types it calls), each as the path from its first type back to it ([A, B, A]), reported once (from the type that sorts first in it).

Implementation

List<List<String>> componentCycles(Map<String, Set<String>> calls) {
  final out = <List<String>>[];
  final seen = <String>{};
  final onPath = <String>[];
  final state = <String, int>{}; // 1: on the path, 2: done
  void visit(String t) {
    state[t] = 1;
    onPath.add(t);
    for (final c in (calls[t] ?? const <String>{}).toList()..sort()) {
      if (state[c] == 1) {
        final cycle = [...onPath.sublist(onPath.indexOf(c)), c];
        // One report per cycle, rotated to start at its smallest type.
        final ring = cycle.sublist(0, cycle.length - 1);
        var start = 0;
        for (var i = 1; i < ring.length; i++) {
          if (ring[i].compareTo(ring[start]) < 0) start = i;
        }
        final rotated = [...ring.sublist(start), ...ring.sublist(0, start), ring[start]];
        if (seen.add(rotated.join('/'))) out.add(rotated);
      } else if (state[c] == null) {
        visit(c);
      }
    }
    onPath.removeLast();
    state[t] = 2;
  }

  for (final t in calls.keys.toList()..sort()) {
    if (state[t] == null) visit(t);
  }
  return out;
}