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.

fix(refactoring): never offer an Extract Method span that yields or exits through a macro (#2956)

Raghav Chamadiya3252225c9d06
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 20425b09e..d3ac54955 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -232,6 +232,18 @@ class LanguageNodeMap:
break_kinds: frozenset[str] = frozenset()
continue_kinds: frozenset[str] = frozenset()
with_kinds: frozenset[str] = frozenset()
+ # * ``yield_kinds`` -- a generator's ``yield``. Not a CFG jump (the
+ # function resumes after it), but it hands a value to the caller, so a
+ # helper lifted around it would yield into nothing: the slicer refuses
+ # a span holding one.
+ # * ``exit_macro_kinds`` / ``exit_macro_names`` -- macro invocation
+ # node(s) and the macros among them whose expansion returns from the
+ # function (Rust ``anyhow::bail!``), matched by the macro's last name
+ # segment. The slicer treats them as jumps for the same reason. A user
+ # macro of the same name that does not exit only hides a span.
+ yield_kinds: frozenset[str] = frozenset()
+ exit_macro_kinds: frozenset[str] = frozenset()
+ exit_macro_names: frozenset[str] = frozenset()
# * ``statement_wrapper_kinds`` -- statement node(s) that merely wrap the
# node the CFG builder should classify, as their last named child.
# Expression-oriented grammars need this: tree-sitter-rust parses every
@@ -340,6 +352,7 @@ _PY = LanguageNodeMap(
break_kinds=frozenset({"break_statement"}),
continue_kinds=frozenset({"continue_statement"}),
with_kinds=frozenset({"with_statement"}),
+ yield_kinds=frozenset({"yield"}),
decorator_kinds=frozenset({"decorator"}),
decorated_definition_kinds=frozenset({"decorated_definition"}),
)
@@ -397,6 +410,7 @@ _TS = LanguageNodeMap(
raise_kinds=frozenset({"throw_statement"}),
break_kinds=frozenset({"break_statement"}),
continue_kinds=frozenset({"continue_statement"}),
+ yield_kinds=frozenset({"yield_expression"}),
)
_JS = _TS # identical control-flow nodes; tree-sitter-javascript shares shape.
@@ -563,6 +577,8 @@ _RUST = LanguageNodeMap(
# early exit the CFG treats as a terminator and the Extract Method slicer
# treats as a jump, so no span containing one is ever offered.
raise_kinds=frozenset({"try_expression"}),
+ exit_macro_kinds=frozenset({"macro_invocation"}),
+ exit_macro_names=frozenset({"bail", "ensure", "try"}),
break_kinds=frozenset({"break_expression"}),
continue_kinds=frozenset({"continue_expression"}),
# Rust parses every statement-position control-flow expression inside an
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 eb25045e3..8ebf80397 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -118,7 +118,13 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
| lmap.catch_kinds
| lmap.boolean_operator_kinds
)
- jump_kinds = lmap.return_kinds | lmap.raise_kinds | lmap.break_kinds | lmap.continue_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
# Expression-oriented grammars (nonempty ``statement_wrapper_kinds``): a
# block's last child that is not a statement is its tail expression -- the
@@ -150,7 +156,9 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
nested_prefix = [0]
code_prefix = [0]
for st in stmts:
- d, jmp = _span_metrics([st], decision_kinds, jump_kinds, scope_kinds)
+ d, jmp = _span_metrics(
+ [st], decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap)
+ )
dec_prefix.append(dec_prefix[-1] + d)
jump_prefix.append(jump_prefix[-1] + (1 if jmp else 0))
nested_prefix.append(
@@ -704,14 +712,37 @@ def _all_blocks(
return blocks
+def _exit_macros(lmap: LanguageNodeMap) -> tuple[frozenset[str], frozenset[str]]:
+ """The macro node kinds and the macro names that exit the function."""
+ return lmap.exit_macro_kinds, lmap.exit_macro_names
+
+
+def _is_jump(
+ node: Node,
+ jump_kinds: frozenset[str],
+ exit_macros: tuple[frozenset[str], frozenset[str]],
+) -> bool:
+ """True for a jump node, or a macro whose name is in *exit_macros*
+ (matched by its last segment: ``bail`` in ``anyhow::bail!``)."""
+ if node.type in jump_kinds:
+ return True
+ kinds, names = exit_macros
+ if node.type not in kinds:
+ return False
+ macro = node.child_by_field_name("macro")
+ name = macro.child_by_field_name("name") or macro if macro is not None else None
+ 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]] = (frozenset(), frozenset()),
) -> tuple[int, bool]:
"""Decision-point count and jump presence within *span* (nested scopes are
- not descended into)."""
+ not descended into). A macro named in *exit_macros* counts as a jump."""
decisions = 0
has_jump = False
for root in span:
@@ -719,8 +750,7 @@ def _span_metrics(
while stack:
node = stack.pop()
t = node.type
- if t in jump_kinds:
- has_jump = True
+ has_jump = has_jump or _is_jump(node, jump_kinds, exit_macros)
if t in decision_kinds:
decisions += 1
for child in node.children:
diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.py
index 284013267..febf37cb8 100644
--- a/tests/unit/health/test_dataflow_langs.py
+++ b/tests/unit/health/test_dataflow_langs.py
@@ -1816,3 +1816,67 @@ def test_a_closure_local_shadowing_an_outer_name_is_not_a_capture():
"""
fn = _first("typescript", src)
assert "t2" not in {u.name for u in fn.def_use.captured}
+
+
+# == Spans a helper cannot carry =================================================
+
+
+def test_python_span_holding_a_yield_is_not_offered():
+ src = """
+ def rows(items, limit):
+ seen = 0
+ for item in items:
+ if item > limit:
+ seen += 1
+ yield item
+ else:
+ seen -= 1
+ print(seen)
+ print(limit)
+ return seen
+ """
+ lmap = get_language_map("python")
+ fn = _first("python", src)
+ assert all(not (e.start_line <= 7 <= e.end_line) for e in find_extractions(fn, lmap))
+
+
+def test_ts_span_holding_a_yield_is_not_offered():
+ src = """
+ function* chunks(items: string[], limit: number) {
+ let seen = 0
+ for (const item of items) {
+ if (item.length > limit) {
+ seen += 1
+ yield item
+ } else {
+ seen -= 1
+ }
+ }
+ log(seen)
+ log(limit)
+ return seen
+ }
+ """
+ lmap = get_language_map("typescript")
+ fn = _first("typescript", src)
+ assert all(not (e.start_line <= 7 <= e.end_line) for e in find_extractions(fn, lmap))
+
+
+def test_rust_span_holding_an_exit_macro_is_not_offered():
+ src = """
+ fn paths(low: &mut Low, state: &State) -> anyhow::Result<Vec<String>> {
+ let mut paths = Vec::new();
+ for arg in low.positional.drain(..) {
+ if state.stdin_consumed && arg == "-" {
+ anyhow::bail!("cannot read stdin twice");
+ }
+ paths.push(arg);
+ }
+ log::debug!("{}", paths.len());
+ log::debug!("{}", state.stdin_consumed);
+ Ok(paths)
+ }
+ """
+ lmap = get_language_map("rust")
+ fn = _first("rust", src)
+ assert all(not (e.start_line <= 6 <= e.end_line) for e in find_extractions(fn, lmap))
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 33de182eb..d2f7b623e 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -160,6 +160,7 @@ def _find_extractions_reference(analysis, lmap):
Extraction,
_all_blocks,
_declared_before_read,
+ _exit_macros,
_function_lines,
_infer_in_out,
_loop_carry_free,
@@ -189,7 +190,13 @@ def _find_extractions_reference(analysis, lmap):
| lmap.catch_kinds
| lmap.boolean_operator_kinds
)
- jump_kinds = lmap.return_kinds | lmap.raise_kinds | lmap.break_kinds | lmap.continue_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
tail_stmt_kinds = (
lmap.statement_wrapper_kinds | lmap.local_decl_kinds
@@ -220,7 +227,9 @@ def _find_extractions_reference(analysis, lmap):
):
continue
span = stmts[i : j + 1]
- decisions, has_jump = _span_metrics(span, decision_kinds, jump_kinds, scope_kinds)
+ decisions, has_jump = _span_metrics(
+ span, decision_kinds, jump_kinds, scope_kinds, _exit_macros(lmap)
+ )
if has_jump or decisions < _MIN_CCN_REMOVED:
continue
slice_nloc = _stmts_nloc(span, lines)