Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): don't plan Extract Method spans over match arms, and bind pattern captures (#3782)
Yunus Ozen72d8e373096c
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.pyindex 4be873583..dbd211271 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py@@ -220,6 +220,9 @@ class PythonDefUseDialect(BaseDefUseDialect):if t in _CONDITIONAL_KINDS:self._process_may_def(node, defs, uses)return+ if t == "case_pattern":+ self._pattern(node, defs, uses)+ returnif t in self.member_access_kinds:self.collect_reads(node, uses) # receiver is a read; member is notreturn@@ -235,6 +238,55 @@ class PythonDefUseDialect(BaseDefUseDialect):for child in node.named_children:self._process(child, defs, uses)+ def _pattern(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ """A ``match`` pattern: a bare name captures (a def), a dotted name is a+ value pattern (its head is a read), and a class pattern's class is a read.+ ``_``, keyword names and literal keys bind nothing."""+ t = node.type+ if t == "dotted_name":+ parts = [c for c in node.named_children if c.type in self.identifier_kinds]+ if len(parts) == 1:+ if node_text(parts[0]) != "_":+ defs.append(self._occ(parts[0]))+ else:+ self._value_name(node, uses)+ return+ if t in ("splat_pattern", "as_pattern"):+ for child in node.named_children:+ if child.type in self.identifier_kinds:+ if node_text(child) != "_":+ defs.append(self._occ(child))+ else:+ self._pattern(child, defs, uses)+ return+ if t == "keyword_pattern":+ # ``x=px``: ``x`` names the attribute, only the pattern after it binds.+ for child in node.named_children[1:]:+ self._pattern(child, defs, uses)+ return+ if t == "class_pattern":+ cls, *args = node.named_children+ self._value_name(cls, uses)+ for child in args:+ self._pattern(child, defs, uses)+ return+ if t == "dict_pattern":+ # Keys are values (``Const.K: v`` reads ``Const``); the patterns bind.+ for child in node.named_children:+ if child.type == "dotted_name":+ self._value_name(child, uses)+ else:+ self._pattern(child, defs, uses)+ return+ for child in node.named_children:+ self._pattern(child, defs, uses)++ def _value_name(self, node: Node, uses: list[Occurrence]) -> None:+ """``Color.RED`` or ``mod.Point`` in a pattern reads its first name only."""+ head = next((c for c in node.named_children if c.type in self.identifier_kinds), None)+ if head is not None:+ uses.append(self._occ(head))+def _import_binds(self, node: Node, defs: list[Occurrence]) -> None:"""``import a.b`` binds ``a``, ``... as c`` binds ``c``, ``from mimport n`` binds ``n``; a ``*`` import binds nothing it names."""diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 8ebc884f2..c6eb59363 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -215,6 +215,11 @@ def find_extractions(evaluated = 0for block, loop in all_blocks(fn_node, lmap.block_kinds, scope_kinds, lmap.loop_kinds):stmts = block.named_children+ # A match/switch body holds the arms, not statements: a span of them is+ # neither a function body nor a valid call site. Each arm's own body is+ # still a block of its own.+ if any(stmt.type in lmap.case_kinds for stmt in stmts):+ continuen = len(stmts)resources = _scoped_resource_indexes(stmts, lmap)is_body = block.id == body_container.iddiff --git a/tests/unit/health/test_python_match_patterns.py b/tests/unit/health/test_python_match_patterns.pynew file mode 100644index 000000000..48aca589b--- /dev/null+++ b/tests/unit/health/test_python_match_patterns.py@@ -0,0 +1,89 @@+"""Python ``match`` in the dataflow layer (#3473).++The arms of a ``match`` are not statements, so Extract Method must not offer a+span made of ``case`` clauses. And a pattern binds the names it captures, so+those are definitions, not reads; the names it only refers to (a class, a+dotted value, a keyword) are not.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.dataflow import analyze_file, find_extractions++KINDS = ["open", "close", "write", "flush", "sync", "seek", "tell", "stat"]+ARM = """ case ("{kind}", name, data):+ if data:+ out.{kind}(name, data)+ elif name:+ out.{kind}(name)+ else:+ log.warn("{kind}")+ log.info(name)+"""+BIG_MATCH = (+ "def handle(event, out, log):\n log.info(event)\n match event:\n"+ + "".join(ARM.format(kind=kind) for kind in KINDS)+ + " case _:\n log.warn(event)\n out.sync()\n return out\n"+)++PATTERNS = """def f(event):+ match event:+ case ("open", name, data):+ print(name, data)+ case Point(x=px, y=py) as pt:+ print(px, py, pt)+ case [a, *others]:+ print(a, others)+ case {"k": c, **kw}:+ print(c, kw)+ case Color.RED | other if other > 3:+ print(other)+ case _:+ pass+"""+++def _analysis(source: str):+ result = analyze_file("m.py", "python", source.encode(), flagged_only=False)+ if result.stats.functions_seen == 0:+ pytest.skip("tree-sitter language pack missing for python")+ (analysis,) = result.functions+ return analysis+++def _case_lines(source: str) -> set[int]:+ return {+ i for i, row in enumerate(source.splitlines(), start=1) if row.lstrip().startswith("case ")+ }+++def test_no_extraction_span_is_made_of_case_clauses() -> None:+ analysis = _analysis(BIG_MATCH)+ case_lines = _case_lines(BIG_MATCH)++ extractions = find_extractions(analysis, get_language_map("python"))++ assert extractions, "the arms' own bodies should still be candidates"+ assert not [x for x in extractions if x.start_line in case_lines]+++def test_pattern_captures_are_definitions() -> None:+ analysis = _analysis(PATTERNS)++ defined = {d.var for d in analysis.def_use.definitions}++ assert {"name", "data", "px", "py", "pt", "a", "others", "c", "kw", "other"} <= defined+ # A keyword names an attribute, a class or dotted name is a value, ``_`` binds nothing.+ assert not defined & {"x", "y", "Point", "Color", "RED", "_"}+++def test_pattern_value_names_are_reads() -> None:+ analysis = _analysis(PATTERNS)++ read = {u.name for block in analysis.def_use.blocks.values() for u in block.uses}++ assert {"Point", "Color"} <= read+ assert not read & {"x", "y", "RED"}