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): give Extract Method plans only the inputs their span uses (#3357)
Raghav Chamadiya6096e29ad331
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py b/packages/core/src/repowise/core/analysis/health/dataflow/defuse.pyindex 4db5bfc39..4b52464f1 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/defuse.py@@ -47,6 +47,8 @@ class Definition:declared_at: int | None = None#: The write declares the name (``Occurrence.declares``).declares: bool = False+ #: An import binds the name (``Occurrence.imports``).+ imports: bool = False@dataclass@@ -107,6 +109,7 @@ def compute_def_use(column=occ.column,declared_at=occ.declared_at,declares=occ.declares,+ imports=occ.imports,)counter += 1bdu.defs.append(definition)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.pyindex 829895444..6c9e936e8 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py@@ -74,6 +74,9 @@ class Occurrence:#: header binder (:meth:`BaseDefUseDialect._loop_scoped`). Never a#: hoisting TS/JS ``var``.declares: bool = False+ #: A name an import statement binds (Python ``import a.b`` binds ``a``).+ #: A lifted span re-imports it rather than pass or return it.+ imports: bool = False@dataclass(frozen=True)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 702dab908..9b0f937dc 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@@ -3,11 +3,13 @@Classifies each identifier in a statement as a write (def) or a read (use).Python's write sites are: assignment LHS (``x = ...``), augmented-assignment LHS(``x += ...`` -- both read and write), tuple/list unpacking (``a, b = ...``),-the walrus operator (``(x := ...)``), ``for`` targets (statement and-comprehension), and ``with ... as`` aliases. Attribute and subscript targets-(``obj.attr = ...`` / ``arr[i] = ...``) bind no *local* variable, so their base-identifiers are reads, not defs -- the precision-first choice that keeps reaching-definitions sound for the locals they actually track.+the walrus operator (``(x := ...)``), ``for`` targets, and ``with ... as``+aliases. A comprehension's ``for`` targets are scoped to the comprehension+(Python 3), so they are neither the function's writes nor its reads.+Attribute and subscript targets (``obj.attr = ...`` / ``arr[i] = ...``) bind+no *local* variable, so their base identifiers are reads, not defs -- the+precision-first choice that keeps reaching definitions sound for the locals+they actually track.All grammar specifics live here; the core (``defuse.py`` / ``reaching.py``) andthe reaching-definitions fixpoint are language-agnostic.@@ -15,9 +17,17 @@ the reaching-definitions fixpoint are language-agnostic.from __future__ import annotations+from dataclasses import replacefrom typing import TYPE_CHECKING-from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse+from .base import (+ NO_RECEIVER,+ BaseDefUseDialect,+ Captured,+ Occurrence,+ Receiver,+ StatementDefUse,+)if TYPE_CHECKING:from tree_sitter import Node@@ -40,6 +50,11 @@ _SPLAT_TARGETS = frozenset({"list_splat_pattern", "dictionary_splat_pattern", "l_SUBSCRIPT_KINDS = frozenset({"subscript"})# Nested scopes whose identifiers belong to a different function._SCOPE_BOUNDARIES = frozenset({"lambda", "function_definition", "async_function_definition"})+_COMPREHENSIONS = frozenset(+ {"list_comprehension", "set_comprehension", "dictionary_comprehension", "generator_expression"}+)+# A module path is not a read; an import writes only the names it binds.+_IMPORT_KINDS = frozenset({"import_statement", "import_from_statement"})class PythonDefUseDialect(BaseDefUseDialect):@@ -153,9 +168,13 @@ class PythonDefUseDialect(BaseDefUseDialect):self._targets(node.child_by_field_name("name"), defs, uses)self._process(node.child_by_field_name("value"), defs, uses)return- if t == "for_in_clause": # comprehension ``for <target> in <iter>``- self._targets(node.child_by_field_name("left"), defs, uses)- self._process(node.child_by_field_name("right"), defs, uses)+ if t in _COMPREHENSIONS:+ self._comprehension(node, defs, uses)+ return+ if t in _IMPORT_KINDS:+ self._import_binds(node, defs)+ return+ if t == "future_import_statement":returnif t == "with_item":self._with_item(node, defs, uses)@@ -175,6 +194,59 @@ class PythonDefUseDialect(BaseDefUseDialect):for child in node.named_children:self._process(child, defs, uses)+ def _import_binds(self, node: Node, defs: list[Occurrence]) -> None:+ """``import a.b`` binds ``a``, ``... as c`` binds ``c``, ``from m+ import n`` binds ``n``; a ``*`` import binds nothing it names."""+ start = len(defs)+ for i, child in enumerate(node.children):+ if node.field_name_for_child(i) != "name":+ continue+ bound = child.child_by_field_name("alias") or child+ if bound.type == "dotted_name" and bound.named_children:+ bound = bound.named_children[0]+ if bound.type in self.identifier_kinds:+ defs.append(replace(self._occ(bound), imports=True))+ self._declare(defs, start, node, binds=False)++ def _comprehension(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:+ """Only the first iterable runs in the enclosing scope; every other read+ of a name a ``for`` clause binds is the comprehension's own, nested+ comprehensions and closures included (``[lambda: v for v in xs]``+ reads no outer ``v``; see :meth:`collect_captured`). A walrus inside+ still writes the enclosing scope (PEP 572)."""+ first_iterable, rest = _split_first_iterable(node)+ outer: list[Occurrence] = []+ inner: list[Occurrence] = []+ self._process(first_iterable, defs, outer)+ for child in rest:+ self._process(child, defs, inner)+ bound = self._comprehension_binders(node)+ kept = [*outer, *(u for u in inner if u.name not in bound)]+ uses.extend(sorted(kept, key=lambda u: (u.line, u.column)))++ def _comprehension_binders(self, node: Node) -> set[str]:+ binders: list[Occurrence] = []+ for child in node.named_children:+ if child.type == "for_in_clause":+ self._targets(child.child_by_field_name("left"), binders, [])+ return {b.name for b in binders}++ def collect_captured(self, node: Node | None, out: Captured, lmap: LanguageNodeMap) -> None:+ """Like the base, but a closure inside a comprehension reading one of+ its binders reads the comprehension's name, not the function's."""+ if node is None or node.type not in _COMPREHENSIONS:+ super().collect_captured(node, out, lmap)+ return+ first_iterable, rest = _split_first_iterable(node)+ self.collect_captured(first_iterable, out, lmap)+ inner = Captured()+ for child in rest:+ self.collect_captured(child, inner, lmap)+ bound = self._comprehension_binders(node)+ out.reads.extend(o for o in inner.reads if o.name not in bound)+ out.shared.extend(o for o in inner.shared if o.name not in bound)+ out.writes.extend(o for o in inner.writes if o.name not in bound)+def _with_item(self, node: Node, defs: list[Occurrence], uses: list[Occurrence]) -> None:value = node.child_by_field_name("value")if value is not None and value.type == "as_pattern":@@ -231,4 +303,22 @@ class PythonDefUseDialect(BaseDefUseDialect):return None+def _split_first_iterable(node: Node) -> tuple[Node | None, list[Node]]:+ """A comprehension's first iterable (evaluated in the enclosing scope) and+ every other part to walk: the body, later ``for`` clauses' iterables, the+ ``if`` filters. ``for`` targets are left out; they bind, not read."""+ first: Node | None = None+ rest: list[Node] = []+ for child in node.named_children:+ if child.type != "for_in_clause":+ rest.append(child)+ continue+ right = child.child_by_field_name("right")+ if first is None:+ first = right+ elif right is not None:+ rest.append(right)+ return first, rest++DIALECT = PythonDefUseDialect()diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.pyindex 99dbaba11..48a8deac8 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py@@ -218,7 +218,11 @@ class RustDefUseDialect(BaseDefUseDialect):self._process(node.child_by_field_name("right"), defs, uses)returnif t == _LET_DECL:+ start = len(defs)self._targets(node.child_by_field_name("pattern"), defs, uses)+ # ``let`` binds a new name (shadowing included) from the end of+ # the statement, so its own initializer reads the outer one.+ self._declare(defs, start, node)self._process(node.child_by_field_name("value"), defs, uses)# ``let ... else { diverge }``: the arm runs only on mismatch, so# anything it writes is a may-def.diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex d66359535..5735d6e52 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -407,11 +407,18 @@ def _var_lines(def_use: FunctionDefUse) -> tuple[dict[str, list[int]], dict[str,Parameter definitions are included (seeded at the signature line), so aparameter naturally counts as "defined before" any body span. Reads insidenested closures (``def_use.captured.reads``) count as uses at their own line.+ An import is not a def here: a helper re-imports a name rather than take+ or return it, and :func:`_declaration_escapes` refuses a span holding an+ import that later code still reads."""def_lines: dict[str, list[int]] = defaultdict(list)use_lines: dict[str, list[int]] = defaultdict(list)+ imported: set[str] = set()for d in def_use.definitions:- def_lines[d.var].append(d.line)+ if d.imports:+ imported.add(d.var)+ else:+ def_lines[d.var].append(d.line)for bdu in def_use.blocks.values():for u in bdu.uses:# A may-def's paired use is bookkeeping, not a read: counted, a@@ -421,7 +428,7 @@ def _var_lines(def_use: FunctionDefUse) -> tuple[dict[str, list[int]], dict[str,# A closure's read counts where the closure is written: lifting the code# around it moves the read with it. Only names this function binds matter.for u in def_use.captured.reads:- if u.name in def_lines:+ if u.name in def_lines or u.name in imported:use_lines[u.name].append(u.line)for lines in def_lines.values():lines.sort()@@ -697,12 +704,13 @@ def _declaration_lines(def_use: FunctionDefUse, *, binding: bool = False) -> dict[str, frozenset[int]]:"""Per variable, the lines that declare it (a ``let`` / ``var`` / ``:=`` /- typed local, as the dialect marks with ``declared_at``). With *binding*,- the lines that create a new binding instead (``declares``: multi-line- declarators and loop binders included, a TS/JS ``var`` not)."""+ typed local, as the dialect marks with ``declared_at``, or an import).+ With *binding*, the lines that create a new binding instead+ (``declares``: multi-line declarators and loop binders included, a TS/JS+ ``var`` not)."""lines: dict[str, set[int]] = defaultdict(set)for d in def_use.definitions:- if (d.declares if binding else d.declared_at is not None):+ if (d.declares if binding else d.declared_at is not None or d.imports):lines[d.var].add(d.line)return {var: frozenset(found) for var, found in lines.items()}diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.pyindex 4dad5094a..f024b247f 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py@@ -107,7 +107,7 @@ from .registry import RefactoringDetector, registerif TYPE_CHECKING:from ..complexity.languages import LanguageNodeMap- from ..dataflow import Extraction, FunctionAnalysis+ from ..dataflow import Definition, Extraction, FunctionAnalysisfrom ..dataflow.dialects.base import BaseDefUseDialect, Receiverfrom ..models import Severity@@ -357,7 +357,7 @@ def _render_fields(render.Slot(p, types.get(p), p in after) for p in extraction.params if p != own)returns = tuple(render.Slot(r, types.get(r)) for r in extraction.returns)- declared, before, rebound = _out_binding(analysis, extraction)+ declared, before, rebound = _out_binding(analysis, extraction, get_language_map(language or ""))fn_node = analysis.fn_nodetexts = render.render(render.HelperShape(@@ -432,20 +432,48 @@ def _read_after(analysis: FunctionAnalysis, extraction: Extraction) -> set[str]:def _out_binding(- analysis: FunctionAnalysis, extraction: Extraction+ analysis: FunctionAnalysis, extraction: Extraction, lmap: LanguageNodeMap | None) -> tuple[bool, bool, bool]:"""Whether the span's output is declared in it (the call must declare it:- an in-span declaration, or no write before the span), whether it was- written before the span, and whether it is written again after it."""+ a declaration among the span's own statements, or no write before the+ span), whether it was written before the span, and whether it is written+ again after it."""if not extraction.returns:return False, False, Falseout, s, e = extraction.returns[0], extraction.start_line, extraction.end_linewrites = [d for d in analysis.def_use.definitions if d.var == out]before = any(d.line < s for d in writes)- declared = any(s <= d.line <= e and d.declares for d in writes) or not before+ declared = (+ any(+ s <= d.line <= e and d.declares and _top_level_declaration(analysis, d, s, e, lmap)+ for d in writes+ )+ or not before+ )return declared, before, any(d.line > e for d in writes)+def _top_level_declaration(+ analysis: FunctionAnalysis, d: Definition, s: int, e: int, lmap: LanguageNodeMap | None+) -> bool:+ """Whether declaration *d* is one of the span's own statements. One in a+ block nested in the span (or a loop header binder) binds only there, so+ the outer name the call writes is not declared by it. True when the tree+ or the language map is missing (the old answer)."""+ fn_node = analysis.fn_node+ if fn_node is None or lmap is None:+ return True+ row = d.line - 1+ node = fn_node.descendant_for_point_range((row, d.column), (row, d.column + len(d.var.encode())))+ while node is not None and node.parent is not None and node.parent.type not in lmap.block_kinds:+ node = node.parent+ if node is None or node.parent is None or node.type not in lmap.local_decl_kinds:+ return False+ # The span's statements are siblings in one block: it starts at s, ends at e.+ rows = [(k.start_point[0] + 1, k.end_point[0] + 1) for k in node.parent.named_children]+ return any(lo == s for lo, _ in rows) and any(hi == e for _, hi in rows)++def _receiver_hazard(receiver: Receiver | None, uses: bool | None, assigns: tuple[str, ...] | None) -> str | None:diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex f53c183dd..08ef87481 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -2089,3 +2089,80 @@ def test_go_name_declared_afresh_after_the_span_does_not_refuse_it():lmap = get_language_map("go")fn = _first("go", src)assert any(e.start_line <= 7 and e.end_line >= 12 for e in find_extractions(fn, lmap))+++# == Rust ``let`` binds a new name ================================================+++def _rust_in_out(src: str, s: int, e: int):+ from repowise.core.analysis.health.dataflow import slice as slicing++ def_use = _first("rust", src).def_use+ def_lines, use_lines = slicing._var_lines(def_use)+ return slicing._infer_in_out(+ def_lines, use_lines, s, e, slicing._declared_before_read(def_use)+ )+++def test_rust_let_reading_the_name_it_shadows_keeps_it_an_input():+ src = """+ fn f(a: i32) -> i32 {+ let x = a * 2;+ println!("{}", x);+ let x = x + 1;+ let y = x * 3;+ y+ }+ """+ assert _rust_in_out(src, 5, 6) == (("x",), ("y",))+++def test_rust_let_else_binder_is_the_spans_own():+ src = """+ fn f(o: Option<i32>, k: i32) -> i32 {+ let base = k + 1;+ let Some(v) = o else { return 0; };+ let w = v + base;+ w+ }+ """+ assert _rust_in_out(src, 4, 5) == (("base", "o"), ("w",))+++def test_rust_nested_let_after_the_span_does_not_make_an_output():+ src = """+ fn f(a: i32, c: bool) -> i32 {+ let mut x = a;+ if c { x += 1; } else { x -= 1; }+ if a > 2 { x *= 2; }+ {+ let x = 5;+ println!("{}", x);+ }+ 0+ }+ """+ assert _rust_in_out(src, 3, 5) == (("a", "c"), ())+++def test_rust_span_splitting_a_closure_from_its_let_local_is_refused():+ fn = _first(+ "rust",+ """+ fn f(a: i32, c: bool) -> i32 {+ let mut n = 0;+ let mut inc = || n += 1;+ if c { inc(); } else { inc(); }+ if a > 1 { inc(); }+ n+ }+ """,+ )+ with pytest.MonkeyPatch.context() as mp:+ from repowise.core.analysis.health.dataflow import slice as slicing++ mp.setattr(slicing, "_MAX_BODY_SHARE", float("inf"))+ mp.setattr(slicing, "_MIN_SLICE_NLOC", 1)+ spans = find_extractions(fn, get_language_map("rust"))+ # The closure writes ``n``, so no span may hold it without ``n``'s reads.+ assert [(x.start_line, x.end_line) for x in spans] == [(5, 6)]diff --git a/tests/unit/health/test_dataflow_reaching.py b/tests/unit/health/test_dataflow_reaching.pyindex d7ddda8d6..e423eec86 100644--- a/tests/unit/health/test_dataflow_reaching.py+++ b/tests/unit/health/test_dataflow_reaching.py@@ -168,16 +168,79 @@ def test_walrus_is_def():assert "n" in defs-def test_comprehension_target_is_def():+def test_comprehension_target_is_scoped_to_the_comprehension():defs, uses = _def_use_names("""- def f(source):+ def f(source, pairs):data = [v * 2 for v in source if v > 0]- return data+ more = {k: [w for w in k] for k, _ in pairs if (n := len(k))}+ return data, more, n+ """+ )+ assert {"data", "more", "n"} <= defs+ assert not {"v", "k", "w"} & (defs | uses)+ assert {"source", "pairs"} <= uses+++def test_first_iterable_reads_the_enclosing_name():+ # Only the outermost iterable runs in the enclosing scope.+ _defs, uses = _def_use_names(+ """+ def f(v):+ return [v for v in v]+ """+ )+ assert "v" in uses+++ "expr",+ [+ "[w for v in xs for w in v]", # a later iterable reads an earlier target+ "[1 for v in xs if v]", # a filter reads a target+ "[[w + v for w in ys] for v in xs]", # a nested comprehension reads an outer one+ "[(lambda: v) for v in xs]", # a closure reads a target+ ],+)+def test_comprehension_reads_of_its_own_targets_stay_inside(expr):+ _cfg, def_use, _r = _analyze(+ f"""+ def f(xs, ys):+ v = w = 0+ out = {expr}+ return out, v, w+ """+ )+ in_line = [u.name for b in def_use.blocks.values() for u in b.uses if u.line == 4]+ captured = [u.name for u in def_use.captured.reads]+ assert not {"v", "w"} & {*in_line, *captured}+ assert "xs" in in_line+++def test_import_module_path_is_not_a_read():+ _defs, uses = _def_use_names(+ """+ def f(server):+ from repowise.server.mcp import Enricher+ import os.path as server_path+ return Enricher+ """+ )+ assert not {"repowise", "server", "mcp", "os", "path"} & uses+++def test_an_import_writes_the_names_it_binds():+ _cfg, def_use, _r = _analyze(+ """+ def f():+ import a.b, c.d as e+ from m.n import (x, y as z)+ from k import *+ return a, e, x, z""")- assert {"data", "v"} <= defs- assert "source" in uses+ imported = {d.var for d in def_use.definitions if d.imports}+ assert imported == {"a", "e", "x", "z"}def test_parameters_are_defs():diff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.pyindex 7d421657b..2ffb577d0 100644--- a/tests/unit/health/test_extract_method_render.py+++ b/tests/unit/health/test_extract_method_render.py@@ -17,6 +17,7 @@ from dataclasses import dataclassimport pytest+from repowise.core.analysis.health.complexity.languages import get_language_mapfrom repowise.core.analysis.health.dataflow import (Extraction,analyze_file,@@ -398,3 +399,65 @@ def test_read_after_names_the_inputs_the_host_still_uses():(fn,) = _functions("python", "py", src)span = Extraction(4, 5, ("cfg", "rows", "total"), ("total",), slice_nloc=2, ccn_removed=1)assert em._read_after(fn, span) == {"cfg", "total"}+++def test_a_rust_let_in_the_span_declares_the_output_it_shadows():+ # ``x`` is written before the span, so only the in-span ``let`` tells the+ # call to declare it (``let x = ...``) rather than assign the old one.+ src = """+ fn f(rows: Vec<i32>) -> i32 {+ let x = 0;+ println!("{}", x);+ let x = rows.len() as i32;+ x+ }+ """+ (fn,) = _functions("rust", "rs", src)+ lets = [d for d in fn.def_use.definitions if d.var == "x"]+ assert lets and all(d.declares and d.declared_at is not None for d in lets)+ span = Extraction(5, 5, ("rows",), ("x",), slice_nloc=1, ccn_removed=1)+ assert em._out_binding(fn, span, get_language_map("rust")) == (True, True, False)+++_NESTED_SHADOW = {+ "rust": (+ "rs",+ """+ fn f(a: i32, c: bool) -> i32 {+ let mut x = a;+ println!("{}", x);+ if c {+ let x = 2;+ println!("{}", x);+ }+ x = a + 1;+ x+ }+ """,+ ),+ "typescript": (+ "ts",+ """+ function f(a: number, c: boolean): number {+ let x = a;+ console.log(x);+ if (c) {+ let x = 2;+ console.log(x);+ }+ x = a + 1;+ return x;+ }+ """,+ ),+}++[email protected]("language", sorted(_NESTED_SHADOW))+def test_a_declaration_nested_in_the_span_does_not_declare_the_output(language: str):+ # The inner ``x`` binds only in its block; the span's top-level write+ # assigns the outer ``x``, so the call assigns rather than declares.+ ext, src = _NESTED_SHADOW[language]+ (fn,) = _functions(language, ext, src)+ span = Extraction(5, 9, ("a", "c"), ("x",), slice_nloc=5, ccn_removed=1)+ assert em._out_binding(fn, span, get_language_map(language)) == (False, True, False)diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.pyindex b5cbe1b14..3aba66373 100644--- a/tests/unit/health/test_refactoring_extract_method.py+++ b/tests/unit/health/test_refactoring_extract_method.py@@ -1175,3 +1175,59 @@ def test_a_refused_span_yields_only_to_a_disjoint_one(monkeypatch):)(s,) = ExtractMethodDetector().detect(ctx)assert s.plan["span"] == {"start": 85, "end": 95}+++def _span_in_out(src: str, s: int, e: int):+ from repowise.core.analysis.health.dataflow import slice as slicer++ def_use = _first(src).def_use+ def_lines, use_lines = slicer._var_lines(def_use)+ declared_first = slicer._declared_before_read(def_use)+ return slicer._infer_in_out(def_lines, use_lines, s, e, declared_first)+++def test_a_comprehension_binder_is_not_a_parameter():+ # Seen on get_health_findings: an earlier comprehension's ``v`` made the+ # span's own ``v`` an input, and the call passed a name the caller lacks.+ src = """+ def f(severity, order, t):+ exact = [v.strip() for v in severity if v]+ b = len(exact)+ allowed = [k for k, v in order.items() if v >= t]+ return allowed, b+ """+ assert _span_in_out(src, 4, 5) == (("exact", "order", "t"), ("allowed", "b"))+++def test_an_import_path_naming_a_parameter_is_not_a_read():+ # Seen on _lifespan: ``from repowise.server...`` read its ``server`` parameter.+ src = """+ def f(server, root):+ a = root / "x"+ from repowise.server.enrich import Enricher+ e = Enricher(a)+ return e+ """+ assert _span_in_out(src, 4, 5) == (("a",), ("e",))+++def test_a_span_holding_an_import_read_after_it_is_refused():+ # The import would leave with the helper; an imported name is never made+ # an input or output (the helper re-imports it).+ src = """+ def f(a, c):+ from pkg.mod import Thing+ if c:+ a += 1+ t = Thing(a)+ return t+ """+ with pytest.MonkeyPatch.context() as mp:+ from repowise.core.analysis.health.dataflow import slice as slicer++ mp.setattr(slicer, "_MAX_BODY_SHARE", float("inf"))+ mp.setattr(slicer, "_MIN_SLICE_NLOC", 1)+ spans = find_extractions(_first(src), get_language_map("python"))+ found = {(x.start_line, x.end_line): (x.params, x.returns) for x in spans}+ assert (3, 5) not in found+ assert found[(4, 6)] == (("a", "c"), ("t",))