Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(refactoring): call an existing function when a clone site already is one (#3390)

Raghav Chamadiyaf1861f630f20
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index ec5f1bf19..97e16798e 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -27,6 +27,11 @@ is a separate, on-request step that does use an LLM
| **Split File** | The files an oversized module splits into, which symbols go where, and the import edits in each dependent. |
| **Performance Fix** | One shared change for a performance problem, with the affected call sites and caller-to-sink paths. |
+When one copy of a duplicated block is already a whole function the other copies
+could call, the Extract Helper plan says so instead of asking for a new helper:
+each other site gets the call that replaces it, or is marked as a copy to delete
+and import. Plan detail carries the call text; lists stay the same size.
+
Each detector reports nothing when a signal it needs is missing, so a gap means
"no suggestion", never a guessed one. Output is deterministic: the same commit
gives the same plans and the same ids.
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index d5fd6a408..85e37fc57 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -18,7 +18,9 @@ Repo-level KPIs are computed from the final per-file metrics.
from __future__ import annotations
import asyncio
+import functools
import os
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
@@ -577,20 +579,23 @@ def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] |
return text.splitlines()
+#: Partner files whose lines one analysis pass keeps (``_repo_lines``).
+_PARTNER_LINES_CACHE = 256
+
+
def _clone_sources(
file_path: str,
own_lines: list[str],
clones: list[ClonePair],
- abs_paths: dict[str, str],
- read_source: SourceReader,
+ read_lines: Callable[[str], list[str] | None],
) -> dict[str, list[str]]:
"""This file's lines plus each clone partner's, for text-level checks."""
out = {file_path: own_lines}
for clone in clones:
for path in (clone.file_a, clone.file_b):
- if path in out or path not in abs_paths:
+ if path in out:
continue
- lines = _read_source_lines(abs_paths[path], read_source)
+ lines = read_lines(path)
if lines is not None:
out[path] = lines
return out
@@ -790,6 +795,9 @@ class HealthAnalyzer:
self.git_meta_map = git_meta_map or {}
self.parsed_files = list(parsed_files or [])
self._abs_paths = {pf.file_info.path: pf.file_info.abs_path for pf in self.parsed_files}
+ # Clone partners' lines, shared by the test-clone gate and Extract
+ # Helper's reuse check. Bounded: partners cluster, a pass reads few.
+ self._repo_lines = functools.lru_cache(maxsize=_PARTNER_LINES_CACHE)(self._read_repo_lines)
# Per-file coverage keyed by repo-relative POSIX path. Each value
# is ``{line_coverage_pct, branch_coverage_pct, covered_lines,
# total_coverable_lines}``. ``None``-equivalent files are simply
@@ -1623,7 +1631,7 @@ class HealthAnalyzer:
_read_source_lines(pf.file_info.abs_path, self.read_source) if clones else None
)
clone_sources = (
- _clone_sources(file_path, source_lines, clones, self._abs_paths, self.read_source)
+ _clone_sources(file_path, source_lines, clones, self._repo_lines)
if source_lines is not None and pf.file_info.is_test
else {}
)
@@ -1746,6 +1754,8 @@ class HealthAnalyzer:
commit_spans=commit_spans(fcx.functions, _commit_entries(fcx, file_git_meta)),
# The Extract Helper snippet; ``None`` unless the file carries clones.
source_lines=source_lines,
+ # Clone partners' lines, read only when one site may be a whole function.
+ read_lines=self._repo_lines,
)
suggestions = detect_refactorings(
rctx,
@@ -1754,6 +1764,14 @@ class HealthAnalyzer:
)
return metric, findings, suggestions
+ def _read_repo_lines(self, path: str) -> list[str] | None:
+ """*path*'s lines: the parsed file's own path, else under the repo root
+ (an update's parsed set is the whole tree, but a caller may pass less)."""
+ abs_path = self._abs_paths.get(path)
+ if abs_path is None and self.repo_root is not None:
+ abs_path = str(Path(self.repo_root) / path)
+ return _read_source_lines(abs_path, self.read_source) if abs_path else None
+
def _is_hotspot(self, meta: dict | object) -> bool:
if isinstance(meta, dict):
return bool(meta.get("is_hotspot", False))
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
index 936fa9529..fc751313b 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_helper.py
@@ -43,15 +43,22 @@ still worth extracting but ranks ``medium``.
from __future__ import annotations
import re
+from collections.abc import Callable
from typing import Any
+import structlog
+
from ....code_origin import is_migration_path, is_vendored_or_generated_path
from ....test_paths import is_test_related_path
from ..duplication.detector import clone_ranges, union_line_count
from ..effort import effort_bucket
+from .graph_signals import defined_symbols
from .language_family import same_language_family
from .models import RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, register
+from .reuse import find_reuse
+
+log = structlog.get_logger(__name__)
# The biomarker this detector answers — the recovered impact is read off it.
_SOURCE_BIOMARKER = "dry_violation"
@@ -321,17 +328,7 @@ def _symbol_spans(graph: Any, file_path: str, cache: dict[str, list[tuple[int, i
hit = cache.get(file_path)
if hit is not None:
return hit
- spans: list[tuple[int, int]] = []
- if graph is not None and file_path in graph:
- for _u, target, data in graph.out_edges(file_path, data=True):
- if data.get("edge_type") != "defines":
- continue
- node = graph.nodes[target]
- if node.get("node_type") != "symbol" or node.get("kind") == "module":
- continue
- start, end = node.get("start_line"), node.get("end_line")
- if isinstance(start, int) and isinstance(end, int) and end >= start:
- spans.append((start, end))
+ spans = [(n["start_line"], n["end_line"]) for _id, n in defined_symbols(graph, file_path)]
cache[file_path] = spans
return spans
@@ -373,10 +370,12 @@ class ExtractHelperDetector(RefactoringDetector):
impact_lookup = self._impact_for_dry_violation(ctx)
spans_cache: dict[str, list[tuple[int, int]]] = {}
+ read = _cached_reader(ctx)
out: list[RefactoringSuggestion] = []
for block in blocks:
suggestion = self._build_suggestion(ctx, block, impact_lookup, spans_cache)
if suggestion is not None:
+ suggestion.plan.update(_reuse_fields(ctx, suggestion.plan["occurrences"], read))
out.append(suggestion)
# Stable order: biggest recovery first, then — because dry_violation
@@ -631,6 +630,39 @@ class ExtractHelperDetector(RefactoringDetector):
return best
+def _cached_reader(ctx: RefactoringContext) -> Callable[[str], list[str] | None] | None:
+ """``ctx.read_lines`` reading each file once per pass, this file from the
+ lines already held; None when no reader was provided."""
+ read_lines = ctx.read_lines
+ if read_lines is None:
+ return None
+ cache: dict[str, list[str] | None] = {ctx.file_path: ctx.source_lines}
+
+ def read(path: str) -> list[str] | None:
+ if path not in cache:
+ cache[path] = read_lines(path)
+ return cache[path]
+
+ return read
+
+
+def _reuse_fields(
+ ctx: RefactoringContext,
+ occurrences: list[dict[str, Any]],
+ read: Callable[[str], list[str] | None] | None,
+) -> dict[str, Any]:
+ """``{"reuse": ...}`` when one site already is a function the others can
+ call (no second copy of it is asked for), else ``{}``."""
+ if read is None:
+ return {}
+ sites = [(o["file"], o["line_start"], o["line_end"]) for o in occurrences]
+ verdict = find_reuse(ctx.graph, ctx.language, sites, read)
+ if verdict.refused:
+ # Counted in the log, not the plan: a refusal changes nothing it serves.
+ log.debug("extract_helper_reuse_refused", file=ctx.file_path, reason=verdict.refused)
+ return {"reuse": verdict.plan} if verdict.plan else {}
+
+
def _cross_file_lines(ctx: RefactoringContext) -> int:
"""Lines of the file covered by clones shared with other files."""
return union_line_count(clone_ranges(ctx.file_path, ctx.clones, cross_file_only=True))
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
index 1633a92f3..16b38353f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -145,3 +145,22 @@ def build_methods_by_file(graph: Any) -> dict[str, tuple[str, ...]]:
if methods:
out[file_path] = tuple(sorted(methods))
return out
+
+
+def defined_symbols(graph: Any, file_path: str) -> list[tuple[str, dict[str, Any]]]:
+ """``(id, node)`` for each declaration *file_path* defines (``defines``
+ edges), the synthetic module symbol left out, with a whole line span.
+ Empty when the graph has no node for the file."""
+ if graph is None or file_path not in graph:
+ return []
+ out = []
+ for _u, target, data in graph.out_edges(file_path, data=True):
+ if data.get("edge_type") != "defines":
+ continue
+ node = graph.nodes[target]
+ if node.get("node_type") != "symbol" or node.get("kind") == "module":
+ continue
+ start, end = node.get("start_line"), node.get("end_line")
+ if isinstance(start, int) and isinstance(end, int) and end >= start:
+ out.append((target, node))
+ return out
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 8ddd58cc0..ffa808dbc 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -36,7 +36,10 @@ For Extract Helper:
carry a graph community label under ``module``, which named a directory the
occurrences did not live in on every measured row. Plans stored before that
removal still carry the key; read ``directory``, which was correct on those
- rows too.
+ rows too. When one site already is a function the others can call, the plan
+ adds ``"reuse": {"existing_symbol", "file", "span", "reason", "sites": [{"file",
+ "span", "action": "replace_with_call" | "delete", "new_text", "replaces"}]}``
+ (``reuse.py``); plan detail serves it, list rows drop it.
- ``evidence`` = ``{"occurrence_count": int, "duplicated_lines": int,
"token_count": int, "co_change_count": int, "is_intra_file": bool}`` — the
size + activity signals that justify extracting a helper.
@@ -103,6 +106,7 @@ For Split File:
from __future__ import annotations
+from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
@@ -200,6 +204,9 @@ class RefactoringContext:
# every other detector ignores it. ``None`` when the file was not read (no
# clones) or the read failed; the detector then omits the snippet.
source_lines: list[str] | None = None
+ # A clone partner's lines by repo path (None: unreadable), for Extract
+ # Helper's reuse check. ``None``: not provided, no plan reuses a function.
+ read_lines: Callable[[str], list[str] | None] | None = None
@dataclass
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
index 691ed5bad..391e6a46d 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recipe.py
@@ -30,6 +30,7 @@ RecipeAction = Literal[
"keep",
"reexport",
"edit",
+ "delete",
]
RECIPE_ACTIONS: tuple[str, ...] = get_args(RecipeAction)
#: What a precondition is: a test run or a test to add first, a plan risk, a plan
@@ -223,7 +224,41 @@ def _extract_notes(
return notes
+def _reused(d: Mapping[str, Any]) -> str | None:
+ """The existing function an Extract Helper plan calls, when it reuses one."""
+ reuse = _dict(_dict(d.get("plan")).get("reuse"))
+ return (_short(reuse.get("existing_symbol")) or None) if reuse else None
+
+
+def _reuse_steps(reuse: Mapping[str, Any]) -> list[Step]:
+ """One step per site that calls the existing function, or deletes a copy of it."""
+ name = _short(reuse.get("existing_symbol"))
+ home = reuse.get("file")
+ link = {k: reuse.get(k) for k in ("existing_symbol", "file", "reason")}
+ steps = []
+ for site in (_dict(s) for s in _list(reuse.get("sites"))):
+ span = _dict(site.get("span"))
+ where = _span(span.get("start"), span.get("end"))
+ lines = f"lines {where['start']}-{where['end']}" if where else "these lines"
+ if site.get("action") == "delete":
+ text = (
+ f"Delete {lines}, a copy of `{name}`, and import `{name}` from `{home}` in its "
+ "place; re-export it if other files import it from here."
+ )
+ steps.append(_step("delete", site.get("file"), where, text, reuse=link))
+ continue
+ imported = "" if site.get("file") == home else f" (import it from `{home}`)"
+ text = f"Replace {lines} with a call to the existing `{name}`{imported}."
+ call = {"replace_span": where, "new_text": site["new_text"]} if site.get("new_text") else None
+ extra = {"call_site": call} if call and where else {}
+ steps.append(_step("replace_with_call", site.get("file"), where, text, reuse=link, **extra))
+ return steps
+
+
def _extract_helper(d: Mapping[str, Any], plan: Mapping[str, Any]) -> list[Step]:
+ reuse = _dict(plan.get("reuse"))
+ if reuse:
+ return _reuse_steps(reuse)
occurrences = [_dict(o) for o in _list(plan.get("occurrences"))]
site = _dict(plan.get("suggested_site"))
where = site.get("directory") or site.get("module")
@@ -422,6 +457,8 @@ def _summary(d: Mapping[str, Any], steps: list[Step]) -> str:
span, name = steps[0]["span"], steps[0]["new_symbol"]["name"]
host = _short(d.get("target_symbol"))
return f"Extract lines {span['start']}-{span['end']} of `{host}` into `{name}`."
+ if kind == "extract_helper" and (name := _reused(d)):
+ return f"Call the existing `{name}` at {len(steps)} site{_s(len(steps))} that repeat it."
if kind == "extract_helper":
return f"Replace the block duplicated at {len(steps) - 1} sites with one shared helper."
if kind == "extract_class":
@@ -554,6 +591,8 @@ def _does_not(d: Mapping[str, Any], steps: list[Step]) -> list[dict[str, str | N
out.append(
{"constraint": f"touch anything outside lines {lines} and {added}", "reason": None}
)
+ elif kind == "extract_helper" and (name := _reused(d)):
+ out.append({"constraint": f"change `{name}` to fit a site", "reason": "its callers rely on it"})
elif kind in _DOES_NOT:
constraint, reason = _DOES_NOT[kind]
out.append({"constraint": constraint, "reason": reason})
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/render.py b/packages/core/src/repowise/core/analysis/health/refactoring/render.py
index 55ea77aa2..5adada63f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/render.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py
@@ -473,8 +473,9 @@ def render_context(
#: What the renderer adds to a stored plan, served on plan detail only.
_DETAIL_SYMBOL_KEYS = ("params", "returns", "signature_text", "return_text", "notes")
-#: A staged plan's stages, parameter object and residual sit on detail too.
-_DETAIL_PLAN_KEYS = ("call_site", "stages", "parameter_object", "orchestrator")
+#: Plan keys on detail only: Extract Method's call and staged plan (stages,
+#: parameter object, residual), Extract Helper's calls to an existing function.
+_DETAIL_PLAN_KEYS = ("call_site", "stages", "parameter_object", "orchestrator", "reuse")
def list_plan(plan: dict) -> dict:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/reuse.py b/packages/core/src/repowise/core/analysis/health/refactoring/reuse.py
new file mode 100644
index 000000000..45c693b0b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/reuse.py
@@ -0,0 +1,648 @@
+"""Call an existing function instead of extracting a new helper (Extract Helper).
+
+A clone group can contain a whole function: one site *is* ``F`` and the others
+repeat its body. A new helper would be a second copy of ``F``, so the plan
+becomes "call ``F``" at every other site, or "delete this copy and import
+``F``" where a site is ``F`` again under the same header.
+
+Precision first: a plan that is wrong is worse than none. Every site must hold,
+or the group keeps its new-helper plan:
+
+- one occurrence and ``F`` cover at least 90% of each other; ``F`` is an
+ undecorated function or method outside tests;
+- the site repeats ``F``'s body line for line, whitespace and whole-line
+ comments aside. The clone index matches token shapes, so the text is checked
+ here: this is the exact (type-1) clone only;
+- every name the body reads that is not its own (a module global, an import)
+ is bound to the same thing in the site's file, and the site's function does
+ not shadow it;
+- ``F`` is reachable: the same file, or a public top-level function the site's
+ file already imports, or one in its directory whose file does not reach the
+ site's (no import cycle). A method only from its own class;
+- the call can stand in for the lines: every parameter of ``F`` is a name the
+ lines use, they assign nothing their function reads elsewhere, a ``return``
+ in them ends that function, they do not ``yield``, and an async ``F`` is
+ called from an async function;
+- a whole copy is deleted only when nothing else could import it, and replaced
+ by a call only when its header is ``F``'s under another name.
+
+Python and TypeScript / JavaScript only: the checks read their statements.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import deque
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import PurePosixPath
+from typing import Any, Literal, NamedTuple, get_args
+
+from ....callable_spans import body_span
+from ...graph_view import ImportEdgeView
+from ...signature_effect import parameter_names
+from . import render
+from .graph_signals import defined_symbols
+from .reuse_names import (
+ binding_count,
+ exported_later,
+ is_builtin,
+ module_bindings,
+ module_of,
+ read_names,
+)
+
+ReuseSiteAction = Literal["replace_with_call", "delete"]
+#: What a reuse plan does at a site. Mirrored in ``packages/types``.
+REUSE_SITE_ACTIONS: tuple[str, ...] = get_args(ReuseSiteAction)
+
+#: Share of each other's lines an occurrence and ``F`` must cover for the site to be ``F``.
+MIN_COVERAGE = 0.9
+#: Lines scanned above a function for a (multi-line) decorator.
+_DECORATOR_SCAN = 20
+_LANGUAGES = frozenset({"python", "typescript", "javascript"})
+_CALLABLE = frozenset({"function", "method"})
+_DEPENDENCY = ("imports", "dynamic_imports")
+_DOC_OPENERS = re.compile(r"^[rRuUbB]?(\"\"\"|''')")
+_RECEIVER = re.compile(r"\b(self|cls|this)\b")
+_YIELD = re.compile(r"\byield\b")
+_PY_SCOPE = re.compile(r"^(global|nonlocal|del)\b")
+_PY_RETURN = re.compile(r"^return\b")
+_JS_RETURN = re.compile(r"(?:^|[\s;{}])return\b")
+_PY_ASSIGN = re.compile(
+ r"^\(?([\w\s,]+?)\)?\s*(?::[^=]+)?(?:[-+*/%&|^@]|//|\*\*|>>|<<)?=(?!=)"
+)
+_PY_BIND = re.compile(r"\b(?:for|as)\s+\(?([\w\s,]+?)\)?\s*(?:\bin\b|:|$)")
+_PY_LAMBDA = re.compile(r"\blambda\s+([\w\s,*=]*):")
+_PY_LOCAL_IMPORT = re.compile(r"^(?:from\s+\S+\s+)?import\s+(.+)$")
+_WALRUS = re.compile(r"([A-Za-z_]\w*)\s*:=")
+_JS_DECL = re.compile(r"\b(?:const|let|var)\s+([^=;]+?)\s*(?:=|;|\bof\b|\bin\b|$)")
+_JS_ASSIGN = re.compile(r"^([A-Za-z_$][\w$]*)\s*(?:[-+*/%&|^]|\*\*|>>>?|<<|\?\?|\|\||&&)?=(?!=)")
+_JS_PARAMS = re.compile(r"\(([^()]*)\)\s*(?::[^=]*)?=>|([A-Za-z_$][\w$]*)\s*=>|catch\s*\(\s*([^)]*)\)")
+_EXPORT = re.compile(r"^export\s+(default\s+)?")
+_JS_METHOD_MODIFIER = re.compile(r"^(?:\w+\s+)*?(static|abstract|get|set)\s|^\*")
+_CLOSERS = re.compile(r"^[})\];,\s]*$")
+_IDENTS = re.compile(r"[A-Za-z_$][\w$]*")
+
+Lines = list[str]
+Occurrence = tuple[str, int, int]
+Site = dict[str, Any]
+Code = list[tuple[int, str]]
+
+
+class Reuse(NamedTuple):
+ """The ``plan.reuse`` payload, or why a site that is a function was refused."""
+
+ plan: dict[str, Any] | None
+ refused: str | None = None
+
+
+@dataclass(frozen=True)
+class _Fn:
+ id: str
+ name: str
+ kind: str
+ file: str
+ start: int
+ end: int
+ parent: str | None
+ signature: str
+ qualified: str
+ is_async: bool
+ private: bool
+ #: The parser's decorator list; None when the graph has none (rebuilt
+ #: from storage), and the source text is read instead.
+ decorators: tuple[str, ...] | None = None
+
+
+class _Repo:
+ """The graph and source one detector pass reads, each file looked up once."""
+
+ def __init__(self, graph: Any, language: str, read: Callable[[str], Lines | None]) -> None:
+ self.graph = graph
+ self.edges = ImportEdgeView(graph)
+ self.language = language
+ self.read = read
+ self._fns: dict[str, list[_Fn]] = {}
+ self._reach: dict[tuple[str, str], bool] = {}
+ self._bindings: dict[str, dict[str, set[tuple[str, ...]]]] = {}
+
+ def functions(self, path: str) -> list[_Fn]:
+ hit = self._fns.get(path)
+ if hit is None:
+ hit = self._fns[path] = _functions(self.graph, path, self.language)
+ return hit
+
+ def bindings(self, path: str) -> dict[str, set[tuple[str, ...]]]:
+ hit = self._bindings.get(path)
+ if hit is None:
+ hit = self._bindings[path] = module_bindings(self.read(path) or [], path, self.language)
+ return hit
+
+ def imports(self, importer: str, imported: str) -> bool:
+ return any(self.edges.has_edge(importer, imported, kind) for kind in _DEPENDENCY)
+
+ def reaches(self, start: str, goal: str) -> bool:
+ """Whether *start* depends on *goal* through file imports."""
+ hit = self._reach.get((start, goal))
+ if hit is None:
+ hit = self._reach[(start, goal)] = self._walk(start, goal)
+ return hit
+
+ def _walk(self, start: str, goal: str) -> bool:
+ seen, queue = {start}, deque([start])
+ while queue:
+ node = queue.popleft()
+ for _u, nxt, data in self.graph.out_edges(node, data=True):
+ if data.get("edge_type") in _DEPENDENCY and nxt not in seen:
+ if nxt == goal:
+ return True
+ seen.add(nxt)
+ queue.append(nxt)
+ return False
+
+
+def find_reuse(
+ graph: Any,
+ language: str,
+ occurrences: list[Occurrence],
+ read: Callable[[str], Lines | None],
+) -> Reuse:
+ """The reuse payload when one occurrence is a function every other site can
+ call, else ``Reuse(None, reason)`` (``reason`` None: no occurrence is one)."""
+ if graph is None or language not in _LANGUAGES:
+ return Reuse(None)
+ repo = _Repo(graph, language, read)
+ candidates = sorted(
+ ((fn, occ) for occ in occurrences for fn in _covered(repo, occ)),
+ key=lambda c: (c[0].private, c[0].file, c[0].start),
+ )
+ refused = None
+ for fn, own in candidates:
+ sites, reason = _sites(repo, fn, [o for o in occurrences if o != own])
+ if sites is not None:
+ return Reuse(_payload(fn, sites))
+ refused = refused or reason
+ return Reuse(None, refused)
+
+
+def _functions(graph: Any, path: str, language: str) -> list[_Fn]:
+ """Functions and methods *path* defines."""
+ out = []
+ for sid, node in defined_symbols(graph, path):
+ if node.get("kind") not in _CALLABLE or node["end_line"] <= node["start_line"]:
+ continue
+ name = str(node.get("name") or "")
+ signature = str(node.get("signature") or "")
+ # ``visibility`` is the parser's export reading (a TS function without
+ # ``export`` is private); Python's underscore is the convention on top.
+ private = node.get("visibility") != "public" or (
+ language == "python" and name.startswith("_")
+ )
+ out.append(
+ _Fn(
+ id=sid,
+ name=name,
+ kind=node["kind"],
+ file=path,
+ start=node["start_line"],
+ end=node["end_line"],
+ parent=node.get("parent_name"),
+ signature=signature,
+ qualified=str(node.get("qualified_name") or ""),
+ # A graph rebuilt from storage has no ``is_async``; the header says it.
+ is_async=bool(node.get("is_async")) or "async" in signature.split("(")[0].split(),
+ private=private,
+ decorators=_decorator_list(node.get("decorators")),
+ )
+ )
+ return out
+
+
+def _decorator_list(value: Any) -> tuple[str, ...] | None:
+ return tuple(str(d) for d in value) if isinstance(value, (list, tuple)) else None
+
+
+def _covered(repo: _Repo, occ: Occurrence) -> list[_Fn]:
+ """Functions the occurrence is: each covers the other at ``MIN_COVERAGE``
+ (a two-line function inside a long block is not the block)."""
+ path, start, end = occ
+ out = []
+ for fn in repo.functions(path):
+ shared = min(end, fn.end) - max(start, fn.start) + 1
+ if shared >= MIN_COVERAGE * max(fn.end - fn.start + 1, end - start + 1):
+ out.append(fn)
+ return out
+
+
+@dataclass(frozen=True)
+class _Source:
+ """``F`` read once: its body, header, own names and the names it reads."""
+
+ fn: _Fn
+ body: Code
+ header: list[str]
+ params: tuple[str | None, list[str]] | None
+ own: frozenset[str]
+ reads: frozenset[str]
+
+
+def _sites(repo: _Repo, fn: _Fn, others: list[Occurrence]) -> tuple[list[Site] | None, str | None]:
+ lines = repo.read(fn.file)
+ src = _source(repo, fn, lines) if lines else None
+ if src is None:
+ return None, "no_body"
+ refused = _source_refusal(repo, src, lines or [])
+ if refused:
+ return None, refused
+ sites = []
+ for occ in others:
+ site, reason = _site(repo, src, occ)
+ if site is None:
+ return None, reason
+ sites.append(site)
+ return sites, None
+
+
+def _source(repo: _Repo, fn: _Fn, lines: Lines) -> _Source | None:
+ lang = repo.language
+ body = _body(lines, fn, lang)
+ if not body:
+ return None
+ header = _header(lines, fn, lang)
+ params = parameter_names(fn.signature, lang, fn.kind)
+ texts = [t for _n, t in body]
+ if params is not None:
+ given = {p for p in (params[0], *params[1]) if p}
+ else:
+ # Destructured parameters: every name the header declares is the function's.
+ given = set(_IDENTS.findall(" ".join(header)))
+ own = given | _assigned(texts, lang) | {"self", "cls", "this", fn.name}
+ # The header's names too: an annotation's type must mean the same at the site.
+ reads = read_names([*texts, *header], lang)
+ return _Source(fn, body, header, params, frozenset(own), frozenset(reads))
+
+
+def _source_refusal(repo: _Repo, src: _Source, lines: Lines) -> str | None:
+ """Why *src* can stand in for no copy at all."""
+ if _decorated(lines, src.fn):
+ return "decorated"
+ if repo.language == "python" and any(_PY_SCOPE.match(t) for _n, t in src.body):
+ return "scope_statement"
+ head = src.header[0] if src.header else ""
+ if repo.language != "python" and src.fn.kind == "method" and _JS_METHOD_MODIFIER.match(head):
+ return "static_or_accessor"
+ return None
+
+
+def _site(repo: _Repo, src: _Source, occ: Occurrence) -> tuple[Site | None, str | None]:
+ path = occ[0]
+ lines = repo.read(path)
+ if not lines:
+ return None, "site_unread"
+ fn = src.fn
+ span = _match(lines, src.body, occ, repo.language, 3 + (fn.end - fn.start) // 10)
+ if span is None:
+ return None, "text_differs"
+ refused = _unreachable(repo, fn, path) or _foreign_names(repo, src, path)
+ if refused:
+ return None, refused
+ enclosing = [g for g in repo.functions(path) if g.start < span[0] and g.end >= span[1]]
+ host = max(enclosing, key=lambda g: g.start, default=None)
+ if host is None:
+ return None, "not_in_function"
+ host_body = _body(lines, host, repo.language)
+ if host_body and (host_body[0][0], host_body[-1][0]) == span:
+ return _twin_site(repo, src, host, span, lines)
+ return _call_site(repo, src, host, span, lines)
+
+
+def _unreachable(repo: _Repo, fn: _Fn, path: str) -> str | None:
+ """Why *path* cannot call *fn*, or None when it can."""
+ if fn.kind == "function" and fn.parent:
+ return "not_importable" # a nested function: only its parent sees it
+ if path == fn.file:
+ return None
+ if fn.kind != "function" or fn.private:
+ return "not_importable"
+ if repo.imports(path, fn.file):
+ return None
+ same_dir = PurePosixPath(path).parent == PurePosixPath(fn.file).parent
+ if not same_dir:
+ return "not_importable"
+ # A new import from a sibling is safe only when the sibling cannot reach back.
+ return "import_cycle" if repo.reaches(fn.file, path) else None
+
+
+def _foreign_names(repo: _Repo, src: _Source, path: str) -> str | None:
+ """Why a name *src* reads would mean something else in *path*, or None."""
+ fn = src.fn
+ if path == fn.file:
+ return None
+ mine, theirs = repo.bindings(fn.file), repo.bindings(path)
+ if "*" in mine or "*" in theirs:
+ return "free_names"
+ for name in src.reads - {fn.name}: # its own name: ``_name_taken`` judges that
+ here, there = mine.get(name), theirs.get(name)
+ if here or there:
+ if here != there:
+ return "free_names"
+ elif name not in src.own and not is_builtin(name, repo.language):
+ return "free_names"
+ return None
+
+
+def _name_taken(repo: _Repo, fn: _Fn, path: str, *, deleting: bool) -> bool:
+ """Whether *path* already binds ``fn.name`` to something other than an
+ import of *fn* (or, when *deleting*, the copy the plan removes)."""
+ if path == fn.file:
+ # The call resolves the module global at run time, so any other
+ # module-level binding of the name (a later def, assignment or import)
+ # could be what it reaches. A method is reached through its receiver.
+ if fn.kind == "method":
+ return False
+ allowed = 2 if deleting else 1
+ return binding_count(repo.read(path) or [], path, repo.language, fn.name) > allowed
+ for binding in repo.bindings(path).get(fn.name, ()):
+ if not (deleting and binding == ("def", path)) and not _imports_fn(binding, fn):
+ return True
+ return False
+
+
+def _imports_fn(binding: tuple[str, ...], fn: _Fn) -> bool:
+ """Whether a site's *binding* of ``fn.name`` is an import of *fn* itself."""
+ if binding[0] != "from" or binding[2] != fn.name:
+ return False
+ module = binding[1]
+ return module == fn.qualified.rpartition(".")[0] or module == _module_path(fn)
+
+
+def _module_path(fn: _Fn) -> str:
+ return module_of(fn.file, "python" if fn.file.endswith(".py") else "typescript")
+
+
+def _twin_site(
+ repo: _Repo, src: _Source, twin: _Fn, span: tuple[int, int], lines: Lines
+) -> tuple[Site | None, str | None]:
+ """*twin* is a whole copy of ``F``. Under the same name it is deleted for an
+ import (a body calling ``F`` by that name would call itself); under another
+ name its header stays and its body becomes one call to ``F``."""
+ fn = src.fn
+ if (fn.kind == "method" or twin.kind == "method") and not _same_class(fn, twin):
+ return None, "receiver"
+ if twin.kind == "function" and twin.parent:
+ return None, "nested" # a closure: its body may read its parent's variables
+ if _decorated(lines, twin):
+ return None, "decorated"
+ theirs = _header(lines, twin, repo.language)
+ if [_renamed(t, twin.name, fn.name) for t in theirs] != src.header:
+ return None, "header_differs"
+ if _name_taken(repo, fn, twin.file, deleting=fn.name == twin.name):
+ return None, "name_taken"
+ if fn.name == twin.name:
+ refused = _undeletable(repo, twin, lines)
+ if refused:
+ return None, refused
+ return _site_dict(twin.file, (twin.start, twin.end), "delete", None, twin), None
+ if src.params is None:
+ return None, "param_mismatch"
+ call = _call(repo.language, fn, src.params, async_host=twin.is_async)
+ if call is None:
+ return None, "host_not_async"
+ return _site_dict(twin.file, span, "replace_with_call", f"return {call}", twin), None
+
+
+def _undeletable(repo: _Repo, twin: _Fn, lines: Lines) -> str | None:
+ """Why the copy *twin* cannot simply go: something else may import it."""
+ if twin.kind == "method":
+ return "twin_exported" # a duplicate method under one name cannot exist
+ head = lines[twin.start - 1].lstrip() if twin.start <= len(lines) else ""
+ if head.startswith("export") or not twin.private:
+ return "twin_exported"
+ if exported_later(lines, twin.name, repo.language):
+ return "twin_exported"
+ for source, _v in repo.graph.in_edges(twin.id):
+ node = repo.graph.nodes[source]
+ if (node.get("file_path") or source) != twin.file:
+ return "twin_imported"
+ return None
+
+
+def _call_site(
+ repo: _Repo, src: _Source, host: _Fn, span: tuple[int, int], lines: Lines
+) -> tuple[Site | None, str | None]:
+ """The lines are a block inside *host*: one call to ``F`` replaces them."""
+ lang = repo.language
+ fn = src.fn
+ block = [t for _n, t in _code(lines, span[0], span[1], lang)]
+ refused = _block_refusal(src, host, block, lang)
+ if refused or src.params is None:
+ return None, refused or "param_mismatch"
+ if _name_taken(repo, fn, host.file, deleting=False):
+ return None, "name_taken"
+ after = [t for _n, t in _code(lines, span[1] + 1, host.end, lang)]
+ elsewhere = [t for _n, t in _code(lines, host.start, span[0] - 1, lang)] + after
+ if _assigned(block, lang) & read_names(elsewhere, lang):
+ return None, "outputs_used_after"
+ # The host's own variable, not the module's; ``F``'s name included, which
+ # the call itself must reach.
+ free = (src.reads - src.own) | {fn.name}
+ if free & _enclosing_names(repo, host.file, lines, span):
+ return None, "free_names"
+ text, refused = _call_text(src, host, block, after, lang)
+ if text is None:
+ return None, refused
+ return _site_dict(host.file, span, "replace_with_call", text, None), None
+
+
+def _call_text(
+ src: _Source, host: _Fn, block: list[str], after: list[str], language: str
+) -> tuple[str | None, str | None]:
+ """The statement replacing *block*: the call, returned when the block
+ returns (only where that ends *host*)."""
+ returns = any((_PY_RETURN if language == "python" else _JS_RETURN).search(t) for t in block)
+ if returns and not all(_CLOSERS.match(t) for t in after):
+ return None, "returns_mid_host"
+ call = _call(language, src.fn, src.params or (None, []), async_host=host.is_async)
+ if call is None:
+ return None, "host_not_async"
+ return (f"return {call}" if returns else call), None
+
+
+def _block_refusal(src: _Source, host: _Fn, block: list[str], language: str) -> str | None:
+ """Why a call to ``F`` cannot stand in for *block* wherever it sits."""
+ fn = src.fn
+ if fn.kind == "method" and not _same_class(fn, host):
+ return "receiver"
+ if host.name == fn.name:
+ return "name_shadowed" # the call would reach the host itself
+ if any(_YIELD.search(t) for t in block):
+ return "generator"
+ if fn.kind != "method" and any(_RECEIVER.search(t) for t in block):
+ return "receiver"
+ if src.params is None or not set(src.params[1]) <= read_names(block, language):
+ return "param_mismatch"
+ return None
+
+
+def _enclosing_names(repo: _Repo, path: str, lines: Lines, span: tuple[int, int]) -> set[str]:
+ """Names every function enclosing *span* binds outside it (a closure sees
+ its parents'): parameters and locals."""
+ lang = repo.language
+ out: set[str] = set()
+ for host in repo.functions(path):
+ if not (host.start < span[0] and host.end >= span[1]):
+ continue
+ params = parameter_names(host.signature, lang, host.kind)
+ if params is not None:
+ out |= set(params[1])
+ else:
+ out |= set(_IDENTS.findall(" ".join(_header(lines, host, lang))))
+ outside = _code(lines, host.start, span[0] - 1, lang) + _code(lines, span[1] + 1, host.end, lang)
+ out |= _assigned([t for _n, t in outside], lang)
+ return out
+
+
+def _call(
+ language: str, fn: _Fn, sig: tuple[str | None, list[str]], *, async_host: bool
+) -> str | None:
+ """The call to *fn*, from the shared renderer; None when the host cannot
+ await it or a Python method is not reached through ``self``."""
+ receiver, params = sig
+ if fn.kind == "method" and language == "python" and receiver != "self":
+ return None
+ shape = render.HelperShape(
+ language=language,
+ name=fn.name,
+ kind=fn.kind,
+ is_async=fn.is_async,
+ params=tuple(render.Slot(p) for p in params),
+ receiver=receiver if fn.kind == "method" else None,
+ async_host=async_host,
+ )
+ out = render.render(shape)
+ return out.call if out else None
+
+
+def _same_class(a: _Fn, b: _Fn) -> bool:
+ return a.file == b.file and a.parent is not None and a.parent == b.parent
+
+
+def _site_dict(
+ path: str, span: tuple[int, int], action: ReuseSiteAction, text: str | None, twin: _Fn | None
+) -> Site:
+ return {
+ "file": path,
+ "span": {"start": span[0], "end": span[1]},
+ "action": action,
+ "new_text": text,
+ "replaces": twin.id if twin else None,
+ }
+
+
+def _payload(fn: _Fn, sites: list[Site]) -> dict[str, Any]:
+ others = len(sites)
+ return {
+ "existing_symbol": fn.id,
+ "file": fn.file,
+ "span": {"start": fn.start, "end": fn.end},
+ "reason": (
+ f"`{fn.name}` already holds this block; "
+ + ("the other site repeats" if others == 1 else f"the other {others} sites repeat")
+ + " its body line for line."
+ ),
+ "sites": sites,
+ }
+
+
+# -- text ----------------------------------------------------------------------
+
+
+def _code(lines: Lines, first: int, last: int, language: str) -> Code:
+ """``(line, text)`` for the code lines of 1-indexed *first*..*last*:
+ whitespace collapsed, blank and whole-line comment lines dropped."""
+ comments = ("#",) if language == "python" else ("//", "/*", "*")
+ out = []
+ for n in range(max(first, 1), min(last, len(lines)) + 1):
+ text = " ".join(lines[n - 1].split())
+ if text and not text.startswith(comments):
+ out.append((n, text))
+ return out
+
+
+def _body(lines: Lines, fn: _Fn, language: str) -> Code:
+ """*fn*'s body code lines, a leading Python docstring left out."""
+ first, last = body_span(lines, fn.start - 1, min(fn.end, len(lines)) - 1)
+ code = _code(lines, first + 1, last + 1, language)
+ if language == "python" and code and (m := _DOC_OPENERS.match(code[0][1])):
+ delim = m.group(1)
+ if delim in code[0][1][m.end() :]:
+ return code[1:]
+ close = next((i for i, (_n, t) in enumerate(code[1:], 1) if delim in t), len(code))
+ return code[close + 1 :]
+ return code
+
+
+def _header(lines: Lines, fn: _Fn, language: str) -> list[str]:
+ """*fn*'s header lines, an ``export`` prefix aside (the import replaces it)."""
+ first, _last = body_span(lines, fn.start - 1, min(fn.end, len(lines)) - 1)
+ head = [t for _n, t in _code(lines, fn.start, first, language)]
+ return [_EXPORT.sub("", head[0]), *head[1:]] if head else head
+
+
+def _decorated(lines: Lines, fn: _Fn) -> bool:
+ """Whether *fn* carries a decorator: the parser's list when the graph has
+ one, else the source above its span (comments and blank lines skipped, a
+ multi-line decorator followed back to its ``@`` line)."""
+ if fn.decorators is not None:
+ return bool(fn.decorators)
+ first = lines[fn.start - 1].strip() if fn.start <= len(lines) else ""
+ if first.startswith("@"):
+ return True
+ depth = 0
+ for n in range(fn.start - 2, max(fn.start - 2 - _DECORATOR_SCAN, -1), -1):
+ text = lines[n].strip()
+ if not text or (depth == 0 and text.startswith(("#", "//", "/*", "*"))):
+ continue
+ depth += text.count(")") - text.count("(")
+ if depth <= 0:
+ return text.startswith("@")
+ return False
+
+
+def _renamed(text: str, old: str, new: str) -> str:
+ return re.sub(rf"(?<![\w$]){re.escape(old)}(?![\w$])", new, text, count=1)
+
+
+def _match(lines: Lines, body: Code, occ: Occurrence, language: str, slack: int) -> tuple[int, int] | None:
+ """Where *body* appears line for line near the occurrence, else None."""
+ window = _code(lines, occ[1] - slack, occ[2] + slack, language)
+ want = [t for _n, t in body]
+ texts = [t for _n, t in window]
+ for i in range(len(texts) - len(want) + 1):
+ if texts[i : i + len(want)] == want:
+ return window[i][0], window[i + len(want) - 1][0]
+ return None
+
+
+def _assigned(texts: list[str], language: str) -> set[str]:
+ """Names the lines bind: assignments, loop, ``as`` and walrus targets,
+ lambda / arrow / catch parameters, local imports, JS declarations.
+ Attribute and item writes bind no name."""
+ found: list[str] = []
+ for t in texts:
+ if language == "python":
+ m = _PY_ASSIGN.match(t)
+ found += _PY_BIND.findall(t) + _PY_LAMBDA.findall(t) + _WALRUS.findall(t)
+ if imp := _PY_LOCAL_IMPORT.match(t):
+ found += [i.split(" as ")[-1].split(".")[0] for i in imp.group(1).split(",")]
+ else:
+ m = _JS_ASSIGN.match(t)
+ found += _JS_DECL.findall(t)
+ found += [" ".join(g) for g in _JS_PARAMS.findall(t)]
+ if m:
+ found.append(m.group(1))
+ return {n for group in found for n in _IDENTS.findall(group)}
+
+
+__all__ = ["MIN_COVERAGE", "REUSE_SITE_ACTIONS", "Reuse", "ReuseSiteAction", "find_reuse"]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/reuse_names.py b/packages/core/src/repowise/core/analysis/health/refactoring/reuse_names.py
new file mode 100644
index 000000000..4b37f368d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/reuse_names.py
@@ -0,0 +1,301 @@
+"""Which names a function's text reads, and what each name is bound to in a file.
+
+A call to an existing function ``F`` stands in for a copy of its body only when
+every name the copy reads means the same thing at the copy's site as in ``F``'s
+module: ``logger`` imported from the same module, ``CONFIG`` the same object.
+This module reads the names off the text and each file's module-level bindings
+off its top-level lines, so :mod:`.reuse` can compare them.
+
+Deliberately narrow, Python and TypeScript / JavaScript only. A binding it does
+not recognise (one made inside a top-level ``if`` or ``try``, a ``require``) is
+no binding, and a name with no binding that is not a local or a builtin is
+"unresolved", which the caller refuses on. Missing a binding costs a plan,
+never a wrong one.
+"""
+
+from __future__ import annotations
+
+import builtins
+import keyword
+import posixpath
+import re
+
+Binding = tuple[str, ...]
+
+_PY_BUILTINS = frozenset(n for n in dir(builtins) if not n.startswith("__"))
+_PY_WORDS = frozenset(keyword.kwlist) | frozenset(keyword.softkwlist)
+_JS_WORDS = frozenset(
+ (
+ "abstract", "any", "as", "async", "await", "bigint", "boolean", "break", "case",
+ "catch", "class", "const", "continue", "debugger", "declare", "default",
+ "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for",
+ "from", "function", "get", "if", "implements", "import", "in", "infer",
+ "instanceof", "interface", "is", "keyof", "let", "new", "never", "null",
+ "number", "object", "of", "package", "private", "protected", "public",
+ "readonly", "return", "satisfies", "set", "static", "string", "super", "switch",
+ "symbol", "this", "throw", "true", "try", "type", "typeof", "undefined",
+ "unique", "unknown", "var", "void", "while", "with", "yield",
+ )
+)
+_JS_GLOBALS = frozenset(
+ (
+ "Array", "ArrayBuffer", "Boolean", "console", "Date", "decodeURIComponent",
+ "encodeURIComponent", "Error", "Infinity", "Intl", "isFinite", "isNaN", "JSON",
+ "Map", "Math", "NaN", "Number", "Object", "parseFloat", "parseInt", "Partial",
+ "Pick", "Omit", "Promise", "Proxy", "Readonly", "Record", "Reflect", "RegExp",
+ "Required", "ReturnType", "Set", "String", "Symbol", "TypeError", "URL",
+ "URLSearchParams", "WeakMap", "WeakSet",
+ )
+)
+_MAX_CONTINUATION = 60
+_JS_EXPORT_STATEMENT = re.compile(
+ r"^(export\s*\{|export\s+default\s+[\w$]+\s*;?$|module\.exports|exports\.)"
+)
+_JS_EXTS = (".tsx", ".ts", ".jsx", ".js", ".mjs", ".cjs")
+
+# Names read from the text: an identifier not after a member dot (spread
+# ``...x`` still reads ``x``) and not inside a number.
+_IDENT = re.compile(r"(?<![\w$])(?<!(?<!\.\.)\.)[A-Za-z_$][\w$]*")
+_PY_STRING = re.compile(r"""([rRbBuUfF]{0,2})("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')""")
+_JS_STRING = re.compile(r"""("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)""")
+_BRACED = re.compile(r"\{([^{}]*)\}")
+_PY_KWARG = re.compile(r"[(,]\s*([A-Za-z_]\w*)\s*=(?!=)")
+# An object key: after ``{`` or ``,``, or opening a line (a key on its own line).
+_JS_KEY = re.compile(r"(?:^|[{,])\s*([A-Za-z_$][\w$]*)\s*:(?!:)")
+# A JSX intrinsic element (``<div``, ``</span>``) names no binding.
+_JSX_TAG = re.compile(r"</?([a-z][\w-]*)")
+_JSX_ATTR = re.compile(r"\s([A-Za-z_$][\w$-]*)=[\"'{]")
+
+_PY_FROM = re.compile(r"^from\s+(\.*)([\w.]*)\s+import\s+(.+)$")
+_PY_IMPORT = re.compile(r"^import\s+(.+)$")
+_PY_DEF = re.compile(r"^(?:async\s+)?(?:def|class)\s+(\w+)")
+_PY_TOP_ASSIGN = re.compile(r"^([\w\s,]+?)\s*(?::[^=]+)?=(?!=)")
+_JS_IMPORT = re.compile(r"""^import\s+(?:type\s+)?(.+?)\s+from\s+['"]([^'"]+)['"]""")
+_JS_DECL = re.compile(
+ r"^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:abstract\s+)?"
+ r"(?:function\*?|class|const|let|var|type|interface|enum)\s+([\[{][^=]*|[A-Za-z_$][\w$]*)"
+)
+
+
+def read_names(texts: list[str], language: str) -> set[str]:
+ """Names *texts* read: string contents, comments, attribute names, keyword
+ arguments, object keys and JSX attribute names left out; a formatted
+ string's or template's expressions kept."""
+ out: set[str] = set()
+ for text in texts:
+ bare = _strip_strings(text, language)
+ bare = re.sub(r"#.*$" if language == "python" else r"//.*$", "", bare)
+ skip = set(_PY_KWARG.findall(bare)) if language == "python" else set(
+ _JS_KEY.findall(bare) + _JSX_ATTR.findall(" " + bare) + _JSX_TAG.findall(bare)
+ )
+ out |= {n for n in _IDENT.findall(bare) if n not in skip}
+ return out - (_PY_WORDS if language == "python" else _JS_WORDS)
+
+
+def is_builtin(name: str, language: str) -> bool:
+ return name in (_PY_BUILTINS if language == "python" else _JS_GLOBALS)
+
+
+def _strip_strings(text: str, language: str) -> str:
+ if language == "python":
+
+ def keep(m: re.Match[str]) -> str:
+ if "f" not in m.group(1).lower():
+ return '""'
+ return " ".join(_expr(e) for e in _BRACED.findall(m.group(2)))
+
+ return _PY_STRING.sub(keep, text)
+
+ def keep_js(m: re.Match[str]) -> str:
+ body = m.group(1)
+ if not body.startswith("`"):
+ return '""'
+ return " ".join(_expr(e) for e in re.findall(r"\$\{([^{}]*)\}", body))
+
+ return _JS_STRING.sub(keep_js, text)
+
+
+def _expr(field: str) -> str:
+ """A format field's expression: its conversion and format spec dropped."""
+ return re.split(r"![rsa]|:(?![=])", field, maxsplit=1)[0]
+
+
+def module_bindings(lines: list[str], path: str, language: str) -> dict[str, set[Binding]]:
+ """Each name *path* binds at module level, mapped to what it is bound to:
+ ``("def", path)`` for a definition here, ``("from", module, name)`` /
+ ``("module", module)`` for an import (relative modules resolved against
+ *path*). ``"*"`` maps to ``{("star",)}`` when the file star-imports."""
+ out: dict[str, set[Binding]] = {}
+ scan = _py_bindings if language == "python" else _js_bindings
+ for statement in _top_level_statements(lines):
+ for name, binding in scan(statement, path):
+ out.setdefault(name, set()).add(binding)
+ return out
+
+
+def binding_count(lines: list[str], path: str, language: str, name: str) -> int:
+ """How many module-level statements in *path* bind *name* (definitions,
+ assignments, imports): :func:`module_bindings` folds them into one set.
+ Python counts the module-level ``if`` / ``try`` / ``with`` blocks too."""
+ if language == "python":
+ statements, scan = _py_module_statements(lines), _py_bindings
+ else:
+ statements, scan = _top_level_statements(lines), _js_bindings
+ return sum(n == name for st in statements for n, _b in scan(st, path))
+
+
+def _py_module_statements(lines: list[str]) -> list[str]:
+ """Statements that run at module level, at any depth inside a compound
+ statement: a ``def`` / ``class`` body and an ``if TYPE_CHECKING:`` block
+ are skipped (neither binds at run time). A bracketed continuation is
+ joined onto its first line."""
+ out: list[str] = []
+ parts: list[str] = []
+ depth = 0
+ skip: int | None = None
+ for raw in lines:
+ text = raw.strip()
+ if depth > 0:
+ parts.append(text)
+ else:
+ if not text or text.startswith("#"):
+ continue
+ indent = len(raw) - len(raw.lstrip())
+ if skip is not None and indent > skip:
+ continue
+ skip = indent if _PY_DEF.match(text) or text.startswith("if TYPE_CHECKING") else None
+ parts = [text]
+ depth = max(0, depth + sum(raw.count(o) - raw.count(c) for o, c in ("()", "{}", "[]")))
+ if depth == 0:
+ out.append(" ".join(parts))
+ elif len(parts) > _MAX_CONTINUATION:
+ depth = 0
+ return out
+
+
+def _top_level_statements(lines: list[str]) -> list[str]:
+ """Unindented lines, a bracketed continuation joined onto its first line.
+ A continuation that runs past ``_MAX_CONTINUATION`` lines (a bracket in a
+ string threw the count off) is dropped: no binding is read from it."""
+ out: list[str] = []
+ parts: list[str] = []
+ depth = 0
+ in_comment = False
+ for raw in lines:
+ if in_comment or (depth == 0 and raw.startswith("/*")):
+ in_comment = "*/" not in raw[2 if not in_comment else 0 :]
+ continue
+ if depth > 0:
+ parts.append(raw.strip())
+ elif raw[:1].strip() and not raw.startswith(("#", "//", "/*", "*")):
+ parts = [raw.strip()]
+ else:
+ continue
+ depth = max(0, depth + sum(raw.count(o) - raw.count(c) for o, c in ("()", "{}", "[]")))
+ if depth == 0:
+ out.append(" ".join(parts))
+ elif len(parts) > _MAX_CONTINUATION:
+ depth = 0
+ return out
+
+
+def _py_bindings(statement: str, path: str) -> list[tuple[str, Binding]]:
+ if m := _PY_FROM.match(statement):
+ module = _py_module(m.group(1), m.group(2), path)
+ names = m.group(3).strip("() ").split(",")
+ out = []
+ for item in (n.strip() for n in names if n.strip()):
+ if item == "*":
+ out.append(("*", ("star",)))
+ continue
+ original, _, alias = item.partition(" as ")
+ out.append((alias.strip() or original.strip(), ("from", module, original.strip())))
+ return out
+ if m := _PY_IMPORT.match(statement):
+ out = []
+ for item in (n.strip() for n in m.group(1).split(",")):
+ original, _, alias = item.partition(" as ")
+ name = alias.strip() or original.split(".")[0].strip()
+ out.append((name, ("module", original.strip() if alias else name)))
+ return out
+ if m := _PY_DEF.match(statement):
+ return [(m.group(1), ("def", path))]
+ if m := _PY_TOP_ASSIGN.match(statement):
+ return [(n, ("def", path)) for n in re.findall(r"\w+", m.group(1))]
+ return []
+
+
+def _py_module(dots: str, module: str, path: str) -> str:
+ if not dots:
+ return module
+ parts = posixpath.dirname(path).split("/")
+ up = len(dots) - 1
+ base = parts[: len(parts) - up] if up else parts
+ return "/".join([*base, *module.split(".")]) if module else "/".join(base)
+
+
+def _js_bindings(statement: str, path: str) -> list[tuple[str, Binding]]:
+ if m := _JS_IMPORT.match(statement):
+ module = _js_module(m.group(2), path)
+ return _js_import_clause(m.group(1), module)
+ if m := _JS_DECL.match(statement):
+ target = m.group(1)
+ names = re.findall(r"[A-Za-z_$][\w$]*", target) if target[0] in "[{" else [target]
+ return [(n, ("def", path)) for n in names]
+ return []
+
+
+def _js_import_clause(clause: str, module: str) -> list[tuple[str, Binding]]:
+ out: list[tuple[str, Binding]] = []
+ braced = re.search(r"\{([^}]*)\}", clause)
+ if braced:
+ for item in (i.strip() for i in braced.group(1).split(",")):
+ item = re.sub(r"^type\s+", "", item)
+ if not item:
+ continue
+ original, _, alias = item.partition(" as ")
+ out.append((alias.strip() or original.strip(), ("from", module, original.strip())))
+ clause = clause[: braced.start()] + clause[braced.end() :]
+ if m := re.search(r"\*\s+as\s+([A-Za-z_$][\w$]*)", clause):
+ out.append((m.group(1), ("module", module)))
+ clause = clause[: m.start()] + clause[m.end() :]
+ default = clause.strip(" ,")
+ if re.fullmatch(r"[A-Za-z_$][\w$]*", default):
+ out.append((default, ("from", module, "default")))
+ return out
+
+
+def _js_module(spec: str, path: str) -> str:
+ if not spec.startswith("."):
+ return spec
+ resolved = posixpath.normpath(posixpath.join(posixpath.dirname(path), spec))
+ for ext in _JS_EXTS:
+ if resolved.endswith(ext):
+ resolved = resolved[: -len(ext)]
+ break
+ return resolved.removesuffix("/index")
+
+
+def exported_later(lines: list[str], name: str, language: str) -> bool:
+ """Whether a statement apart from *name*'s definition exports it: an
+ ``export { name }`` / ``export default name`` / ``module.exports`` line, or
+ Python's ``__all__``."""
+ word = re.compile(rf"(?<![\w$]){re.escape(name)}(?![\w$])")
+ quoted = re.compile(rf"['\"]{re.escape(name)}['\"]")
+ for statement in _top_level_statements(lines):
+ if language == "python":
+ if statement.startswith("__all__") and quoted.search(statement):
+ return True
+ elif _JS_EXPORT_STATEMENT.match(statement) and word.search(statement):
+ return True
+ return False
+
+
+def module_of(path: str, language: str) -> str:
+ """*path* as the module string a relative import of it resolves to."""
+ if language == "python":
+ return path.removesuffix(".py").removesuffix("/__init__")
+ return _js_module("./" + posixpath.basename(path), path)
+
+
+__all__ = ["binding_count", "exported_later", "is_builtin", "module_bindings", "module_of", "read_names"]
diff --git a/packages/core/src/repowise/core/analysis/signature_effect.py b/packages/core/src/repowise/core/analysis/signature_effect.py
index 08236243a..d417043e4 100644
--- a/packages/core/src/repowise/core/analysis/signature_effect.py
+++ b/packages/core/src/repowise/core/analysis/signature_effect.py
@@ -329,6 +329,28 @@ def _parse_signature(sig: str, lang: str | None, kind: str | None) -> _Signature
return _Signature(params=params, returns=returns, receiver=receiver)
+def parameter_names(
+ signature: str, language: str | None = None, kind: str | None = None
+) -> tuple[str | None, list[str]] | None:
+ """The receiver (Python's ``self`` / ``cls``, a Rust ``&self``, a Go
+ receiver; None when there is none) and the names a call passes in order.
+
+ None when the list cannot be parsed or a call could not fill it by
+ position alone: a variadic, a keyword-only marker or argument, or a
+ destructured parameter.
+ """
+ lang = (language or "").lower() or None
+ parsed = _parse_signature(_normalize(signature, lang), lang, kind)
+ if parsed is None:
+ return None
+ names: list[str] = []
+ for param in parsed.params:
+ if param.kind != "param" or param.keyword_only or not param.name.isidentifier():
+ return None
+ names.append(param.name)
+ return parsed.receiver, names
+
+
def _split_default(text: str, lang: str | None, param: _Param) -> str:
at = _find_top(text, lang, "=")
if at is None:
diff --git a/packages/core/src/repowise/core/callable_spans.py b/packages/core/src/repowise/core/callable_spans.py
new file mode 100644
index 000000000..a5f30fcb0
--- /dev/null
+++ b/packages/core/src/repowise/core/callable_spans.py
@@ -0,0 +1,61 @@
+"""Where a function's header ends and its body lies, read off its source lines.
+
+Language-agnostic bracket counting over the lines a symbol's span covers, for
+consumers that hold a symbol's line range and its file's text but no parse
+tree: the skeleton view elides bodies, and refactoring compares two functions'
+bodies line for line.
+"""
+
+from __future__ import annotations
+
+import re
+
+#: Max lines scanned past a symbol's start to find the end of its signature.
+_SIG_SCAN_MAX = 12
+
+#: A body's last line that only closes it (``}``, ``});``, ``end``).
+_CLOSER_RE = re.compile(r"\s*(?:[})\];,]+|end)\s*")
+
+
+def signature_end(lines: list[str], start: int, end: int) -> int:
+ """Last 0-indexed line of the signature starting at *start*.
+
+ Bracket-balance scan, language-agnostic: the signature ends on the first
+ line where parens/brackets are balanced and the line closes with a body
+ opener (``:``/``{``), a terminator (``;``), or the param list itself.
+ Allman-style braces (``{`` alone on the next line) are folded in. Falls
+ back to the start line when nothing matches within the scan window.
+ """
+ depth = 0
+ last = min(start + _SIG_SCAN_MAX - 1, end)
+ for i in range(start, last + 1):
+ line = lines[i]
+ depth += line.count("(") - line.count(")")
+ depth += line.count("[") - line.count("]")
+ if depth > 0:
+ continue
+ stripped = line.strip()
+ if not stripped:
+ continue
+ if stripped.endswith((":", "{", ";", "=>")):
+ return i
+ if stripped.startswith(("@", "#[")):
+ continue # annotation/attribute line a symbol's bounds may start on
+ # Signature closed without a body opener — check for an Allman brace.
+ j = i + 1
+ if j <= end and lines[j].strip().startswith("{"):
+ return j
+ return i
+ return start
+
+
+def body_span(lines: list[str], start: int, end: int) -> tuple[int, int]:
+ """First and last 0-indexed line of the body of the callable on lines
+ *start*..*end*: below its signature, above a line that only closes it.
+ Empty (first > last) for a one-line callable."""
+ body_start = signature_end(lines, start, end) + 1
+ body_end = end - 1 if end >= body_start and _CLOSER_RE.fullmatch(lines[end]) else end
+ return body_start, body_end
+
+
+__all__ = ["body_span", "signature_end"]
diff --git a/packages/core/src/repowise/core/distill/skeleton.py b/packages/core/src/repowise/core/distill/skeleton.py
index 6b3e5a015..84f09ae79 100644
--- a/packages/core/src/repowise/core/distill/skeleton.py
+++ b/packages/core/src/repowise/core/distill/skeleton.py
@@ -36,6 +36,7 @@ import re
from collections.abc import Sequence
from dataclasses import dataclass, field, replace
+from repowise.core.callable_spans import body_span, signature_end
from repowise.core.distill.budget import estimate_tokens
__all__ = [
@@ -51,9 +52,6 @@ DEFAULT_TOKEN_BUDGET = 1800
#: Hotspot files get proportionally more body context.
_HOTSPOT_BUDGET_FACTOR = 1.25
-#: Max lines scanned past a symbol's start to find the end of its signature.
-_SIG_SCAN_MAX = 12
-
#: Docstring lines kept directly under a signature before eliding the rest.
#: One line = the summary; the elision marker right after it signals more.
_DOCSTRING_KEEP_LINES = 1
@@ -86,10 +84,6 @@ _DOCSTRING_DELIMS = ('"""', "'''")
#: Symbol kinds whose body plus mode elides; every other kind is kept whole.
_CALLABLE_KINDS = frozenset({"function", "method"})
-#: A body's last line that only closes it (``}``, ``});``, ``end``) stays in
-#: plus mode, so the elision sits inside a well-formed block.
-_CLOSER_RE = re.compile(r"\s*(?:[})\];,]+|end)\s*")
-
@dataclass(frozen=True)
class SkeletonSymbol:
@@ -186,7 +180,7 @@ def build_skeleton(
sig_ends: dict[int, int] = {} # symbol index -> 0-indexed signature end
for idx, sym in enumerate(usable):
s = sym.start_line - 1
- e = _signature_end(lines, s, sym.end_line - 1)
+ e = signature_end(lines, s, sym.end_line - 1)
sig_ends[idx] = e
for i in range(s, e + 1):
keep[i] = True
@@ -280,38 +274,6 @@ def _keep_preamble(lines: list[str], first_start: int, keep: list[bool]) -> None
keep[j] = True
-def _signature_end(lines: list[str], start: int, end: int) -> int:
- """Last 0-indexed line of the signature starting at *start*.
-
- Bracket-balance scan, language-agnostic: the signature ends on the first
- line where parens/brackets are balanced and the line closes with a body
- opener (``:``/``{``), a terminator (``;``), or the param list itself.
- Allman-style braces (``{`` alone on the next line) are folded in. Falls
- back to the start line when nothing matches within the scan window.
- """
- depth = 0
- last = min(start + _SIG_SCAN_MAX - 1, end)
- for i in range(start, last + 1):
- line = lines[i]
- depth += line.count("(") - line.count(")")
- depth += line.count("[") - line.count("]")
- if depth > 0:
- continue
- stripped = line.strip()
- if not stripped:
- continue
- if stripped.endswith((":", "{", ";", "=>")):
- return i
- if stripped.startswith(("@", "#[")):
- continue # annotation/attribute line a symbol's bounds may start on
- # Signature closed without a body opener — check for an Allman brace.
- j = i + 1
- if j <= end and lines[j].strip().startswith("{"):
- return j
- return i
- return start
-
-
def _elide_callable_bodies(
lines: list[str], symbols: list[SkeletonSymbol], keep: list[bool]
) -> None:
@@ -325,8 +287,7 @@ def _elide_callable_bodies(
if sym.kind not in _CALLABLE_KINDS or start <= covered_until:
continue
covered_until = end
- body_start = _signature_end(lines, start, end) + 1
- body_end = end - 1 if end >= body_start and _CLOSER_RE.fullmatch(lines[end]) else end
+ body_start, body_end = body_span(lines, start, end)
for i in range(body_start, body_end + 1):
keep[i] = False
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index accfde774..2cd735f14 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -161,6 +161,29 @@ export interface RefactoringPlanPayoff {
new_symbol?: string;
}
+/** What an Extract Helper reuse plan does at a site: replace the lines with a
+ * call to the existing function, or delete a whole copy of it. Mirrors
+ * ``refactoring.reuse.REUSE_SITE_ACTIONS``. */
+export type ReuseSiteAction = "replace_with_call" | "delete";
+
+/** An Extract Helper plan's `plan.reuse`, on plan detail only: one site is
+ * already a function the others call instead of a new helper. */
+export interface ExtractHelperReuse {
+ existing_symbol: string;
+ file: string;
+ span: { start: number; end: number };
+ reason: string;
+ sites: Array<{
+ file: string;
+ span: { start: number; end: number };
+ action: ReuseSiteAction;
+ /** The statement that replaces the span; null for a deleted copy. */
+ new_text: string | null;
+ /** The copy's symbol id, when the site is a whole copy. */
+ replaces: string | null;
+ }>;
+}
+
/** What one recipe step does to the code. Mirrors ``refactoring.recipe.RECIPE_ACTIONS``. */
export type RecipeAction =
| "extract"
@@ -171,7 +194,8 @@ export type RecipeAction =
| "cut_import"
| "keep"
| "reexport"
- | "edit";
+ | "edit"
+ | "delete";
/** What must hold before the edit: tests that pass, a characterization test to
* add, a plan risk, risks never checked (`unchecked`), or a plan type not yet
@@ -211,6 +235,9 @@ export interface RecipeStep {
to_file?: string | null;
/** Extract Helper: the directory the shared helper belongs in. */
directory?: string | null;
+ /** Extract Helper: the existing function this step calls (or whose copy it
+ * deletes) instead of a new helper. */
+ reuse?: { existing_symbol: string; file: string; reason: string };
applicability?: "mechanical" | "judgment";
/** This step's own checks, where they differ from the plan's. */
verify?: { commands: string[]; tests: string[]; coverage: string };
diff --git a/packages/ui/__tests__/refactoring/extract-helper-reuse.test.tsx b/packages/ui/__tests__/refactoring/extract-helper-reuse.test.tsx
new file mode 100644
index 000000000..fdc8c9270
--- /dev/null
+++ b/packages/ui/__tests__/refactoring/extract-helper-reuse.test.tsx
@@ -0,0 +1,66 @@
+/**
+ * An Extract Helper plan that reuses an existing function shows that function
+ * and each site's action, not a new `helper()`.
+ */
+
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+
+import { PlanDetail } from "../../src/refactoring/plan-detail";
+
+const plan = {
+ id: "plan-reuse",
+ refactoring_type: "extract_helper",
+ file_path: "pkg/b.py",
+ target_symbol: "pkg/b.py::run",
+ line_start: 6,
+ line_end: 11,
+ plan: {
+ occurrences: [
+ { file: "pkg/b.py", line_start: 6, line_end: 11 },
+ { file: "pkg/util.py", line_start: 4, line_end: 11 },
+ ],
+ suggested_name: "normalize_helper",
+ reuse: {
+ existing_symbol: "pkg/util.py::normalize",
+ file: "pkg/util.py",
+ span: { start: 4, end: 11 },
+ reason: "`normalize` already holds this block; the other 2 sites repeat its body line for line.",
+ sites: [
+ {
+ file: "pkg/b.py",
+ span: { start: 6, end: 11 },
+ action: "replace_with_call",
+ new_text: "return normalize(text, sep)",
+ replaces: null,
+ },
+ {
+ file: "pkg/c.py",
+ span: { start: 3, end: 9 },
+ action: "delete",
+ new_text: null,
+ replaces: "pkg/c.py::normalize",
+ },
+ ],
+ },
+ },
+ evidence: { duplicated_lines: 6 },
+ impact_delta: 0,
+ effort_bucket: "S",
+ blast_radius: {},
+ confidence: "high",
+ source_biomarker: "duplication",
+ rank_score: 1,
+} satisfies RefactoringPlan;
+
+describe("Extract Helper reuse detail", () => {
+ it("names the existing function and each site's call or delete", () => {
+ render(<PlanDetail plan={plan} />);
+ expect(screen.getByText("normalize()")).toBeTruthy();
+ expect(screen.getByText("return normalize(text, sep)")).toBeTruthy();
+ expect(screen.getByText(/Delete copy, lines 3–9/)).toBeTruthy();
+ expect(screen.queryByText(/normalize_helper/)).toBeNull();
+ expect(screen.queryByText(/Extract it once/)).toBeNull();
+ });
+});
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index a5035d5c9..299ebd46e 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -12,6 +12,7 @@ import {
extractClassGroups,
extractHelperDetail,
extractHelperOccurrences,
+ extractHelperReuse,
extractMethodPlan,
extractMethodSignature,
extractMethodStages,
@@ -27,7 +28,7 @@ import {
splitShimRequired,
} from "./types";
import type { ExtractStage } from "./types";
-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";
+import type { ExtractHelperReuse, RefactoringPlan } from "@repowise-dev/types/refactoring";
export interface PlanDetailProps {
plan: RefactoringPlan;
@@ -226,6 +227,73 @@ function StagedExtract({
/** One accent for every type. See the note in `plan-before.tsx`. */
const ACCENT = "var(--color-accent-fill)";
+/** Extract Helper when one site already is a function: name it, and say what
+ * each other site does (call it, or delete a copy of it). */
+function ReuseDetail({
+ reuse,
+ fileHref,
+ hideIntro,
+}: {
+ reuse: ExtractHelperReuse;
+ fileHref: PlanDetailProps["fileHref"];
+ hideIntro: boolean;
+}) {
+ const name = reuse.existing_symbol.split("::").pop() ?? reuse.existing_symbol;
+ return (
+ <div className="space-y-3">
+ {hideIntro ? null : (
+ <p className="text-xs text-[var(--color-text-tertiary)]">{reuse.reason}</p>
+ )}
+ <div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3.5">
+ <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Existing function
+ </div>
+ <FileRef
+ path={reuse.file}
+ line={reuse.span.start || null}
+ fileHref={fileHref}
+ label={`${name}()`}
+ className="mt-1 block break-all font-semibold"
+ />
+ </div>
+ <div className="space-y-1.5">
+ <div className="text-caption uppercase tracking-wide text-[var(--color-text-tertiary)]">
+ Change at {reuse.sites.length} site{reuse.sites.length === 1 ? "" : "s"}
+ </div>
+ <ul className="divide-y divide-[var(--color-border-default)] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
+ {reuse.sites.map((s, i) => (
+ <li key={i} className="space-y-1.5 px-3.5 py-2.5">
+ <div className="flex items-center justify-between gap-3">
+ <span className="min-w-0 flex-1">
+ <FileRef
+ path={s.file}
+ line={s.span.start || null}
+ fileHref={fileHref}
+ className="block truncate"
+ />
+ </span>
+ <span className="shrink-0 text-2xs tabular-nums text-[var(--color-text-tertiary)]">
+ {s.action === "delete" ? "Delete copy" : "Replace"}, lines {s.span.start}–
+ {s.span.end}
+ </span>
+ </div>
+ {s.action === "delete" ? (
+ <p className="text-2xs text-[var(--color-text-secondary)]">
+ Import <code>{name}</code> from <code>{reuse.file}</code> in its place.
+ </p>
+ ) : s.new_text ? (
+ <code className="block whitespace-pre-wrap break-all rounded bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-2xs text-[var(--color-text-secondary)]">
+ {s.new_text}
+ </code>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProps) {
const accent = ACCENT;
@@ -365,6 +433,8 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
}
if (plan.refactoring_type === "extract_helper") {
+ const reuse = extractHelperReuse(plan);
+ if (reuse) return <ReuseDetail reuse={reuse} fileHref={fileHref} hideIntro={hideIntro} />;
const occ = extractHelperOccurrences(plan);
const site = helperSite(plan);
const detail = extractHelperDetail(plan);
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 2a9f485aa..b13be5fa7 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -9,6 +9,7 @@
import type {
ExtractCallSite,
+ ExtractHelperReuse,
ExtractSlot,
GeneratedCode,
RefactoringPlan,
@@ -76,6 +77,38 @@ export function extractHelperOccurrences(plan: RefactoringPlan): ExtractHelperOc
});
}
+/** The existing function an Extract Helper plan calls instead of a new
+ * helper, and what happens at each other site; `null` when the plan adds a
+ * new helper. Sites with an unknown action are dropped. */
+export function extractHelperReuse(plan: RefactoringPlan): ExtractHelperReuse | null {
+ const r = plan.plan?.reuse as Record<string, unknown> | undefined;
+ if (!r || typeof r.existing_symbol !== "string" || !Array.isArray(r.sites)) return null;
+ const span = (v: unknown) => {
+ const s = (v ?? {}) as Record<string, unknown>;
+ return { start: Number(s.start ?? 0), end: Number(s.end ?? 0) };
+ };
+ const sites = r.sites.flatMap((raw): ExtractHelperReuse["sites"] => {
+ const s = (raw ?? {}) as Record<string, unknown>;
+ if (s.action !== "replace_with_call" && s.action !== "delete") return [];
+ return [
+ {
+ file: String(s.file ?? ""),
+ span: span(s.span),
+ action: s.action,
+ new_text: typeof s.new_text === "string" ? s.new_text : null,
+ replaces: typeof s.replaces === "string" ? s.replaces : null,
+ },
+ ];
+ });
+ return {
+ existing_symbol: r.existing_symbol,
+ file: String(r.file ?? ""),
+ span: span(r.span),
+ reason: typeof r.reason === "string" ? r.reason : "",
+ sites,
+ };
+}
+
/** Where the shared helper should live — a directory.
*
* `directory` is the only namespace a plan carries. Plans stored before that
diff --git a/tests/unit/health/test_engine_partner_lines.py b/tests/unit/health/test_engine_partner_lines.py
new file mode 100644
index 000000000..31734a946
--- /dev/null
+++ b/tests/unit/health/test_engine_partner_lines.py
@@ -0,0 +1,24 @@
+"""The health pass reads a clone partner's lines by repo path, once."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.health import HealthAnalyzer
+
+
+def test_a_partner_outside_the_parsed_set_is_read_under_the_repo_root(tmp_path: Path) -> None:
+ (tmp_path / "pkg").mkdir()
+ (tmp_path / "pkg" / "a.py").write_text("x = 1\ny = 2\n", encoding="utf-8")
+ reads: list[str] = []
+
+ def read_source(path: str) -> bytes | None:
+ reads.append(path)
+ return Path(path).read_bytes() if Path(path).is_file() else None
+
+ # An incremental pass may hand over only the files it re-parsed.
+ analyzer = HealthAnalyzer(None, parsed_files=[], repo_root=tmp_path, source_reader=read_source)
+ assert analyzer._repo_lines("pkg/a.py") == ["x = 1", "y = 2"]
+ assert analyzer._repo_lines("pkg/a.py") == ["x = 1", "y = 2"]
+ assert len(reads) == 1
+ assert analyzer._repo_lines("pkg/missing.py") is None
diff --git a/tests/unit/health/test_refactoring_reuse.py b/tests/unit/health/test_refactoring_reuse.py
new file mode 100644
index 000000000..f1001fabe
--- /dev/null
+++ b/tests/unit/health/test_refactoring_reuse.py
@@ -0,0 +1,481 @@
+"""Extract Helper names an existing function when one clone site already is it.
+
+A clone group whose one occurrence is a whole function ``F`` is planned as
+"call ``F``" at the other sites (or "delete this copy" when a site is ``F``
+again), never as a second copy. Anything that could make the call wrong keeps
+the new-helper plan: these tests pin each refusal.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.health.duplication import ClonePair
+from repowise.core.analysis.health.refactoring import RefactoringContext, detect_refactorings
+from repowise.core.analysis.health.refactoring.recipe import build_recipe
+from repowise.core.analysis.health.refactoring.render import list_plan
+from repowise.core.analysis.health.refactoring.reuse import find_reuse
+from repowise.core.analysis.signature_effect import parameter_names
+
+_BODY = [
+ " parts = text.split(sep)",
+ " cleaned = [p.strip() for p in parts]",
+ " joined = sep.join(cleaned)",
+ " if not joined:",
+ ' return ""',
+ " return joined.lower()",
+]
+
+
+def _fn(name: str = "normalize", params: str = "text, sep", body: list[str] | None = None) -> list[str]:
+ return [f"def {name}({params}):", ' """Normalise a separated string."""', *(body or _BODY)]
+
+
+def _host(
+ body: list[str] | None = None, tail: list[str] | None = None, params: str = "text, sep"
+) -> list[str]:
+ return [f"def run({params}):", ' print("start")', *(body or _BODY), *(tail or [])]
+
+
+class _Repo:
+ """Files, their symbols and import edges, as the graph and reader see them."""
+
+ def __init__(self) -> None:
+ self.graph = nx.DiGraph()
+ self.files: dict[str, list[str]] = {}
+
+ def file(self, path: str, lines: list[str]) -> _Repo:
+ self.files[path] = lines
+ self.graph.add_node(path, node_type="file")
+ return self
+
+ def symbol(self, path: str, name: str, start: int, end: int, signature: str, **attrs) -> _Repo:
+ parent = attrs.get("parent_name")
+ sid = attrs.get("sid") or (f"{path}::{parent}::{name}" if parent else f"{path}::{name}")
+ module = path.removesuffix(".py").replace("/", ".")
+ self.graph.add_node(
+ sid,
+ node_type="symbol",
+ kind=attrs.get("kind", "function"),
+ name=name,
+ file_path=path,
+ start_line=start,
+ end_line=end,
+ signature=signature,
+ visibility=attrs.get("visibility", "private" if name.startswith("_") else "public"),
+ parent_name=parent,
+ qualified_name=f"{module}.{name}",
+ is_async=False,
+ )
+ self.graph.add_edge(path, sid, edge_type="defines")
+ return self
+
+ def imports(self, importer: str, imported: str) -> _Repo:
+ self.graph.add_edge(importer, imported, edge_type="imports")
+ return self
+
+ def reuse(self, occurrences, language: str = "python"):
+ return find_reuse(self.graph, language, occurrences, self.files.get)
+
+
+_OCCURRENCES = [("pkg/b.py", 6, 11), ("pkg/util.py", 4, 11)]
+
+
+def _pair(
+ body: list[str] | None = None,
+ util_head: list[str] | None = None,
+ host_head: list[str] | None = None,
+ name: str = "normalize",
+ params: str = "text, sep",
+ host_params: str = "text, sep",
+) -> _Repo:
+ """``pkg/util.py`` defining F on lines 4-11; ``pkg/b.py`` whose ``run``
+ (lines 4-11) repeats F's body on lines 6-11. ``b`` imports ``util``."""
+ util = [*(util_head or ["import json", "", ""]), *_fn(name, params, body)]
+ host = [*(host_head or ["from pkg.util import normalize", "", ""]), *_host(body, params=host_params)]
+ return (
+ _Repo()
+ .file("pkg/util.py", util)
+ .file("pkg/b.py", host)
+ .symbol("pkg/util.py", name, 4, len(util), f"def {name}({params})")
+ .symbol("pkg/b.py", "run", 4, len(host), f"def run({host_params})")
+ .imports("pkg/b.py", "pkg/util.py")
+ )
+
+
+def test_a_block_that_is_a_whole_function_becomes_a_call_to_it() -> None:
+ reuse = _pair().reuse(_OCCURRENCES).plan
+ assert reuse["existing_symbol"] == "pkg/util.py::normalize"
+ (site,) = reuse["sites"]
+ assert site == {
+ "file": "pkg/b.py",
+ "span": {"start": 6, "end": 11},
+ "action": "replace_with_call",
+ "new_text": "return normalize(text, sep)",
+ "replaces": None,
+ }
+ plan = {"occurrences": [], "reuse": reuse}
+ recipe = build_recipe({"refactoring_type": "extract_helper", "plan": plan})
+ (step,) = recipe["steps"]
+ assert step["action"] == "replace_with_call"
+ assert step["call_site"]["new_text"] == "return normalize(text, sep)"
+ assert step["reuse"]["existing_symbol"] == "pkg/util.py::normalize"
+ assert recipe["summary"].startswith("Call the existing `normalize`")
+ # A list row stays the size it was: the texts are for plan detail.
+ assert "reuse" not in list_plan(plan)
+
+
+def test_the_detector_attaches_reuse_only_with_a_reader() -> None:
+ repo = _pair()
+ pair = ClonePair("pkg/b.py", "pkg/util.py", 6, 11, 4, 11, token_count=60)
+ ctx = RefactoringContext(
+ file_path="pkg/b.py",
+ language="python",
+ nloc=200,
+ clones=[pair],
+ graph=repo.graph,
+ source_lines=repo.files["pkg/b.py"],
+ read_lines=repo.files.get,
+ )
+ (plan,) = [s for s in detect_refactorings(ctx) if s.refactoring_type == "extract_helper"]
+ assert plan.plan["reuse"]["existing_symbol"] == "pkg/util.py::normalize"
+ ctx.read_lines = None
+ (plain,) = [s for s in detect_refactorings(ctx) if s.refactoring_type == "extract_helper"]
+ assert "reuse" not in plain.plan
+
+
+def test_a_private_function_in_another_module_is_not_importable() -> None:
+ repo = _pair(name="_normalize", host_head=["import os", "", ""])
+ assert repo.reuse(_OCCURRENCES).refused == "not_importable"
+
+
+def test_a_parameter_the_lines_never_use_is_refused() -> None:
+ assert _pair(params="text, sep, strict").reuse(_OCCURRENCES).refused == "param_mismatch"
+
+
+def test_a_keyword_only_parameter_is_refused() -> None:
+ assert _pair(params="text, *, sep").reuse(_OCCURRENCES).refused == "param_mismatch"
+ assert parameter_names("def f(a, *rest)", "python", "function") is None
+ assert parameter_names("function f({ a, b }: P)", "typescript", "function") is None
+
+
+def test_a_value_the_host_reads_afterwards_is_refused() -> None:
+ body = _BODY[:3]
+ util = ["import json", "", "", *_fn(body=body)]
+ host = ["import os", "", "", *_host(body=body, tail=[" print(joined)"])]
+ repo = (
+ _Repo()
+ .file("pkg/util.py", util)
+ .file("pkg/b.py", host)
+ .symbol("pkg/util.py", "normalize", 4, len(util), "def normalize(text, sep)")
+ .symbol("pkg/b.py", "run", 4, len(host), "def run(text, sep)")
+ .imports("pkg/b.py", "pkg/util.py")
+ )
+ assert repo.reuse([("pkg/b.py", 6, 8), ("pkg/util.py", 4, 8)]).refused == "outputs_used_after"
+
+
+# -- names the body reads -------------------------------------------------------
+
+
+def test_a_module_global_bound_differently_at_the_site_is_refused() -> None:
+ body = [" parts = text.split(SEP)", *_BODY[1:]]
+ repo = _pair(body, util_head=["SEP = ','", "", ""], host_head=["SEP = ';'", "", ""])
+ assert repo.reuse(_OCCURRENCES).refused == "free_names"
+
+
+def test_an_imported_helper_must_come_from_the_same_module() -> None:
+ body = [" parts = clean(text).split(sep)", *_BODY[1:]]
+
+ def build(source: str) -> _Repo:
+ util_head = ["from pkg.text import clean", "", ""]
+ host_head = [f"from {source} import clean", "from pkg.util import normalize", ""]
+ return _pair(body, util_head=util_head, host_head=host_head)
+
+ assert build("pkg.other").reuse(_OCCURRENCES).refused == "free_names"
+ assert build("pkg.text").reuse(_OCCURRENCES).plan is not None
+
+
+def test_a_host_variable_shadowing_a_module_name_is_refused() -> None:
+ body = [" parts = text.split(json.dumps(sep))", *_BODY[1:]]
+ repo = _pair(body, host_head=["import json", "", ""], host_params="text, sep, json")
+ assert repo.reuse(_OCCURRENCES).refused == "free_names"
+
+
+def test_a_site_binding_the_name_elsewhere_is_refused() -> None:
+ repo = _pair(host_head=["from pkg.other import normalize", "", ""])
+ assert repo.reuse(_OCCURRENCES).refused == "name_taken"
+
+
+def test_a_same_file_rebinding_of_the_name_is_refused() -> None:
+ def build(tail: list[str]) -> _Repo:
+ lines = [*_fn(), "", *_host(), *tail]
+ return (
+ _Repo()
+ .file("pkg/util.py", lines)
+ .symbol("pkg/util.py", "normalize", 1, 8, "def normalize(text, sep)")
+ .symbol("pkg/util.py", "run", 10, 17, "def run(text, sep)")
+ )
+
+ occurrences = [("pkg/util.py", 12, 17), ("pkg/util.py", 1, 8)]
+ assert build([]).reuse(occurrences).plan is not None
+ guarded = ["try:", " from fast import normalize", "except ImportError:", " pass"]
+ typing_only = ["if TYPE_CHECKING:", " from pkg.other import normalize"]
+ for tail in (["normalize = str.lower"], ["from pkg.other import normalize"], guarded):
+ assert build(tail).reuse(occurrences).refused == "name_taken"
+ assert build(typing_only).reuse(occurrences).plan is not None
+
+
+def test_a_same_file_copy_under_the_same_name_is_still_deleted() -> None:
+ def build(tail: list[str]) -> _Repo:
+ lines = [*_fn("_normalize"), "", *_fn("_normalize"), *tail]
+ return (
+ _Repo()
+ .file("pkg/util.py", lines)
+ .symbol("pkg/util.py", "_normalize", 1, 8, "def _normalize(text, sep)")
+ .symbol("pkg/util.py", "_normalize", 10, 17, "def _normalize(text, sep)", sid="copy")
+ )
+
+ occurrences = [("pkg/util.py", 1, 8), ("pkg/util.py", 10, 17)]
+ (site,) = build([]).reuse(occurrences).plan["sites"]
+ assert site["action"] == "delete" and site["replaces"] == "copy"
+ assert build(["_normalize = str.lower"]).reuse(occurrences).refused == "name_taken"
+
+
+def test_scope_statements_and_walrus_targets_are_read() -> None:
+ body = [" global CACHE", *_BODY[:5]]
+ repo = _pair(body)
+ assert repo.reuse(_OCCURRENCES).refused == "scope_statement"
+ walrus = [" if (n := len(text)) > 3:", " text = text[:n]", *_BODY[:4]]
+ util = ["import json", "", "", *_fn(body=walrus)]
+ host = ["import os", "", "", *_host(body=walrus, tail=[" print(n)"])]
+ repo = (
+ _Repo()
+ .file("pkg/util.py", util)
+ .file("pkg/b.py", host)
+ .symbol("pkg/util.py", "normalize", 4, len(util), "def normalize(text, sep)")
+ .symbol("pkg/b.py", "run", 4, len(host), "def run(text, sep)")
+ .imports("pkg/b.py", "pkg/util.py")
+ )
+ assert repo.reuse([("pkg/b.py", 6, 11), ("pkg/util.py", 4, 11)]).refused == "outputs_used_after"
+
+
+# -- reach ---------------------------------------------------------------------
+
+
+def test_a_sibling_whose_file_imports_the_site_is_an_import_cycle() -> None:
+ repo = _pair(host_head=["import os", "", ""])
+ repo.graph.remove_edge("pkg/b.py", "pkg/util.py")
+ assert repo.reuse(_OCCURRENCES).plan is not None # a sibling, no cycle
+ repo.imports("pkg/util.py", "pkg/b.py")
+ assert repo.reuse(_OCCURRENCES).refused == "import_cycle"
+
+
+def test_another_directory_needs_an_existing_import() -> None:
+ repo = _pair(host_head=["import os", "", ""])
+ repo.file("app/b.py", repo.files["pkg/b.py"]).symbol("app/b.py", "run", 4, 11, "def run(text, sep)")
+ occurrences = [("app/b.py", 6, 11), ("pkg/util.py", 4, 11)]
+ assert repo.reuse(occurrences).refused == "not_importable"
+ repo.imports("app/b.py", "pkg/util.py")
+ assert repo.reuse(occurrences).plan is not None
+
+
+# -- decorators and method forms -------------------------------------------------
+
+
+def test_a_decorated_function_is_refused() -> None:
+ repo = _pair(util_head=["import functools", "", "@functools.cache"])
+ assert repo.reuse(_OCCURRENCES).refused == "decorated"
+
+
+def _method(lines: list[str]) -> list[str]:
+ return [" " + t for t in lines]
+
+
+def test_a_static_method_is_refused() -> None:
+ lines = ["class C:", " @staticmethod", *_method(_fn()), "", *_method(_host(params="self, text, sep"))]
+ repo = (
+ _Repo()
+ .file("pkg/c.py", lines)
+ .symbol("pkg/c.py", "C", 1, len(lines), "class C", kind="class")
+ .symbol("pkg/c.py", "normalize", 3, 10, "def normalize(text, sep)", kind="method", parent_name="C")
+ .symbol("pkg/c.py", "run", 12, 19, "def run(self, text, sep)", kind="method", parent_name="C")
+ )
+ assert repo.reuse([("pkg/c.py", 3, 10), ("pkg/c.py", 14, 19)]).refused == "decorated"
+
+
+def test_a_method_is_called_through_self_from_its_own_class() -> None:
+ fn = _method(_fn(params="self, text, sep"))
+ lines = ["class C:", *fn, "", *_method(_host(params="self, text, sep"))]
+ repo = (
+ _Repo()
+ .file("pkg/c.py", lines)
+ .symbol("pkg/c.py", "C", 1, len(lines), "class C", kind="class")
+ .symbol("pkg/c.py", "normalize", 2, 9, "def normalize(self, text, sep)", kind="method", parent_name="C")
+ .symbol("pkg/c.py", "run", 11, 18, "def run(self, text, sep)", kind="method", parent_name="C")
+ )
+ (site,) = repo.reuse([("pkg/c.py", 2, 9), ("pkg/c.py", 13, 18)]).plan["sites"]
+ assert site["new_text"] == "return self.normalize(text, sep)"
+
+
+def test_a_typescript_static_method_is_refused() -> None:
+ body = [" const n = a + 1;", " const m = n * 2;", " const k = m - 3;", " return k;", " }"]
+ lines = ["class K {", " static f(a: number): number {", *body, " g(a: number): number {", *body, "}"]
+ repo = (
+ _Repo()
+ .file("ui/k.ts", lines)
+ .symbol("ui/k.ts", "K", 1, len(lines), "class K", kind="class")
+ .symbol("ui/k.ts", "f", 2, 7, "f(a: number) -> number", kind="method", parent_name="K")
+ .symbol("ui/k.ts", "g", 8, 13, "g(a: number) -> number", kind="method", parent_name="K")
+ )
+ verdict = repo.reuse([("ui/k.ts", 2, 7), ("ui/k.ts", 8, 13)], "typescript")
+ assert verdict.refused == "static_or_accessor"
+
+
+# -- whole copies ------------------------------------------------------------------
+
+
+_TS_BODY = [" const primary = variant === 1;", " if (!primary) {", " return 0;", " }", " return 2;", "}"]
+_TS_OCCURRENCES = [("ui/atoms.ts", 1, 7), ("ui/panel.ts", 3, 9)]
+
+
+def _ts_twins(twin_head: str = "", twin_visibility: str = "private") -> _Repo:
+ atoms = ["export function pick(variant: number): number {", *_TS_BODY]
+ panel = ["import x from './x';", "", f"{twin_head}function pick(variant: number): number {{", *_TS_BODY]
+ return (
+ _Repo()
+ .file("ui/atoms.ts", atoms)
+ .file("ui/panel.ts", panel)
+ .symbol("ui/atoms.ts", "pick", 1, 7, "function pick(variant: number): number")
+ .symbol("ui/panel.ts", "pick", 3, 9, "function pick(variant: number): number", visibility=twin_visibility)
+ )
+
+
+def test_a_private_typescript_copy_of_an_exported_function_is_deleted() -> None:
+ reuse = _ts_twins().reuse(_TS_OCCURRENCES, "typescript").plan
+ assert reuse["existing_symbol"] == "ui/atoms.ts::pick"
+ (site,) = reuse["sites"]
+ assert site["action"] == "delete" and site["replaces"] == "ui/panel.ts::pick"
+ recipe = build_recipe({"refactoring_type": "extract_helper", "plan": {"reuse": reuse}})
+ (step,) = recipe["steps"]
+ assert step["action"] == "delete" and step["span"] == {"start": 3, "end": 9}
+ assert "import `pick` from `ui/atoms.ts`" in step["text"]
+
+
+def test_an_exported_or_default_exported_copy_is_not_deleted() -> None:
+ for head in ("export ", "export default "):
+ repo = _ts_twins(head, twin_visibility="public")
+ assert repo.reuse(_TS_OCCURRENCES, "typescript").refused == "twin_exported"
+
+
+def test_a_copy_other_files_call_is_not_deleted() -> None:
+ repo = _ts_twins()
+ repo.file("ui/other.ts", ["x"]).graph.add_edge("ui/other.ts", "ui/panel.ts::pick", edge_type="calls")
+ assert repo.reuse(_TS_OCCURRENCES, "typescript").refused == "twin_imported"
+
+
+def test_a_decorated_copy_is_refused() -> None:
+ repo = _ts_twins()
+ repo.files["ui/panel.ts"][1] = "@memo"
+ assert repo.reuse(_TS_OCCURRENCES, "typescript").refused == "decorated"
+
+
+def test_a_renamed_copy_calls_the_original_only_under_the_same_header() -> None:
+ def build(header: str) -> _Repo:
+ util = ["import json", "", "", *_fn()]
+ copy = ["from pkg.util import normalize", "", "", header, *_fn()[1:]]
+ return (
+ _Repo()
+ .file("pkg/util.py", util)
+ .file("pkg/b.py", copy)
+ .symbol("pkg/util.py", "normalize", 4, 11, "def normalize(text, sep)")
+ .symbol("pkg/b.py", "_clean", 4, 11, header.rstrip(":"))
+ .imports("pkg/b.py", "pkg/util.py")
+ )
+
+ occurrences = [("pkg/b.py", 4, 11), ("pkg/util.py", 4, 11)]
+ (site,) = build("def _clean(text, sep):").reuse(occurrences).plan["sites"]
+ assert site["action"] == "replace_with_call"
+ assert site["new_text"] == "return normalize(text, sep)"
+ differs = build("def _clean(text, sep) -> str:").reuse(occurrences)
+ assert differs.refused == "header_differs"
+
+
+def test_a_public_python_copy_is_not_deleted() -> None:
+ lines = ["import json", "", "", *_fn()]
+ repo = (
+ _Repo()
+ .file("pkg/a.py", lines)
+ .file("pkg/util.py", list(lines))
+ .symbol("pkg/a.py", "normalize", 4, 11, "def normalize(text, sep)")
+ .symbol("pkg/util.py", "normalize", 4, 11, "def normalize(text, sep)")
+ )
+ assert repo.reuse([("pkg/a.py", 4, 11), ("pkg/util.py", 4, 11)]).refused == "twin_exported"
+
+
+def test_a_default_parameter_is_passed_by_position() -> None:
+ (site,) = _pair(params="text, sep=','").reuse(_OCCURRENCES).plan["sites"]
+ assert site["new_text"] == "return normalize(text, sep)"
+
+
+def test_a_copy_exported_by_a_later_statement_is_not_deleted() -> None:
+ repo = _ts_twins()
+ repo.files["ui/panel.ts"].append("export { pick };")
+ assert repo.reuse(_TS_OCCURRENCES, "typescript").refused == "twin_exported"
+
+
+def test_a_decorator_above_a_comment_or_spanning_lines_is_found() -> None:
+ commented = _pair(util_head=["import functools", "@functools.cache", "# memoised"])
+ assert commented.reuse(_OCCURRENCES).refused == "decorated"
+ multi = _pair(util_head=["@register(", " name='n',", ")"])
+ assert multi.reuse(_OCCURRENCES).refused == "decorated"
+
+
+def test_the_parsers_decorator_list_wins_over_the_text() -> None:
+ repo = _pair()
+ repo.graph.nodes["pkg/util.py::normalize"]["decorators"] = ["@functools.cache"]
+ assert repo.reuse(_OCCURRENCES).refused == "decorated"
+ repo = _pair(util_head=["import json", "", "# @not a decorator, a comment"])
+ repo.graph.nodes["pkg/util.py::normalize"]["decorators"] = []
+ assert repo.reuse(_OCCURRENCES).plan is not None
+
+
+def test_a_closure_sees_its_parents_variables() -> None:
+ body = [" parts = text.split(json.dumps(sep))", *(" " + t for t in _BODY[1:])]
+ util = ["import json", "", "", *_fn(body=[t[4:] for t in body])]
+ host = [
+ "import json",
+ "",
+ "",
+ "def outer(json):",
+ " def run(text, sep):",
+ ' print("start")',
+ *body,
+ " return run",
+ ]
+ repo = (
+ _Repo()
+ .file("pkg/util.py", util)
+ .file("pkg/b.py", host)
+ .symbol("pkg/util.py", "normalize", 4, 11, "def normalize(text, sep)")
+ .symbol("pkg/b.py", "outer", 4, 13, "def outer(json)")
+ .symbol("pkg/b.py", "run", 5, 12, "def run(text, sep)", parent_name="outer")
+ .imports("pkg/b.py", "pkg/util.py")
+ )
+ assert repo.reuse([("pkg/b.py", 7, 12), ("pkg/util.py", 4, 11)]).refused == "free_names"
+ # As a whole copy, the closure is refused outright.
+ del host[5]
+ repo.files["pkg/b.py"] = host
+ repo.graph.nodes["pkg/b.py::outer::run"]["end_line"] = 11
+ assert repo.reuse([("pkg/b.py", 6, 11), ("pkg/util.py", 4, 11)]).refused == "nested"
+
+
+def test_a_host_local_named_like_the_function_is_refused() -> None:
+ repo = _pair(host_params="text, sep, normalize")
+ assert repo.reuse(_OCCURRENCES).refused == "free_names"
+
+
+def test_a_block_comment_binds_nothing() -> None:
+ from repowise.core.analysis.health.refactoring.reuse_names import module_bindings
+
+ lines = ["/*", "import a from './a';", "*/", "import b from './b';"]
+ assert set(module_bindings(lines, "ui/x.ts", "typescript")) == {"b"}
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index 5c593d4a9..a9a480d07 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -184,6 +184,12 @@ def test_refactoring_payoff_outcomes_match_python() -> None:
assert _union_members("RefactoringPayoffOutcome", "refactoring.ts") == set(PAYOFF_OUTCOMES)
+def test_reuse_site_actions_match_python() -> None:
+ from repowise.core.analysis.health.refactoring.reuse import REUSE_SITE_ACTIONS
+
+ assert _union_members("ReuseSiteAction", "refactoring.ts") == set(REUSE_SITE_ACTIONS)
+
+
def _interface_body(name: str, module: str) -> str:
"""The text between `export interface <name> {` and its closing brace."""
text = (_TYPES_SRC / module).read_text(encoding="utf-8")