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:
@@ -38,18 +38,20 @@ def co_changed(log: str) -> dict[str, int]:
|
||||
return {path: len(others) for path, others in partners.items()}
|
||||
|
||||
|
||||
def bench(units: list[Unit], places: list[Place], spread: dict[str, int]) -> RunScores | None:
|
||||
"""How well each metric ranks the units the seats named above the rest; None when no named place is a measured unit."""
|
||||
def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[str, int]) -> RunScores | None:
|
||||
"""How well each metric ranks the units the seats named above the rest; None when the named units are none or all of them. unresolved counts the places that named no tracked file."""
|
||||
names = {(place.path, place.name) for place in places}
|
||||
named = [unit for unit in units if (unit.path, unit.name) in names]
|
||||
if not named or len(named) == len(units):
|
||||
return None
|
||||
rest = [unit for unit in units if (unit.path, unit.name) not in names]
|
||||
measured = {(unit.path, unit.name) for unit in named}
|
||||
unmeasured = len({place for place in places if (place.path, place.name) not in measured})
|
||||
found = {(unit.path, unit.name) for unit in named}
|
||||
unmeasured = unresolved + len({place for place in places if (place.path, place.name) not in found})
|
||||
scores = {}
|
||||
for metric, value in METRICS.items():
|
||||
scores[metric] = Score(auc([value(unit, spread) for unit in named], [value(unit, spread) for unit in rest]), top_k(units, named, lambda unit: value(unit, spread)))
|
||||
named_values = [value(unit, spread) for unit in named]
|
||||
rest_values = [value(unit, spread) for unit in rest]
|
||||
scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values))
|
||||
return RunScores(len(units), len(named), unmeasured, scores)
|
||||
|
||||
|
||||
@@ -59,10 +61,15 @@ def auc(named: list[int], rest: list[int]) -> float:
|
||||
return wins / (len(named) * len(rest))
|
||||
|
||||
|
||||
def top_k(units: list[Unit], named: list[Unit], value: Callable[[Unit], int]) -> float:
|
||||
"""The share of the metric's top k units the seats named, k being how many they named; a tie at the cut counts in order of the units."""
|
||||
top = sorted(units, key=value, reverse=True)[:len(named)]
|
||||
return sum(unit in named for unit in top) / len(named)
|
||||
def top_k(named: list[int], rest: list[int]) -> float:
|
||||
"""The share of the metric's k highest units the seats named, k being how many they named. Units tied at the cut share its remaining seats evenly, as a random order of them would."""
|
||||
k = len(named)
|
||||
cut = sorted(named + rest, reverse=True)[k - 1]
|
||||
above = sum(value > cut for value in named)
|
||||
seats = k - above - sum(value > cut for value in rest)
|
||||
tied_named = sum(value == cut for value in named)
|
||||
tied = tied_named + sum(value == cut for value in rest)
|
||||
return (above + seats * tied_named / tied) / k
|
||||
|
||||
|
||||
def medians(runs: list[RunScores]) -> dict[str, Score]:
|
||||
|
||||
@@ -15,7 +15,9 @@ medians. Places that name no Python function or method, such as a section of a m
|
||||
counted as unmeasured.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
|
||||
history cannot be read, a run's commit is missing, or no scoring run names a measured unit.
|
||||
history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A
|
||||
run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the
|
||||
table.
|
||||
"""
|
||||
import pathlib
|
||||
import subprocess
|
||||
@@ -23,7 +25,7 @@ import sys
|
||||
|
||||
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score
|
||||
from failure import Failure
|
||||
from metric_bench.python_units import measured, python_units
|
||||
from metric_bench.python_units import measured, python_units, Unit
|
||||
from metric_bench.places import resolved, scoring_runs, ScoringRun
|
||||
|
||||
|
||||
@@ -45,15 +47,20 @@ def main(argv: list[str]) -> int:
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return failed(Failure(f"could not read {history}: {failure}"))
|
||||
rows = []
|
||||
gone = []
|
||||
for run in scoring_runs(text):
|
||||
if isinstance(git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
|
||||
gone.append(run.heading)
|
||||
continue
|
||||
scores = run_scores(run, top)
|
||||
if isinstance(scores, Failure):
|
||||
return failed(scores)
|
||||
if scores:
|
||||
rows.append((run.heading, scores))
|
||||
skipped = "".join(f"\nSkipped, its commit is not in {top}: {heading}" for heading in gone)
|
||||
if not rows:
|
||||
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures"))
|
||||
print(table(rows))
|
||||
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md → \"History\"{skipped}"))
|
||||
print(table(rows) + ("\n" + skipped if skipped else ""))
|
||||
return 0
|
||||
|
||||
|
||||
@@ -62,16 +69,20 @@ def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure:
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
tracked = listed.split("\n")
|
||||
units = []
|
||||
units: list[Unit] = []
|
||||
for path in filter(measured, tracked):
|
||||
source = git(["show", f"{run.commit}:{path}"], top)
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
units += python_units(path, source)
|
||||
found = python_units(path, source)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
units += found
|
||||
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
return bench(units, resolved(run.places, tracked), co_changed(log))
|
||||
places = resolved(run.places, tracked)
|
||||
return bench(units, places, len(run.places) - len(places), co_changed(log))
|
||||
|
||||
|
||||
def table(rows: list[tuple[str, RunScores]]) -> str:
|
||||
|
||||
@@ -4,6 +4,7 @@ import re
|
||||
|
||||
from markdown_sections import sections
|
||||
|
||||
# The format: skills/larv-review/SKILL.md §3 → "History", which names this reader.
|
||||
RUN = re.compile(r"^(.+), (.+) at ([0-9a-f]{7,40})$")
|
||||
SEAT_PLACES = re.compile(r"^.+, (hardest first|would restructure first):$")
|
||||
# `path:line` or `:line`, then the unit's name where one follows.
|
||||
|
||||
@@ -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