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): keep a C# using declaration with the code it guards (#3463)

Yunus Ozen8a4e2d7ae93a
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 49bac5d91..248202c49 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -270,6 +270,15 @@ class LanguageNodeMap:
await_scope_kinds: frozenset[str] = frozenset()
exit_macro_kinds: frozenset[str] = frozenset()
exit_macro_names: frozenset[str] = frozenset()
+ # * ``scoped_resource_decl_kinds`` / ``scoped_resource_decl_tokens`` --
+ # a declaration whose resource the enclosing block disposes at its end
+ # (C# ``using var``: a ``local_declaration_statement`` carrying a
+ # ``using`` token). A helper holding one disposes it when the helper
+ # returns, so the slicer refuses a span that holds one unless the span
+ # runs to the end of the block. Block-scoped forms (``using (...) { }``,
+ # ``with``, try-with-resources) need no entry: a span holds them whole.
+ scoped_resource_decl_kinds: frozenset[str] = frozenset()
+ scoped_resource_decl_tokens: 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
@@ -974,6 +983,8 @@ _CSHARP = LanguageNodeMap(
raise_kinds=frozenset({"throw_statement"}),
break_kinds=frozenset({"break_statement"}),
continue_kinds=frozenset({"continue_statement"}),
+ scoped_resource_decl_kinds=frozenset({"local_declaration_statement"}),
+ scoped_resource_decl_tokens=frozenset({"using"}),
)
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 4861e49c8..8ebc884f2 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -216,6 +216,7 @@ def find_extractions(
for block, loop in all_blocks(fn_node, lmap.block_kinds, scope_kinds, lmap.loop_kinds):
stmts = block.named_children
n = len(stmts)
+ resources = _scoped_resource_indexes(stmts, lmap)
is_body = block.id == body_container.id
keeps_tail = tail_stmt_kinds is not None and _tail_is_block_value(
stmts, tail_stmt_kinds, fn_node, lmap
@@ -264,6 +265,8 @@ def find_extractions(
s, e, returns, decl_lines, def_lines, use_lines, declared_first, outer
):
continue
+ if _disposes_early(resources, i, j, pre.code):
+ continue
if pre.nested[j + 1] > pre.nested[i]:
continue
if shared is not None and _closure_state_crosses(shared, span, s, e, block, lmap):
@@ -294,6 +297,27 @@ def find_extractions(
return _sorted(out)
+def _scoped_resource_indexes(stmts: list[Node], lmap: LanguageNodeMap) -> list[int]:
+ """Positions in *stmts* of declarations whose resource the block disposes
+ at its end (``scoped_resource_decl_kinds``)."""
+ if not lmap.scoped_resource_decl_kinds:
+ return []
+ return [
+ k
+ for k, st in enumerate(stmts)
+ if st.type in lmap.scoped_resource_decl_kinds
+ and any(not c.is_named and c.type in lmap.scoped_resource_decl_tokens for c in st.children)
+ ]
+
+
+def _disposes_early(resources: list[int], i: int, j: int, code: list[int]) -> bool:
+ """Whether statements ``i..j`` hold a declaration from *resources* while code
+ after them still runs in the block (*code* is the block's code-line prefix
+ sum). A helper would dispose the resource when it returns, before that code
+ runs, where the original disposes it at the end of the block."""
+ return code[-1] > code[j + 1] and any(i <= k <= j for k in resources)
+
+
@dataclass(frozen=True)
class FunctionFacts:
"""What a whole function does, counted on the complexity walk's visits.
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 683df5969..4d64a6608 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/stages.py
@@ -68,6 +68,7 @@ from .slice import (
_declaration_escapes,
_declaration_lines,
_declared_before_read,
+ _disposes_early,
_function_lines,
_hoisted_bindings,
_identifiers,
@@ -77,6 +78,7 @@ from .slice import (
_reads_observing,
_receiver_facts,
_scan_for,
+ _scoped_resource_indexes,
_stmt_assigns,
_unwrap_container,
_valueless_lines,
@@ -378,6 +380,7 @@ class _Cutter:
# 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.resources = _scoped_resource_indexes(code, lmap)
self.carried = carried(facts.analysis, loops, facts.def_lines) if loops else frozenset()
def _sum(self, series: list[int], i: int, j: int) -> int:
@@ -484,6 +487,8 @@ class _Cutter:
return False
if any(self.escapes[i : j + 1]):
return False
+ if _disposes_early(self.resources, i, j, pre.code):
+ return False
return not any((i <= a <= j) != (i <= b <= j) for a, b in self.timer_pairs)
def _own_bindings_dropped(
diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.py
index f7c8d5490..7469b4984 100644
--- a/tests/unit/health/test_dataflow_langs.py
+++ b/tests/unit/health/test_dataflow_langs.py
@@ -1480,6 +1480,112 @@ def test_csharp_extract_method_fires():
assert best.slice_nloc >= 6
+# A ``using var`` is disposed at the end of the block that declares it, so a
+# helper holding it would dispose it when the helper returns (#3452).
+_CSHARP_USING_DECLARATION = """
+class Demo {
+ int Process(string path, int[] records, int threshold) {
+ %s var stream = System.IO.File.OpenRead(path);
+ int total = 0;
+ int count = 0;
+ foreach (int v in records) {
+ if (v > threshold) {
+ total += v + (int)stream.Position;
+ count++;
+ } else {
+ total -= v;
+ }
+ }
+ if (count > 0) {
+ total = total / count;
+ }
+ if (total > 100) {
+ total = 100;
+ }
+ System.IO.File.Delete(path);
+ return total;
+ }
+}
+"""
+
+
[email protected]("keyword", ["using", "await using"])
+def test_csharp_span_never_ends_a_using_declaration_early(keyword):
+ _require("csharp")
+ src = _CSHARP_USING_DECLARATION % keyword
+ using_line = next(n for n, ln in enumerate(src.splitlines(), 1) if "var stream" in ln)
+ extractions = find_extractions(_first("csharp", src), get_language_map("csharp"))
+ assert not [
+ (e.start_line, e.end_line) for e in extractions if e.start_line <= using_line <= e.end_line
+ ]
+ # A span after the declaration takes the resource as a parameter.
+ assert any(e.start_line == using_line + 1 and "stream" in e.params for e in extractions)
+
+
+def test_csharp_span_inside_a_using_block_is_still_offered():
+ _require("csharp")
+ src = """
+class Demo {
+ int Process(string path, int[] records, int threshold) {
+ using (var stream = System.IO.File.OpenRead(path)) {
+ int total = 0;
+ int count = 0;
+ foreach (int v in records) {
+ if (v > threshold) {
+ total += v + (int)stream.Position;
+ count++;
+ } else {
+ total -= v;
+ }
+ }
+ if (count > 0) {
+ total = total / count;
+ }
+ if (total > 100) {
+ total = 100;
+ }
+ System.IO.File.Delete(path);
+ return total;
+ }
+ }
+}
+"""
+ lines = src.splitlines()
+ block_start = next(n for n, ln in enumerate(lines, 1) if "using (" in ln)
+ block_end = next(n for n, ln in enumerate(lines, 1) if "return total;" in ln) + 1
+ extractions = find_extractions(_first("csharp", src), get_language_map("csharp"))
+ assert any(block_start < e.start_line and e.end_line < block_end for e in extractions)
+
+
+def test_csharp_stage_never_ends_a_using_declaration_early():
+ _require("csharp")
+ from repowise.core.analysis.health.dataflow.stages import find_stages
+
+ section = """
+ if (a > {n}) {{
+ total += {n};
+ }} else {{
+ total -= {n};
+ }}
+ if (total > {n}0) {{
+ total = {n};
+ }}"""
+ src = (
+ "class Demo {\n int Run(string path, int a) {\n int total = 0;\n"
+ " using var stream = System.IO.File.OpenRead(path);"
+ + "".join(section.format(n=k) for k in range(1, 7))
+ + "\n System.IO.File.Delete(path);\n return total;\n }\n}\n"
+ )
+ using_line = next(n for n, ln in enumerate(src.splitlines(), 1) if "using var" in ln)
+ plan = find_stages(_first("csharp", src), get_language_map("csharp"))
+ assert plan.stages
+ assert not [
+ (st.start_line, st.end_line)
+ for st in plan.stages
+ if st.start_line <= using_line <= st.end_line
+ ]
+
+
def test_csharp_extractions_are_deterministic():
lmap = get_language_map("csharp")
fn = _first("csharp", _CSHARP_PROCESS)