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(health): stop defer_in_loop and list_insert_zero_in_loop firing when a later statement ends the loop (#4768)

Raghav Chamadiya770e3a327783
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
index 4771e8d10..2ea26daa5 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
@@ -74,7 +74,7 @@ import re
from typing import TYPE_CHECKING, ClassVar
if TYPE_CHECKING:
- from collections.abc import Iterator
+ from collections.abc import Callable, Iterator
from tree_sitter import Node
@@ -545,6 +545,22 @@ class BasePerfDialect:
if cur.type not in prune or cur == node:
stack.extend(cur.children)
+ @classmethod
+ def _exit_follows(
+ cls, stmt: Node, is_exit: Callable[[Node], bool], jumps: frozenset[str]
+ ) -> bool:
+ """A later statement in *stmt*'s block ends the loop (*is_exit*), and no
+ statement before it holds a jump (*jumps*, e.g. ``continue``) that could
+ loop back first. Then *stmt* runs at most once per loop entry."""
+ nxt = stmt.next_named_sibling
+ while nxt is not None:
+ if is_exit(nxt):
+ return True
+ if any(n.type in jumps for n in cls._walk(nxt)):
+ return False
+ nxt = nxt.next_named_sibling
+ return False
+
@staticmethod
def _grows(magnitude: LoopMagnitude | None) -> LoopMagnitude | None:
"""A projection of a growing source grows; nothing else carries through it."""
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
index 32211dc93..f77fde465 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
@@ -476,48 +476,33 @@ class GoPerfDialect(IterableSources):
)
def _defer_runs_once_per_entry(self, defer_node: Node) -> bool:
- """True when the statement right after the defer leaves every loop.
-
- A ``defer`` immediately followed by a ``return``, or by a ``break``
- that exits the loop, can only be reached once before control leaves
- the loop, so the deferred call is registered at most once and the
- ``defer_in_loop`` leak does not apply. A ``break`` inside a
- ``switch``/``select`` case leaves the case (loop keeps running), a
- labeled ``break`` only counts when the label names a statement at or
- outside the loop, and in a loop nest the exit must leave the OUTERMOST
- loop — otherwise each outer iteration re-enters and registers the
- defer again.
+ """True when a later statement in the defer's block leaves every loop.
+
+ A ``defer`` followed in its own block by a ``return``, or by a
+ ``break`` that exits the loop, with no ``continue``/``goto`` in
+ between, can only be reached once before control leaves the loop, so
+ the deferred call is registered at most once and the ``defer_in_loop``
+ leak does not apply. A ``break`` inside a ``switch``/``select`` case
+ leaves the case (loop keeps running), a labeled ``break`` only counts
+ when the label names a statement at or outside the loop, and in a loop
+ nest the exit must leave the OUTERMOST loop — otherwise each outer
+ iteration re-enters and registers the defer again. Ceiling: a ``goto``
+ never counts as an exit.
"""
- nxt = self._next_statement(defer_node)
- if nxt is None:
- return False
- if nxt.type == "return_statement":
+ return self._exit_follows(
+ defer_node, self._leaves_all_loops, frozenset({"continue_statement", "goto_statement"})
+ )
+
+ def _leaves_all_loops(self, stmt: Node) -> bool:
+ if stmt.type == "return_statement":
# ``return`` exits the whole function — unless a func literal or
# method sits between the loop and this statement, in which case it
# only exits that inner scope and the loop continues.
- return self._scope_below_loop(defer_node) is None
- if nxt.type == "break_statement":
- return self._break_exits_all_loops(nxt)
+ return self._scope_below_loop(stmt) is None
+ if stmt.type == "break_statement":
+ return self._break_exits_all_loops(stmt)
return False
- @staticmethod
- def _next_statement(node: Node) -> Node | None:
- """The first sibling statement after ``node`` in the same block."""
- parent = node.parent
- if parent is None:
- return None
- seen = False
- for child in parent.children:
- if not seen:
- if child == node:
- seen = True
- continue
- # Skip trailing comments and punctuation (the ``;`` separator of
- # single-line bodies is an unnamed child of the statement list).
- if child.is_named and child.type != "comment":
- return child
- return None
-
def _scope_below_loop(self, node: Node) -> Node | None:
"""The nearest func-like scope between ``node`` and its loop, if any."""
cur = node.parent
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
index 7f4ee59b5..fcefa3902 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
@@ -443,14 +443,9 @@ class PythonPerfDialect(
if method in _PY_LOCK_METHODS and self.callee_is_attribute(node):
return "lock_in_loop"
# ``lst.insert(0, x)`` shifts the whole list each pass: a literal ``0``, on a
- # list not re-created per iteration and not a ``deque`` (O(1) at the front).
- if (
- method == "insert"
- and self.callee_is_attribute(node)
- and self._first_arg_is_zero(node)
- and not self._receiver_reset_in_loop(node, root)
- and not self._receiver_bound_to_deque(node, root)
- ):
+ # list not re-created per iteration, not a ``deque`` (O(1) at the front) and
+ # not followed by an exit that ends the loop.
+ if method == "insert" and self._front_insert_repeats(node, root):
return "list_insert_zero_in_loop"
# ``pd.concat([acc, chunk])`` / ``pandas.concat(...)`` in a loop copies
# the whole frame each pass -> O(n^2); collect a list and concat once.
@@ -495,6 +490,46 @@ class PythonPerfDialect(
stack.extend(n.children)
return False
+ def _front_insert_repeats(self, node: Node, root: str) -> bool:
+ if not (self.callee_is_attribute(node) and self._first_arg_is_zero(node)):
+ return False
+ return not (
+ self._receiver_reset_in_loop(node, root)
+ or self._receiver_bound_to_deque(node, root)
+ or self._loop_ends_after(node)
+ )
+
+ def _loop_ends_after(self, node: Node) -> bool:
+ """A ``return``/``raise`` (or, with one loop around *node*, a ``break``)
+ follows *node*'s statement in its block, so it runs once per call.
+ Ceiling: a flag-driven exit (``stop = True`` then ``if stop: break``) is
+ still reported."""
+ stmt = node
+ while stmt.parent is not None and stmt.parent.type != "block":
+ if stmt.type in self.scope_kinds: # a lambda body runs elsewhere
+ return False
+ stmt = stmt.parent
+ loops, in_try = self._enclosing_loops(stmt)
+ if not loops:
+ return False
+ # A ``raise`` inside a ``try`` may be caught and the loop go on, and a
+ # ``break`` in a loop nest leaves only the inner loop.
+ exits = {"return_statement"} if in_try else {"return_statement", "raise_statement"}
+ if loops == 1:
+ exits.add("break_statement")
+ return self._exit_follows(
+ stmt, lambda s: s.type in exits, frozenset({"continue_statement"})
+ )
+
+ def _enclosing_loops(self, stmt: Node) -> tuple[int, bool]:
+ """Loops around *stmt* in its scope, and whether a ``try`` sits among them."""
+ loops, in_try, cur = 0, False, stmt.parent
+ while cur is not None and cur.type not in self.scope_kinds:
+ loops += cur.type in ("for_statement", "while_statement")
+ in_try = in_try or cur.type == "try_statement"
+ cur = cur.parent
+ return loops, in_try
+
def _receiver_reset_in_loop(self, node: Node, name: str) -> bool:
"""True if the call's receiver ``name`` is re-assigned (reset to a fresh
list) inside an enclosing loop body — so the per-front-insert is bounded
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index 8e504e28a..37da7ddb3 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -759,6 +759,39 @@ def test_python_list_insert_zero_vs_variable_index():
assert not any(k == "list_insert_zero_in_loop" for k, _ in _hits("python", reset))
+_INSERT_ZERO = "def f(xs, out, ok):\n for x in xs:\n{body}"
+
+
+ "body,fires",
+ [
+ (" out.insert(0, x)\n return\n", False),
+ (" if ok:\n out.insert(0, x)\n return\n", False),
+ (" out.insert(0, x)\n log(x)\n break\n", False),
+ (" out.insert(0, x)\n raise ValueError(x)\n", False),
+ # A conditional exit, or a ``continue`` that can skip the exit, still repeats.
+ (" out.insert(0, x)\n if ok:\n break\n", True),
+ (" out.insert(0, x)\n if ok:\n continue\n break\n", True),
+ # The exit comes before the insert, not after it.
+ (" if ok:\n break\n out.insert(0, x)\n", True),
+ # ``break`` leaves only the inner loop of a nest.
+ (" for y in x:\n out.insert(0, y)\n break\n", True),
+ (" for y in x:\n out.insert(0, y)\n return\n", False),
+ # A ``raise`` an ``except`` in the same iteration can catch.
+ (
+ " try:\n out.insert(0, x)\n raise ValueError\n"
+ " except ValueError:\n pass\n",
+ True,
+ ),
+ # A flag-driven exit is not followed (click's ``stop = True``).
+ (" out.insert(0, x)\n stop = True\n if stop:\n break\n", True),
+ ],
+)
+def test_python_list_insert_zero_before_loop_exit(body, fires):
+ kinds = [k for k, _ in _hits("python", _INSERT_ZERO.format(body=body))]
+ assert ("list_insert_zero_in_loop" in kinds) is fires
+
+
def test_ts_json_parse_only_deep_clone_idiom():
"""Bare ``JSON.parse(x.payload)`` of a distinct per-iteration payload is
necessary work (Phase-7d: bare parse/stringify was 0% precision)."""
diff --git a/tests/unit/health/test_perf_go_defer_exit.py b/tests/unit/health/test_perf_go_defer_exit.py
index 47f2aacd6..ae1aab922 100644
--- a/tests/unit/health/test_perf_go_defer_exit.py
+++ b/tests/unit/health/test_perf_go_defer_exit.py
@@ -1,6 +1,7 @@
"""``defer_in_loop`` exit shapes for the Go perf dialect (#2938).
-A ``defer`` whose next statement in the same block leaves the loop — a
+A ``defer`` followed in its block, with no ``continue`` or ``goto`` between,
+by a statement that leaves the loop — a
``return``, or a ``break`` that exits the ``for`` (not a ``switch``/``select``
case, and not merely an inner loop of a nest) — can only be reached once, so
the deferred call is registered at most once and the leak anti-pattern does
@@ -25,7 +26,7 @@ def _hits(src: str):
# ---------------------------------------------------------------------------
-# The defer runs once: the next statement leaves the loop (or the function)
+# The defer runs once: a later statement leaves the loop (or the function)
# ---------------------------------------------------------------------------
_EXIT_CASES = [
@@ -101,6 +102,27 @@ _EXIT_CASES = [
"} } }",
"return inside a select case exits the function",
),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); h(); break } }",
+ "a call between the defer and the break",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); defer h(); break } }",
+ "both defers before the break are covered",
+ ),
+ (
+ "package m\nfunc f(xs []int) error { for _, x := range xs { defer g(); h(x); return nil } }",
+ "defer, use, then return",
+ ),
+ (
+ "package m\nfunc f(xs []int, ok bool){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tif ok {\n"
+ "\t\th()\n"
+ "\t}\n"
+ "\tbreak\n} }",
+ "caddy shape: defer, an if without a jump, then break",
+ ),
]
@@ -110,7 +132,7 @@ def test_defer_exit_suppresses_finding(src, note):
# ---------------------------------------------------------------------------
-# The defer repeats: the next statement does not leave the loop
+# The defer repeats: no later statement in its block leaves the loop
# ---------------------------------------------------------------------------
_REPEAT_CASES = [
@@ -122,10 +144,6 @@ _REPEAT_CASES = [
"package m\nfunc f(xs []int){ for _, x := range xs { h(); defer g() } }",
"defer as the last statement of the body",
),
- (
- "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); h(); break } }",
- "a call between the defer and the break means it is not the next statement",
- ),
(
"package m\nfunc f(xs []int){ for _, x := range xs { defer g(); continue } }",
"defer then continue",
@@ -209,10 +227,6 @@ _REPEAT_CASES = [
"package m\nfunc f(xs []int){ for _, x := range xs { break; defer g() } }",
"break BEFORE the defer does not cover it",
),
- (
- "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); defer h(); break } }",
- "only the last defer is covered by the break",
- ),
(
"package m\nfunc f(xs []int){ for _, x := range xs { defer g(); break missing } }",
"a break with an undefined label stays conservative",
@@ -243,6 +257,24 @@ _REPEAT_CASES = [
"} } }",
"plain defer inside a switch case",
),
+ (
+ "package m\nfunc f(xs []int, ok bool){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tif ok {\n"
+ "\t\tcontinue\n"
+ "\t}\n"
+ "\tbreak\n} }",
+ "a conditional continue before the break skips it",
+ ),
+ (
+ "package m\nfunc f(xs []int, ok bool){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tif ok {\n"
+ "\t\tbreak\n"
+ "\t}\n"
+ "\th()\n} }",
+ "a conditional break does not end every iteration",
+ ),
]