Files
claude-config/bin/metric_bench/python_units.py
T

101 lines
4.7 KiB
Python

import ast
import collections
import dataclasses
import sys
from failure import Failure
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
@dataclasses.dataclass(frozen=True)
class Unit:
path: str
name: str
cognitive: int
length: int
shared_state: int
def measured(path: str) -> bool:
"""A Python file outside the tests."""
folders, _, name = path.rpartition("/")
return name.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in folders.split("/")
def python_units(path: str, source: str) -> list[Unit] | Failure:
"""Each module-level function and each method in source, with its metrics."""
try:
tree = ast.parse(source)
except (SyntaxError, ValueError) as failure:
return Failure(f"could not parse {path} on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}")
units = []
for node in tree.body:
if isinstance(node, FUNCTION):
units.append(unit(path, node, 0))
elif isinstance(node, ast.ClassDef):
shared = shared_writes(node)
units += [unit(path, method, shared[method.name]) for method in node.body if isinstance(method, FUNCTION)]
return units
def unit(path: str, node: ast.FunctionDef | ast.AsyncFunctionDef, shared: int) -> Unit:
globals_written = sum(len(statement.names) for statement in ast.walk(node) if isinstance(statement, ast.Global | ast.Nonlocal))
return Unit(path, node.name, cognitive(node), (node.end_lineno or node.lineno) - node.lineno + 1, shared + globals_written)
def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]:
"""For each method, how many of the attributes it writes on self another method of the class writes too."""
writers = collections.defaultdict(set)
for method in cls.body:
if isinstance(method, FUNCTION):
for node in ast.walk(method):
for target in written(node):
if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
writers[target.attr].add(method.name)
return collections.Counter(method for methods in writers.values() if len(methods) > 1 for method in methods)
def written(node: ast.AST) -> list[ast.expr]:
if isinstance(node, ast.Assign):
return node.targets
return [node.target] if isinstance(node, ast.AugAssign | ast.AnnAssign) else []
# SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition.
def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int:
return sum(score(node, 0, function.name) for node in function.body)
def score(node: ast.AST, nesting: int, name: str) -> int:
"""The cognitive complexity node adds at nesting depth nesting, its children included; name is the function's own, a call to it counting as recursion."""
def inside(nodes: list, depth: int = nesting + 1) -> int:
return sum(score(child, depth, name) for child in nodes)
if isinstance(node, ast.If):
return 1 + nesting + branches(node, nesting, name)
if isinstance(node, ast.For | ast.AsyncFor | ast.While):
head = node.test if isinstance(node, ast.While) else node.iter
return 1 + nesting + score(head, nesting, name) + inside(node.body) + (1 + inside(node.orelse) if node.orelse else 0)
if isinstance(node, ast.Try | ast.TryStar):
handlers = sum(1 + nesting + inside(handler.body) for handler in node.handlers)
return inside(node.body, nesting) + handlers + inside(node.orelse, nesting) + inside(node.finalbody, nesting)
if isinstance(node, ast.Match):
return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body) for case in node.cases)
if isinstance(node, ast.IfExp):
return 1 + nesting + inside([node.test, node.body, node.orelse])
if isinstance(node, ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp):
return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)))
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
return inside(node.body if isinstance(node.body, list) else [node.body])
own = 1 if isinstance(node, ast.BoolOp) or isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name else 0
return own + inside(list(ast.iter_child_nodes(node)), nesting)
def branches(node: ast.If, nesting: int, name: str) -> int:
"""An if's test and bodies; an elif or else adds 1 at no extra depth."""
total = score(node.test, nesting, name) + sum(score(child, nesting + 1, name) for child in node.body)
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
return total + 1 + branches(node.orelse[0], nesting, name)
return total + (1 + sum(score(child, nesting + 1, name) for child in node.orelse) if node.orelse else 0)