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): suppress defer_in_loop when the next statement exits the loop (#2942)

Pushpak7313fffeb684d90
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 90490dd82..b78bcd3d6 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
@@ -280,6 +280,8 @@ class GoPerfDialect(BasePerfDialect):
def loop_stmt_marker(self, node: Node, list_names: frozenset[str]) -> str | None:
if node.type == "defer_statement":
+ if self._defer_runs_once_per_entry(node):
+ return None
return "defer_in_loop"
# ``go func(){…}()`` spawned per element of a ``for … range`` loop fans
# out one goroutine per item with no concurrency bound (the spawn-
@@ -296,6 +298,148 @@ class GoPerfDialect(BasePerfDialect):
return "goroutine_in_unbounded_loop"
return None
+ # Statements an unlabeled Go ``break`` can exit. ``for_statement`` is Go's
+ # only loop; an unlabeled ``break`` inside a ``switch``/``select`` case
+ # leaves the case, not the loop.
+ _GO_BREAKABLE_KINDS: frozenset[str] = frozenset(
+ {
+ "for_statement",
+ "expression_switch_statement",
+ "type_switch_statement",
+ "select_statement",
+ }
+ )
+ # Function-scoped bodies a ``return`` (or a labeled ``break`` target) is
+ # relative to; a ``func`` literal nested in a loop is its own scope.
+ _GO_FUNC_KINDS: frozenset[str] = frozenset(
+ {"function_declaration", "method_declaration", "func_literal"}
+ )
+
+ 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.
+ """
+ nxt = self._next_statement(defer_node)
+ if nxt is None:
+ return False
+ if nxt.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 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
+ while cur is not None:
+ if cur.type in self._GO_FUNC_KINDS:
+ return cur
+ if cur.type == "for_statement":
+ return None
+ cur = cur.parent
+ return None
+
+ def _break_exits_all_loops(self, brk: Node) -> bool:
+ label = self._break_label(brk)
+ if label is None:
+ # An unlabeled ``break`` leaves the innermost breakable statement.
+ # If that is a switch/select, the loop keeps running; if it is the
+ # loop, no further loop may wrap it up to the function scope, or an
+ # outer iteration re-enters and registers the defer again.
+ innermost = self._innermost_breakable(brk)
+ if innermost is None or innermost.type != "for_statement":
+ return False
+ return self._no_loop_above(innermost)
+ # ``break L`` counts only when ``L`` labels a ``for`` statement that
+ # encloses the defer, and no further loop wraps that statement up to
+ # the function scope (an outer iteration would re-enter and register
+ # the defer again).
+ target = self._labeled_statement_ancestor(brk, label)
+ if target is None:
+ # Undefined label (invalid Go): stay conservative and report.
+ return False
+ if not any(c.type == "for_statement" for c in target.children):
+ return False
+ return self._no_loop_above(target)
+
+ def _no_loop_above(self, node: Node) -> bool:
+ """True if no ``for`` loop wraps ``node`` below its function scope."""
+ cur = node.parent
+ while cur is not None:
+ if cur.type == "for_statement":
+ return False
+ if cur.type in self._GO_FUNC_KINDS:
+ return True
+ cur = cur.parent
+ return True
+
+ def _innermost_breakable(self, node: Node) -> Node | None:
+ cur = node.parent
+ while cur is not None:
+ if cur.type in self._GO_BREAKABLE_KINDS:
+ return cur
+ if cur.type in self._GO_FUNC_KINDS:
+ return None
+ cur = cur.parent
+ return None
+
+ @staticmethod
+ def _break_label(brk: Node) -> str | None:
+ lab = brk.child_by_field_name("label")
+ if lab is None:
+ # tree-sitter-go exposes ``break outer`` without a named field:
+ # the label is a bare ``label_name`` child after ``break``.
+ for child in brk.children:
+ if child.type == "label_name":
+ lab = child
+ break
+ if lab is None or lab.text is None:
+ return None
+ return lab.text.decode("utf-8", "replace")
+
+ @staticmethod
+ def _labeled_statement_ancestor(node: Node, label: str) -> Node | None:
+ cur = node.parent
+ while cur is not None:
+ if cur.type == "labeled_statement":
+ lab = cur.child_by_field_name("label")
+ if lab is not None and lab.text is not None and lab.text.decode(
+ "utf-8", "replace"
+ ) == label:
+ return cur
+ cur = cur.parent
+ return None
+
def _bounded_by_semaphore(self, go_node: Node) -> bool:
"""True if the spawn is guarded by a genuine buffered-channel semaphore.
diff --git a/tests/unit/health/test_perf_go_defer_exit.py b/tests/unit/health/test_perf_go_defer_exit.py
new file mode 100644
index 000000000..47f2aacd6
--- /dev/null
+++ b/tests/unit/health/test_perf_go_defer_exit.py
@@ -0,0 +1,319 @@
+"""``defer_in_loop`` exit shapes for the Go perf dialect (#2938).
+
+A ``defer`` whose next statement in the same block 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
+not apply. Every other shape keeps firing.
+
+The cases avoid io/regex/concat sinks so the only marker in play is
+``defer_in_loop``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+
+_REPORTED = [("defer_in_loop", "")]
+
+
+def _hits(src: str):
+ fc = walk_file("t.go", "go", src.encode())
+ return sorted((h.kind, h.detail) for h in fc.perf_hits)
+
+
+# ---------------------------------------------------------------------------
+# The defer runs once: the next statement leaves the loop (or the function)
+# ---------------------------------------------------------------------------
+
+_EXIT_CASES = [
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); break } }",
+ "range loop: defer then break",
+ ),
+ (
+ "package m\nfunc f(n int){ for i := 0; i < n; i++ { defer g(); break } }",
+ "three-clause for: defer then break",
+ ),
+ (
+ "package m\nfunc f(){ for { defer g(); break } }",
+ "bare for{}: defer then break",
+ ),
+ (
+ "package m\nfunc f(n int){ for n > 0 { defer g(); break } }",
+ "for-cond: defer then break",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { defer g(); return } }",
+ "range loop: defer then bare return",
+ ),
+ (
+ "package m\nfunc f(xs []int) error { for _, x := range xs { defer g(); return nil } }",
+ "defer then return nil",
+ ),
+ (
+ "package m\nfunc f(xs []int) (int, error) { for _, x := range xs { defer g(); return x, nil } }",
+ "defer then multi-value return",
+ ),
+ (
+ "package m\n"
+ "func f(xs []string, cached bool){\n"
+ "\tfor _, n := range xs {\n"
+ "\t\tif cached {\n"
+ "\t\t\tdefer g()\n"
+ "\t\t\tbreak\n"
+ "\t\t}\n"
+ "\t\th()\n"
+ "\t}\n}",
+ "hugo shape: defer then break inside an if in the body",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\t// the reader above is all we need\n"
+ "\tbreak\n} }",
+ "comment between the defer and the break is skipped",
+ ),
+ (
+ "package m\nfunc f(xs []int){\nouter:\n\tfor _, x := range xs {\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak outer\n"
+ "\t}\n}",
+ "labeled break naming the loop exits it",
+ ),
+ (
+ "package m\nfunc f(xs []int){\nouter:\n\tfor _, x := range xs {\n"
+ "\t\tfor j := 0; j < x; j++ {\n"
+ "\t\t\tdefer g()\n"
+ "\t\t\tbreak outer\n"
+ "\t\t}\n"
+ "\t\th()\n"
+ "\t}\n}",
+ "labeled break out of an inner loop exits every loop",
+ ),
+ (
+ "package m\nfunc f(ch chan int){ for { select {\n"
+ "\tcase <-ch:\n"
+ "\t\tdefer g()\n"
+ "\t\treturn\n"
+ "} } }",
+ "return inside a select case exits the function",
+ ),
+]
+
+
[email protected]("src,note", _EXIT_CASES, ids=[c[1] for c in _EXIT_CASES])
+def test_defer_exit_suppresses_finding(src, note):
+ assert _hits(src) == [], note
+
+
+# ---------------------------------------------------------------------------
+# The defer repeats: the next statement does not leave the loop
+# ---------------------------------------------------------------------------
+
+_REPEAT_CASES = [
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { defer g() } }",
+ "baseline: plain defer in a range loop",
+ ),
+ (
+ "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",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { switch x {\n"
+ "\tcase 1:\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak\n"
+ "\tdefault:\n"
+ "\t\th()\n} } }",
+ "unlabeled break in a switch case leaves the case, not the loop",
+ ),
+ (
+ "package m\nfunc f(ch chan int, xs []int){ for _, x := range xs {\n"
+ "\tselect {\n"
+ "\tcase <-ch:\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak\n"
+ "\tdefault:\n"
+ "\t\th()\n"
+ "\t}\n} }",
+ "unlabeled break in a select case leaves the case, not the loop",
+ ),
+ (
+ "package m\nfunc f(v any, xs []int){ for _, x := range xs { switch v.(type) {\n"
+ "\tcase int:\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak\n"
+ "\tdefault:\n"
+ "\t\th()\n} } }",
+ "unlabeled break in a type-switch case leaves the case, not the loop",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "inner:\n"
+ "\tswitch x {\n"
+ "\tcase 1:\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak inner\n"
+ "\tdefault:\n"
+ "\t\th()\n"
+ "\t}\n} }",
+ "labeled break naming the switch (inside the loop) keeps the loop running",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "blk:\n"
+ "\tif x > 1 {\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak blk\n"
+ "\t}\n"
+ "\th()\n} }",
+ "labeled break naming an if-block inside the loop keeps the loop running",
+ ),
+ (
+ "package m\nfunc f(xs [][]int){ for _, row := range xs { for _, x := range row {\n"
+ "\tdefer g()\n"
+ "\tbreak\n"
+ "} } }",
+ "unlabeled break exits only the inner loop; the outer one re-enters",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tswitch x {\n"
+ "\tcase 1:\n"
+ "\t\th()\n"
+ "\t}\n"
+ "} }",
+ "a defer before a switch that does not exit keeps firing (shape guard)",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tgoto done\n"
+ "} \ndone:\n\th()\n}",
+ "goto after the defer is out of scope for the syntactic check",
+ ),
+ (
+ "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",
+ ),
+ (
+ "package m\nfunc f(xs [][]int){ for _, row := range xs { if len(row) > 0 {\n"
+ "\tfor _, x := range row {\n"
+ "\t\tdefer g()\n"
+ "\t\tbreak\n"
+ "\t}\n"
+ "\th()\n"
+ "} } }",
+ "inner-loop break behind an if still re-enters via the outer loop",
+ ),
+ (
+ "package m\nfunc f(ch chan int){ for { select {\n"
+ "\tcase <-ch:\n"
+ "\t\tdefer g()\n"
+ "\t\th()\n"
+ "} } }",
+ "plain defer inside a select case",
+ ),
+ (
+ "package m\nfunc f(xs []int){ for _, x := range xs { switch x {\n"
+ "\tcase 1:\n"
+ "\t\tdefer g()\n"
+ "\t\th()\n"
+ "} } }",
+ "plain defer inside a switch case",
+ ),
+]
+
+
[email protected]("src,note", _REPEAT_CASES, ids=[c[1] for c in _REPEAT_CASES])
+def test_defer_repeat_keeps_finding(src, note):
+ assert _hits(src) == _REPORTED, note
+
+
+def test_two_plain_defers_report_both():
+ src = (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tdefer h()\n"
+ "} }"
+ )
+ assert _hits(src) == [("defer_in_loop", ""), ("defer_in_loop", "")]
+
+
+def test_only_the_uncovered_defer_reports():
+ """A covered defer (followed by the exit) and an uncovered one in the
+ same body: exactly one finding, for the uncovered one."""
+ src = (
+ "package m\nfunc f(xs []int){ for _, x := range xs {\n"
+ "\tdefer g()\n"
+ "\tif x > 1 {\n"
+ "\t\tdefer h()\n"
+ "\t\tbreak\n"
+ "\t}\n"
+ "\th()\n"
+ "} }"
+ )
+ assert _hits(src) == [("defer_in_loop", "")]
+
+
+# ---------------------------------------------------------------------------
+# The issue's own repro shapes, io markers included
+# ---------------------------------------------------------------------------
+
+
+def test_issue_repro_os_open_shapes():
+ """The five shapes from #2938: three stop firing, two keep firing."""
+ suppress = [
+ 'package m\nimport "os"\n'
+ "func f(n string){ for { f, _ := os.Open(n); defer f.Close(); break } }",
+ 'package m\nimport "os"\n'
+ "func f(n string, cached bool){ for {\n"
+ "\tif cached {\n"
+ "\t\tf, _ := os.Open(n)\n"
+ "\t\tdefer f.Close()\n"
+ "\t\tbreak\n"
+ "\t}\n"
+ "\tos.Stat(n)\n} }",
+ 'package m\nimport "os"\n'
+ "func f(n string){ for { f, _ := os.Open(n); defer f.Close(); return } }",
+ ]
+ for src in suppress:
+ kinds = [h.kind for h in walk_file("t.go", "go", src.encode()).perf_hits]
+ assert "defer_in_loop" not in kinds, src
+
+ repeat = [
+ 'package m\nimport "os"\n'
+ "func f(n string){ for { f, _ := os.Open(n); defer f.Close(); f.Stat() } }",
+ 'package m\nimport "os"\n'
+ "func f(n string){ for { switch n {\n"
+ '\tcase "a":\n'
+ "\t\tf, _ := os.Open(n)\n"
+ "\t\tdefer f.Close()\n"
+ "\t\tbreak\n"
+ '\tdefault:\n'
+ "\t\th()\n} } }",
+ ]
+ for src in repeat:
+ kinds = [h.kind for h in walk_file("t.go", "go", src.encode()).perf_hits]
+ assert "defer_in_loop" in kinds, src