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(refactoring): refuse an Extract Method span whose declaration the later code still names (#2970)
Raghav Chamadiya63476c7e1f00
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 7691fabe2..51a344ed8 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -111,6 +111,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[def_lines, use_lines = _var_lines(analysis.def_use)declared_first = _declared_before_read(analysis.def_use)hoisted = _hoisted_bindings(def_lines, use_lines)+ decl_lines = _declaration_lines(analysis.def_use)decision_kinds = (lmap.branch_kinds| lmap.loop_kinds@@ -198,6 +199,10 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[continueif any(s <= first_def <= e and first_use < s for first_def, first_use in hoisted):continue+ if _declaration_escapes(+ s, e, returns, decl_lines, def_lines, use_lines, declared_first+ ):+ continueif nested_prefix[j + 1] > nested_prefix[i]:continueif loop is not None and not _loop_carry_free(@@ -451,6 +456,65 @@ def _hoisted_bindings(return sorted(hoisted)+def _declaration_lines(def_use: FunctionDefUse) -> dict[str, frozenset[int]]:+ """Per variable, the lines that declare it (a ``let`` / ``var`` / ``:=`` /+ typed local, as the dialect marks with ``declared_at``)."""+ lines: dict[str, set[int]] = defaultdict(set)+ for d in def_use.definitions:+ if d.declared_at is not None:+ lines[d.var].add(d.line)+ return {var: frozenset(found) for var, found in lines.items()}+++def _declaration_escapes(+ s: int,+ e: int,+ returns: tuple[str, ...],+ decl_lines: dict[str, frozenset[int]],+ def_lines: dict[str, list[int]],+ use_lines: dict[str, list[int]],+ declared_first: dict[str, frozenset[int]],+) -> bool:+ """True when the span declares a name the code after it still refers to.++ A returned name is fine: the caller declares it from the helper's result.+ Otherwise the declaration leaves with the span and the caller's next+ reference names nothing, even when that reference is a plain assignment+ (Go ``var out T`` in the span, ``out = x`` after it, which is why liveness+ did not make it an OUT). A later reference that declares the name afresh+ (``y, err := g()``, a second ``for i := ...``, whose reads on that line+ follow the declaration per *declared_first*) needs nothing from the span.+ Block scopes are not modelled, so a same-named variable of an outer scope+ read after the span also refuses: a missed span, never a broken one.+ """+ return any(+ var not in returns+ and any(s <= ln <= e for ln in declared)+ and _needed_after(var, e, declared, def_lines, use_lines, declared_first)+ for var, declared in decl_lines.items()+ )+++def _needed_after(+ var: str,+ e: int,+ declared: frozenset[int],+ def_lines: dict[str, list[int]],+ use_lines: dict[str, list[int]],+ declared_first: dict[str, frozenset[int]],+) -> bool:+ """True when the first reference to *var* after line *e* relies on an+ earlier declaration: it is a plain use or assignment, not a fresh one."""+ uses = use_lines.get(var, ())+ after = [ln for ln in (*def_lines.get(var, ()), *uses) if ln > e]+ if not after:+ return False+ first = min(after)+ if first not in declared:+ return True+ return first in uses and first not in declared_first.get(var, ())++def _outs_definitely_assigned(span: list[Node],returns: tuple[str, ...],diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.pyindex 4de4e00e1..2060e0dfb 100644--- a/tests/unit/health/test_dataflow_langs.py+++ b/tests/unit/health/test_dataflow_langs.py@@ -2026,3 +2026,66 @@ def test_rust_match_arm_binders_are_params_of_a_span_in_the_arm():spans = [e for e in find_extractions(fn, get_language_map("rust")) if e.start_line <= 7]assert spansassert all({"negated", "ranges"} <= set(e.params) for e in spans)+++# == A declaration the code after the span still needs ==========================+++def test_go_span_declaring_a_name_assigned_after_it_is_not_offered():+ # ``var out []int`` moves with the span, but ``out = formats`` and the+ # return after it still name it; liveness alone saw no OUT.+ src = """+ package main++ func paths(formats []int, link bool) ([]int, map[int]int) {+ targets := make(map[int]int)+ for i, f := range formats {+ if f > 2 {+ targets[f] = i+ } else {+ targets[f] = -i+ }+ }+ var out []int+ if link {+ out = formats+ }+ return out, targets+ }+ """+ lmap = get_language_map("go")+ spans = find_extractions(_first("go", src), lmap)+ # Holding ``var out`` is fine only when the span returns ``out``.+ assert all("out" in e.returns for e in spans if e.start_line <= 13 <= e.end_line)+ assert any(e.end_line == 12 for e in spans) # the loop alone is still offered+++def test_go_name_declared_afresh_after_the_span_does_not_refuse_it():+ src = """+ package main++ func load(items []string) int {+ total := 0+ for _, it := range items {+ n, err := parse(it)+ if err == nil {+ total += n+ }+ log(it)+ log(n)+ }+ for i := 0; i < total; i++ {+ if i%2 == 0 {+ total--+ }+ }+ m, err := finish(total)+ if err != nil {+ return 0+ }+ return m+ }+ """+ 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))