Files

88 lines
3.7 KiB
Python

"""Python functions of a source text, measured with the same five measures as the Rust ones (see rmetrics).
complexity = 1 + `if`, conditional expression, `for`, `while`, `except`, `match` case, comprehension (and each of its
`if`s) and every extra operand of `and`/`or`. nesting = the deepest chain of compound statements (`if`, loops, `try`,
`with`, `match`) inside the body; an `elif` chain is flat. Nested functions and classes are measured on their own.
"""
import ast
from .model import Fn, count_wide
DEFS = (ast.FunctionDef, ast.AsyncFunctionDef)
SCOPES = DEFS + (ast.ClassDef,)
BRANCH_NAMES = ("If", "IfExp", "For", "AsyncFor", "While", "ExceptHandler", "match_case")
BRANCH_NODES = tuple(getattr(ast, name) for name in BRANCH_NAMES if hasattr(ast, name))
COMPOUND = tuple(getattr(ast, name) for name in ("If", "For", "AsyncFor", "While", "Try", "With", "AsyncWith", "Match")
if hasattr(ast, name))
def own_nodes(node):
"""Every node inside `node` that does not belong to a nested function or class."""
stack = list(ast.iter_child_nodes(node))
while stack:
current = stack.pop()
yield current
if not isinstance(current, SCOPES):
stack.extend(ast.iter_child_nodes(current))
def _points(node):
if isinstance(node, BRANCH_NODES):
return 1
if isinstance(node, ast.BoolOp):
return len(node.values) - 1
if isinstance(node, ast.comprehension):
return 1 + len(node.ifs)
return 0
def complexity(fn):
return 1 + sum(_points(node) for node in own_nodes(fn) if not isinstance(node, SCOPES))
def _blocks(stmt):
"""[(statements, extra depth)] for the lists a compound statement owns; an `elif` stays on the level of its `if`."""
if isinstance(stmt, ast.Try):
lists = [stmt.body, stmt.orelse, stmt.finalbody] + [handler.body for handler in stmt.handlers]
return [(block, 1) for block in lists]
if hasattr(stmt, "cases"):
return [(case.body, 1) for case in stmt.cases]
orelse = getattr(stmt, "orelse", [])
elif_chain = isinstance(stmt, ast.If) and len(orelse) == 1 and isinstance(orelse[0], ast.If)
return [(stmt.body, 1), (orelse, 0 if elif_chain else 1)]
def nesting(stmts, depth=0):
"""The deepest nesting of compound statements in a statement list (`depth` is the level of the list)."""
compound = [stmt for stmt in stmts if isinstance(stmt, COMPOUND)]
inner = [nesting(block, depth + extra) for stmt in compound for block, extra in _blocks(stmt)]
return max([depth] + inner)
def param_count(fn):
"""Parameters of a def: positional, keyword-only, `*args` and `**kwargs`; `self` and `cls` count."""
args = fn.args
named = len(args.posonlyargs) + len(args.args) + len(args.kwonlyargs)
return named + (args.vararg is not None) + (args.kwarg is not None)
def _collect(body, chain, test, found):
for node in body:
if isinstance(node, SCOPES):
name = ".".join(chain + [node.name])
if isinstance(node, DEFS):
found.append((name, node, test))
_collect(node.body, chain + [node.name], test, found)
def scan(text, wide, test=False):
"""[Fn] of a Python source text; a repeated key gets `#2`, `#3`."""
found, seen, result = [], {}, []
_collect(ast.parse(text).body, [], test, found)
for name, node, is_test in sorted(found, key=lambda item: item[1].lineno):
seen[name] = seen.get(name, 0) + 1
key = name + (f"#{seen[name]}" if seen[name] > 1 else "")
end = node.end_lineno
result.append(Fn(key, node.lineno, end, end - node.lineno + 1, complexity(node), nesting(node.body),
count_wide(wide, node.lineno, end), is_test, param_count(node)))
return result