Files
kdm-re/tools/wave/scc.py
T

124 lines
4.7 KiB
Python

"""Strongly-connected-component grouping for the call graph.
docs/reconstruction-loop.md 3a's globals-first gate cannot clear a mutually
recursive cycle one function at a time: A needs B verified first, B needs A.
Tarjan's algorithm collapses every such cycle into one component id, so a
dispatcher treats it as one all-or-nothing claim and verification unit instead
of deadlocking on the gate or trying to find a linear order for it.
The component's members are marked ``verified`` together only after their
combined differential passes, run with the members together because neither
can satisfy "all callees verified first" alone. This is an exception to the
globals-first gate's literal wording only for callees inside the component.
Every callee and every read-global outside the component must still be verified
first before the component qualifies.
"""
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
from __future__ import annotations
import argparse
import json
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Generic, TypeVar
Node = TypeVar("Node")
@dataclass(frozen=True, slots=True)
class SccResult(Generic[Node]):
component_of: dict[Node, int]
components: tuple[tuple[Node, ...], ...]
@dataclass(slots=True) # noqa: MUTABLE_OK - DFS accumulator mutated through the walk
class _TarjanState(Generic[Node]):
counter: int = 0
indices: dict[Node, int] = field(default_factory=dict)
low_links: dict[Node, int] = field(default_factory=dict)
on_stack: dict[Node, bool] = field(default_factory=dict)
path: list[Node] = field(default_factory=list)
components: list[tuple[Node, ...]] = field(default_factory=list)
def next_index(self) -> int:
value = self.counter
self.counter += 1
return value
def _strong_connect(start: Node, graph: dict[Node, tuple[Node, ...]], state: _TarjanState[Node]) -> None:
work: list[tuple[Node, int]] = [(start, 0)]
state.indices[start] = state.low_links[start] = state.next_index()
state.path.append(start)
state.on_stack[start] = True
while work:
node, child_index = work[-1]
children = graph.get(node, ())
if child_index < len(children):
work[-1] = (node, child_index + 1)
child = children[child_index]
if child not in state.indices:
state.indices[child] = state.low_links[child] = state.next_index()
state.path.append(child)
state.on_stack[child] = True
work.append((child, 0))
elif state.on_stack.get(child, False):
state.low_links[node] = min(state.low_links[node], state.indices[child])
continue
work.pop()
if work:
parent, _ = work[-1]
state.low_links[parent] = min(state.low_links[parent], state.low_links[node])
if state.low_links[node] == state.indices[node]:
members: list[Node] = []
while True:
member = state.path.pop()
state.on_stack[member] = False
members.append(member)
if member == node:
break
state.components.append(tuple(members))
def tarjan_scc(graph: dict[Node, tuple[Node, ...]]) -> SccResult[Node]:
"""Iterative Tarjan's algorithm: no Python call-stack recursion limit on deep chains."""
state: _TarjanState[Node] = _TarjanState()
for start in graph:
if start not in state.indices:
_strong_connect(start, graph, state)
component_of = {node: i for i, members in enumerate(state.components) for node in members}
return SccResult(component_of=component_of, components=tuple(state.components))
def cyclic_components(result: SccResult[Node]) -> tuple[tuple[Node, ...], ...]:
"""Components with more than one member: a real mutual-recursion unit."""
return tuple(members for members in result.components if len(members) > 1)
def main() -> int:
parser = argparse.ArgumentParser(
description="Group a call graph's functions into SCC claim units.",
)
parser.add_argument(
"graph_json", type=Path,
help="JSON object mapping node -> list of callee nodes (e.g. an adjacency fixture)",
)
args = parser.parse_args()
with args.graph_json.open(encoding="utf-8") as source:
raw: dict[str, list[str]] = json.load(source)
graph: dict[str, tuple[str, ...]] = {node: tuple(callees) for node, callees in raw.items()}
result = tarjan_scc(graph)
cycles = cyclic_components(result)
print(f"nodes={len(graph)} components={len(result.components)} cycles={len(cycles)}")
for members in cycles:
print(f" cycle unit: {sorted(members)}")
return 0
if __name__ == "__main__":
sys.exit(main())