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(dataflow): add C# def/use dataflow dialect and Extract Method support (#2893) (#2919)

Rishabh Mishradfc7a8bd5520
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 7d3031b91..93996cc87 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -297,8 +297,8 @@ This table is why a language is Full and not Good.
| Svelte · Vue | ✅ | ✅ | ✅ | no | no | ✅ | ✅ |
| Java | ✅ | ✅ | ✅ | no | no | ✅ | ✅ |
| Go | ✅ | n/a | ✅ | no | no | ✅ | ✅ |
-| Rust · C++ | ✅ | ✅ | ✅ | no | no | ✅ | ✅ |
-| C# · Scala · Ruby | ✅ | ✅ | ✅ | no | no | no | ✅ |
+| Rust · C++ · C# | ✅ | ✅ | ✅ | no | no | ✅ | ✅ |
+| Scala · Ruby | ✅ | ✅ | ✅ | no | no | no | ✅ |
| Kotlin | ✅ | ✅ | ✅ | no | no | no | ✅ |
| Dart | ✅ | n/a | ✅ | no | no | no | ✅ |
| Object Pascal | ✅ | n/a | ✅ | n/a | n/a | no | ✅ |
@@ -350,7 +350,7 @@ Mechanics behind these:
|----------|------|
| Vue · Svelte | Template binding forms (`v-for`, `{#each}`) |
| Kotlin | Extract Method, which needs a grammar that labels control flow |
-| Scala · Ruby · C# | Extract Method (dataflow dialect) |
+| Scala · Ruby | Extract Method (dataflow dialect) |
| GDScript | Health markers (complexity, performance, dataflow) |
| Object Pascal | A dedicated `uses` resolver |
| COBOL | Copybook resolution, dialect coverage, health markers |
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 de1117f44..4344c1d8b 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -908,6 +908,19 @@ _CSHARP = LanguageNodeMap(
# invocations whose callee chain begins with ``Assert``.
assert_call_kinds=frozenset({"invocation_expression"}),
call_kinds=frozenset({"invocation_expression"}),
+ # ``x = ...`` and ``x += ...`` are both an ``assignment_expression`` (the
+ # dialect tells them apart by the ``operator`` token, as in Java and Go), so
+ # the augmented set stays empty.
+ assignment_kinds=frozenset({"assignment_expression"}),
+ local_decl_kinds=frozenset(
+ {"local_declaration_statement", "using_statement", "variable_declaration"}
+ ),
+ if_kinds=frozenset({"if_statement"}),
+ block_kinds=frozenset({"block"}),
+ return_kinds=frozenset({"return_statement", "yield_statement"}),
+ raise_kinds=frozenset({"throw_statement"}),
+ break_kinds=frozenset({"break_statement"}),
+ continue_kinds=frozenset({"continue_statement"}),
)
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
index dcd161221..3824d5ad9 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
@@ -15,6 +15,7 @@ def/use pass is silent for it (no dialect = no signal), the safe default.
from __future__ import annotations
from . import cpp as _cpp
+from . import csharp as _csharp
from . import go as _go
from . import java as _java
from . import python as _python
@@ -44,6 +45,8 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (
("java", _java.DIALECT),
("rust", _rust.DIALECT),
("cpp", _cpp.DIALECT),
+ ("csharp", _csharp.DIALECT),
+ ("razor", _csharp.DIALECT),
# A C parse tree carries no C++-only node (``for_range_loop``, lambdas,
# ``co_await``), so the C++ dialect reads it whole.
("c", _cpp.DIALECT),
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/csharp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/csharp.py
new file mode 100644
index 000000000..4617f3cb4
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/csharp.py
@@ -0,0 +1,329 @@
+"""C# ``DefUseDialect``.
+
+Classifies each identifier in a statement as a write (def) or a read (use).
+C#'s write sites are: ``local_declaration_statement`` / ``variable_declaration``
+(each nested ``variable_declarator`` binds one name), plain and compound
+assignments (both an ``assignment_expression`` -- told apart by the operator
+token, ``=`` vs ``+=``, as in Java and Go), update expressions (``x++`` /
+``--x``, read-modify-write), the binder of a ``foreach`` (``foreach (int v in
+xs)`` / ``foreach (var (a, b) in pairs)``), the C-style ``for`` initializer,
+``using`` declarations and statements, ``out var`` / ``out T`` / ``out``
+arguments (writes), ``ref`` arguments (both read and write), pattern variables
+(``is string s``, ``case Foo f``) and tuple deconstruction (``(int p, int q) =
+...``). A ``catch (Exception e)`` binder stays an unmatched use, matching the
+Java and C++ dialects. Field targets (``obj.f = ...`` / ``this.f = ...``) and
+indexer targets (``arr[i] = ...``) bind no *local*, so their base identifiers
+are reads.
+
+An ``invocation_expression``'s called method name is not a variable, so the
+walk processes only its receiver and arguments. A ``switch`` statement or
+switch expression stays a single CFG statement (no per-arm blocks), so writes
+inside an arm are recorded as may-defs (both a def and a use), keeping the
+must-def proof conservative.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .base import BaseDefUseDialect, Occurrence, StatementDefUse
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from ...complexity.languages import LanguageNodeMap
+
+# Write-site / structural node kinds
+_ASSIGN_KINDS = frozenset({"assignment_expression"})
+_UPDATE_KINDS = frozenset({"prefix_unary_expression", "postfix_unary_expression"})
+_DECL_KINDS = frozenset({"local_declaration_statement", "variable_declaration", "using_statement"})
+_DECLARATOR = "variable_declarator"
+_FOREACH = "foreach_statement"
+_INVOCATION = "invocation_expression"
+_ARGUMENT = "argument"
+_DECLARATION_EXPR = "declaration_expression"
+_DECLARATION_PATTERN = "declaration_pattern"
+_IS_PATTERN = "is_pattern_expression"
+
+# Field (``obj.f``, ``this.f``) and indexer (``arr[i]``) targets bind no local.
+_MEMBER_ACCESS = "member_access_expression"
+_CONDITIONAL_ACCESS = "conditional_access_expression"
+_ELEMENT_ACCESS = "element_access_expression"
+
+# A ``switch`` is one CFG statement; writes inside its arms are may-defs.
+_CONDITIONAL_KINDS = frozenset({"switch_statement", "switch_expression"})
+
+# Nested scopes whose identifiers belong to a different function.
+_SCOPE_BOUNDARIES = frozenset(
+ {
+ "lambda_expression",
+ "anonymous_method_expression",
+ "local_function_statement",
+ "class_declaration",
+ "struct_declaration",
+ "record_declaration",
+ "interface_declaration",
+ }
+)
+
+# Callee node kinds that name a function/method, not a variable.
+_CALLEE_NAME_KINDS = frozenset({"generic_name", "qualified_name"})
+
+
+class CSharpDefUseDialect(BaseDefUseDialect):
+ language = "csharp"
+ member_access_kinds = frozenset({_MEMBER_ACCESS, _CONDITIONAL_ACCESS})
+ keyword_kinds = frozenset()
+ enclosing_binder_kinds = frozenset({"local_function_statement"})
+
+ def _is_scope_boundary(self, node: Node) -> bool:
+ return node.type in _SCOPE_BOUNDARIES
+
+ def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
+ """Collect variable reads under *node*.
+
+ Like the base collector, but an ``invocation_expression`` contributes only
+ its receiver and arguments -- never the called method name.
+ """
+ if node is None:
+ return
+ t = node.type
+ if t == _INVOCATION:
+ fn = node.child_by_field_name("function") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if fn is not None and (
+ fn.type in self.member_access_kinds or fn.type not in _CALLEE_NAME_KINDS
+ ):
+ self.collect_reads(fn, out)
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ for arg in args.named_children:
+ if arg.type == _ARGUMENT:
+ # 'out' argument writes the target rather than reading it.
+ has_out = any(c.type == "out" for c in arg.children)
+ if not has_out:
+ for c in arg.named_children:
+ self.collect_reads(c, out)
+ else:
+ self.collect_reads(arg, out)
+ return
+ if t in self.member_access_kinds:
+ receiver = node.child_by_field_name("expression") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if receiver is not None:
+ self.collect_reads(receiver, out)
+ return
+ if t in (
+ _DECLARATION_PATTERN,
+ "var_pattern",
+ _DECLARATION_EXPR,
+ "subpattern",
+ "recursive_pattern",
+ ):
+ return
+ if t in self.identifier_kinds:
+ out.append(self._occ(node))
+ return
+ if self._is_scope_boundary(node):
+ return
+ for child in node.named_children:
+ self.collect_reads(child, out)
+
+ # -- public contract ------------------------------------------------------
+
+ def statement_def_use(
+ self, node: Node, lmap: LanguageNodeMap, *, head_only: bool
+ ) -> StatementDefUse:
+ defs: list[Occurrence] = []
+ uses: list[Occurrence] = []
+ if head_only:
+ self._head(node, lmap, defs, uses)
+ else:
+ self._process(node, defs, uses)
+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+
+ def parameter_defs(self, fn_node: Node) -> tuple[Occurrence, ...]:
+ """Names bound by the signature."""
+ params_node = fn_node.child_by_field_name("parameters")
+ if params_node is None:
+ return ()
+ out: list[Occurrence] = []
+ for child in params_node.named_children:
+ name_node = child.child_by_field_name("name")
+ if name_node is not None and name_node.type in self.identifier_kinds:
+ out.append(self._occ(name_node))
+ else:
+ for sub in child.named_children:
+ if sub.type in self.identifier_kinds:
+ out.append(self._occ(sub))
+ break
+ return tuple(out)
+
+ # -- head (loop clause / if condition) ------------------------------------
+
+ def _head(
+ self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]
+ ) -> None:
+ t = node.type
+ if t == _FOREACH: # ``foreach (int r in records)`` / ``foreach (var (a, b) in pairs)``
+ start = len(defs)
+ self._targets(node.child_by_field_name("left"), defs, uses)
+ self._declare(defs, start, node.child_by_field_name("left") or node)
+ self._process(node.child_by_field_name("right"), defs, uses)
+ elif t in lmap.loop_kinds: # for: init/cond/update; while / do: cond
+ self._process(node.child_by_field_name("initializer"), defs, uses)
+ self._process(node.child_by_field_name("condition"), defs, uses)
+ self._process(node.child_by_field_name("update"), defs, uses)
+ elif t in lmap.branch_kinds:
+ self._process(node.child_by_field_name("condition"), defs, uses)
+ else:
+ self._process(node, defs, uses)
+
+ # -- the unified expression / statement walk ------------------------------
+
+ def _process(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ if node is None:
+ return
+ t = node.type
+ if t in _ASSIGN_KINDS:
+ left = node.child_by_field_name("left")
+ self._targets(left, defs, uses)
+ op = node.child_by_field_name("operator")
+ if op is not None and op.text not in (b"=", None): # compound: read too
+ self.collect_reads(left, uses)
+ self._process(node.child_by_field_name("right"), defs, uses)
+ return
+ if t in _UPDATE_KINDS: # ``x++`` / ``--x`` -- read-modify-write
+ has_update = any(
+ c.type in ("++", "--") or c.text in (b"++", b"--") for c in node.children
+ )
+ if has_update:
+ arg = node.child_by_field_name("argument") or (
+ node.named_children[0] if node.named_children else None
+ )
+ self._targets(arg, defs, uses)
+ self.collect_reads(arg, uses)
+ return
+ for child in node.named_children:
+ self._process(child, defs, uses)
+ return
+ if t in _DECL_KINDS:
+ for child in node.named_children:
+ if child.type == _DECLARATOR:
+ start = len(defs)
+ name_node = child.child_by_field_name("name")
+ self._targets(name_node, defs, uses)
+ self._declare(defs, start, child)
+ for sub in child.named_children:
+ if sub != name_node:
+ self._process(sub, defs, uses)
+ else:
+ self._process(child, defs, uses)
+ return
+ if t == _INVOCATION:
+ fn = node.child_by_field_name("function") or (
+ node.named_children[0] if node.named_children else None
+ )
+ if fn is not None:
+ if fn.type in self.member_access_kinds:
+ self.collect_reads(fn, uses)
+ elif fn.type not in _CALLEE_NAME_KINDS:
+ self._process(fn, defs, uses)
+ args = node.child_by_field_name("arguments") or (
+ node.named_children[1] if len(node.named_children) > 1 else None
+ )
+ if args is not None:
+ for arg in args.named_children:
+ if arg.type == _ARGUMENT:
+ has_out = any(c.type == "out" for c in arg.children)
+ has_ref = any(c.type == "ref" for c in arg.children)
+ if has_out:
+ # 'out' argument is a write (def)
+ for c in arg.named_children:
+ self._targets(c, defs, uses)
+ elif has_ref:
+ # 'ref' argument is both a write (def) and a read (use)
+ for c in arg.named_children:
+ self._targets(c, defs, uses)
+ self.collect_reads(c, uses)
+ else:
+ for c in arg.named_children:
+ self._process(c, defs, uses)
+ else:
+ self._process(arg, defs, uses)
+ return
+ if t == _IS_PATTERN:
+ self._process(
+ node.child_by_field_name("expression") or node.child_by_field_name("left"),
+ defs,
+ uses,
+ )
+ self._targets(node.child_by_field_name("pattern"), defs, uses)
+ return
+ if t in (_DECLARATION_PATTERN, "var_pattern", "recursive_pattern", _DECLARATION_EXPR):
+ self._targets(node, defs, uses)
+ return
+ if t in _CONDITIONAL_KINDS:
+ self._process_may_def(node, defs, uses)
+ return
+ if t in self.member_access_kinds:
+ self.collect_reads(node, uses)
+ return
+ if t in self.identifier_kinds:
+ uses.append(self._occ(node))
+ return
+ if self._is_scope_boundary(node):
+ self.boundary_def(node, defs)
+ return
+ for child in node.named_children:
+ self._process(child, defs, uses)
+
+ # -- write-target extraction ----------------------------------------------
+
+ def _targets(self, node: Node | None, defs: list[Occurrence], uses: list[Occurrence]) -> None:
+ if node is None:
+ return
+ t = node.type
+ if t in self.identifier_kinds:
+ defs.append(self._occ(node))
+ return
+ if t in (_MEMBER_ACCESS, _CONDITIONAL_ACCESS, _ELEMENT_ACCESS): # obj.f / arr[i]
+ self.collect_reads(node, uses)
+ return
+ if t == _DECLARATION_PATTERN:
+ name = node.child_by_field_name("name")
+ if name is not None and name.type in self.identifier_kinds:
+ defs.append(self._occ(name))
+ return
+ if t == _DECLARATION_EXPR:
+ name = node.child_by_field_name("name")
+ if name is not None and name.type in self.identifier_kinds:
+ defs.append(self._occ(name))
+ else:
+ for c in node.named_children:
+ if c.type in self.identifier_kinds:
+ defs.append(self._occ(c))
+ break
+ return
+ if t == "recursive_pattern":
+ type_node = node.child_by_field_name("type")
+ for child in node.named_children:
+ if child != type_node:
+ self._targets(child, defs, uses)
+ return
+ if t == "subpattern":
+ pattern = node.child_by_field_name("pattern") or (
+ node.named_children[-1] if node.named_children else None
+ )
+ if pattern is not None and pattern != node:
+ self._targets(pattern, defs, uses)
+ return
+ for child in node.named_children:
+ self._targets(child, defs, uses)
+
+
+DIALECT = CSharpDefUseDialect()
diff --git a/tests/unit/health/test_dataflow_langs.py b/tests/unit/health/test_dataflow_langs.py
index 70563dd9e..f7c8d5490 100644
--- a/tests/unit/health/test_dataflow_langs.py
+++ b/tests/unit/health/test_dataflow_langs.py
@@ -1246,6 +1246,329 @@ def test_cpp_extraction_never_spans_a_jump():
assert "throw_statement" in lmap.raise_kinds
+# == C# ==================================================================
+
+# Every C# write shape in one method: declarations (int a = 1, b = 2), compound
+# and plain assignment, ++/--, tuple deconstruction, using declaration and
+# statement, is-pattern, switch pattern, foreach binder, C-style for, indexer and
+# member targets (not locals), out/ref args, lambda/local func, and try/catch.
+_CSHARP_SHAPES = """
+class Demo {
+ int Shapes(int[] input, int baseVal, out int outResult, ref int refCount) {
+ int total = 0;
+ int a = 1, b = 2;
+ int acc = baseVal;
+ acc += a;
+ acc++;
+ --acc;
+ (int p, int q) = (1, 2);
+ (a, b) = (3, 4);
+ using var x = open();
+ using (var y = open()) {
+ acc += 1;
+ }
+ if (obj is string s) {
+ acc += s.Length;
+ }
+ switch (input) {
+ case int[] arr:
+ acc += arr.Length;
+ break;
+ default:
+ break;
+ }
+ foreach (int r in input) {
+ acc += r;
+ }
+ for (int i = 0; i < 10; i++) {
+ acc += i;
+ }
+ int[] seen = new int[10];
+ seen[a] = b;
+ this.field = acc;
+ obj.field = acc;
+ DoOut(out var outLocal);
+ DoOutT(out int outTLocal);
+ DoOut(out outResult);
+ DoRef(ref refCount);
+ var lam = (int z) => z + acc;
+ int LocalFunc(int w) => w + 1;
+ try {
+ acc += 1;
+ } catch (Exception e) {
+ acc -= 1;
+ }
+ return acc;
+ }
+}
+"""
+
+
+def test_csharp_def_use_classification():
+ fn = _first("csharp", _CSHARP_SHAPES)
+ defs = _def_names(fn)
+ # Declarations, for/foreach binders, tuple deconstruction, using, out/ref args, pattern variables, and local function are locals.
+ assert {
+ "total",
+ "a",
+ "b",
+ "acc",
+ "p",
+ "q",
+ "x",
+ "y",
+ "s",
+ "arr",
+ "r",
+ "i",
+ "seen",
+ "outLocal",
+ "outTLocal",
+ "outResult",
+ "refCount",
+ "lam",
+ "LocalFunc",
+ } <= defs
+ assert {"input", "baseVal", "outResult", "refCount"} <= defs # parameters
+ # Field (``this.field = ...``) and indexer (``seen[a] = ...``) targets bind no local: bases are reads.
+ assert "field" not in defs
+ # Lambda parameter z and catch binder e are not defs of enclosing method.
+ assert "z" not in defs
+ uses = _use_names(fn)
+ assert {"baseVal", "input", "seen", "a", "b", "acc", "obj", "refCount", "r", "s"} <= uses
+ # Member names (Length) are never variable reads; bare callee identifiers (open, DoOut, DoRef)
+ # are recorded as uses so delegate invocations (cb(n)) are captured as reads.
+ assert "Length" not in uses
+ assert {"open", "DoOut", "DoRef"} <= uses
+
+
+def test_csharp_compound_assign_reads_target():
+ fn = _first(
+ "csharp",
+ """
+ class Demo {
+ int f(int x) {
+ int acc = 0;
+ acc += x;
+ return acc;
+ }
+ }
+ """,
+ )
+ assert "acc" in _def_names(fn)
+ assert "acc" in _use_names(fn)
+
+
+def test_csharp_for_and_while_heads():
+ fn = _first(
+ "csharp",
+ """
+ class Demo {
+ int loops(int n) {
+ int sum = 0;
+ for (int j = 0; j < n; j++) {
+ sum += j;
+ }
+ while (sum < 100) {
+ sum *= 2;
+ }
+ return sum;
+ }
+ }
+ """,
+ )
+ assert "j" in _def_names(fn)
+ headers = [b for b in fn.cfg.blocks if b.kind == "loop_header"]
+ assert len(headers) == 2
+ assert fn.cfg.back_edges()
+
+
+def test_csharp_else_if_chain_branches():
+ fn = _first(
+ "csharp",
+ """
+ class Demo {
+ int grade(int x) {
+ int y = 0;
+ if (x == 1) {
+ y = 1;
+ } else if (x == 2) {
+ y = 2;
+ } else if (x == 3) {
+ y = 3;
+ } else {
+ y = 4;
+ }
+ return y;
+ }
+ }
+ """,
+ )
+ branches = [b for b in fn.cfg.blocks if b.kind == "branch"]
+ assert len(branches) == 3
+ assert fn.cfg.exit_id in fn.cfg.reachable_ids()
+
+
+def test_csharp_switch_arm_writes_are_may_defs():
+ fn = _first(
+ "csharp",
+ """
+ class Demo {
+ int f(int x) {
+ int y = 0;
+ switch (x) {
+ case 1:
+ y = 10;
+ break;
+ default:
+ y = 20;
+ break;
+ }
+ return y;
+ }
+ }
+ """,
+ )
+ decl_line = min(d.line for d in fn.def_use.definitions if d.var == "y")
+ switch_defs = [d for d in fn.def_use.definitions if d.var == "y" and d.line > decl_line]
+ assert switch_defs, "expected the arm writes to register as defs"
+ use_lines = {u.line for b in fn.def_use.blocks.values() for u in b.uses if u.name == "y"}
+ assert {d.line for d in switch_defs} <= use_lines
+
+
+_CSHARP_PROCESS = """
+class Demo {
+ int Process(int[] records, int threshold) {
+ int errors = 0;
+ var results = new System.Collections.Generic.List<int>();
+ foreach (int r in records) {
+ if (r < 0) {
+ errors++;
+ continue;
+ }
+ results.Add(r);
+ }
+ int total = 0;
+ int count = 0;
+ foreach (int v in results) {
+ if (v > threshold) {
+ total += v;
+ count++;
+ } else {
+ total -= v;
+ }
+ }
+ int average = 0;
+ if (count > 0) {
+ average = total / count;
+ }
+ return average + errors;
+ }
+}
+"""
+
+
+def test_csharp_extract_method_fires():
+ lmap = get_language_map("csharp")
+ extractions = find_extractions(_first("csharp", _CSHARP_PROCESS), lmap)
+ assert extractions, "expected at least one C# extraction"
+ best = extractions[0]
+ assert "average" in best.returns
+ assert "results" in best.params and "threshold" in best.params
+ assert len(best.returns) <= 1
+ assert best.ccn_removed >= 1
+ assert best.slice_nloc >= 6
+
+
+def test_csharp_extractions_are_deterministic():
+ lmap = get_language_map("csharp")
+ fn = _first("csharp", _CSHARP_PROCESS)
+
+ def serialize():
+ return [
+ (e.start_line, e.end_line, e.params, e.returns, e.ccn_removed)
+ for e in find_extractions(fn, lmap)
+ ]
+
+ first = serialize()
+ for _ in range(3):
+ assert serialize() == first
+
+
+def test_csharp_flagged_only_gate_skips_small_functions():
+ _require("csharp")
+ lines = ["class Demo {", " int big(int x) {", " int y = 0;"]
+ for i in range(12):
+ lines += [f" if (x == {i}) {{", f" y = {i};", " }"]
+ lines += [" return y;", " }", " int tiny() {", " return 1;", " }", "}"]
+ result = build_cfgs_for_file("m.cs", "csharp", "\n".join(lines).encode())
+ if result.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for csharp")
+ assert result.stats.functions_seen == 2
+ assert result.stats.functions_built == 1
+ assert [fc.name for fc in result.functions] == ["big"]
+
+
+def test_csharp_append_loop_is_independent():
+ assert _independent(
+ "csharp",
+ """
+ class Demo {
+ void f(int[] items) {
+ foreach (int item in items) {
+ int r = fetch(item); // HIT
+ store(r);
+ }
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_csharp_accumulator_is_carried():
+ assert not _independent(
+ "csharp",
+ """
+ class Demo {
+ int f(int[] items) {
+ int acc = 0;
+ foreach (int item in items) {
+ acc = acc + fetch(item); // HIT
+ }
+ return acc;
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
+def test_csharp_switch_conditional_write_refuses_promotion():
+ assert not _independent(
+ "csharp",
+ """
+ class Demo {
+ void f(int[] items) {
+ int flag = 0;
+ foreach (int item in items) {
+ switch (item) {
+ case 1:
+ flag = 1;
+ break;
+ default:
+ break;
+ }
+ int r = fetch(flag); // HIT
+ store(r);
+ }
+ }
+ }
+ """,
+ "HIT",
+ )
+
+
def test_c_extract_method_fires():
# Same shape as the C++ repro: two accumulation loops, a ``continue``, and
# an ``average`` tail. C reuses the C++ dialect, so the same plan fires.
@@ -1597,6 +1920,25 @@ _TWO_LOOPS = {
return sum + total
}
""",
+ "csharp": """
+ class Demo {
+ int Run(int[] a, int n) {
+ int sum = 0;
+ for (int i = 0; i < n; i++) {
+ sum += a[i];
+ }
+ int total = 0;
+ for (int i = 0; i < n; i++) {
+ if (a[i] > 0) {
+ total += a[i];
+ } else {
+ total -= a[i];
+ }
+ }
+ return sum + total;
+ }
+ }
+ """,
}
@@ -1683,6 +2025,25 @@ _READ_THEN_WRITE = {
return sum + total
}
""",
+ "csharp": """
+ class Demo {
+ int Run(int[] a, int n, int total) {
+ int sum = 0;
+ for (int j = 0; j < n; j++) {
+ sum += a[j];
+ }
+ total = total + a[0];
+ for (int k = 1; k < n; k++) {
+ if (a[k] > 0) {
+ total += a[k];
+ } else {
+ total -= a[k];
+ }
+ }
+ return sum + total;
+ }
+ }
+ """,
}
@@ -2281,3 +2642,154 @@ def test_rust_span_splitting_a_closure_from_its_let_local_is_refused():
spans = find_extractions(fn, get_language_map("rust"))
# The closure writes ``n``, so no span may hold it without ``n``'s reads.
assert [(x.start_line, x.end_line) for x in spans] == [(5, 6)]
+
+
+def test_csharp_local_declared_and_read_on_one_line_in_the_span_is_not_a_parameter():
+ fn = _first(
+ "csharp",
+ """
+ class Demo {
+ int Run(int[] a, int n) {
+ int sum = 0;
+ for (int j = 0; j < n; j++) {
+ int t = a[j];
+ sum += t;
+ }
+ int total = 0;
+ for (int k = 0; k < n; k++) {
+ int t = a[k]; total += t;
+ if (t > 0) {
+ total += 1;
+ } else {
+ total -= 1;
+ }
+ }
+ return sum + total;
+ }
+ }
+ """,
+ )
+
+ extractions = find_extractions(fn, get_language_map("csharp"))
+
+ assert extractions, "expected the second loop as an extraction"
+ assert all("t" not in x.params for x in extractions)
+ assert (("a", "n"), ("total",)) in [(x.params, x.returns) for x in extractions]
+
+
+def test_csharp_switch_arm_binder_inside_the_span_is_not_a_param():
+ src = """
+ class Demo {
+ int Process(object obj, int limit) {
+ switch (obj) {
+ case int i:
+ int armVal = i * 2;
+ log(armVal);
+ break;
+ default:
+ break;
+ }
+ int total = 0;
+ for (int j = 0; j < limit; j++) {
+ total += j;
+ }
+ for (int k = 0; k < limit; k++) {
+ if (k > 0) {
+ total += k;
+ } else {
+ total -= k;
+ }
+ }
+ return total;
+ }
+ }
+ """
+ lmap = get_language_map("csharp")
+ fn = _first("csharp", src)
+ spans = find_extractions(fn, lmap)
+ assert spans
+ for s in spans:
+ assert "armVal" not in s.params
+
+
+def test_csharp_delegate_call_records_callee_as_read():
+ src = """
+ class Demo {
+ int M(Func<int, int> cb, int n) {
+ var r = 0;
+ if (n > 0) {
+ r = cb(n);
+ r += 1;
+ }
+ return r;
+ }
+ }
+ """
+ fn = _first("csharp", src)
+ from repowise.core.analysis.health.dataflow import slice as slicing
+
+ def_use = fn.def_use
+ dl, ul = slicing._var_lines(def_use)
+ params, returns = slicing._infer_in_out(
+ dl,
+ ul,
+ 5,
+ 7,
+ slicing._declared_before_read(def_use),
+ reads=slicing._reads_observing(fn, dl),
+ )
+ assert "cb" in params
+ assert "n" in params
+ assert returns == ("r",)
+
+
+def test_csharp_update_expression_inside_if_records_def():
+ src = """
+ class Demo {
+ int M(int a) {
+ int tryCount = 0;
+ int waitDuration = 0;
+ if (a > 0) {
+ tryCount++;
+ waitDuration = 5;
+ }
+ return tryCount + waitDuration;
+ }
+ }
+ """
+ fn = _first("csharp", src)
+ lmap = get_language_map("csharp")
+ from repowise.core.analysis.health.dataflow import slice as slicing
+
+ def_use = fn.def_use
+ dl, ul = slicing._var_lines(def_use)
+ _, returns = slicing._infer_in_out(
+ dl,
+ ul,
+ 5,
+ 8,
+ slicing._declared_before_read(def_use),
+ reads=slicing._reads_observing(fn, dl),
+ )
+ assert "tryCount" in returns
+ assert "waitDuration" in returns
+ extractions = find_extractions(fn, lmap)
+ assert not any(x.start_line <= 5 and x.end_line >= 8 for x in extractions)
+
+
+def test_csharp_lambda_writing_outer_local_records_def():
+ src = """
+ class Demo {
+ int M(int a) {
+ int tryCount = 0;
+ Action act = () => { tryCount++; };
+ act();
+ return tryCount;
+ }
+ }
+ """
+ fn = _first("csharp", src)
+ lmap = get_language_map("csharp")
+ assert any(occ.name == "tryCount" for occ in fn.def_use.captured.writes)
+ extractions = find_extractions(fn, lmap)
+ assert not any(x.start_line <= 4 and x.end_line >= 5 for x in extractions)