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(health): say whether an Extract Method helper is a method and what it writes (#3330)

Raghav Chamadiyae4da188ee526
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 07765791c..461855c74 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -208,6 +208,11 @@ Most plans answer a health finding, so per-path marker rules in
await inside a nested function, closure or Rust `async` block does not count.
When the function holding the span is not declared async (a C++ coroutine), the
step is a judgment call with reason `async_helper_unexpressible`.
+- An Extract Method plan says whether the helper must be a method on the same
+ object (the span uses `self`, `this` or a Go receiver) and which of the
+ object's fields the span assigns directly, under `new_symbol`. A span that uses `this`
+ outside a class, or writes fields of a Go value receiver, is a judgment call
+ (`receiver_unbound`, `receiver_copy_written`).
- Move Method never targets a class the method only instantiates, or an ancestor of
its own class.
- Split File works on any language with call resolution and suggests a split only
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
index 7c41282ea..e0da5d2fd 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
@@ -25,6 +25,10 @@ if TYPE_CHECKING:
# ``field_identifier`` / ``property_identifier`` / ``type_identifier`` ...).
# Used by both the assertion-callee scan and the class self-member probe.
_IDENTIFIER_SUFFIX = "identifier"
+_PROP_FIELD_NAMES = ("property", "attribute", "field", "name")
+# ``expression`` is C#'s receiver field on ``member_access_expression`` (its
+# ``this`` token is unnamed, so the positional fallback would pick the member).
+_OBJECT_FIELD_NAMES = ("object", "value", "argument", "operand", "expression")
# Leaf node types that carry a declared name at the bottom of a C/C++
# ``declarator`` chain.
@@ -40,6 +44,44 @@ _MAX_CALLEE_PATH = 100
_PLAIN_PATH = re.compile(r"[\w$#]+(?:\.[\w$#]+)*")
+def member_object(node: Node) -> Node | None:
+ """The receiver child of a member-access (or index) node."""
+ for field_name in _OBJECT_FIELD_NAMES:
+ obj = node.child_by_field_name(field_name)
+ if obj is not None:
+ return obj
+ return next((c for c in node.children if c.is_named), None)
+
+
+def member_name(node: Node) -> Node | None:
+ """The member-name child of a member-access node."""
+ for field_name in _PROP_FIELD_NAMES:
+ prop = node.child_by_field_name(field_name)
+ if prop is not None:
+ return prop
+ named = [c for c in node.children if c.is_named]
+ return next((c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)), None)
+
+
+def self_member_name(node: Node, names: frozenset[str]) -> str | None:
+ """Extract ``member`` from a ``self.member`` / ``this.member`` access.
+
+ Returns the member name when the receiver token is one of *names*
+ (a language's ``self_identifiers``, or a Go receiver's own name);
+ otherwise ``None`` (so ``other.x`` and
+ ``a.b.c``'s outer hops are ignored — only direct instance access
+ counts toward cohesion).
+ """
+ obj, prop = member_object(node), member_name(node)
+ if obj is None or prop is None or obj is prop:
+ return None
+ if obj.text is None or prop.text is None:
+ return None
+ if obj.text.decode("utf-8", errors="replace") not in names:
+ return None
+ return prop.text.decode("utf-8", errors="replace")
+
+
def _pascal_unwrap_name(name: Node) -> Node:
"""Pascal: unwrap ``genericDot`` (``TFoo.Bar``) / ``genericTpl`` (``Bar<T>``)
name wrappers down to the leaf identifier.
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
index 18c91ce60..2ebd99c85 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
@@ -25,7 +25,14 @@ from typing import TYPE_CHECKING, NamedTuple
from ....ingestion.python_overload import is_python_overload
from ....test_paths import is_test_related_path
-from .ast_utils import _IDENTIFIER_SUFFIX, _find_name, is_function_node, is_misread_scope
+from .ast_utils import (
+ _find_name,
+ is_function_node,
+ is_misread_scope,
+ member_name,
+ member_object,
+ self_member_name,
+)
from .languages import LanguageNodeMap, get_language_map
from .models import ClassComplexity, CohesionGroup, FunctionComplexity
from .nloc import CodeLineIndex
@@ -36,10 +43,6 @@ if TYPE_CHECKING:
from tree_sitter import Node
-_PROP_FIELD_NAMES = ("property", "attribute", "field", "name")
-# ``expression`` is C#'s receiver field on ``member_access_expression`` (its
-# ``this`` token is unnamed, so the positional fallback would pick the member).
-_OBJECT_FIELD_NAMES = ("object", "value", "argument", "operand", "expression")
# Fields of a binding node that hold the bound name, in probe order.
_BINDING_NAME_FIELDS = ("name", "declarator", "left", "parameters")
# A method's signature children: names there declare, they do not reference.
@@ -224,43 +227,6 @@ def _bound_names(node: Node, lmap: LanguageNodeMap) -> list[str]:
return [_text(c) for c in named if c.type in lmap.identifier_kinds]
-def _receiver(node: Node) -> Node | None:
- """The receiver child of a member-access node."""
- for field_name in _OBJECT_FIELD_NAMES:
- obj = node.child_by_field_name(field_name)
- if obj is not None:
- return obj
- return next((c for c in node.children if c.is_named), None)
-
-
-def _member(node: Node) -> Node | None:
- """The member-name child of a member-access node."""
- for field_name in _PROP_FIELD_NAMES:
- prop = node.child_by_field_name(field_name)
- if prop is not None:
- return prop
- named = [c for c in node.children if c.is_named]
- return next((c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)), None)
-
-
-def _self_member_name(node: Node, lmap: LanguageNodeMap) -> str | None:
- """Extract ``member`` from a ``self.member`` / ``this.member`` access.
-
- Returns the member name when the receiver token is one of the
- language's ``self_identifiers``; otherwise ``None`` (so ``other.x`` and
- ``a.b.c``'s outer hops are ignored — only direct instance access
- counts toward cohesion).
- """
- obj, prop = _receiver(node), _member(node)
- if obj is None or prop is None or obj is prop:
- return None
- if obj.text is None or prop.text is None:
- return None
- if obj.text.decode("utf-8", errors="replace") not in lmap.self_identifiers:
- return None
- return prop.text.decode("utf-8", errors="replace")
-
-
def _is_callee(node: Node, lmap: LanguageNodeMap) -> bool:
"""Whether *node* is the function a call invokes (``self.x()``)."""
parent = node.parent
@@ -283,7 +249,7 @@ def _self_member_nodes(method_node: Node, lmap: LanguageNodeMap) -> Iterator[tup
if node.type in lmap.class_kinds:
continue # nested class has its own self
if node.type in lmap.member_access_kinds:
- name = _self_member_name(node, lmap)
+ name = self_member_name(node, lmap.self_identifiers)
if name:
yield node, name
stack.extend(node.children)
@@ -324,7 +290,7 @@ def _foreign_member_id(node: Node, lmap: LanguageNodeMap) -> int | None:
to another object, never to the enclosing class."""
if node.type not in lmap.member_access_kinds:
return None
- obj, prop = _receiver(node), _member(node)
+ obj, prop = member_object(node), member_name(node)
if obj is None or prop is None or obj.id == prop.id:
return None # a bare call (``id()``) has no receiver
return prop.id
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index a5e3bfa0c..104233d86 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -90,7 +90,7 @@ class LanguageNodeMap:
# denote the instance (``self`` / ``this`` / ``$this`` / ``cls``), and
# ``member_access_kinds`` to the node type(s) for ``receiver.member``
# access. The receiver and member-name children are pulled out by the
- # generic field-name probe in ``walker._self_member_name`` (it tries
+ # generic field-name probe in ``ast_utils.self_member_name`` (it tries
# the ``object``/``value`` and ``property``/``attribute``/``field``/
# ``name`` fields, then falls back to positional children), so most
# tree-sitter grammars need only the node-type names below.
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py
index 0c5a9b411..03f172234 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/base.py
@@ -40,6 +40,7 @@ precision-first contract the perf pillar depends on.
from __future__ import annotations
+import re
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Protocol, runtime_checkable
@@ -106,6 +107,45 @@ class Captured:
writes: list[Occurrence] = field(default_factory=list)
+@dataclass(frozen=True)
+class Receiver:
+ """How a function's body reaches the instance it runs on.
+
+ ``names`` are the tokens naming it (``self``, ``this``, a Go receiver's
+ own name); empty for a plain function. ``access_kinds`` are the dialect's
+ ``receiver.member`` node types and ``write_kinds`` its assignment,
+ compound assignment and increment nodes. ``implicit``: a bare name can be a field
+ (Java, C++), so a span may use or write the instance without naming it.
+ ``copy``: the method holds a copy (a Go value receiver), so a field write
+ reaches the caller only through this frame. ``bound``: False when
+ ``this`` is not an instance a helper method could share (a TS/JS
+ function outside a class).
+ """
+
+ names: frozenset[str] = frozenset()
+ access_kinds: frozenset[str] = frozenset()
+ write_kinds: frozenset[str] = frozenset()
+ implicit: bool = False
+ copy: bool = False
+ bound: bool = True
+
+
+#: A function with no instance: it is never a method.
+NO_RECEIVER = Receiver()
+
+#: ``super`` reaches the instance too (Python ``super()``, TS / Java ``super``).
+SUPER = "super"
+
+
+def mentions_receiver(node: Node, names: frozenset[str]) -> bool:
+ """Whether *node*'s text holds one of *names* (or ``super``) as a word.
+ A text test, so a mention in a string or comment counts: it can only
+ make an answer unknown or cost a walk, never hide a use."""
+ words = "|".join(re.escape(n) for n in sorted(names | {SUPER}))
+ text = (node.text or b"").decode("utf-8", "replace")
+ return re.search(rf"(?<![\w$])(?:{words})(?![\w$])", text) is not None
+
+
@runtime_checkable
class DefUseDialect(Protocol):
"""The contract a per-language def/use dialect satisfies."""
@@ -137,6 +177,10 @@ class BaseDefUseDialect:
#: reads, only the receiver is a variable; the member name is skipped.
member_access_kinds: frozenset[str] = frozenset()
+ #: Nodes that write their target: assignment, compound assignment and
+ #: increment (``x++``), for the receiver fields a span writes.
+ receiver_write_kinds: frozenset[str] = frozenset()
+
#: Node types for a keyword / named argument (``f(key=value)``). Only the
#: value is a variable read; the keyword name is skipped.
keyword_kinds: frozenset[str] = frozenset()
@@ -406,6 +450,35 @@ class BaseDefUseDialect:
Default: none (a language with no override seeds no parameters)."""
return ()
+ def receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """The instance *fn_node* runs on (:class:`Receiver`), ``NO_RECEIVER``
+ for a plain function, None when this language cannot tell.
+
+ A function with no receiver of its own nested in one that has one (a
+ Python inner ``def``, a Go func literal, a Java or C++ lambda) can
+ still reach the outer instance through the captured name; that is
+ unknown, not "none", unless the name never appears in it. An outer
+ implicit receiver (Java, C++) can be reached by a bare field name, so
+ it is always unknown.
+ """
+ own = self._own_receiver(fn_node, lmap)
+ if own is None or own.names:
+ return own
+ outer_fn = _enclosing_function(fn_node, lmap)
+ if outer_fn is None:
+ return own
+ outer = self.receiver(outer_fn, lmap)
+ if outer is None or outer.implicit:
+ return None if outer is None or outer.names else own
+ return None if outer.names and mentions_receiver(fn_node, outer.names) else own
+
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """The receiver *fn_node* declares itself. Default: None (unknown)."""
+ return None
+
+ def _receiver(self, names: frozenset[str], **flags: bool) -> Receiver:
+ return Receiver(names, self.member_access_kinds, self.receiver_write_kinds, **flags)
+
def statement_def_use(
self, node: Node, lmap: LanguageNodeMap, *, head_only: bool
) -> StatementDefUse: # pragma: no cover - abstract
@@ -436,6 +509,18 @@ class BaseDefUseDialect:
_Scopes = dict[str, list[tuple[tuple[int, int], tuple[int, int]]]]
+def _enclosing_function(node: Node, lmap: LanguageNodeMap) -> Node | None:
+ """The nearest function or lambda holding *node*, stopping at a class
+ (a method's class body starts a new instance)."""
+ holders = lmap.function_kinds | lmap.lambda_kinds
+ cur = node.parent
+ while cur is not None and cur.type not in lmap.class_kinds:
+ if cur.type in holders:
+ return cur
+ cur = cur.parent
+ return None
+
+
def _pos(occ: Occurrence) -> tuple[int, int]:
return (occ.line - 1, occ.column)
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
index b0a292d93..442ae0474 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
@@ -38,7 +38,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse
if TYPE_CHECKING:
from tree_sitter import Node
@@ -70,9 +70,19 @@ _SCOPE_BOUNDARIES = frozenset({"lambda_expression"})
_CALLEE_NAME_KINDS = frozenset({"identifier", "qualified_identifier", "template_function"})
+def _declarator_name(fn_node: Node) -> Node | None:
+ """The innermost node of a definition's ``declarator`` chain (its name),
+ None for a lambda, which has no declarator."""
+ name = fn_node.child_by_field_name("declarator")
+ while name is not None and name.child_by_field_name("declarator") is not None:
+ name = name.child_by_field_name("declarator")
+ return name
+
+
class CppDefUseDialect(BaseDefUseDialect):
language = "cpp"
member_access_kinds = frozenset({_FIELD_EXPRESSION})
+ receiver_write_kinds = _ASSIGN_KINDS | _UPDATE_KINDS
keyword_kinds = frozenset() # C++ has no keyword arguments.
def _is_scope_boundary(self, node: Node) -> bool:
@@ -120,6 +130,27 @@ class CppDefUseDialect(BaseDefUseDialect):
out.append(self._occ(name_node))
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """``this`` for a member function defined in its class (a bare name
+ can also be a field); none for a ``static`` one or a free function.
+ Unknown for an out-of-class ``A::f`` definition (whether it is static
+ is declared in the class, which this file may not hold) and for a
+ lambda, which captures ``this`` or not in a list this does not read."""
+ name = _declarator_name(fn_node)
+ if name is None:
+ return None
+ if any(
+ c.type == "storage_class_specifier" and c.text == b"static"
+ for c in fn_node.named_children
+ ):
+ return NO_RECEIVER
+ parent = fn_node.parent
+ if parent is not None and parent.type == "template_declaration":
+ parent = parent.parent
+ if parent is not None and parent.type == "field_declaration_list":
+ return self._receiver(lmap.self_identifiers, implicit=True)
+ return None if name.type == "qualified_identifier" else NO_RECEIVER
+
def _parameter_list(self, fn_node: Node) -> Node | None:
node: Node | None = fn_node
for _ in range(6):
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py
index d3ed7762c..ee2226adc 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/go.py
@@ -19,7 +19,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse
if TYPE_CHECKING:
from tree_sitter import Node
@@ -45,6 +45,7 @@ _SCOPE_BOUNDARIES = frozenset({"func_literal"})
class GoDefUseDialect(BaseDefUseDialect):
language = "go"
member_access_kinds = frozenset({"selector_expression"})
+ receiver_write_kinds = _ASSIGN_KINDS | _INC_DEC_KINDS
keyword_kinds = frozenset() # Go has no keyword arguments.
def _is_scope_boundary(self, node: Node) -> bool:
@@ -79,6 +80,18 @@ class GoDefUseDialect(BaseDefUseDialect):
out.append(self._occ(child))
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """The method receiver's own name; a value receiver (``s T``, not
+ ``s *T``) is a copy. An unnamed receiver is unreachable from the body."""
+ plist = fn_node.child_by_field_name("receiver")
+ decl = plist.named_children[0] if plist is not None and plist.named_children else None
+ name = decl.child_by_field_name("name") if decl is not None else None
+ if name is None or not name.text or name.text == b"_":
+ return NO_RECEIVER
+ kind = decl.child_by_field_name("type")
+ copy = kind is not None and kind.type != "pointer_type"
+ return self._receiver(frozenset({name.text.decode("utf-8", "replace")}), copy=copy)
+
# -- head (loop clause / if condition) ------------------------------------
def _head(
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
index c6ab18205..285388e5b 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
@@ -24,7 +24,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse
if TYPE_CHECKING:
from tree_sitter import Node
@@ -54,6 +54,7 @@ _SCOPE_BOUNDARIES = frozenset({"lambda_expression", "class_body"})
class JavaDefUseDialect(BaseDefUseDialect):
language = "java"
member_access_kinds = frozenset({"field_access"})
+ receiver_write_kinds = _ASSIGN_KINDS | _UPDATE_KINDS
keyword_kinds = frozenset() # Java has no keyword arguments.
def _is_scope_boundary(self, node: Node) -> bool:
@@ -101,6 +102,17 @@ class JavaDefUseDialect(BaseDefUseDialect):
out.append(self._occ(name_node))
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """``this`` for an instance method or constructor, where a bare name
+ can also be a field; a ``static`` method has none. A lambda has none
+ of its own: it reaches the enclosing method's (``receiver``)."""
+ if fn_node.type in lmap.lambda_kinds:
+ return NO_RECEIVER
+ modifiers = next((c for c in fn_node.named_children if c.type == "modifiers"), None)
+ if modifiers is not None and any(c.type == "static" for c in modifiers.children):
+ return NO_RECEIVER
+ return self._receiver(lmap.self_identifiers, implicit=True)
+
def _binder_identifier(self, node: Node) -> Node | None:
named = node.child_by_field_name("name")
if named is not None and named.type in self.identifier_kinds:
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py
index fc973bf6a..8222a4832 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py
@@ -17,7 +17,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+from .base import NO_RECEIVER, BaseDefUseDialect, Occurrence, Receiver, StatementDefUse
if TYPE_CHECKING:
from tree_sitter import Node
@@ -45,6 +45,7 @@ _SCOPE_BOUNDARIES = frozenset({"lambda", "function_definition", "async_function_
class PythonDefUseDialect(BaseDefUseDialect):
language = "python"
member_access_kinds = frozenset({"attribute"})
+ receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS
keyword_kinds = frozenset({"keyword_argument"})
# A nested ``def`` is visible in the enclosing scope from its statement on.
@@ -81,6 +82,25 @@ class PythonDefUseDialect(BaseDefUseDialect):
out.append(self._occ(name_node))
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """A method's first parameter when it is ``self`` / ``cls`` and the
+ function sits in a class body; a nested function reaches ``self`` as a
+ captured name instead, which is already one of its parameters. A
+ ``@staticmethod``'s first parameter is an ordinary argument."""
+ params = self.parameter_defs(fn_node)
+ if not params or params[0].name not in lmap.self_identifiers:
+ return NO_RECEIVER
+ holder = fn_node.parent
+ if holder is not None and holder.type in lmap.decorated_definition_kinds:
+ decorators = (c.text for c in holder.children if c.type in lmap.decorator_kinds)
+ if any(text and text.strip().endswith(b"staticmethod") for text in decorators):
+ return NO_RECEIVER
+ holder = holder.parent
+ owner = holder.parent if holder is not None else None
+ if owner is None or owner.type not in lmap.class_kinds:
+ return NO_RECEIVER
+ return self._receiver(frozenset({params[0].name}))
+
# -- head (compound construct condition / loop clause) --------------------
def _head(
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py
index 6d5ae4f0f..c0e10c59c 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/rust.py
@@ -32,7 +32,14 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse, echoes
+from .base import (
+ NO_RECEIVER,
+ BaseDefUseDialect,
+ Occurrence,
+ Receiver,
+ StatementDefUse,
+ echoes,
+)
if TYPE_CHECKING:
from tree_sitter import Node
@@ -93,6 +100,7 @@ _SCOPE_BOUNDARIES = frozenset({"closure_expression", "function_item", "async_blo
class RustDefUseDialect(BaseDefUseDialect):
language = "rust"
member_access_kinds = frozenset({"field_expression"})
+ receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS
keyword_kinds = frozenset() # struct-literal field names are not reads.
# ``self`` is its own node type in tree-sitter-rust, not an ``identifier``;
# without it here every ``self.field`` read would drop its receiver (Go and
@@ -142,6 +150,13 @@ class RustDefUseDialect(BaseDefUseDialect):
self._targets(child.child_by_field_name("pattern"), out, sink)
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """``self`` when the signature takes it (``self_parameter``)."""
+ params = fn_node.child_by_field_name("parameters")
+ if params is None or not any(c.type == "self_parameter" for c in params.named_children):
+ return NO_RECEIVER
+ return self._receiver(lmap.self_identifiers)
+
# -- head (loop clause / if condition) ------------------------------------
def _head(
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py
index e52356f95..0720e4f68 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/ts_js.py
@@ -19,7 +19,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
-from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+from .base import BaseDefUseDialect, Occurrence, Receiver, StatementDefUse
if TYPE_CHECKING:
from tree_sitter import Node
@@ -57,11 +57,17 @@ _SCOPE_BOUNDARIES = frozenset(
"method_definition",
}
)
+_THIS = frozenset({"this"})
+
+
+def _is_static(method: Node) -> bool:
+ return any(c.type == "static" for c in method.children)
class TsJsDefUseDialect(BaseDefUseDialect):
language = "typescript"
member_access_kinds = frozenset({"member_expression"})
+ receiver_write_kinds = _ASSIGN_KINDS | _AUG_KINDS | _UPDATE_KINDS
keyword_kinds = frozenset() # object-property keys are not variable reads.
# ``shorthand_property_identifier`` is an object-literal read (``{ days }``
# reads the local ``days``). Its ``_pattern`` twin is the destructuring
@@ -106,6 +112,23 @@ class TsJsDefUseDialect(BaseDefUseDialect):
self._targets(pattern, out, sink)
return tuple(out)
+ def _own_receiver(self, fn_node: Node, lmap: LanguageNodeMap) -> Receiver | None:
+ """``this``, bound when it is a class instance: a class method, or an
+ arrow function (which takes ``this`` from where it is written) inside
+ one or in a class field. An object-literal method or a plain function
+ gets ``this`` from its caller, so a helper method cannot share it. In
+ a ``static`` method ``this`` is the class, not an instance: judged
+ unbound too, the conservative call."""
+ node = fn_node
+ while node is not None and node.type not in lmap.class_kinds:
+ if node.type in _SCOPE_BOUNDARIES and node.type != "arrow_function":
+ parent = node.parent
+ in_class = node.type == "method_definition" and parent is not None
+ bound = in_class and parent.type == "class_body" and not _is_static(node)
+ return self._receiver(_THIS, bound=bound)
+ node = node.parent
+ return self._receiver(_THIS, bound=node is not None)
+
# -- head (loop clause / if condition) ------------------------------------
def _head(
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
index 1a9af9cc8..d66359535 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -33,7 +33,9 @@ from collections import defaultdict
from dataclasses import dataclass
from typing import TYPE_CHECKING, NamedTuple
+from ..complexity.ast_utils import member_object, self_member_name
from ..complexity.nloc import _code_line_numbers
+from .dialects.base import SUPER, mentions_receiver
if TYPE_CHECKING:
from tree_sitter import Node
@@ -41,6 +43,7 @@ if TYPE_CHECKING:
from ..complexity.languages import LanguageNodeMap
from .analyze import FunctionAnalysis
from .defuse import FunctionDefUse
+ from .dialects.base import Receiver
# Gates (precision-first; tuned to suppress trivial or unwieldy extractions).
_MIN_STMTS = 2 # at least two statements
@@ -73,6 +76,16 @@ class Extraction:
carries (the complexity the residual method sheds). ``needs_async`` is
True when the span suspends (an ``await_kinds`` token outside any nested
scope): the helper must be async and its call site awaited.
+
+ ``uses_receiver`` says whether the span names the instance its method
+ runs on (``self``, ``this``, ``super``, a Go receiver; lambdas in the
+ span count, they share it), and ``receiver_assigns`` which of its fields
+ the span assigns directly (``self.x = ...``, ``self.x[k] += ...``,
+ ``this.n++``, unpacking targets): not through an alias, a mutating call
+ (``self.items.append``) or ``del``. Both are None when the language cannot
+ tell (no receiver model, or a bare name that may be a field in Java /
+ C++), and ``receiver_assigns`` also when an assignment target rooted at
+ the receiver has a shape this does not read.
"""
start_line: int
@@ -82,14 +95,54 @@ class Extraction:
slice_nloc: int
ccn_removed: int
needs_async: bool = False
+ uses_receiver: bool | None = None
+ receiver_assigns: tuple[str, ...] | None = None
+
+
+class _Scan(NamedTuple):
+ """The node kinds the per-statement walk counts, built once per function."""
+
+ decisions: frozenset[str]
+ jumps: frozenset[str]
+ scopes: frozenset[str]
+ exit_macros: tuple[frozenset[str], frozenset[str]]
+ awaits: tuple[frozenset[str], frozenset[str]]
+ lambdas: frozenset[str] = frozenset()
+ receiver: Receiver | None = None
+
+
+class _Metrics(NamedTuple):
+ """What :func:`_span_metrics` finds in a span or a whole function body."""
+
+ decisions: int
+ jump: bool
+ awaits: bool
+ receiver_use: bool = False
+ receiver_assigns: frozenset[str] = frozenset()
-def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[Extraction]:
+class _Prefix(NamedTuple):
+ """Per-statement metrics of one block as prefix sums (``writes`` stays
+ per statement: only the spans that pass every gate union it)."""
+
+ decisions: list[int]
+ jumps: list[int]
+ awaits: list[int]
+ nested: list[int]
+ code: list[int]
+ receiver: list[int]
+ assigns: list[frozenset[str]]
+
+
+def find_extractions(
+ analysis: FunctionAnalysis, lmap: LanguageNodeMap, receiver: Receiver | None = None
+) -> list[Extraction]:
"""Return safe Extract Method candidates for *analysis*, best first.
Best is most complexity removed, then largest span, then fewest parameters,
then earliest -- a deterministic order. Empty when the function has no AST
- node retained or no span clears the extractability gates.
+ node retained or no span clears the extractability gates. *receiver* is
+ the function's instance (``DefUseDialect.receiver``), None when unknown.
"""
fn_node = analysis.fn_node
if fn_node is None:
@@ -117,21 +170,9 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
hoisted = _hoisted_bindings(def_lines, use_lines)
decl_lines = _declaration_lines(analysis.def_use)
shared = _closure_state(analysis.def_use, def_lines, use_lines)
- decision_kinds = (
- lmap.branch_kinds
- | lmap.loop_kinds
- | lmap.case_kinds
- | lmap.catch_kinds
- | lmap.boolean_operator_kinds
- )
- jump_kinds = (
- lmap.return_kinds
- | lmap.raise_kinds
- | lmap.break_kinds
- | lmap.continue_kinds
- | lmap.yield_kinds
- )
- scope_kinds = lmap.function_kinds | lmap.lambda_kinds
+ scan = _scan_for(lmap, receiver, fn_node)
+ scope_kinds = scan.scopes
+ free_writes = _free_write_lines(analysis.def_use) if receiver and receiver.implicit else []
# Expression-oriented grammars (nonempty ``statement_wrapper_kinds``): a
# block's last child that is not a statement is its tail expression -- the
# block's implicit value. A span ending on one would silently drop that
@@ -151,31 +192,8 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
keeps_tail = tail_stmt_kinds is not None and _tail_is_block_value(
stmts, tail_stmt_kinds, fn_node, lmap
)
- # One subtree walk per statement, then O(1) metrics per span via
- # prefix sums. _span_metrics processes each span statement's subtree
- # independently, so a span's decision count is the sum over its
- # statements and its jump bit the OR — walking each statement once
- # replaces the per-span re-walks that made this loop O(n^2 * subtree).
if n >= _MIN_STMTS:
- dec_prefix = [0]
- jump_prefix = [0]
- # Named-nested-function count rides the same prefix sums, for the
- # same reason: the check is a subtree walk, and asking it per
- # candidate span would put the O(n^2 * subtree) cost straight back.
- nested_prefix = [0]
- code_prefix = [0]
- await_prefix = [0]
- for st in stmts:
- d, jmp, awaits = _span_metrics(
- [st], decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap), _awaits(lmap)
- )
- dec_prefix.append(dec_prefix[-1] + d)
- jump_prefix.append(jump_prefix[-1] + (1 if jmp else 0))
- await_prefix.append(await_prefix[-1] + (1 if awaits else 0))
- nested_prefix.append(
- nested_prefix[-1] + (1 if _holds_a_named_nested_function([st], lmap) else 0)
- )
- code_prefix.append(code_prefix[-1] + _stmts_nloc([st], lines))
+ pre = _block_prefix(stmts, scan, lines, lmap)
for i in range(n):
for j in range(i, n):
evaluated += 1
@@ -189,11 +207,11 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
continue
if keeps_tail and j == n - 1:
continue
- decisions = dec_prefix[j + 1] - dec_prefix[i]
- has_jump = jump_prefix[j + 1] > jump_prefix[i]
+ decisions = pre.decisions[j + 1] - pre.decisions[i]
+ has_jump = pre.jumps[j + 1] > pre.jumps[i]
if has_jump or decisions < _MIN_CCN_REMOVED:
continue
- slice_nloc = code_prefix[j + 1] - code_prefix[i]
+ slice_nloc = pre.code[j + 1] - pre.code[i]
if not _MIN_SLICE_NLOC <= slice_nloc < max_slice_nloc:
continue
span = stmts[i : j + 1]
@@ -210,7 +228,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
s, e, returns, decl_lines, def_lines, use_lines, declared_first
):
continue
- if nested_prefix[j + 1] > nested_prefix[i]:
+ if pre.nested[j + 1] > pre.nested[i]:
continue
if shared is not None and _closure_state_crosses(shared, span, s, e, block, lmap):
continue
@@ -218,6 +236,7 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
span, loop, s, e, def_lines, use_lines, lmap
):
continue
+ uses, assigns = _receiver_facts(receiver, pre, i, j, _count_in(free_writes, s, e))
out.append(
Extraction(
start_line=s,
@@ -226,12 +245,88 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
returns=returns,
slice_nloc=slice_nloc,
ccn_removed=decisions,
- needs_async=await_prefix[j + 1] > await_prefix[i],
+ needs_async=pre.awaits[j + 1] > pre.awaits[i],
+ uses_receiver=uses,
+ receiver_assigns=assigns,
)
)
return _sorted(out)
+def _scan_for(lmap: LanguageNodeMap, receiver: Receiver | None, fn_node: Node) -> _Scan:
+ """The walk's kinds for *fn_node*. The receiver is looked for only when
+ its name (or ``super``) appears in the function's text at all: most
+ functions never mention it, and then no node needs the check."""
+ if receiver is not None and not (receiver.names and mentions_receiver(fn_node, receiver.names)):
+ receiver = None
+ return _Scan(
+ decisions=lmap.branch_kinds
+ | lmap.loop_kinds
+ | lmap.case_kinds
+ | lmap.catch_kinds
+ | lmap.boolean_operator_kinds,
+ jumps=lmap.return_kinds
+ | lmap.raise_kinds
+ | lmap.break_kinds
+ | lmap.continue_kinds
+ | lmap.yield_kinds,
+ scopes=lmap.function_kinds | lmap.lambda_kinds,
+ exit_macros=_exit_macros(lmap),
+ awaits=_awaits(lmap),
+ lambdas=lmap.lambda_kinds,
+ receiver=receiver,
+ )
+
+
+def _block_prefix(
+ stmts: list[Node], scan: _Scan, lines: list[str], lmap: LanguageNodeMap
+) -> _Prefix:
+ """One subtree walk per statement, so every span's metrics come from
+ prefix sums in O(1): a span's decision count is the sum over its
+ statements and its jump bit the OR, and re-walking per span made the
+ candidate loop O(n^2 * subtree). The named-nested-function check rides
+ the same sums for the same reason."""
+ pre = _Prefix([0], [0], [0], [0], [0], [0], [])
+ for st in stmts:
+ m = _span_metrics([st], scan)
+ pre.decisions.append(pre.decisions[-1] + m.decisions)
+ pre.jumps.append(pre.jumps[-1] + m.jump)
+ pre.awaits.append(pre.awaits[-1] + m.awaits)
+ pre.nested.append(pre.nested[-1] + _holds_a_named_nested_function([st], lmap))
+ pre.code.append(pre.code[-1] + _stmts_nloc([st], lines))
+ pre.receiver.append(pre.receiver[-1] + m.receiver_use)
+ pre.assigns.append(m.receiver_assigns)
+ return pre
+
+
+def _free_write_lines(def_use: FunctionDefUse) -> list[int]:
+ """Sorted lines writing a name the function neither declares nor takes
+ as a parameter: in Java or C++ that is a field (or a C++ global) written
+ without ``this``, so the span's receiver writes are not all known."""
+ params = {p.name for p in def_use.params}
+ declared = {d.var for d in def_use.definitions if d.declares or d.declared_at is not None}
+ return sorted(
+ d.line for d in def_use.definitions if d.var not in params and d.var not in declared
+ )
+
+
+def _receiver_facts(
+ receiver: Receiver | None, pre: _Prefix, i: int, j: int, free_writes: int
+) -> tuple[bool | None, tuple[str, ...] | None]:
+ """``uses_receiver`` / ``receiver_assigns`` for the span over statements
+ ``i..j`` (see :class:`Extraction`)."""
+ if receiver is None:
+ return None, None
+ if not receiver.names:
+ return False, ()
+ named = pre.receiver[j + 1] > pre.receiver[i]
+ found = frozenset().union(*pre.assigns[i : j + 1])
+ fields = None if _UNREAD_TARGET in found else tuple(sorted(found))
+ if receiver.implicit:
+ return (True if named else None), (None if free_writes else fields)
+ return named, fields
+
+
def _tail_is_block_value(
stmts: list[Node], tail_stmt_kinds: frozenset[str], fn_node: Node, lmap: LanguageNodeMap
) -> bool:
@@ -1005,34 +1100,139 @@ def _is_jump(
return name is not None and bool(name.text) and name.text.decode("utf-8", "replace") in names
-def _span_metrics(
- span: list[Node],
- decision_kinds: frozenset[str],
- jump_kinds: frozenset[str],
- scope_kinds: frozenset[str],
- exit_macros: tuple[frozenset[str], frozenset[str]],
- awaits: tuple[frozenset[str], frozenset[str]],
-) -> tuple[int, bool, bool]:
- """Decision-point count, jump presence and await presence within *span*
- (nested scopes are not descended into). A macro named in *exit_macros*
- counts as a jump; an await under one of *awaits*' scope kinds (``async``
- blocks) does not suspend the function, so it does not count."""
- await_kinds, await_scope_kinds = awaits
+def _span_metrics(span: list[Node], scan: _Scan) -> _Metrics:
+ """Decision points, jump and await presence, and receiver references
+ within *span*: a candidate span's statements, or a function body's for
+ facts about the whole function. Nested scopes are not descended into,
+ except a lambda for the receiver alone, since it shares the instance. A
+ macro named in ``scan.exit_macros`` counts as a jump; an await under one
+ of the await scope kinds (``async`` blocks) does not suspend the
+ function."""
+ await_kinds, await_scope_kinds = scan.awaits
+ receiver = scan.receiver
decisions = 0
- has_jump = False
- has_await = False
+ has_jump = has_await = uses = False
+ assigns: set[str] = set()
for root in span:
- stack: list[tuple[Node, bool]] = [(root, True)]
+ # (node, whether its awaits count, inside a lambda: receiver only)
+ stack: list[tuple[Node, bool, bool]] = [(root, True, False)]
while stack:
- node, counts_await = stack.pop()
- t = node.type
- has_jump = has_jump or _is_jump(node, jump_kinds, exit_macros)
- has_await = has_await or (counts_await and t in await_kinds)
- if t in decision_kinds:
- decisions += 1
- counts_await = counts_await and t not in await_scope_kinds
- for child in node.children:
- if child.type in scope_kinds:
- continue
- stack.append((child, counts_await))
- return decisions, has_jump, has_await
+ node, counts_await, nested = stack.pop()
+ if receiver is not None:
+ uses = _receiver_ref(node, receiver, assigns) or uses
+ if not nested:
+ t = node.type
+ has_jump = has_jump or _is_jump(node, scan.jumps, scan.exit_macros)
+ has_await = has_await or (counts_await and t in await_kinds)
+ decisions += t in scan.decisions
+ counts_await = counts_await and t not in await_scope_kinds
+ _push_children(node, stack, counts_await, nested, scan)
+ return _Metrics(decisions, has_jump, has_await, uses, frozenset(assigns))
+
+
+def _push_children(
+ node: Node,
+ stack: list[tuple[Node, bool, bool]],
+ counts_await: bool,
+ nested: bool,
+ scan: _Scan,
+) -> None:
+ """Queue *node*'s children: nested scopes are skipped, except a lambda
+ when the receiver is looked for (it shares the instance)."""
+ for child in node.children:
+ if child.type not in scan.scopes:
+ stack.append((child, counts_await, nested))
+ elif scan.receiver is not None and child.type in scan.lambdas:
+ stack.append((child, False, True))
+
+
+# Index access on a receiver field (``self.cache[k] = v``) assigns into it.
+_INDEX_KINDS = frozenset({"subscript", "subscript_expression", "index_expression", "array_access"})
+# Unpacking targets whose named children are targets themselves
+# (``a, self.b = ...``, ``[this.x, y] = ...``).
+_UNPACK_KINDS = frozenset(
+ {
+ "pattern_list",
+ "tuple_pattern",
+ "list_pattern",
+ "expression_list",
+ "tuple",
+ "list",
+ "array_pattern",
+ "object_pattern",
+ "parenthesized_expression",
+ "list_splat_pattern",
+ "rest_pattern",
+ }
+)
+# Marks a target rooted at the receiver whose shape is not read, so the
+# span's assigned fields are unknown.
+_UNREAD_TARGET = ""
+
+
+def _receiver_ref(node: Node, receiver: Receiver, assigns: set[str]) -> bool:
+ """True when *node* names the receiver; an assignment to one of its
+ fields adds the field's name to *assigns* (the receiver leaf under it is
+ visited next)."""
+ if node.type in receiver.write_kinds:
+ target = (
+ node.child_by_field_name("left")
+ or node.child_by_field_name("argument")
+ or (node.named_children[0] if node.named_children else None)
+ )
+ if target is not None:
+ _collect_assigned(target, receiver, assigns)
+ return False
+ return _is_receiver(node, receiver)
+
+
+def _collect_assigned(target: Node, receiver: Receiver, assigns: set[str]) -> None:
+ """The receiver fields one assignment target writes, unpacking included;
+ a target of another shape that mentions the receiver makes them unknown."""
+ if target.type in _UNPACK_KINDS:
+ for each in target.named_children:
+ _collect_assigned(each, receiver, assigns)
+ return
+ if target.type in ("assignment_pattern", "object_assignment_pattern"): # ``[this.a = 1]``
+ left = target.child_by_field_name("left")
+ if left is not None:
+ _collect_assigned(left, receiver, assigns)
+ return
+ if target.type == "pair_pattern": # ``{key: this.a}``
+ value = target.child_by_field_name("value")
+ if value is not None:
+ _collect_assigned(value, receiver, assigns)
+ return
+ field = _receiver_field(target, receiver)
+ if field:
+ assigns.add(field)
+ elif target.type not in receiver.access_kinds | _INDEX_KINDS and mentions_receiver(
+ target, receiver.names
+ ):
+ assigns.add(_UNREAD_TARGET)
+
+
+def _is_receiver(node: Node, receiver: Receiver) -> bool:
+ """A leaf naming the receiver: a ``this`` / ``self`` / ``super`` token,
+ or an identifier spelling a named receiver (Python ``self``, Go ``s``)
+ or ``super`` (Python's no-argument ``super()``)."""
+ if node.children or not node.text:
+ return False
+ if node.type in receiver.names or node.type == SUPER:
+ return True
+ if node.type != "identifier":
+ return False
+ text = node.text.decode("utf-8", "replace")
+ return text in receiver.names or text == SUPER
+
+
+def _receiver_field(target: Node, receiver: Receiver) -> str | None:
+ """``x`` for an assignment target ``self.x``, ``self.x.y`` or ``self.x[k]``."""
+ cur: Node | None = target
+ while cur is not None and (cur.type in receiver.access_kinds or cur.type in _INDEX_KINDS):
+ if cur.type in receiver.access_kinds:
+ field = self_member_name(cur, receiver.names)
+ if field is not None:
+ return field
+ cur = member_object(cur)
+ return None
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index 42c66a869..c14ebccf9 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -54,6 +54,16 @@ Plan shape (open dict, no migration):
is awaited. An awaiting plan also carries ``async_host``: False when the
enclosing function is not declared async, which makes the step a judgment
call (``preconditions``) rather than a mechanical one.
+- ``plan.new_symbol`` = ``{"kind": "method" | "function" | None, "async":
+ bool, "receiver": str | None, "uses_receiver": bool | None, "assigns":
+ [str, ...] | None}`` -- whether the helper must be a method (the span uses
+ ``self`` / ``this`` / ``super`` / the Go receiver, or may read a Java / C++
+ field bare, ``uses_receiver`` None), the receiver name a method keeps, and
+ the receiver fields the span assigns directly (``Extraction``). None where
+ the language cannot tell. ``new_symbol.async`` is the canonical async key;
+ ``needs_async`` stays for stored rows and their readers. ``plan.receiver_hazard`` is set only when the
+ receiver cannot be shared as it is (``_receiver_hazard``), which makes the
+ step a judgment call.
- ``evidence`` = ``{"slice_nloc": int, "ccn_removed": int}`` -- the size and
complexity (code lines, decision points) the residual method sheds.
- ``blast_radius`` = ``{"scope": "local"}`` -- extraction is local (a new
@@ -76,7 +86,7 @@ from ..biomarkers.large_method import LargeMethodDetector
from ..complexity.cyclomatic import _is_boolean_operator, is_markup
from ..complexity.languages import get_language_map
from ..complexity.nloc import is_string_stmt
-from ..dataflow import find_extractions
+from ..dataflow import find_extractions, get_defuse_dialect
from ..effort import effort_bucket
from ..perf.dialects import PERF_DIALECTS
from ..scoring import severity_deduction
@@ -87,6 +97,7 @@ from .registry import RefactoringDetector, register
if TYPE_CHECKING:
from ..complexity.languages import LanguageNodeMap
from ..dataflow import Extraction, FunctionAnalysis
+ from ..dataflow.dialects.base import Receiver
from ..models import Severity
# The function-level structural biomarkers this detector answers. A function is
@@ -134,6 +145,7 @@ class ExtractMethodDetector(RefactoringDetector):
out: list[RefactoringSuggestion] = []
names = ScopeNames(lmap)
+ dialect = get_defuse_dialect(ctx.language or "")
# Source order, so the first of two colliding plans keeps the name.
for analysis in sorted(analyses, key=lambda a: (a.start_line, a.end_line)):
matched = self._findings_for(analysis, ctx.findings)
@@ -143,7 +155,9 @@ class ExtractMethodDetector(RefactoringDetector):
if jsx_plumbing_dominates(analysis.fn_node, lmap):
continue
markers = {getattr(f, "biomarker_type", "") for f in matched}
- best = _choose(analysis, find_extractions(analysis, lmap), markers)
+ fn_node = analysis.fn_node
+ receiver = dialect.receiver(fn_node, lmap) if dialect and fn_node else None
+ best = _choose(analysis, find_extractions(analysis, lmap, receiver), markers)
if best is None:
continue
impact, share, source = self._impact_for(analysis, best, matched)
@@ -165,6 +179,7 @@ class ExtractMethodDetector(RefactoringDetector):
),
),
**_async_fields(analysis, best, lmap, ctx.language),
+ **_symbol_fields(best, receiver),
},
evidence={
"slice_nloc": best.slice_nloc,
@@ -266,6 +281,55 @@ def _async_fields(
return {"needs_async": True, "async_host": host_is_async(analysis.fn_node, lmap, language)}
+def _symbol_fields(extraction: Extraction, receiver: Receiver | None) -> dict[str, Any]:
+ """``new_symbol``: what the helper is (``kind`` method or function, None
+ when the language cannot tell), ``async``, the ``receiver`` a method
+ reaches its instance by, whether the span uses it (None: it may, by a
+ bare field name), and the receiver fields it assigns directly
+ (``assigns``, None when not all are known). ``receiver_hazard`` only when
+ lifting the span changes what the receiver is (``_receiver_hazard``)."""
+ uses, assigns = extraction.uses_receiver, extraction.receiver_assigns
+ hazard = _receiver_hazard(receiver, uses, assigns)
+ kind: str | None = None
+ if receiver is not None and hazard != "receiver_unbound":
+ kind = "method" if receiver.implicit or uses else "function"
+ name = min(receiver.names) if kind == "method" and receiver is not None else None
+ fields: dict[str, Any] = {
+ "new_symbol": {
+ "kind": kind,
+ # Canonical async key; ``needs_async`` is kept for stored rows.
+ "async": extraction.needs_async,
+ "receiver": name,
+ "uses_receiver": uses,
+ "assigns": list(assigns) if assigns is not None else None,
+ }
+ }
+ if hazard:
+ fields["receiver_hazard"] = hazard
+ return fields
+
+
+def _receiver_hazard(
+ receiver: Receiver | None, uses: bool | None, assigns: tuple[str, ...] | None
+) -> str | None:
+ """Why a helper cannot share the span's receiver as it is, or None.
+
+ ``receiver_unbound``: the span uses ``this`` where it is not a class
+ instance (a TS/JS plain function or object-literal method), so no helper
+ method can be given the same one. ``receiver_copy_written``: the span
+ assigns a field of a Go value receiver, a copy, so a helper holding its
+ own copy loses the write the rest of the method reads (also when the
+ assigned fields are unknown).
+ """
+ if receiver is None or not uses:
+ return None
+ if not receiver.bound:
+ return "receiver_unbound"
+ if receiver.copy and (assigns is None or assigns):
+ return "receiver_copy_written"
+ return None
+
+
def host_is_async(fn_node: Any, lmap: LanguageNodeMap, language: str | None) -> bool:
"""Whether *fn_node* is declared async, by the perf pass's own test: a
dedicated async node kind, else the language's perf dialect."""
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index 57c1762f0..4db1fb54f 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -299,6 +299,9 @@ _TYPE_INSTRUCTIONS: dict[str, str] = {
"and return the plan's 'returns' value(s), and replace the original lines "
"with a call to it. When the plan's 'needs_async' is true the span awaits: "
"declare the helper async and await the call that replaces the lines. "
+ "When the plan's 'new_symbol.kind' is 'method' the span uses its receiver "
+ "('new_symbol.receiver'): make the helper a method of the same object and "
+ "call it through that receiver rather than passing it as an argument. "
"Preserve behaviour exactly; change nothing outside the "
"span and the single call site."
),
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py
index 8bd794807..eda89d777 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/preconditions.py
@@ -40,6 +40,8 @@ JUDGMENT_REASONS = (
"detector_confidence_below_high",
"inverts_imports_across_files",
"needs_design",
+ "receiver_copy_written",
+ "receiver_unbound",
"reshapes_class_surface",
"rewrites_dependent_imports",
"unclassified_refactoring_type",
@@ -131,12 +133,16 @@ def _extract_method_reasons(suggestion: RefactoringSuggestion, facts: dict[str,
R1's dataflow gate proves the span behaviour-preserving before it is ever
offered, and the blast radius is categorically local, so the only thing left
- to check is that the detector itself was sure, and that an awaiting span
- has an async function to land in.
+ to check is that the detector itself was sure, that an awaiting span
+ has an async function to land in, and that the helper can share the
+ span's receiver (``extract_method._receiver_hazard``).
"""
plan = suggestion.plan or {}
if plan.get("needs_async") and plan.get("async_host") is False:
return ["async_helper_unexpressible"]
+ hazard = plan.get("receiver_hazard")
+ if hazard in JUDGMENT_REASONS:
+ return [hazard]
if not facts["local_scope"]:
return ["changes_symbol_home"]
if suggestion.confidence != "high":
diff --git a/packages/ui/__tests__/refactoring/extract-method-types.test.ts b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
index 2f70da2f7..079c8820a 100644
--- a/packages/ui/__tests__/refactoring/extract-method-types.test.ts
+++ b/packages/ui/__tests__/refactoring/extract-method-types.test.ts
@@ -69,6 +69,28 @@ describe("extract_method plan accessors", () => {
expect(planSynopsis(awaiting)).toBe("Extract 19 lines into an async helper");
});
+ it("reads new_symbol and the receiver hazard, null for a plan stored before them", () => {
+ const old = extractMethodPlan(extractMethodPlanFixture());
+ expect([old.kind, old.uses_receiver, old.assigns, old.receiver_hazard]).toEqual([null, null, null, null]);
+ const em = extractMethodPlan(
+ extractMethodPlanFixture({
+ plan: {
+ span: { start: 30, end: 48 },
+ params: [],
+ returns: [],
+ new_symbol: { kind: "method", async: false, receiver: "s", uses_receiver: true, assigns: ["n"] },
+ receiver_hazard: "receiver_copy_written",
+ },
+ }),
+ );
+ expect([em.kind, em.uses_receiver, em.assigns, em.receiver_hazard]).toEqual([
+ "method",
+ true,
+ ["n"],
+ "receiver_copy_written",
+ ]);
+ });
+
it("returns a null span when the plan omits it", () => {
const em = extractMethodPlan(extractMethodPlanFixture({ plan: { params: [], returns: [] } }));
expect(em.span).toBeNull();
diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
index 7bd4d8f3b..88f8e1aa2 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
@@ -73,6 +73,11 @@ function extractMethodSteps(plan: RefactoringPlan): string {
`- **Parameters (in):** ${params}`,
`- **Returns (out):** ${returns}`,
...(em.needs_async ? ["- **Async:** the span awaits, so declare the helper async and await its call"] : []),
+ ...(em.kind === "method"
+ ? [
+ `- **Method:** the span ${em.uses_receiver ? "uses" : "may use"} its object, so make the helper a method of the same object`,
+ ]
+ : []),
"",
"Move exactly those lines into the new helper in the same scope, pass the parameters above, return the value(s) above, and replace the original lines with a single call to it. Preserve behavior exactly: change nothing outside the span and that one call site.",
].join("\n");
diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsx
index e3986b622..6e6d1fcc6 100644
--- a/packages/ui/src/refactoring/plan-detail.tsx
+++ b/packages/ui/src/refactoring/plan-detail.tsx
@@ -488,6 +488,13 @@ export function PlanDetail({ plan, fileHref, hideIntro = false }: PlanDetailProp
async, so an async helper cannot be written in its place.
</p>
) : null}
+ {em.receiver_hazard ? (
+ <p className="mt-2 text-2xs text-[var(--color-text-tertiary)]">
+ {em.receiver_hazard === "receiver_unbound"
+ ? "Judgment call: the span uses this outside a class, so no helper method can share it."
+ : "Judgment call: the span writes fields of a value receiver (a copy), so a helper with its own copy would lose those writes."}
+ </p>
+ ) : null}
</div>
</div>
);
diff --git a/packages/ui/src/refactoring/types.ts b/packages/ui/src/refactoring/types.ts
index 3fc9449f2..ba09d7a4d 100644
--- a/packages/ui/src/refactoring/types.ts
+++ b/packages/ui/src/refactoring/types.ts
@@ -161,10 +161,24 @@ export interface ExtractMethodPlan {
/** For an awaiting span: false when the enclosing function is not async, so
* the step is a judgment call. Null when the plan does not say. */
async_host: boolean | null;
+ /** The helper is a method sharing the span's receiver, or a plain function.
+ * Null when the language cannot tell or the plan predates the field. */
+ kind: "method" | "function" | null;
+ /** Whether the span uses the helper's object; null when it may, through a
+ * bare field name (Java, C++), or the plan does not say. */
+ uses_receiver: boolean | null;
+ /** Receiver fields the span assigns directly (not through an alias, a
+ * mutating call or delete). Null when not all are known. */
+ assigns: string[] | null;
+ /** Why the helper cannot share the receiver as it is (a judgment call). */
+ receiver_hazard: "receiver_unbound" | "receiver_copy_written" | null;
}
+const RECEIVER_HAZARDS = ["receiver_unbound", "receiver_copy_written"] as const;
+
export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {
const p = (plan.plan ?? {}) as Record<string, unknown>;
+ const sym = (p.new_symbol ?? {}) as Record<string, unknown>;
const rawSpan = p.span as Record<string, unknown> | undefined;
const span =
rawSpan && typeof rawSpan === "object"
@@ -177,6 +191,10 @@ export function extractMethodPlan(plan: RefactoringPlan): ExtractMethodPlan {
suggested_name: typeof p.suggested_name === "string" ? p.suggested_name : null,
needs_async: p.needs_async === true,
async_host: typeof p.async_host === "boolean" ? p.async_host : null,
+ kind: sym.kind === "method" || sym.kind === "function" ? sym.kind : null,
+ uses_receiver: typeof sym.uses_receiver === "boolean" ? sym.uses_receiver : null,
+ assigns: Array.isArray(sym.assigns) ? (sym.assigns as string[]) : null,
+ receiver_hazard: RECEIVER_HAZARDS.find((h) => h === p.receiver_hazard) ?? null,
};
}
diff --git a/tests/unit/health/test_extract_method_receiver.py b/tests/unit/health/test_extract_method_receiver.py
new file mode 100644
index 000000000..a6aac9383
--- /dev/null
+++ b/tests/unit/health/test_extract_method_receiver.py
@@ -0,0 +1,512 @@
+"""Extract Method knows whether the helper is a method and what it writes.
+
+A span that uses ``self`` / ``this`` / a Go receiver has to become a method
+sharing that instance, and a span that assigns the receiver's fields changes
+the object the rest of the function sees. The slicer records both in the same
+per-statement walk it already runs; each language's def/use dialect names its
+receiver. Where lifting the span would change what the receiver is (a Go
+value receiver written, ``this`` in a function outside a class), the step is a
+judgment call. A language that cannot tell says unknown, never "no".
+"""
+
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass, replace
+
+import pytest
+
+from repowise.core.analysis.health.complexity.languages import get_language_map
+from repowise.core.analysis.health.dataflow import (
+ analyze_file,
+ find_extractions,
+ get_defuse_dialect,
+)
+from repowise.core.analysis.health.dataflow.dialects.base import (
+ NO_RECEIVER,
+ BaseDefUseDialect,
+)
+from repowise.core.analysis.health.refactoring.extract_method import ExtractMethodDetector
+from repowise.core.analysis.health.refactoring.identity import refactoring_public_id
+from repowise.core.analysis.health.refactoring.models import (
+ RefactoringContext,
+ RefactoringSuggestion,
+)
+from repowise.core.analysis.health.refactoring.preconditions import classify_step
+
+
+@dataclass
+class _Finding:
+ biomarker_type: str
+ function_name: str
+ line_start: int
+ health_impact: float
+
+
+def _functions(language: str, ext: str, src: str):
+ from repowise.core.ingestion.parser import _get_language
+
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ res = analyze_file(f"m.{ext}", language, textwrap.dedent(src).encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ return res.functions
+
+
+def _receiver(language: str, fn):
+ return get_defuse_dialect(language).receiver(fn.fn_node, get_language_map(language))
+
+
+def _facts(language: str, ext: str, src: str, index: int = 0):
+ """``(uses_receiver, receiver_assigns)`` per candidate span, keyed by span."""
+ fn = _functions(language, ext, src)[index]
+ rec = _receiver(language, fn)
+ return {
+ (x.start_line, x.end_line): (x.uses_receiver, x.receiver_assigns)
+ for x in find_extractions(fn, get_language_map(language), rec)
+ }
+
+
+def _span(facts: dict, start: int):
+ """The facts of the candidate span opening on *start* (all agree)."""
+ found = {v for (s, _e), v in facts.items() if s == start}
+ assert len(found) == 1, (start, facts)
+ return found.pop()
+
+
+def _plans(language: str, ext: str, src: str):
+ fns = _functions(language, ext, src)
+ ctx = RefactoringContext(
+ file_path=f"m.{ext}",
+ language=language,
+ nloc=100,
+ findings=[_Finding("complex_method", f.name, f.start_line, 1.5) for f in fns],
+ function_analyses=fns,
+ )
+ return ExtractMethodDetector().detect(ctx)
+
+
+# Lines 4-11 compute a local; lines 12-20 write the instance's fields.
+_PY = """
+class Acc:
+ def run(self, items, limit):
+ total = 0
+ for it in items:
+ if it > limit:
+ total += it
+ elif it < 0:
+ total -= it
+ else:
+ total += 1
+ if total > 10:
+ self.big = True
+ self.hits[total] = 1
+ elif total < 0:
+ self.small += 1
+ else:
+ self.small = 0
+ self.done = total
+ return total
+"""
+
+
+def test_python_span_writing_self_fields_is_a_method_and_names_them():
+ facts = _facts("python", "py", _PY)
+ assert _span(facts, 4) == (False, ())
+ assert _span(facts, 12) == (True, ("big", "done", "hits", "small"))
+
+
+def test_python_plan_carries_new_symbol():
+ plans = {p.plan["span"]["start"]: p for p in _plans("python", "py", _PY)}
+ (plan,) = plans.values()
+ sym = plan.plan["new_symbol"]
+ if plan.plan["span"]["start"] >= 12:
+ assert sym == {
+ "kind": "method",
+ "async": False,
+ "receiver": "self",
+ "uses_receiver": True,
+ "assigns": ["big", "done", "hits", "small"],
+ }
+ else:
+ assert sym == {
+ "kind": "function",
+ "async": False,
+ "receiver": None,
+ "uses_receiver": False,
+ "assigns": [],
+ }
+ assert "receiver_hazard" not in plan.plan
+ assert classify_step(plan).classification == "mechanical"
+
+
+def test_python_staticmethod_and_module_function_have_no_receiver():
+ src = """
+ class A:
+ @staticmethod
+ def s(self, x):
+ return x
+
+ def m(self):
+ return self
+
+ def free(self):
+ return self
+ """
+ fns = {f.name: f for f in _functions("python", "py", src)}
+ assert _receiver("python", fns["s"]) is NO_RECEIVER
+ assert _receiver("python", fns["free"]) is NO_RECEIVER
+ assert _receiver("python", fns["m"]).names == frozenset({"self"})
+
+
+_TS = """
+class Acc {
+ run(items: number[], limit: number) {
+ let total = 0;
+ for (const it of items) {
+ if (it > limit) {
+ total += it;
+ } else {
+ total -= it;
+ }
+ }
+ if (total > 10) {
+ items.forEach((x) => { this.n++; });
+ } else {
+ this.small = total;
+ }
+ this.done = total;
+ return total;
+ }
+}
+"""
+
+
+def test_typescript_this_in_an_arrow_counts_and_increments_are_writes():
+ facts = _facts("typescript", "ts", _TS)
+ assert _span(facts, 4) == (False, ())
+ assert _span(facts, 12) == (True, ("done", "n", "small"))
+
+
+ ("src", "bound"),
+ [
+ ("class A { m() { return 1; } }", True),
+ ("class A { f = () => { return 1; }; }", True),
+ ("function f() { return 1; }", False),
+ ("const o = { m() { return 1; } };", False),
+ ],
+)
+def test_typescript_this_is_bound_only_inside_a_class(src, bound):
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ lmap = get_language_map("typescript")
+ root = Parser(_get_language("typescript")).parse(src.encode()).root_node
+ stack, fn = [root], None
+ while stack and fn is None:
+ node = stack.pop()
+ if node.type in lmap.function_kinds | lmap.lambda_kinds:
+ fn = node
+ stack.extend(reversed(node.children))
+ assert get_defuse_dialect("typescript").receiver(fn, lmap).bound is bound
+
+
+_PLAIN_JS = """
+function run(items, limit) {
+ // Comment lines keep the span under the share of the function a plan
+ // may take, so the span below is the one offered.
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ const a = items.length;
+ const b = limit * 2;
+ const c = a + b;
+ const d = c - limit;
+ const e = d * a;
+ const f = e + 1;
+ log(a, b, c, d, e, f);
+ if (a > limit) {
+ this.big = true;
+ this.count = a;
+ } else if (a > 5) {
+ this.mid = true;
+ this.count = b;
+ } else {
+ this.small = true;
+ this.count = c;
+ }
+ this.done = f;
+ return f;
+}
+"""
+
+
+def test_this_in_a_plain_function_is_a_judgment_call():
+ (plan,) = _plans("javascript", "js", _PLAIN_JS)
+ assert plan.plan["new_symbol"]["assigns"]
+ assert plan.plan["receiver_hazard"] == "receiver_unbound"
+ assert plan.plan["new_symbol"]["kind"] is None
+ assert classify_step(plan).reasons == ("receiver_unbound",)
+
+
+_GO = """
+package m
+
+func (s {recv}) Run(items []int, limit int) int {{
+ total := 0
+ for _, it := range items {{
+ if it > limit {{
+ total += it
+ }} else {{
+ total -= it
+ }}
+ }}
+ if total > 10 {{
+ s.big = true
+ s.n++
+ }} else {{
+ s.small = 1
+ }}
+ s.done = total
+ return total
+}}
+"""
+
+
+def test_go_value_receiver_write_is_flagged_and_pointer_is_not():
+ facts = _facts("go", "go", _GO.format(recv="Acc"))
+ assert _span(facts, 13) == (True, ("big", "done", "n", "small"))
+ fn = _functions("go", "go", _GO.format(recv="Acc"))[0]
+ assert _receiver("go", fn).copy is True
+ fn = _functions("go", "go", _GO.format(recv="*Acc"))[0]
+ assert _receiver("go", fn).copy is False
+
+
+def test_go_hazard_classifies_judgment():
+ from repowise.core.analysis.health.refactoring.extract_method import _receiver_hazard
+
+ fn = _functions("go", "go", _GO.format(recv="Acc"))[0]
+ rec = _receiver("go", fn)
+ assert _receiver_hazard(rec, True, ("big",)) == "receiver_copy_written"
+ assert _receiver_hazard(rec, True, ()) is None
+ assert _receiver_hazard(replace(rec, copy=False), True, ("big",)) is None
+
+
+_JAVA = """
+class Acc {{
+ {static}int run(int[] items, int limit) {{
+ int total = 0;
+ for (int it : items) {{
+ if (it > limit) {{
+ total += it;
+ }} else {{
+ total -= it;
+ }}
+ }}
+ if (total > 10) {{
+ this.big = true;
+ {bare}
+ }} else {{
+ this.small = 1;
+ }}
+ this.done = total;
+ return total;
+ }}
+}}
+"""
+
+
+def test_java_bare_field_write_makes_writes_unknown():
+ facts = _facts("java", "java", _JAVA.format(static="", bare="count++;"))
+ assert _span(facts, 4) == (None, ()) # a bare name may be a field
+ assert _span(facts, 12) == (True, None)
+ facts = _facts("java", "java", _JAVA.format(static="", bare="items[0] = 1;"))
+ assert _span(facts, 12) == (True, ("big", "done", "small"))
+
+
+def test_java_static_method_has_no_receiver():
+ fn = _functions("java", "java", _JAVA.format(static="static ", bare="count++;"))[0]
+ assert _receiver("java", fn) is NO_RECEIVER
+
+
+def test_rust_and_cpp_receivers():
+ rust = """
+ impl A {
+ fn f(&mut self) {}
+ fn g() {}
+ }
+ """
+ fns = {f.name: f for f in _functions("rust", "rs", rust)}
+ assert _receiver("rust", fns["f"]).names == frozenset({"self"})
+ assert _receiver("rust", fns["g"]) is NO_RECEIVER
+ cpp = """
+ class A {
+ void f() { x = 1; }
+ static void g() { }
+ };
+ void A::h() { }
+ void free_fn() { }
+ """
+ fns = {f.name: f for f in _functions("cpp", "cpp", cpp)}
+ rec = {name: _receiver("cpp", fn) for name, fn in fns.items()}
+ assert rec["f"].implicit is True
+ assert rec["g"] is NO_RECEIVER
+ assert rec["A::h"] is None # whether it is static lives in the class
+ assert rec["free_fn"] is NO_RECEIVER
+
+
+def test_a_language_without_a_receiver_model_says_unknown():
+ assert BaseDefUseDialect().receiver(None, get_language_map("python")) is None
+
+
+def test_new_symbol_does_not_change_the_public_id():
+ (plan,) = _plans("python", "py", _PY)
+ bare = RefactoringSuggestion(
+ **{
+ **plan.__dict__,
+ "plan": {k: v for k, v in plan.plan.items() if k != "new_symbol"},
+ }
+ )
+ assert refactoring_public_id(plan) == refactoring_public_id(bare)
+
+
+def test_the_same_walk_gives_whole_function_facts():
+ """One walk serves a span and a whole body: a function's awaits and
+ receiver assignments come from its body's statements."""
+ from repowise.core.analysis.health.dataflow.slice import _scan_for, _span_metrics
+
+ src = """
+ class A:
+ async def run(self, rows):
+ if not rows:
+ return
+ for r in rows:
+ if r is None:
+ raise ValueError(r)
+ self.seen += 1
+ yield await r.load()
+ """
+ (fn,) = _functions("python", "py", src)
+ lmap = get_language_map("python")
+ body = fn.fn_node.child_by_field_name("body").named_children
+ m = _span_metrics(body, _scan_for(lmap, _receiver("python", fn), fn.fn_node))
+ assert (m.jump, m.awaits) == (True, True)
+ assert (m.receiver_use, m.receiver_assigns) == (True, frozenset({"seen"}))
+
+
+def _first_named(language: str, src: str, kinds: frozenset[str]):
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ root = Parser(_get_language(language)).parse(textwrap.dedent(src).encode()).root_node
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ if node.type in kinds:
+ return node
+ stack.extend(reversed(node.children))
+ raise AssertionError(kinds)
+
+
+_PY_INNER = """
+class A:
+ def m(self):
+ def inner(v):
+ {body}
+"""
+
+
+ ("language", "src", "kind", "expected"),
+ [
+ # A nested def reaching the outer self: unknown, not "no receiver".
+ ("python", _PY_INNER.format(body="self.x = v"), "function_definition", None),
+ ("python", _PY_INNER.format(body="return v"), "function_definition", "none"),
+ ("go", "package m\nfunc (s *S) M() { f := func() { s.n = 1 }; f() }\n", "func_literal", None),
+ ("go", "package m\nfunc (s *S) M() { f := func() { x := 1; _ = x }; f() }\n", "func_literal", "none"),
+ ("java", "class A { void m() { Runnable r = () -> { x = 1; }; } }", "lambda_expression", None),
+ ("java", "class A { static void m() { Runnable r = () -> { x = 1; }; } }", "lambda_expression", "none"),
+ ("cpp", "struct A { void m() { auto f = [this]() { x = 1; }; } };", "lambda_expression", None),
+ ],
+)
+def test_a_nested_function_reaching_the_outer_receiver_is_unknown(language, src, kind, expected):
+ lmap = get_language_map(language)
+ outer_kinds = lmap.function_kinds
+ node = _first_named(language, src, frozenset({kind}))
+ if kind in outer_kinds: # the nested def, not the method holding it
+ stack = list(node.child_by_field_name("body").children)
+ while stack:
+ cur = stack.pop()
+ if cur.type == kind:
+ node = cur
+ break
+ stack.extend(cur.children)
+ rec = get_defuse_dialect(language).receiver(node, lmap)
+ assert (rec is NO_RECEIVER if expected == "none" else rec is None), rec
+
+
+def test_super_counts_as_a_receiver_use():
+ src = """
+ class A(B):
+ def run(self, items, limit):
+ total = 0
+ for it in items:
+ if it > limit:
+ total += it
+ elif it < 0:
+ total -= it
+ else:
+ total += 1
+ print(total)
+ if total > 10:
+ super().flush(total)
+ print(total)
+ else:
+ print(-total)
+ print(limit)
+ return total
+ """
+ facts = _facts("python", "py", src)
+ assert _span(facts, 12) == (True, ())
+
+
+def test_unpacking_targets_are_assignments_and_an_unread_shape_is_unknown():
+ src = """
+ class A:
+ def run(self, items, limit):
+ total = 0
+ for it in items:
+ if it > limit:
+ total += it
+ elif it < 0:
+ total -= it
+ else:
+ total += 1
+ print(total)
+ if total > 10:
+ self.a, (self.b, x) = total, (1, 2)
+ print(x)
+ else:
+ self.c = 0
+ print(limit)
+ return total
+ """
+ assert _span(_facts("python", "py", src), 12) == (True, ("a", "b", "c"))
+ rebinding = src.replace("self.c = 0", "self = other")
+ assert _span(_facts("python", "py", rebinding), 12) == (True, None)
+
+
+def test_typescript_static_method_this_is_the_class():
+ node = _first_named(
+ "typescript", "class A { static m() { return this; } }", frozenset({"method_definition"})
+ )
+ assert get_defuse_dialect("typescript").receiver(node, get_language_map("typescript")).bound is False
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index ab7287425..169857cf7 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -164,6 +164,7 @@ def _find_extractions_reference(analysis, lmap):
_infer_in_out,
_loop_carry_free,
_outs_definitely_assigned,
+ _Scan,
_sorted,
_span_metrics,
_stmts_nloc,
@@ -227,13 +228,15 @@ def _find_extractions_reference(analysis, lmap):
):
continue
span = stmts[i : j + 1]
- decisions, has_jump, has_await = _span_metrics(
+ decisions, has_jump, has_await, *_ = _span_metrics(
span,
- decision_kinds,
- jump_kinds,
- scope_kinds,
- _exit_macros(lmap),
- (lmap.await_kinds, lmap.await_scope_kinds),
+ _Scan(
+ decision_kinds,
+ jump_kinds,
+ scope_kinds,
+ _exit_macros(lmap),
+ (lmap.await_kinds, lmap.await_scope_kinds),
+ ),
)
if has_jump or decisions < _MIN_CCN_REMOVED:
continue
@@ -575,8 +578,23 @@ def test_detector_emits_suggestion_for_flagged_function():
assert 0 < share < 1
assert s.impact_delta == round(1.5 * share, 3)
# Plan shape is the locked schema.
- assert set(s.plan) == {"span", "params", "returns", "suggested_name", "needs_async"}
+ assert set(s.plan) == {
+ "span",
+ "params",
+ "returns",
+ "suggested_name",
+ "needs_async",
+ "new_symbol",
+ }
assert s.plan["needs_async"] is False
+ # A module-level function: the helper is a plain function too.
+ assert s.plan["new_symbol"] == {
+ "kind": "function",
+ "async": False,
+ "receiver": None,
+ "uses_receiver": False,
+ "assigns": [],
+ }
assert set(s.plan["span"]) == {"start", "end"}
assert set(s.evidence) == {"slice_nloc", "ccn_removed"}
# A categorical claim, not a count: extraction is local, so there is nothing
@@ -923,7 +941,7 @@ def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):
trivial = Extraction(10, 17, ("a",), (), slice_nloc=8, ccn_removed=1)
worth = Extraction(20, 27, ("b",), (), slice_nloc=8, ccn_removed=3)
- monkeypatch.setattr(extract_method, "find_extractions", lambda _a, _l: [trivial, worth])
+ monkeypatch.setattr(extract_method, "find_extractions", lambda _a, _l, _r=None: [trivial, worth])
fn = _Shape(12, 40)
analysis = type(
"A", (), {"name": "f", "start_line": 1, "end_line": 50, "ccn": 12, "nloc": 40,
@@ -1136,7 +1154,7 @@ def test_a_refused_span_yields_only_to_a_disjoint_one(monkeypatch):
shrunk = Extraction(2, 55, ("a",), (), slice_nloc=40, ccn_removed=8) # overlaps it
disjoint = Extraction(85, 95, ("b",), (), slice_nloc=10, ccn_removed=3)
monkeypatch.setattr(
- extract_method, "find_extractions", lambda _a, _l: [whole, shrunk, disjoint]
+ extract_method, "find_extractions", lambda _a, _l, _r=None: [whole, shrunk, disjoint]
)
analysis = type(
"A", (), {"name": "f", "start_line": 1, "end_line": 100, "ccn": 30, "nloc": 90,