Answer architecture round 1: make cognitive complexity a pure recursion, share a tied top-k cut evenly, count unresolved places, skip a run whose commit is gone, fail on a file that does not parse, link the history's format and its reader both ways, reword item 85's order, and record the worse ruling
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import ast
|
||||
import collections
|
||||
import dataclasses
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
|
||||
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
@@ -20,12 +23,12 @@ def measured(path: str) -> bool:
|
||||
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]:
|
||||
"""Each module-level function and each method in source, with its metrics; a source that does not parse has none."""
|
||||
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):
|
||||
return []
|
||||
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):
|
||||
@@ -61,97 +64,37 @@ def written(node: ast.AST) -> list[ast.expr]:
|
||||
|
||||
# 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:
|
||||
counter = Cognitive(function.name)
|
||||
counter.within(function.body, 0)
|
||||
return counter.score
|
||||
return sum(score(node, 0, function.name) for node in function.body)
|
||||
|
||||
|
||||
class Cognitive(ast.NodeVisitor):
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
self.nesting = 0
|
||||
self.score = 0
|
||||
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)
|
||||
|
||||
def within(self, nodes: list, deeper: int = 1) -> None:
|
||||
self.nesting += deeper
|
||||
for node in nodes:
|
||||
self.visit(node)
|
||||
self.nesting -= deeper
|
||||
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 structure(self) -> None:
|
||||
self.score += 1 + self.nesting
|
||||
|
||||
def visit_If(self, node: ast.If) -> None:
|
||||
self.structure()
|
||||
self.branch(node)
|
||||
|
||||
def branch(self, node: ast.If) -> None:
|
||||
self.visit(node.test)
|
||||
self.within(node.body)
|
||||
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
|
||||
self.score += 1
|
||||
self.branch(node.orelse[0])
|
||||
elif node.orelse:
|
||||
self.score += 1
|
||||
self.within(node.orelse)
|
||||
|
||||
def loop(self, node: ast.For | ast.AsyncFor | ast.While, head: ast.expr) -> None:
|
||||
self.structure()
|
||||
self.visit(head)
|
||||
self.within(node.body)
|
||||
if node.orelse:
|
||||
self.score += 1
|
||||
self.within(node.orelse)
|
||||
|
||||
def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
|
||||
self.loop(node, node.iter)
|
||||
|
||||
visit_AsyncFor = visit_For
|
||||
|
||||
def visit_While(self, node: ast.While) -> None:
|
||||
self.loop(node, node.test)
|
||||
|
||||
def visit_Try(self, node: ast.Try | ast.TryStar) -> None:
|
||||
self.within(node.body, 0)
|
||||
for handler in node.handlers:
|
||||
self.structure()
|
||||
self.within(handler.body)
|
||||
self.within(node.orelse, 0)
|
||||
self.within(node.finalbody, 0)
|
||||
|
||||
visit_TryStar = visit_Try
|
||||
|
||||
def visit_Match(self, node: ast.Match) -> None:
|
||||
self.structure()
|
||||
self.visit(node.subject)
|
||||
for case in node.cases:
|
||||
self.within(case.body)
|
||||
|
||||
def visit_IfExp(self, node: ast.IfExp) -> None:
|
||||
self.structure()
|
||||
self.within([node.test, node.body, node.orelse])
|
||||
|
||||
def visit_BoolOp(self, node: ast.BoolOp) -> None:
|
||||
self.score += 1
|
||||
self.generic_visit(node)
|
||||
|
||||
def comprehension(self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp) -> None:
|
||||
for generator in node.generators:
|
||||
self.structure()
|
||||
self.score += len(generator.ifs)
|
||||
self.within(list(ast.iter_child_nodes(node)))
|
||||
|
||||
visit_DictComp = visit_GeneratorExp = visit_ListComp = visit_SetComp = comprehension
|
||||
|
||||
def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
||||
self.within(node.body)
|
||||
|
||||
visit_AsyncFunctionDef = visit_FunctionDef
|
||||
|
||||
def visit_Lambda(self, node: ast.Lambda) -> None:
|
||||
self.within([node.body])
|
||||
|
||||
def visit_Call(self, node: ast.Call) -> None:
|
||||
if isinstance(node.func, ast.Name) and node.func.id == self.name:
|
||||
self.score += 1
|
||||
self.generic_visit(node)
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user