128 lines
5.6 KiB
Python
128 lines
5.6 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 of a module-level class in source, with its metrics."""
|
|
try:
|
|
tree = ast.parse(source)
|
|
except (SyntaxError, ValueError) as failure:
|
|
return Failure(f"{path} does not parse 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):
|
|
targets = node.targets
|
|
elif isinstance(node, ast.AugAssign | ast.AnnAssign | ast.For | ast.AsyncFor | ast.comprehension):
|
|
targets = [node.target]
|
|
elif isinstance(node, ast.withitem) and node.optional_vars:
|
|
targets = [node.optional_vars]
|
|
else:
|
|
return []
|
|
return [leaf for target in targets for leaf in assigned(target)]
|
|
|
|
|
|
def assigned(target: ast.expr) -> list[ast.expr]:
|
|
"""What a target writes: each part of an unpacking, and for `x[i] = …` the x."""
|
|
if isinstance(target, ast.Tuple | ast.List):
|
|
return [leaf for element in target.elts for leaf in assigned(element)]
|
|
if isinstance(target, ast.Starred | ast.Subscript):
|
|
return assigned(target.value)
|
|
return [target]
|
|
|
|
|
|
# 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 inside(function.body, 0, function.name)
|
|
|
|
|
|
# One case per node type, as the white paper gives one rule per structure.
|
|
def score(node: ast.AST, nesting: int, name: str) -> int:
|
|
"""The cognitive complexity `node` adds, its children included, at nesting depth `nesting`; a call to `name`, the function's own, counts as recursion."""
|
|
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, nesting + 1, name) + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0)
|
|
if isinstance(node, ast.Try | ast.TryStar):
|
|
handlers = sum(1 + nesting + inside(handler.body, nesting + 1, name) for handler in node.handlers)
|
|
return inside(node.body + node.orelse + node.finalbody, nesting, name) + handlers
|
|
if isinstance(node, ast.Match):
|
|
return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body, nesting + 1, name) for case in node.cases)
|
|
if isinstance(node, ast.IfExp):
|
|
return 1 + nesting + inside([node.test, node.body, node.orelse], nesting + 1, name)
|
|
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)), nesting + 1, name)
|
|
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
|
|
return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name)
|
|
return (isinstance(node, ast.BoolOp) or called(node) == name) + inside(list(ast.iter_child_nodes(node)), nesting, name)
|
|
|
|
|
|
def called(node: ast.AST) -> str | None:
|
|
"""The function a call names, or the method it calls on self."""
|
|
if not isinstance(node, ast.Call):
|
|
return None
|
|
if isinstance(node.func, ast.Name):
|
|
return node.func.id
|
|
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == "self":
|
|
return node.func.attr
|
|
return None
|
|
|
|
|
|
def inside(nodes: list, nesting: int, name: str) -> int:
|
|
return sum(score(node, nesting, name) for node in nodes)
|
|
|
|
|
|
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) + inside(node.body, nesting + 1, name)
|
|
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
|
|
return total + 1 + branches(node.orelse[0], nesting, name)
|
|
return total + (1 + inside(node.orelse, nesting + 1, name) if node.orelse else 0)
|