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): stage a loop body, keep guard-narrowed TS types, flag source-text tests (#3433)

Raghav Chamadiyaa1f57441678d
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 1767a667d..571a016cf 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -110,7 +110,8 @@ rows of their own.
Plan detail also lists `risks`, one sentence each, to read before applying the
plan: an accepted decision that governs the file, callers or importers of what
the plan moves, a target nothing reaches (delete it instead), and recent commits
-on the same lines. A governed plan's steps are `judgment`, and its
+on the same lines, and a test the plan runs that asserts on the function's own
+source text. A governed plan's steps are `judgment`, and its
`blast_radius.co_change_partners` names the files that usually change with it.
A newly accepted decision shows here after the next index or update.
@@ -256,14 +257,20 @@ Most plans answer a health finding, so per-path marker rules in
(`receiver_unbound`, `receiver_copy_written`).
- An Extract Method plan writes out the new helper's header and the line that
replaces the span, in the file's language, with parameter types where the code
- declares them. Plan detail shows both with a copy button. Where the code names
- no helper or type, the text reads `<name>` or `<type>` for you to fill in.
+ declares them. In TypeScript, an optional parameter is written `T | undefined`,
+ and a type an earlier guard narrows (`if (!x) return;`) is written narrowed, or
+ a note asks for the narrowed type. Plan detail shows both with a copy button.
+ Where the code names no helper or type, the text reads `<name>` or `<type>` for
+ you to fill in.
- A Python, TypeScript or JavaScript function too complex for one helper can
get a staged plan instead: several helpers the function calls in order, each
small enough to leave the finding behind. Plan detail lists them as steps,
with a shared parameter object when many values pass between them, and the
plan's estimated gain is the whole drop in the function's complexity. The
- plan's own span, header and call are its first stage. When a function moves
+ plan's own span, header and call are its first stage. When the work sits
+ inside one loop or `if`, the stages are cut from its body and the function
+ keeps the loop and calls them each time round. A stage running across several
+ labelled sections is named after them. When a function moves
between a single helper and a staged plan, or its stages change, the plan
gets a new id.
- Move Method never targets a class the method only instantiates, or an ancestor of
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 18ea61079..8d344e0c9 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
@@ -60,6 +60,25 @@ _SCOPE_BOUNDARIES = frozenset(
_THIS = frozenset({"this"})
+_OPENERS, _CLOSERS = "([{<", ")]}>"
+
+
+def union_arms(typ: str) -> list[str]:
+ """The arms of a TypeScript union type written as *typ*, split on ``|``
+ outside brackets (``Map<string, A | B> | undefined`` has two)."""
+ arms, depth, start = [], 0, 0
+ for n, ch in enumerate(typ):
+ if ch in _OPENERS:
+ depth += 1
+ elif ch in _CLOSERS and typ[n - 1 : n + 1] != "=>":
+ depth -= 1
+ elif ch == "|" and depth == 0:
+ arms.append(typ[start:n].strip())
+ start = n + 1
+ arms.append(typ[start:].strip())
+ return [a for a in arms if a]
+
+
def _is_static(method: Node) -> bool:
return any(c.type == "static" for c in method.children)
@@ -100,6 +119,17 @@ class TsJsDefUseDialect(BaseDefUseDialect):
self._process(node, defs, uses)
return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+ def declared_type(self, name: Node) -> str | None:
+ """The base rule, plus ``| undefined`` for an optional parameter
+ (``x?: T`` holds ``T | undefined`` until something narrows it)."""
+ typ = super().declared_type(name)
+ if typ is None or name.parent is None or name.parent.type != "optional_parameter":
+ return typ
+ arms = union_arms(typ)
+ if "undefined" in arms:
+ return typ
+ return f"({typ}) | undefined" if len(arms) == 1 and "=>" in typ else f"{typ} | undefined"
+
def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:
params_node = fn_node.child_by_field_name("parameters")
if params_node is None:
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/loop_cut.py b/packages/core/src/repowise/core/analysis/health/dataflow/loop_cut.py
new file mode 100644
index 000000000..a63d58e23
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/loop_cut.py
@@ -0,0 +1,113 @@
+"""What a staged split cut from a loop body must respect.
+
+A stage inside a loop body runs once per iteration, called by the function,
+which keeps the loop. Two things the lines alone do not show:
+
+- **Jumps.** A ``break`` / ``continue`` inside a stage must stay inside it: one
+ that leaves it would leave the helper instead (:func:`escapes`).
+- **Carried values.** A value one iteration writes and the next reads must come
+ back out of the stage writing it, or the function would hand the next
+ iteration the old value (:func:`carried`).
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import TYPE_CHECKING
+
+from .reaching import definitions_at, observed_definitions
+from .slice import _statements_by_line
+from .span import is_comment
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from ..complexity.languages import LanguageNodeMap
+ from .analyze import FunctionAnalysis
+
+
+def escapes(st: Node, lmap: LanguageNodeMap) -> bool:
+ """Whether *st* holds a ``break`` / ``continue`` that leaves it."""
+ scopes = lmap.function_kinds | lmap.lambda_kinds
+ # A C-family ``switch`` (Go's ``select``) holds a ``break``; a Python,
+ # Rust or Kotlin ``match`` / ``when`` does not.
+ switches = frozenset(k for k in lmap.switch_kinds if "switch" in k or k == "select_statement")
+ stack: list[tuple[Node, bool, bool]] = [(st, False, False)]
+ while stack:
+ node, in_loop, in_switch = stack.pop()
+ if node.type in lmap.break_kinds or node.type in lmap.continue_kinds:
+ if _leaves(node, in_loop, in_switch, lmap):
+ return True
+ continue
+ # Only the loop's body repeats: a ``break`` in a Python ``for ... else``
+ # leaves the loop around it.
+ body = node.child_by_field_name("body") if node.type in lmap.loop_kinds else None
+ switch = in_switch or node.type in switches
+ for child in node.children:
+ if child.type not in scopes:
+ looped = in_loop or (body is not None and child.id == body.id)
+ stack.append((child, looped, switch))
+ return False
+
+
+def _leaves(jump: Node, in_loop: bool, in_switch: bool, lmap: LanguageNodeMap) -> bool:
+ """Whether *jump* leaves the statement it was found in: a labelled one
+ always may, else one no enclosing loop body (or switch, for ``break``)
+ inside it holds."""
+ if any(c.type.endswith("identifier") for c in jump.named_children):
+ return True
+ return not (in_loop or (in_switch and jump.type in lmap.break_kinds))
+
+
+def carried(
+ analysis: FunctionAnalysis, loops: tuple[Node, ...], def_lines: dict[str, list[int]]
+) -> frozenset[str]:
+ """Names some loop in *loops* carries into its next iteration. Every read
+ counts, a may-def's paired use included: it is how a value passes a write
+ that may not happen."""
+ defs = analysis.reaching.definitions
+ reads: dict[str, list[tuple[int, list[int]]]] = defaultdict(list)
+ for use, seen in observed_definitions(analysis.def_use, analysis.reaching):
+ reads[use.name].append((use.line, [defs[i].line for i in seen]))
+ statements = _statements_by_line(analysis.cfg)
+ out: set[str] = set()
+ for loop in loops:
+ out |= _carried_in(analysis, loop, statements, reads, def_lines)
+ return frozenset(out)
+
+
+def _carried_in(
+ analysis: FunctionAnalysis,
+ loop: Node,
+ statements: dict[int, tuple[int, int]],
+ reads: dict[str, list[tuple[int, list[int]]]],
+ def_lines: dict[str, list[int]],
+) -> set[str]:
+ """Names *loop* carries: written in its body by a definition reaching the
+ body's first statement (around the back edge), and read in the loop where
+ a value from outside it may still arrive, so a later iteration's read sees
+ the earlier one's write."""
+ body = loop.child_by_field_name("body")
+ code = [c for c in body.named_children if not is_comment(c)] if body is not None else []
+ at = statements.get(code[0].start_point[0] + 1) if code else None
+ if at is None:
+ return set()
+ defs = analysis.reaching.definitions
+ lo, hi = loop.start_point[0] + 1, loop.end_point[0] + 1
+ b_lo, b_hi = body.start_point[0] + 1, body.end_point[0] + 1
+ out = set()
+ for var, lines in def_lines.items():
+ if not any(b_lo <= ln <= b_hi for ln in lines):
+ continue
+ entering = definitions_at(analysis.def_use, analysis.reaching, at[0], var, at[1])
+ if not any(b_lo <= defs[i].line <= b_hi for i in entering):
+ continue
+ if any(
+ lo <= ln <= hi and any(d < lo or d > hi for d in seen)
+ for ln, seen in reads.get(var, ())
+ ):
+ out.add(var)
+ return out
+
+
+__all__ = ["carried", "escapes"]
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/span.py b/packages/core/src/repowise/core/analysis/health/dataflow/span.py
index ecaf764f9..717c04fbb 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/span.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/span.py
@@ -84,5 +84,21 @@ def _comment_above(anchor: Node) -> list[str]:
return lines
+def exiting_guard(st: Node, lmap: LanguageNodeMap, exits: frozenset[str]) -> Node | None:
+ """The condition of *st* when it is a guard: an ``if`` with no ``else`` /
+ ``elif`` arm whose last statement is one of *exits* (the consequence
+ itself when it is one, TS / JS ``if (!x) throw e;``); None otherwise."""
+ if st.type not in lmap.if_kinds or st.child_by_field_name("alternative") is not None:
+ return None
+ if any(c.type in ("else_clause", "elif_clause") for c in st.children):
+ return None
+ body = st.child_by_field_name("consequence")
+ if body is None:
+ return None
+ stmts = [c for c in body.named_children if not is_comment(c)]
+ last = body if body.type in exits or not stmts else stmts[-1]
+ return st.child_by_field_name("condition") if last.type in exits else None
+
+
def is_comment(node: Node) -> bool:
return "comment" in node.type
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/stages.py b/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
index 655a3b79c..080656081 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
@@ -7,10 +7,15 @@ into K contiguous stages, each a helper the function then calls in sequence.
- **Effective body.** A ``try`` / ``with`` statement holding most of a block's
decision points is a wrapper: its body is cut instead, and the wrapper (with
its ``except`` / ``finally`` and anything around it) stays in the function.
+ Past that, a loop or ``if`` holding most of them offers its body (the arm
+ holding the most) as a deeper block, repeatedly; the statement itself stays
+ in the function, which calls the stages from inside it. A deeper block's
+ split is taken only when it lifts more than the outer one.
- **Stages.** Each is a run of that body's statements with ``CCN <= 10`` and
- ``NLOC <= 60``, at least two decision points, and no ``return`` / ``yield``
- (a ``raise`` propagates from a helper unchanged; the body is never inside a
- loop, so a ``break`` / ``continue`` cannot leave the stage). Its inputs and
+ ``NLOC <= 60``, at least two decision points, no ``return`` / ``yield``, and
+ no ``break`` / ``continue`` that leaves it (a ``raise`` propagates from a
+ helper unchanged). In a loop body, a value one iteration writes and the
+ next reads comes back out of the stage writing it. Its inputs and
outputs come from the same line liveness as a single span; an output not
written on every path is also passed in (``inout``), so a skipped write hands
back the value it came with. Every input must be written on every path into
@@ -49,6 +54,7 @@ from typing import TYPE_CHECKING
from ..complexity.nloc import is_string_stmt
from .assigned import DefiniteAssignment
+from .loop_cut import carried, escapes
from .reaching import observed_definitions
from .slice import (
_MIN_SLICE_NLOC,
@@ -71,7 +77,7 @@ from .slice import (
_unwrap_container,
_var_lines,
)
-from .span import is_comment, section_heads
+from .span import exiting_guard, is_comment, section_heads
if TYPE_CHECKING:
from tree_sitter import Node
@@ -90,6 +96,8 @@ _STAGE_MIN_DECISIONS = 2
_CONTEXT_OVER = 5
# A wrapper holding this share of a block's decision points is unwrapped.
_WRAPPER_SHARE = 0.6
+# Loop bodies and ``if`` arms looked into below the outermost cut.
+_MAX_DEPTH = 6
# Cut costs, in one integer scale. A decision point left in the function
# outweighs everything else; then the interface, the cut hints, the count.
@@ -148,15 +156,42 @@ def find_stages(
if body is None:
return StagePlan(reason="no_tree")
blocks = _Blocks(analysis, lmap, receiver, prefixes if prefixes is not None else {})
- block = _effective_block(_unwrap_container(body, lmap.block_kinds), blocks, lmap)
+ facts = _FunctionFacts(analysis)
+ first: StagePlan | None = None
+ best: StagePlan | None = None
+ for block, loops in _descent(_unwrap_container(body, lmap.block_kinds), blocks, lmap):
+ # A block cannot lift more decision points than it holds.
+ if best is not None and blocks.code(block)[1].decisions[-1] <= best.ccn_removed:
+ break
+ plan = _plan_block(analysis, lmap, receiver, blocks, facts, block, loops, max_returns)
+ first = first or plan
+ # A deeper level wins only by lifting more: ties keep the outer cut.
+ if plan.stages and (best is None or plan.ccn_removed > best.ccn_removed):
+ best = plan
+ return best or first or StagePlan(reason="no_tree")
+
+
+def _plan_block(
+ analysis: FunctionAnalysis,
+ lmap: LanguageNodeMap,
+ receiver: Receiver | None,
+ blocks: _Blocks,
+ facts: _FunctionFacts,
+ block: Node,
+ loops: tuple[Node, ...],
+ max_returns: int,
+) -> StagePlan:
+ """The staged split of *block*, nested in *loops* (outermost first)."""
code, pre = blocks.code(block)
if len(code) < 2:
return StagePlan(reason="one_statement")
- cutter = _Cutter(analysis, lmap, receiver, block, code, pre, max_returns)
+ cutter = _Cutter(facts, lmap, receiver, block, code, pre, max_returns, loops)
stages = cutter.cut()
if len(stages) < 2:
return StagePlan(reason="fewer_than_two_stages")
- context = _context(stages, cutter.def_lines, receiver)
+ context = _context(stages, facts.def_lines, receiver)
+ if not _inputs_held(stages, facts.def_lines):
+ return StagePlan(reason="composition")
composed = _composes(analysis, stages, context)
if composed is None:
return StagePlan(reason="composition")
@@ -205,24 +240,86 @@ def _select(pre: _Prefix, keep: list[int]) -> _Prefix:
return out
-def _effective_block(block: Node, blocks: _Blocks, lmap: LanguageNodeMap) -> Node:
- """*block*, or the body of the ``try`` / ``with`` wrapper holding most of
- its decision points, repeatedly."""
+def _descent(
+ root: Node, blocks: _Blocks, lmap: LanguageNodeMap
+) -> list[tuple[Node, tuple[Node, ...]]]:
+ """The blocks a staged split may cut, outermost first, each with the loops
+ holding it: the body under its ``try`` / ``with`` wrappers (module
+ docstring), then, while one statement holds most of a block's decision
+ points, the loop body or ``if`` arm it puts them in."""
wrappers = lmap.try_kinds | lmap.with_kinds
- while True:
- code, pre = blocks.code(block)
- per = [pre.decisions[k + 1] - pre.decisions[k] for k in range(len(code))]
- total = sum(per)
- if not total:
- return block
- top = code[max(range(len(code)), key=per.__getitem__)]
- inner = top.child_by_field_name("body") if top.type in wrappers else None
- if inner is None:
- return block
- inner = _unwrap_container(inner, lmap.block_kinds)
- if blocks.code(inner)[1].decisions[-1] < _WRAPPER_SHARE * total:
- return block
- block = inner
+ block = root
+ while (step := _dominant_arm(block, blocks, lmap, wrappers)) is not None:
+ block = step[0]
+ chain: list[tuple[Node, tuple[Node, ...]]] = [(block, ())]
+ loops: tuple[Node, ...] = ()
+ nested = wrappers | lmap.loop_kinds | lmap.if_kinds
+ while len(chain) <= _MAX_DEPTH and (step := _dominant_arm(block, blocks, lmap, nested)):
+ block, holder = step
+ if holder.type in lmap.loop_kinds:
+ loops = (*loops, holder)
+ chain.append((block, loops))
+ return chain
+
+
+def _dominant_arm(
+ block: Node, blocks: _Blocks, lmap: LanguageNodeMap, kinds: frozenset[str]
+) -> tuple[Node, Node] | None:
+ """The block inside *block*'s most complex statement (of *kinds*) holding
+ at least ``_WRAPPER_SHARE`` of *block*'s decision points, with that
+ statement; None when there is none."""
+ code, pre = blocks.code(block)
+ per = [pre.decisions[k + 1] - pre.decisions[k] for k in range(len(code))]
+ total = sum(per)
+ if not total:
+ return None
+ top = code[max(range(len(code)), key=per.__getitem__)]
+ if top.type not in kinds:
+ return None
+ arms = [_unwrap_container(a, lmap.block_kinds) for a in _arms(top, lmap)]
+ arms = [a for a in arms if a.type in lmap.block_kinds]
+ if not arms:
+ return None
+ inner = max(arms, key=lambda a: blocks.code(a)[1].decisions[-1])
+ if blocks.code(inner)[1].decisions[-1] < _WRAPPER_SHARE * total:
+ return None
+ return inner, top
+
+
+def _arms(st: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """The statement blocks *st* runs: a wrapper's or loop's body, each arm of
+ an ``if`` (Python ``elif`` / ``else`` clauses, a TS / JS ``else``)."""
+ if st.type not in lmap.if_kinds:
+ body = st.child_by_field_name("body")
+ return [body] if body is not None else []
+ out = [st.child_by_field_name("consequence")]
+ for clause in st.children:
+ if clause.type == "elif_clause":
+ out.append(clause.child_by_field_name("consequence"))
+ elif clause.type == "else_clause":
+ out.append(clause.child_by_field_name("body") or next(iter(clause.named_children), None))
+ return [a for a in out if a is not None]
+
+
+class _FunctionFacts:
+ """The per-function facts every block's cut reads, built once."""
+
+ def __init__(self, analysis: FunctionAnalysis) -> None:
+ self.analysis = analysis
+ def_use = analysis.def_use
+ self.def_lines, self.use_lines = _var_lines(def_use)
+ self.declared_first = _declared_before_read(def_use)
+ self.hoisted = _hoisted_bindings(self.def_lines, self.use_lines)
+ self.decl_lines = _declaration_lines(def_use)
+ self.shared = _closure_state(def_use, self.def_lines, self.use_lines)
+ self.reads = _reads_observing(analysis, self.def_lines)
+ self.assigned = DefiniteAssignment(analysis)
+ self.inner_bindings = _inner_bindings(def_use)
+ self.rereads = _rereads(analysis)
+ self.import_lines: dict[str, list[int]] = {}
+ for d in def_use.definitions:
+ if d.imports:
+ self.import_lines.setdefault(d.var, []).append(d.line)
class _Cutter:
@@ -230,31 +327,37 @@ class _Cutter:
def __init__(
self,
- analysis: FunctionAnalysis,
+ facts: _FunctionFacts,
lmap: LanguageNodeMap,
receiver: Receiver | None,
block: Node,
code: list[Node],
pre: _Prefix,
max_returns: int,
+ loops: tuple[Node, ...] = (),
) -> None:
self.lmap, self.receiver, self.block, self.code = lmap, receiver, block, code
self.max_returns = max_returns
- def_use = analysis.def_use
- self.def_lines, self.use_lines = _var_lines(def_use)
- self.declared_first = _declared_before_read(def_use)
- self.hoisted = _hoisted_bindings(self.def_lines, self.use_lines)
- self.decl_lines = _declaration_lines(def_use)
- self.shared = _closure_state(def_use, self.def_lines, self.use_lines)
- self.reads = _reads_observing(analysis, self.def_lines)
+ self.def_lines, self.use_lines = facts.def_lines, facts.use_lines
+ self.declared_first = facts.declared_first
+ self.hoisted = facts.hoisted
+ self.decl_lines = facts.decl_lines
+ self.shared = facts.shared
+ self.reads = facts.reads
self.pre = pre
self._assigns: dict[tuple[int, str], bool] = {}
self.cut_cost = _cut_costs(code)
self.banners = [c == 0 for c in self.cut_cost]
self.timer_pairs = _timer_pairs(code)
self.guards = [_guard_names(st, lmap) for st in code]
- self.assigned = DefiniteAssignment(analysis)
- self.inner_bindings = _inner_bindings(def_use)
+ self.assigned = facts.assigned
+ self.inner_bindings = facts.inner_bindings
+ self.rereads, self.import_lines = facts.rereads, facts.import_lines
+ # In a loop body: a break / continue leaving a stage would leave the
+ # helper instead, and a value carried to the next iteration must come
+ # back out of the stage that writes it.
+ self.escapes = [escapes(st, lmap) for st in code] if loops else [False] * len(code)
+ self.carried = carried(facts.analysis, loops, facts.def_lines) if loops else frozenset()
def _sum(self, series: list[int], i: int, j: int) -> int:
return series[j + 1] - series[i]
@@ -308,10 +411,15 @@ class _Cutter:
return None
span = self.code[i : j + 1]
s, e = span[0].start_point[0] + 1, span[-1].end_point[0] + 1
+ if any(s <= ln <= e for v in self.rereads for ln in self.def_lines.get(v, ())):
+ return None
params, returns = _infer_in_out(
self.def_lines, self.use_lines, s, e, self.declared_first, reads=self.reads
)
returns = self._own_bindings_dropped(span, s, e, returns)
+ if self.carried:
+ written = {v for v in self.carried if any(s <= ln <= e for ln in self.def_lines[v])}
+ returns = tuple(sorted(set(returns) | written))
params = self._with_inouts(i, j, s, params, returns)
if params is None or len(returns) > self.max_returns:
return None
@@ -336,8 +444,8 @@ class _Cutter:
def _shape_allows(self, i: int, j: int) -> bool:
"""The checks prefix sums answer: size, no return / yield, no named
- nested function, and no timer started on one side of the cut and
- stopped on the other."""
+ nested function, no break / continue leaving the stage, and no timer
+ started on one side of the cut and stopped on the other."""
pre = self.pre
if self._sum(pre.decisions, i, j) < _STAGE_MIN_DECISIONS:
return False
@@ -345,6 +453,8 @@ class _Cutter:
return False
if self._sum(pre.exits, i, j) or self._sum(pre.nested, i, j):
return False
+ if any(self.escapes[i : j + 1]):
+ return False
return not any((i <= a <= j) != (i <= b <= j) for a, b in self.timer_pairs)
def _own_bindings_dropped(
@@ -398,11 +508,26 @@ class _Cutter:
for var in returns:
if var in params or any(self._writes(k, var) for k in range(i, j + 1)):
continue
+ if self._import_fallback(var, i, j):
+ continue
if not any(ln < s for ln in self.def_lines.get(var, ())):
return None
extra.append(var)
return tuple(sorted((*params, *extra))) if extra else params
+ def _import_fallback(self, var: str, i: int, j: int) -> bool:
+ """Whether one of statements ``i..j`` is a ``try`` whose body imports
+ *var* and whose every handler assigns it (``try: from m import x`` /
+ ``except ImportError: x = None``): bound on every path the stage
+ completes. A handler that only passes leaves it unbound."""
+ for st in self.code[i : j + 1]:
+ body = st.child_by_field_name("body") if st.type in self.lmap.try_kinds else None
+ handlers = [c for c in st.children if c.type in self.lmap.catch_kinds]
+ if body is None or not handlers or not _holds_line(body, self.import_lines.get(var, ())):
+ continue
+ if all(_holds_line(h, self.def_lines.get(var, ())) for h in handlers):
+ return True
+ return False
def _writes(self, k: int, var: str) -> bool:
"""Whether statement *k* writes *var* on every path through it (the
@@ -415,6 +540,33 @@ class _Cutter:
return self._assigns[key]
+def _rereads(analysis: FunctionAnalysis) -> frozenset[str]:
+ """Names a multi-line statement writes and also reads on a later line of
+ itself (``msgs = [\\n m for m in msgs]``). Lines order its write before
+ those reads, so neither the inputs nor the outputs of a stage writing one
+ can be read off lines (a known limit of the def / use line model)."""
+ out: set[str] = set()
+ for block in analysis.cfg.blocks:
+ bdu = analysis.def_use.block(block.id)
+ if bdu is None:
+ continue
+ for st in block.statements:
+ if st.is_head or st.end_line == st.start_line:
+ continue
+ for d in bdu.defs:
+ if st.start_line <= d.line <= st.end_line and any(
+ u.name == d.var and d.line < u.line <= st.end_line and not u.echo
+ for u in bdu.uses
+ ):
+ out.add(d.var)
+ return frozenset(out)
+
+
+def _holds_line(node: Node, lines: list[int]) -> bool:
+ lo, hi = node.start_point[0] + 1, node.end_point[0] + 1
+ return any(lo <= ln <= hi for ln in lines)
+
+
def _timer_pairs(code: list[Node]) -> list[tuple[int, int]]:
"""``(a, b)``: statement ``a`` starts a timer (``timings.start("x")``)
that statement ``b`` stops, the first such at or after ``a``."""
@@ -445,24 +597,10 @@ def _cut_costs(code: list[Node]) -> list[int]:
def _guard_names(st: Node, lmap: LanguageNodeMap) -> frozenset[str]:
- """The names a guard statement tests: an ``if`` with no else arm whose
- last statement is itself a raise (Python ``if not x: raise E``) or throw
- (TS / JS ``if (!x) throw e;`` or ``{ ...; throw e; }``). Type checkers
- narrow ``x`` after such a guard, which a helper holding it would undo.
- Empty for anything else, a raise nested deeper included."""
- if st.type not in lmap.if_kinds or st.child_by_field_name("alternative") is not None:
- return frozenset()
- if any(c.type in ("else_clause", "elif_clause") for c in st.children):
- return frozenset()
- body = st.child_by_field_name("consequence")
- if body is None:
- return frozenset()
- stmts = [c for c in body.named_children if not is_comment(c)]
- # ``if (!x) throw e;`` has the throw itself as its consequence.
- last = body if body.type in lmap.raise_kinds or not stmts else stmts[-1]
- if last.type not in lmap.raise_kinds:
- return frozenset()
- condition = st.child_by_field_name("condition")
+ """The names a guard that raises tests (Python ``if not x: raise E``, TS /
+ JS ``if (!x) throw e;``). Type checkers narrow ``x`` after it, which a
+ helper holding it would undo."""
+ condition = exiting_guard(st, lmap, lmap.raise_kinds)
return frozenset(_identifiers(condition)) if condition is not None else frozenset()
@@ -496,6 +634,24 @@ def _context(
return tuple(shared) if len(shared) > _CONTEXT_OVER else ()
+def _inputs_held(stages: tuple[Extraction, ...], def_lines: dict[str, list[int]]) -> bool:
+ """Whether the function holds every stage input at that stage's call:
+ written outside every stage, or handed back by an earlier one. An input
+ only a later stage hands back (or none) would be unbound at the call; a
+ loop-carried one is also written before the loop, outside every stage."""
+
+ def inside(line: int) -> bool:
+ return any(x.start_line <= line <= x.end_line for x in stages)
+
+ earlier: set[str] = set()
+ for x in stages:
+ for p in x.params:
+ if p not in earlier and all(inside(ln) for ln in def_lines.get(p, ())):
+ return False
+ earlier.update(x.returns)
+ return True
+
+
def _composes(
analysis: FunctionAnalysis, stages: tuple[Extraction, ...], context: tuple[str, ...]
) -> tuple[tuple[tuple[str, ...], ...], frozenset[str]] | None:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
index 39539796b..be9169011 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/annotations.py
@@ -12,9 +12,11 @@ stored with the plan's rank, so plan detail serves it without a query.
from __future__ import annotations
import json
-from collections.abc import Mapping, Sequence
+import re
+from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timedelta
+from pathlib import Path
from typing import Any, Literal
from sqlalchemy import func, select
@@ -24,12 +26,12 @@ from ....co_change import parse_partners
from ....persistence.crud.analysis.dead_code import get_dead_code_findings
from ....persistence.crud.authority import governing_decisions_by_file
from ....persistence.crud.git import get_git_metadata_bulk
-from ....persistence.models import GitCommit, GitFunctionBlame
+from ....persistence.models import GitCommit, GitFunctionBlame, Repository
from ..queue.eligibility import DeadSpan, dead_spans, dead_target
from .extract_helper import ACTIVE_CO_CHANGE
from .models import RefactoringSuggestion
-RiskKind = Literal["decision", "public_api", "active_edit", "dead_code"]
+RiskKind = Literal["decision", "public_api", "active_edit", "dead_code", "source_text"]
#: Commits on the target inside this many days before the newest indexed
#: commit read as someone working on it now.
@@ -45,6 +47,11 @@ _RELOCATING = frozenset({"split_file", "extract_class", "move_method"})
#: The blast-radius key each file-level builder writes its dependents under.
_DEPENDENTS_KEY = {"split_file": "dependent_count", "extract_class": "dependents_count"}
_BATCH = 500
+#: A test reading a function's own source text (``inspect.getsource(m.f)``)
+#: asserts how it is written, which a split changes.
+_GETSOURCE = re.compile(r"\bgetsource(?:lines)?\(\s*([A-Za-z_][\w.]*)\s*\)")
+#: Larger files are not read for it: generated fixtures, not tests.
+_MAX_TEST_BYTES = 1 << 20
FunctionCommits = tuple[int, int, tuple[str, ...]]
@@ -111,6 +118,8 @@ class AnnotationFacts:
(committed_at, author)``; ``None`` when history is too shallow to tell
recent from all, which is no signal rather than a quiet target. ``dead``
is the sure dead-code spans by file (:func:`..queue.eligibility.dead_spans`).
+ ``sources_read`` is, per test file the plans run, the ``getsource``
+ arguments it passes (:data:`_GETSOURCE`).
"""
decisions: Mapping[str, list[tuple[str, str]]] = field(default_factory=dict)
@@ -118,10 +127,14 @@ class AnnotationFacts:
functions: Mapping[str, list[FunctionCommits]] = field(default_factory=dict)
recent: Mapping[str, tuple[datetime, str]] | None = None
dead: Mapping[str, list[DeadSpan]] = field(default_factory=dict)
+ sources_read: Mapping[str, frozenset[str]] = field(default_factory=dict)
-def annotate(suggestion: RefactoringSuggestion, facts: AnnotationFacts) -> PlanAnnotations:
- """*suggestion*'s annotations from *facts*. Pure."""
+def annotate(
+ suggestion: RefactoringSuggestion, facts: AnnotationFacts, tests: Sequence[str] = ()
+) -> PlanAnnotations:
+ """*suggestion*'s annotations from *facts*; *tests* are the ones its
+ validation runs. Pure."""
decisions = list(facts.decisions.get(suggestion.file_path, ()))
risks = [
PlanRisk(
@@ -135,6 +148,7 @@ def annotate(suggestion: RefactoringSuggestion, facts: AnnotationFacts) -> PlanA
_dead_code_risk(suggestion, facts.dead),
_public_api_risk(suggestion),
_active_edit_risk(suggestion, facts),
+ _source_text_risk(suggestion, tests, facts.sources_read),
):
if risk is not None:
risks.append(risk)
@@ -212,6 +226,82 @@ def _active_edit_risk(suggestion: RefactoringSuggestion, facts: AnnotationFacts)
)
+def _source_text_risk(
+ suggestion: RefactoringSuggestion,
+ tests: Sequence[str],
+ sources_read: Mapping[str, frozenset[str]],
+) -> PlanRisk | None:
+ """A test the plan runs that may read the split function's own source text."""
+ if suggestion.refactoring_type != "extract_method" or not suggestion.target_symbol:
+ return None
+ owners = _owners(suggestion)
+ name = suggestion.target_symbol.rsplit(".", 1)[-1]
+ readers = sorted(
+ path
+ for path in _test_files(tests)
+ if any(_names_target(read, name, owners) for read in sources_read.get(path, ()))
+ )
+ if not readers:
+ return None
+ who = readers[0] if len(readers) == 1 else f"{len(readers)} test files"
+ return PlanRisk(
+ "source_text",
+ f"{who} may read the source text of `{name}`; check what it asserts about that "
+ "text after the split.",
+ readers[0],
+ )
+
+
+def _owners(suggestion: RefactoringSuggestion) -> frozenset[str]:
+ """What may qualify the target in a test: its module's path parts and the
+ classes in its symbol (``CredentialPool`` of ``CredentialPool.refresh``)."""
+ module = Path(suggestion.file_path).with_suffix("").parts
+ return frozenset((*module, *suggestion.target_symbol.split(".")[:-1]))
+
+
+def _names_target(read: str, name: str, owners: frozenset[str]) -> bool:
+ """Whether a ``getsource`` argument (``flow._run_upgrade``) names the
+ target: the same last name, qualified by nothing or by one of *owners*."""
+ *qualifier, last = read.split(".")
+ return last == name and (not qualifier or qualifier[-1] in owners)
+
+
+def _test_files(tests: Iterable[str]) -> list[str]:
+ """The files of test ids (``path::name``), once each, in order."""
+ return list(dict.fromkeys(test.split("::", 1)[0] for test in tests))
+
+
+def _sources_read(root: Path, files: Iterable[str]) -> dict[str, frozenset[str]]:
+ """Per test file under *root* that reads any, the ``getsource``
+ arguments it passes. Read once at finalize; a file outside *root*,
+ missing (a hosted index has no checkout) or too large says nothing."""
+ base = root.resolve()
+ out: dict[str, frozenset[str]] = {}
+ for rel in files:
+ path = (root / rel).resolve()
+ try:
+ if not path.is_relative_to(base) or path.stat().st_size > _MAX_TEST_BYTES:
+ continue
+ text = path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ reads = frozenset(_unaliased(m, text) for m in _GETSOURCE.findall(text))
+ if reads:
+ out[rel] = reads
+ return out
+
+
+def _unaliased(read: str, text: str) -> str:
+ """*read* with a leading import alias replaced by the name it stands for
+ (``cl.run`` after ``import agent.conversation_loop as cl`` reads
+ ``conversation_loop.run``)."""
+ head, dot, rest = read.partition(".")
+ if not dot:
+ return read
+ found = re.search(rf"\bimport\s+([\w.]+)\s+as\s+{re.escape(head)}\b", text)
+ return f"{found.group(1).rsplit('.', 1)[-1]}.{rest}" if found else read
+
+
def _target_functions(
suggestion: RefactoringSuggestion, functions: Mapping[str, list[FunctionCommits]]
) -> list[FunctionCommits]:
@@ -235,10 +325,17 @@ def _s(count: int) -> str:
async def load_annotation_facts(
- session: AsyncSession, repository_id: str, suggestions: Sequence[RefactoringSuggestion]
+ session: AsyncSession,
+ repository_id: str,
+ suggestions: Sequence[RefactoringSuggestion],
+ tests: Iterable[str] = (),
) -> AnnotationFacts:
- """Every fact :func:`annotate` reads, for the whole plan set at once."""
+ """Every fact :func:`annotate` reads, for the whole plan set at once;
+ *tests* are the ones the Extract Method plans run."""
files = sorted({item.file_path for item in suggestions if item.file_path})
+ root = await session.scalar(
+ select(Repository.local_path).where(Repository.id == repository_id)
+ )
metadata = await get_git_metadata_bulk(session, repository_id, files)
dead = await get_dead_code_findings(session, repository_id)
recent = await _recent_commits(session, repository_id)
@@ -248,6 +345,7 @@ async def load_annotation_facts(
functions=await _function_commits(session, repository_id, files) if recent else {},
recent=recent,
dead=dead_spans(dead),
+ sources_read=_sources_read(Path(root), _test_files(tests)) if root else {},
)
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 7c5402e8b..b414d7d7f 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
@@ -118,6 +118,7 @@ from . import render
from .declarative import declarative_flat
from .helper_naming import ScopeNames, helper_names, out_value_name
from .models import RefactoringContext, RefactoringSuggestion
+from .narrowing import narrowed, narrowings
from .registry import RefactoringDetector, register
if TYPE_CHECKING:
@@ -158,6 +159,8 @@ _HIGH_MIN_SHARE = 0.1
# Above this no single helper of a stage's size brings the function under it.
_STAGE_MIN_CCN = 2 * STAGE_MAX_CCN + 1
+# Languages whose types a guard narrows (``narrowing``).
+_NARROWING_LANGUAGES = frozenset({"typescript", "tsx"})
# Keys a stage carries that the plan's own (stage 1) keys do not.
_STAGE_ONLY_KEYS = ("ccn", "nloc", "context_params")
@@ -415,7 +418,9 @@ def _staged_fields(
for x, reimports in zip(staged.stages, staged.imports, strict=True):
name = render.private_name(
language,
- names.claim_first(analysis, helper_names(analysis, x, lmap, language, imports)),
+ names.claim_first(
+ analysis, helper_names(analysis, x, lmap, language, imports, sections=True)
+ ),
)
carried = [p for p in x.params if p in context]
own = replace(x, params=tuple(p for p in x.params if p not in context))
@@ -492,9 +497,10 @@ def _parameter_object(
if not staged.context:
return None
first = staged.stages[0].start_line
- probe = Extraction(first, first, staged.context, (), 0, 0)
+ probe = Extraction(first, staged.stages[0].end_line, staged.context, (), 0, 0)
types = _declared_types(analysis, probe, dialect)
- fields = tuple(render.Slot(n, types.get(n)) for n in staged.context)
+ narrowed_at = _narrow(analysis, probe, language, types)
+ fields = tuple(render.Slot(n, types.get(n), narrowed_at=narrowed_at.get(n)) for n in staged.context)
# Every name the function writes or reads (a module global ``ctx`` too).
def_use = analysis.def_use
taken = {d.var for d in def_use.definitions}
@@ -580,12 +586,15 @@ def _render_fields(
*leading* slots come first (a staged plan's parameter object)."""
new_symbol = symbol["new_symbol"]
types = _declared_types(analysis, extraction, dialect)
+ narrowed_at = _narrow(analysis, extraction, language, types)
# Only a Rust value moves when passed, so only Rust asks what is read later.
after = _read_after(analysis, extraction) if language == "rust" else set()
# A method reaches its instance through the receiver, not an argument.
own = new_symbol["receiver"] if new_symbol["kind"] == "method" else None
params = leading + tuple(
- render.Slot(p, types.get(p), p in after) for p in extraction.params if p != own
+ render.Slot(p, types.get(p), p in after, narrowed_at.get(p))
+ for p in extraction.params
+ if p != own
)
returns = tuple(render.Slot(r, types.get(r)) for r in extraction.returns)
declared, before, rebound = _out_binding(analysis, extraction, get_language_map(language or ""))
@@ -656,6 +665,38 @@ def _declared_types(
return found
+def _narrow(
+ analysis: FunctionAnalysis, extraction: Extraction, language: str | None, types: dict[str, str]
+) -> dict[str, int]:
+ """Apply the guards above a TypeScript span to its inputs' *types*
+ (``narrowing``): a narrower type the declaration proves replaces it, and
+ a name narrowed to one it does not loses its type and comes back with the
+ guard's line, for the plan's note."""
+ if language not in _NARROWING_LANGUAGES or not extraction.params:
+ return {}
+ def_lines: dict[str, list[int]] = {}
+ for d in analysis.def_use.definitions:
+ def_lines.setdefault(d.var, []).append(d.line)
+ found = narrowings(
+ analysis.fn_node,
+ get_language_map(language),
+ extraction.start_line,
+ extraction.end_line,
+ set(extraction.params),
+ def_lines,
+ )
+ unknown: dict[str, int] = {}
+ for name, guard in found.items():
+ declared = types.get(name)
+ exact = narrowed(declared, guard.drops) if declared and guard.drops is not None else None
+ if exact:
+ types[name] = exact
+ else:
+ types.pop(name, None)
+ unknown[name] = guard.line
+ return unknown
+
+
def _read_after(analysis: FunctionAnalysis, extraction: Extraction) -> set[str]:
"""The IN names the function reads after the span (a closure's read counts
where the closure is written)."""
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py
index 3d7b6f413..bab5ce294 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/helper_naming.py
@@ -62,6 +62,9 @@ _SNAKE_CASE = "snake_case"
# outside itself names it the way an OUT name would, wrongly.
_VALUE_VERBS = frozenset({"compute", "calculate", "calc", "derive", "get", "build", "make"})
+# Past this a name joining several sections reads as a sentence, not a name.
+_MAX_JOINED_WORDS = 6
+
# How far below a scope a sibling definition can sit: ``export const f = () =>``
# is four levels under a TS module, a decorated Python method three under its
# class. Deeper nodes are expressions, which a scan for names need not visit.
@@ -99,14 +102,18 @@ def helper_name(
lmap: LanguageNodeMap,
language: str | None,
modules: frozenset[str] = frozenset(),
+ *,
+ sections: bool = False,
) -> str | None:
"""A deterministic starting name for the helper, before the collision
check, or ``None`` when nothing in the code anchors one. *modules* are the
- file's imported names (:func:`dataflow.effects.imported_names`)."""
+ file's imported names (:func:`dataflow.effects.imported_names`). With
+ *sections* (a staged plan's stage), a span running across several named
+ sections is named after all of them (:func:`_joined`)."""
stmts = span_statements(analysis.fn_node, extraction.start_line, extraction.end_line, lmap)
if not stmts:
return None
- words = _anchored_words(stmts, lmap)
+ words = _anchored_words(stmts, lmap, sections=sections)
own = Ownership(
owned=owned_names(stmts, lmap),
declared=declared_names(analysis.fn_node, analysis.def_use, lmap),
@@ -124,11 +131,14 @@ def helper_names(
lmap: LanguageNodeMap,
language: str | None,
modules: frozenset[str] = frozenset(),
+ *,
+ sections: bool = False,
) -> Iterator[str]:
"""Starting names, best first: :func:`helper_name`, then the host function
qualified by each subject of the span (``render_card_directive``). Lazy, so
- the subjects are read only when the anchored name is missing or taken."""
- anchored = helper_name(analysis, extraction, lmap, language, modules)
+ the subjects are read only when the anchored name is missing or taken.
+ *sections* as for :func:`helper_name`."""
+ anchored = helper_name(analysis, extraction, lmap, language, modules, sections=sections)
if anchored:
yield anchored
stmts = span_statements(analysis.fn_node, extraction.start_line, extraction.end_line, lmap)
@@ -148,20 +158,43 @@ def _overlap(host: list[str], subject: list[str]) -> int:
return next((n for n in range(top, 0, -1) if host[-n:] == subject[:n]), 0)
-def _anchored_words(stmts: list[Any], lmap: LanguageNodeMap) -> list[str]:
+def _anchored_words(stmts: list[Any], lmap: LanguageNodeMap, *, sections: bool = False) -> list[str]:
"""The words of the label or banner naming the span, ``[]`` without one.
The span may be the whole body of ``with timed(...)``; else the label or
banner heads its first statement. A label or banner names only its own
section, so one heading a later top-level statement means the span runs
- across sections, and neither names it.
+ across sections, and neither names it alone: with *sections* the name
+ joins them when the first statement opens a section too, else it is ``[]``.
"""
wrapper = enclosing_with(stmts, lmap)
if wrapper is not None and (label := _label(wrapper)):
return label
heads = [_label(stmt) or banner_words(comment) for stmt, comment in section_heads(stmts)]
# A later head means a second section starts inside the span.
- return heads[0] if heads and not any(heads[1:]) else []
+ if heads and not any(heads[1:]):
+ return heads[0]
+ return _joined([h for h in heads if h]) if sections and heads and heads[0] else []
+
+
+def _joined(heads: list[list[str]]) -> list[str]:
+ """One name for the sections *heads* name: their shared leading words,
+ then each one's own words, the last after ``and`` (``persist_kg_and_git``).
+ ``[]`` when a section adds no words of its own or the name would run past
+ ``_MAX_JOINED_WORDS``."""
+ common = 0
+ while all(len(h) > common and h[common] == heads[0][common] for h in heads):
+ common += 1
+ tails: list[list[str]] = []
+ for head in heads:
+ if head[common:] not in tails:
+ tails.append(head[common:])
+ if any(not tail for tail in tails):
+ return []
+ words = list(heads[0][:common])
+ for n, tail in enumerate(tails):
+ words.extend(["and", *tail] if n and n == len(tails) - 1 else tail)
+ return words if len(words) <= _MAX_JOINED_WORDS else []
def _label(stmt: Any) -> list[str]:
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py b/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py
new file mode 100644
index 000000000..e03db045f
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/narrowing.py
@@ -0,0 +1,176 @@
+"""What a TypeScript guard above an Extract Method span narrows.
+
+``if (!reply) return;`` narrows ``reply`` from ``Reply | undefined`` to
+``Reply`` for the code after it, the span included. A helper parameter typed
+with the declared type undoes that, and the lifted code stops compiling where
+it relies on it. A guard counts when it exits (``return``, ``throw``,
+``continue``, ``break``) with no ``else`` and sits before the span in a block
+holding it, and only for a name nothing writes between the guard and the end
+of the span.
+
+The arms a test removes are known for ``!x``, ``x == null`` / ``=== null``,
+``x == undefined`` / ``=== undefined`` and ``typeof x === "undefined"``,
+alone or joined by ``||``. ``typeof``, ``instanceof`` and ``Array.isArray``
+narrow to a type the declaration does not name, so those are reported with no
+arms: the plan says the parameter needs the narrowed type instead of writing
+one.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from ..dataflow.dialects.ts_js import union_arms
+from ..dataflow.span import exiting_guard, span_statements
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from ..complexity.languages import LanguageNodeMap
+
+_FALSY = frozenset({"undefined", "null", "false"})
+_NULLISH = frozenset({"undefined", "null"})
+_EQUALITY = {"==": _NULLISH, "===": None}
+_EXITS = frozenset({"return_statement", "throw_statement", "continue_statement", "break_statement"})
+
+
+@dataclass(frozen=True)
+class Narrowing:
+ """The guard's line and the union arms it removes (None: it narrows to a
+ type the declaration does not name)."""
+
+ line: int
+ drops: frozenset[str] | None
+
+
+def narrowings(
+ fn_node: Node | None,
+ lmap: LanguageNodeMap,
+ start: int,
+ end: int,
+ names: set[str],
+ def_lines: dict[str, list[int]],
+) -> dict[str, Narrowing]:
+ """Per name in *names*, the nearest guard narrowing it over lines
+ *start*..*end* (module docstring)."""
+ stmts = span_statements(fn_node, start, end, lmap)
+ out: dict[str, Narrowing] = {}
+ node = stmts[0] if stmts else None
+ while node is not None and node.parent is not None and node is not fn_node:
+ if node.parent.type in lmap.block_kinds:
+ sib = node.prev_named_sibling
+ while sib is not None:
+ line = sib.start_point[0] + 1
+ for name, drops in _guard_tests(sib, lmap).items():
+ rebound = any(sib.end_point[0] + 1 < ln <= end for ln in def_lines.get(name, ()))
+ if name in names and name not in out and not rebound:
+ out[name] = Narrowing(line, drops)
+ sib = sib.prev_named_sibling
+ node = node.parent
+ return out
+
+
+def narrowed(declared: str, drops: frozenset[str]) -> str | None:
+ """*declared* without the union arms in *drops*; None when nothing is left."""
+ arms = union_arms(declared)
+ kept = [a for a in arms if a not in drops]
+ if len(kept) == len(arms):
+ return declared
+ return " | ".join(kept) or None
+
+
+def _guard_tests(st: Node, lmap: LanguageNodeMap) -> dict[str, frozenset[str] | None]:
+ """What an exiting ``if`` with no ``else`` proves false about each name."""
+ condition = exiting_guard(st, lmap, _EXITS)
+ return _false_means(condition) if condition is not None else {}
+
+
+def _false_means(expr: Node) -> dict[str, frozenset[str] | None]:
+ """Per name, the arms *expr* being false removes."""
+ expr = _peel(expr)
+ op = _operator(expr)
+ if expr.type == "binary_expression" and op == "||":
+ return _merged(
+ _false_means(expr.child_by_field_name("left")),
+ _false_means(expr.child_by_field_name("right")),
+ )
+ if expr.type == "unary_expression" and op == "!":
+ arg = _peel(expr.child_by_field_name("argument"))
+ if arg.type == "identifier":
+ return {_text(arg): _FALSY}
+ return dict.fromkeys(_typed_names(arg))
+ if expr.type == "binary_expression" and op in _EQUALITY:
+ return _equality(expr, op)
+ # ``a && b`` being false proves neither side false.
+ return {} if op == "&&" else dict.fromkeys(_typed_names(expr))
+
+
+def _merged(
+ a: dict[str, frozenset[str] | None], b: dict[str, frozenset[str] | None]
+) -> dict[str, frozenset[str] | None]:
+ """Both sides of ``||`` false: a name tested on both loses both sides'
+ arms (``a === null || a === undefined``); an unknown narrowing stays one."""
+ out = dict(a)
+ for name, drops in b.items():
+ if name not in out:
+ out[name] = drops
+ elif out[name] is not None and drops is not None:
+ out[name] = out[name] | drops
+ else:
+ out[name] = None
+ return out
+
+
+def _equality(expr: Node, op: str) -> dict[str, frozenset[str] | None]:
+ """``x == null``, ``x === undefined``, ``typeof x === "undefined"``."""
+ sides = [_peel(expr.child_by_field_name(f)) for f in ("left", "right")]
+ texts = [_text(s) for s in sides]
+ for k in (0, 1):
+ other, value = sides[k], texts[1 - k]
+ if other.type == "identifier" and value in _NULLISH:
+ return {_text(other): _EQUALITY[op] or frozenset({value})}
+ if _operator(other) == "typeof" and value.strip("'\"`") == "undefined":
+ arg = _peel(other.child_by_field_name("argument"))
+ if arg.type == "identifier":
+ return {_text(arg): frozenset({"undefined"})}
+ return dict.fromkeys(_typed_names(expr))
+
+
+def _typed_names(expr: Node) -> list[str]:
+ """Names a ``typeof`` / ``instanceof`` / ``Array.isArray`` test in *expr*
+ narrows to a type the declaration does not name."""
+ out = []
+ stack = [expr]
+ while stack:
+ node = stack.pop()
+ target = None
+ if node.type == "unary_expression" and _operator(node) == "typeof":
+ target = node.child_by_field_name("argument")
+ elif node.type == "binary_expression" and _operator(node) == "instanceof":
+ target = node.child_by_field_name("left")
+ elif node.type == "call_expression" and _text(node.child_by_field_name("function")) == "Array.isArray":
+ args = node.child_by_field_name("arguments")
+ target = args.named_children[0] if args is not None and args.named_children else None
+ if target is not None and _peel(target).type == "identifier":
+ out.append(_text(_peel(target)))
+ stack.extend(node.named_children)
+ return out
+
+
+def _peel(node: Node) -> Node:
+ while node.type == "parenthesized_expression" and node.named_children:
+ node = node.named_children[0]
+ return node
+
+
+def _operator(node: Node) -> str | None:
+ op = node.child_by_field_name("operator")
+ return _text(op) if op is not None else None
+
+
+def _text(node: Node | None) -> str:
+ return (node.text or b"").decode("utf-8", "replace") if node is not None else ""
+
+
+__all__ = ["Narrowing", "narrowed", "narrowings"]
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 5adada63f..a1c7e4aca 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/render.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/render.py
@@ -80,12 +80,15 @@ _RUST_COPY = frozenset(
@dataclass(frozen=True)
class Slot:
- """One parameter or output: its name, declared type (None: unknown), and
- whether the host reads it after the span (a Rust move would end that)."""
+ """One parameter or output: its name, declared type (None: unknown),
+ whether the host reads it after the span (a Rust move would end that),
+ and the line of a guard above the span narrowing it to a type the code
+ does not write (``narrowing``)."""
name: str
type: str | None = None
read_after: bool = False
+ narrowed_at: int | None = None
@dataclass(frozen=True)
@@ -203,11 +206,12 @@ def _notes(s: HelperShape, family: str) -> list[str]:
if family in ("ts", "js"):
out.extend(_undefined_arm_notes(s))
if family == "ts":
- untyped = [p.name for p in s.params if not p.type]
+ untyped = [p.name for p in s.params if not p.type and p.narrowed_at is None]
if untyped:
out.append(
f"Write the types of {', '.join(untyped)}: the code declares none for them."
)
+ out.extend(_narrowed_note(p) for p in s.params if not p.type and p.narrowed_at)
if family == "rust":
unknown = [p.name for p in _rust_unsure(s)]
if unknown:
@@ -220,6 +224,13 @@ def _notes(s: HelperShape, family: str) -> list[str]:
return out
+def _narrowed_note(slot: Slot) -> str:
+ return (
+ f"Type {slot.name} as the guard on line {slot.narrowed_at} narrows it: a wider "
+ "type undoes that narrowing."
+ )
+
+
# -- shared pieces -----------------------------------------------------------
@@ -468,7 +479,8 @@ def render_context(
return ContextText(None, f"const {var} = {{ {names} }};", ())
lines = [f" {f.name}: {f.type or TYPE_PLACEHOLDER};" for f in fields]
declaration = "\n".join([f"interface {name} {{", *lines, "}"])
- return ContextText(declaration, f"const {var}: {name} = {{ {names} }};", ())
+ notes = tuple(_narrowed_note(f) for f in fields if not f.type and f.narrowed_at)
+ return ContextText(declaration, f"const {var}: {name} = {{ {names} }};", notes)
#: What the renderer adds to a stored plan, served on plan detail only.
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
index 3b6f6ecdc..dc4038728 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py
@@ -297,10 +297,20 @@ async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[An
).scalars()
ranked = await hydrate_recommendations(session, repository_id, list(rows), step_verify=True)
facts = await load_annotation_facts(
- session, repository_id, [item.suggestion for item in ranked]
+ session,
+ repository_id,
+ [item.suggestion for item in ranked],
+ tests=[
+ test
+ for item in ranked
+ if item.suggestion.refactoring_type == "extract_method"
+ for test in item.validation.tests
+ ],
)
ranked = [
- dataclasses.replace(item, annotations=annotate(item.suggestion, facts))
+ dataclasses.replace(
+ item, annotations=annotate(item.suggestion, facts, item.validation.tests)
+ )
for item in ranked
]
await store_plan_ranks(session, repository_id, ranked)
diff --git a/packages/types/src/refactoring.ts b/packages/types/src/refactoring.ts
index 2cd735f14..303d17d4b 100644
--- a/packages/types/src/refactoring.ts
+++ b/packages/types/src/refactoring.ts
@@ -59,9 +59,9 @@ export interface StepVerify {
}
/** What another layer says to check before applying a plan: a decision that
- * governs its file, consumers of what it moves, dead code it touches, or
- * recent commits on its lines. */
-export type PlanRiskKind = "decision" | "public_api" | "active_edit" | "dead_code";
+ * governs its file, consumers of what it moves, dead code it touches, recent
+ * commits on its lines, or a test that reads the function's source text. */
+export type PlanRiskKind = "decision" | "public_api" | "active_edit" | "dead_code" | "source_text";
/** One sentence to read before applying the plan. `ref` is the decision id or
* the newest commit sha, when the risk has one. */
@@ -207,6 +207,7 @@ export type RecipePreconditionKind =
| "public_api"
| "active_edit"
| "dead_code"
+ | "source_text"
| "unchecked"
| "kind_unaudited";
diff --git a/tests/unit/health/test_extract_method_narrowing.py b/tests/unit/health/test_extract_method_narrowing.py
new file mode 100644
index 000000000..43125454a
--- /dev/null
+++ b/tests/unit/health/test_extract_method_narrowing.py
@@ -0,0 +1,100 @@
+"""TypeScript plan types after a guard: ``if (!x) return;`` narrows ``x`` for the
+lifted lines, so the helper parameter takes the narrowed type, or a note when
+the code does not write it (openclaw ``pdf-tool.model-config.ts``: a typed
+parameter whose narrowing came from a guard did not compile)."""
+
+from __future__ import annotations
+
+import textwrap
+
+import pytest
+
+from repowise.core.analysis.health.dataflow import Extraction, analyze_file
+from repowise.core.analysis.health.dataflow.dialects.ts_js import union_arms
+from repowise.core.analysis.health.refactoring import render
+from repowise.core.analysis.health.refactoring.extract_method import _narrow
+from repowise.core.analysis.health.refactoring.narrowing import narrowed
+
+_SRC = """
+function run(reply?: Reply, opts: Opts | null, kind: unknown, n: number, late?: string) {
+ if (!reply) {
+ return;
+ }
+ if (opts === null) throw new Error("no opts");
+ if (typeof kind !== "string") return;
+ const model = pick(n);
+ if (!model || n < 0) return;
+ if (!late) return;
+ late = other(n);
+ send(reply, opts, kind, model, late);
+ log(reply);
+}
+"""
+
+
+def _analysis():
+ from repowise.core.ingestion.parser import _get_language
+
+ if _get_language("typescript") is None:
+ pytest.skip("tree-sitter language pack missing for typescript")
+ src = textwrap.dedent(_SRC)
+ res = analyze_file("m.ts", "typescript", src.encode(), flagged_only=False)
+ if not res.functions:
+ pytest.skip("tree-sitter language pack missing for typescript")
+ lines = src.splitlines()
+ span = next(i for i, ln in enumerate(lines, 1) if ln.strip().startswith("send("))
+ return res.functions[0], span, lines
+
+
+def test_a_guard_narrows_the_declared_type_or_says_the_type_is_narrower():
+ fn, span, lines = _analysis()
+ params = ("reply", "opts", "kind", "model", "late")
+ types = {"reply": "Reply | undefined", "opts": "Opts | null", "kind": "unknown", "late": "string | undefined"}
+ notes = _narrow(fn, Extraction(span, span + 1, params, (), 0, 0), "typescript", types)
+ assert types["reply"] == "Reply" and types["opts"] == "Opts"
+ # ``typeof`` narrows to a type the code does not write; ``model`` has none.
+ guard = next(i for i, ln in enumerate(lines, 1) if "typeof kind" in ln)
+ assert "kind" not in types and notes["kind"] == guard
+ assert notes["model"] == next(i for i, ln in enumerate(lines, 1) if "!model" in ln)
+ # ``late`` is written after its guard: the declared type stands.
+ assert types["late"] == "string | undefined" and "late" not in notes
+
+
+def test_javascript_and_python_spans_are_left_alone():
+ fn, span, _ = _analysis()
+ types = {"reply": "Reply | undefined"}
+ assert _narrow(fn, Extraction(span, span, ("reply",), (), 0, 0), "javascript", types) == {}
+ assert types == {"reply": "Reply | undefined"}
+
+
+def test_union_arms_split_outside_brackets():
+ assert union_arms("Map<string, A | B> | undefined") == ["Map<string, A | B>", "undefined"]
+ assert union_arms("(a: A | B) => void") == ["(a: A | B) => void"]
+ assert narrowed("A | null | undefined", frozenset({"undefined", "null", "false"})) == "A"
+ assert narrowed("A", frozenset({"undefined"})) == "A"
+ assert narrowed("undefined", frozenset({"undefined"})) is None
+
+
+def test_a_narrowed_parameter_without_a_type_gets_its_own_note():
+ texts = render.render(
+ render.HelperShape(
+ language="typescript",
+ name="send",
+ kind="function",
+ is_async=False,
+ params=(render.Slot("reply"), render.Slot("model", narrowed_at=7)),
+ )
+ )
+ assert texts.notes == (
+ "Write the types of reply: the code declares none for them.",
+ "Type model as the guard on line 7 narrows it: a wider type undoes that narrowing.",
+ )
+
+
+def test_a_name_tested_twice_in_one_guard_loses_both_arms():
+ from repowise.core.analysis.health.refactoring.narrowing import _merged
+
+ assert _merged({"a": frozenset({"null"})}, {"a": frozenset({"undefined"})}) == {
+ "a": frozenset({"null", "undefined"})
+ }
+ assert _merged({"a": frozenset({"null"})}, {"a": None, "b": None}) == {"a": None, "b": None}
diff --git a/tests/unit/health/test_extract_method_render.py b/tests/unit/health/test_extract_method_render.py
index 56f0293f4..c82b9a66e 100644
--- a/tests/unit/health/test_extract_method_render.py
+++ b/tests/unit/health/test_extract_method_render.py
@@ -286,7 +286,8 @@ _TYPED_SOURCES = {
}
_EXPECTED_TYPES = {
"python": {"a": "int", "b": None, "c": "list[str]", "x": "dict[str, int]"},
- "typescript": {"a": "number", "b": "string", "c": None, "x": "Map<string, number>"},
+ # An optional parameter holds `undefined` until something narrows it.
+ "typescript": {"a": "number", "b": "string | undefined", "c": None, "x": "Map<string, number>"},
"go": {"a": "int", "b": "int", "c": "string", "x": "[]string", "y": None},
"java": {"a": "int", "b": "String[]", "c": "int", "x": "int", "y": None},
"rust": {"a": "i32", "b": "&mut Vec<u8>", "c": None, "d": None, "x": "u64"},
diff --git a/tests/unit/health/test_extract_method_stages.py b/tests/unit/health/test_extract_method_stages.py
index d3a720b61..71d152d89 100644
--- a/tests/unit/health/test_extract_method_stages.py
+++ b/tests/unit/health/test_extract_method_stages.py
@@ -11,7 +11,7 @@ fixture mirrors ``update_cmd/persistence.py::_persist_full_update_async``: an
from __future__ import annotations
import textwrap
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
import pytest
@@ -622,3 +622,283 @@ def test_code_no_path_reaches_has_no_bound_inputs():
assigned = DefiniteAssignment(fn)
assert {"x", "y"} <= assigned.before(4, 4)
assert assigned.before(5, 5) is None
+
+
+_WORDS = ("alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta")
+
+
+def _item_section(n: int, *, extra: str = "") -> str:
+ """One section of a loop body: a banner and a branch on the item. Each
+ reads its own option, so no single span carries more than one section."""
+ return f"""
+ # Handle {_WORDS[n]}
+ if item.kind == "k{n}" and item.ready:
+ handle_{n}(item, a, seen, opt_{n}){extra}
+ elif item.other_{n} or b:
+ skip_{n}(item, last)
+"""
+
+
+def _loop_fn(*, extras: dict[int, str] | None = None, tail: str = "last = item") -> str:
+ extras = extras or {}
+ body = "".join(_item_section(n, extra=extras.get(n, "")) for n in range(8))
+ return f"""
+def run(items, a, b, {", ".join(f"opt_{n}" for n in range(8))}):
+ seen = []
+ last = None
+ for item in items:
+{textwrap.indent(textwrap.dedent(body), " " * 8)}
+ {tail}
+ return seen, last
+"""
+
+
+def _spans(plan) -> list[tuple[int, int]]:
+ return [(s["span"]["start"], s["span"]["end"]) for s in plan.plan["stages"]]
+
+
+def test_a_loop_body_is_cut_and_the_loop_stays_in_the_function():
+ # hermes ``cron/scheduler.py::_deliver_result``: the work sits in one ``for``.
+ src = _loop_fn()
+ lines = textwrap.dedent(src).splitlines()
+ loop = next(i for i, ln in enumerate(lines, 1) if ln.strip().startswith("for item"))
+ plan = _plans(src)["run"]
+ spans = _spans(plan)
+ assert len(spans) >= 2
+ assert all(s > loop for s, _ in spans)
+ assert all("item" in s["params"] for s in plan.plan["stages"])
+ residual = plan.plan["orchestrator"]
+ # The loop's own decision point stays with the function.
+ assert residual["ccn_after"] >= 2
+ # A stage running across two banners is named after both.
+ assert "_handle_gamma_and_delta" in [s["suggested_name"] for s in plan.plan["stages"]]
+
+
+def test_a_name_joining_sections_keeps_shared_words_once():
+ from repowise.core.analysis.health.refactoring.helper_naming import _joined
+
+ assert _joined([["persist", "kg"], ["persist", "git"]]) == ["persist", "kg", "and", "git"]
+ assert _joined([["persist", "kg"], ["persist", "git"], ["persist", "decisions"]]) == [
+ "persist", "kg", "git", "and", "decisions"
+ ]
+ # A section adding no words of its own, or a name past six words, gives none.
+ assert _joined([["load", "config"], ["load"]]) == []
+ assert _joined([["load", "the", "pages"], ["sweep", "old", "rows"]]) == []
+
+
+def test_a_value_the_next_iteration_reads_comes_back_out_of_its_stage():
+ # ``last`` is written in the last section and read by the first on the next
+ # iteration: the stage writing it hands it back, the reading one takes it in.
+ src = _loop_fn(extras={7: "\n last = item"})
+ stages = _plans(src)["run"].plan["stages"]
+ lines = textwrap.dedent(src).splitlines()
+ write = next(
+ i for i, ln in enumerate(lines, 1) if ln.strip() == "last = item" and ln.startswith(" " * 12)
+ )
+ writer = next(s for s in stages if s["span"]["start"] <= write <= s["span"]["end"])
+ assert "last" in writer["returns"] and "last" in writer["params"]
+ assert all("last" in s["params"] for s in stages)
+
+
+def test_a_continue_leaving_a_section_keeps_that_section_in_the_function():
+ src = _loop_fn(extras={3: "\n if item.done:\n continue"})
+ lines = textwrap.dedent(src).splitlines()
+ jump = next(i for i, ln in enumerate(lines, 1) if ln.strip() == "continue")
+ spans = _spans(_plans(src)["run"])
+ assert len(spans) >= 2
+ assert not any(s <= jump <= e for s, e in spans)
+
+
+def test_one_if_arm_holding_the_work_is_cut():
+ body = "".join(_item_section(n) for n in range(8)).replace("item", "cfg")
+ src = f"""
+def apply(cfg, a, b, seen, last, {", ".join(f"opt_{n}" for n in range(8))}):
+ if cfg.enabled:
+{textwrap.indent(textwrap.dedent(body), " " * 8)}
+ return seen
+"""
+ lines = textwrap.dedent(src).splitlines()
+ head = next(i for i, ln in enumerate(lines, 1) if ln.strip() == "if cfg.enabled:")
+ spans = _spans(_plans(src)["apply"])
+ assert len(spans) >= 2 and all(s > head for s, _ in spans)
+
+
+ ("language", "ext", "src", "expected"),
+ [
+ ("python", "py", "for r in rows:\n if r:\n break", False),
+ ("python", "py", "if r:\n continue", True),
+ # A ``for ... else`` arm is not the loop's body: its break leaves the outer loop.
+ ("python", "py", "for r in rows:\n pass\nelse:\n break", True),
+ ("typescript", "ts", "switch (k) { case 1: break; }", False),
+ ("typescript", "ts", "switch (k) { case 1: continue; }", True),
+ ("typescript", "ts", "inner: for (const r of rows) { break inner; }", True),
+ ("typescript", "ts", "items.forEach(() => { return; });", False),
+ ],
+)
+def test_a_jump_leaves_a_statement_only_when_nothing_in_it_holds_it(language, ext, src, expected):
+ from repowise.core.analysis.health.dataflow.loop_cut import escapes as _escapes
+
+ wrapped = (
+ f"def f(rows, r, k, items):\n while True:\n{textwrap.indent(src, ' ' * 8)}\n"
+ if language == "python"
+ else f"function f(rows, r, k, items) {{ while (true) {{ {src} }} }}"
+ )
+ fn = _functions(wrapped, language, ext)[0]
+ lmap = get_language_map(language)
+ loop = next(c for c in fn.fn_node.child_by_field_name("body").named_children if c.type in lmap.loop_kinds)
+ body = loop.child_by_field_name("body")
+ first = next(c for c in body.named_children if "comment" not in c.type)
+ assert _escapes(first, lmap) is expected
+
+
+def test_a_statement_reading_its_own_target_on_a_later_line_is_never_staged():
+ # hermes ``run_conversation``: ``messages = [\n msg for msg in messages ...]``
+ # orders its write before its reads by line, so the stage lost ``messages``.
+ src = _loop_fn(extras={2: "\n seen = [\n s for s in seen if s\n ]"})
+ lines = textwrap.dedent(src).splitlines()
+ rebind = next(i for i, ln in enumerate(lines, 1) if ln.strip() == "seen = [")
+ spans = _spans(_plans(src)["run"])
+ assert not any(s <= rebind <= e for s, e in spans)
+
+
+def test_an_import_with_a_fallback_binds_on_every_path():
+ # hermes ``load_gateway_config``: ``try: from m import r as _pr`` /
+ # ``except: _pr = None`` binds ``_pr``; the stage needs no older value.
+ fallback = """
+ try:
+ from reg import registry as hooks
+ except ImportError:
+ hooks = None
+"""
+ body = "".join(_item_section(n) + (fallback if n == 7 else "") for n in range(8))
+ src = f"""
+def run(items, a, b, last, {", ".join(f"opt_{n}" for n in range(8))}):
+ seen = []
+ hooks = None
+ for item in items:
+{textwrap.indent(textwrap.dedent(body), " " * 8)}
+ return seen, hooks
+"""
+ stages = _plans(src)["run"].plan["stages"]
+ writer = next(s for s in stages if "hooks" in s["returns"])
+ assert "hooks" not in writer["params"]
+
+
+def test_an_input_only_another_stage_writes_refuses_the_plan():
+ from repowise.core.analysis.health.dataflow.stages import _inputs_held
+
+ one = Extraction(10, 20, ("a",), (), 5, 3)
+ two = Extraction(30, 40, ("x",), (), 5, 3)
+ assert not _inputs_held((one, two), {"a": [1], "x": [15]})
+ assert _inputs_held((one, two), {"a": [1], "x": [15, 25]})
+ assert _inputs_held((replace(one, returns=("x",)), two), {"a": [1], "x": [15]})
+ # Only a later stage hands ``p`` back: unbound at the first stage's call.
+ three = Extraction(50, 60, (), ("p",), 5, 3)
+ first = Extraction(10, 20, ("p",), (), 5, 3)
+ assert not _inputs_held((first, two, three), {"p": [55], "x": [1]})
+ # Written before the stages too (a loop-carried value): held.
+ assert _inputs_held((first, two, three), {"p": [2, 55], "x": [1]})
+
+
+def _stage_writing(stages, lines, text):
+ line = next(i for i, ln in enumerate(lines, 1) if ln.strip() == text)
+ return next(s for s in stages if s["span"]["start"] <= line <= s["span"]["end"])
+
+
+def test_a_counter_only_its_own_stage_reads_comes_back_out():
+ # ``count`` is read and bumped by one stage and never after the loop: the
+ # next iteration's call must still see the bumped value.
+ src = _loop_fn(extras={3: "\n count += 1"}, tail="seen.sort()")
+ src = src.replace(" last = None\n", " last = None\n count = 0\n")
+ stages = _plans(src)["run"].plan["stages"]
+ writer = _stage_writing(stages, textwrap.dedent(src).splitlines(), "count += 1")
+ assert "count" in writer["returns"] and "count" in writer["params"]
+
+
+def test_a_value_the_while_header_reads_comes_back_out():
+ body = "".join(_item_section(n) for n in range(8))
+ src = f"""
+def run(items, a, b, last, {", ".join(f"opt_{n}" for n in range(8))}):
+ seen = []
+ pos = 0
+ while pos < len(items):
+ item = items[pos]
+{textwrap.indent(textwrap.dedent(body), " " * 8)}
+ if item.skip and item.far:
+ pos += 2
+ elif item.step or a:
+ pos += 1
+ else:
+ pos = len(items)
+ return seen
+"""
+ stages = _plans(src)["run"].plan["stages"]
+ writer = _stage_writing(stages, textwrap.dedent(src).splitlines(), "pos += 2")
+ assert "pos" in writer["returns"]
+
+
+def test_an_async_loop_body_gets_awaited_stages():
+ src = _loop_fn().replace("def run(", "async def run(").replace("for item in items:", "async for item in items:")
+ src = src.replace("handle_", "await handle_")
+ stages = _plans(src)["run"].plan["stages"]
+ assert len(stages) >= 2
+ assert all(s["new_symbol"]["async"] and "await " in s["call_site"]["new_text"] for s in stages)
+
+
+def test_an_import_whose_handler_only_passes_is_not_bound_by_it():
+ fallback = """
+ try:
+ from reg import registry as hooks
+ hooks = wrap(hooks)
+ except ImportError:
+ pass
+"""
+ body = "".join(_item_section(n) + (fallback if n == 7 else "") for n in range(8))
+ src = f"""
+def run(items, a, b, last, {", ".join(f"opt_{n}" for n in range(8))}):
+ seen = []
+ hooks = None
+ for item in items:
+{textwrap.indent(textwrap.dedent(body), " " * 8)}
+ return seen, hooks
+"""
+ stages = _plans(src)["run"].plan["stages"]
+ writer = next(s for s in stages if "hooks" in s["returns"])
+ assert "hooks" in writer["params"]
+
+
+def _ts_section(n: int) -> str:
+ return f"""
+ // Handle {_WORDS[n]}
+ if (item.kind === "k{n}" && item.ready) {{
+ handle{n}(item, a, seen, opt{n});
+ }} else if (item.other{n} || b) {{
+ skip{n}(item);
+ }}
+"""
+
+
[email protected]("shape", ["labelled", "do_while"])
+def test_typescript_loop_bodies_are_cut(shape):
+ body = textwrap.indent(textwrap.dedent("".join(_ts_section(n) for n in range(8))), " ")
+ opts = ", ".join(f"opt{n}" for n in range(8))
+ if shape == "labelled":
+ loop = f" outer: for (const item of items) {{\n{body}\n }}\n"
+ else:
+ loop = (
+ f" let item = items[0];\n do {{\n{body}\n"
+ " if (item.next && item.ok) { item = item.next; } else if (item.done || a) { item = null; }\n"
+ " } while (item);\n"
+ )
+ src = f"function run(items, a, b, seen, {opts}) {{\n{loop} return seen;\n}}\n"
+ plan = _plans(src, "typescript", "ts")["run"]
+ if shape == "labelled":
+ # The flow graph keeps a labelled statement whole, so nothing in it
+ # is known to be bound: no stage is cut there.
+ assert "stages" not in plan.plan
+ return
+ assert len(plan.plan["stages"]) >= 2
+ if shape == "do_while":
+ writer = _stage_writing(plan.plan["stages"], src.splitlines(), "if (item.next && item.ok) { item = item.next; } else if (item.done || a) { item = null; }")
+ assert writer["returns"] == ["item"]
diff --git a/tests/unit/health/test_plan_annotations.py b/tests/unit/health/test_plan_annotations.py
index 4ff0f8ae3..22966bc6a 100644
--- a/tests/unit/health/test_plan_annotations.py
+++ b/tests/unit/health/test_plan_annotations.py
@@ -217,3 +217,33 @@ def test_composition_not_told_about_decisions_leaves_governance_unknown() -> Non
step = live.steps[0].applicability
assert "governed_by_decision" in step.unknowns
assert "governed_by_decision" not in step.reasons
+
+
+def test_a_test_reading_the_split_function_source_is_a_risk(tmp_path: Path) -> None:
+ from repowise.core.analysis.health.refactoring.annotations import _sources_read
+
+ # ours ``test_full_upgrade_progress.py`` asserts on ``inspect.getsource(_run_upgrade)``.
+ (tmp_path / "tests").mkdir()
+ (tmp_path / "tests" / "test_flow.py").write_text(
+ "import inspect\nimport svc.orders as so\nsrc = inspect.getsource(so.handle)\n"
+ "lines = inspect.getsourcelines(other.handle)\n",
+ encoding="utf-8",
+ )
+ (tmp_path / "tests" / "test_plain.py").write_text(
+ "def test_x():\n assert handle()\n", encoding="utf-8"
+ )
+ files = ["tests/test_flow.py", "tests/test_plain.py", "tests/missing.py", "../outside.py"]
+ (tmp_path.parent / "outside.py").write_text("inspect.getsource(handle)\n", encoding="utf-8")
+ read = _sources_read(tmp_path, files)
+ # The alias reads as the module it names; a file outside the root is not read.
+ assert read == {"tests/test_flow.py": frozenset({"orders.handle", "other.handle"})}
+ facts = AnnotationFacts(sources_read=read)
+ notes = annotate(plan(), facts, ["tests/test_flow.py::test_a", "tests/test_plain.py::test_x"])
+ assert kinds(notes) == ["source_text"]
+ assert notes.risks[0].ref == "tests/test_flow.py"
+ assert "may read the source text of `handle`" in notes.risks[0].text
+ # Another module's ``handle``, a test the plan does not run, a plan that keeps the body.
+ other = AnnotationFacts(sources_read={"tests/test_flow.py": frozenset({"other.handle"})})
+ assert annotate(plan(), other, ["tests/test_flow.py::test_a"]).risks == ()
+ assert annotate(plan(), facts, ["tests/test_plain.py::test_x"]).risks == ()
+ assert annotate(plan("split_file"), facts, ["tests/test_flow.py::test_a"]).risks == ()