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): bind the catch variable as a def in Java, C# and C++ dataflow dialects (#3396) (#3483)

Aman1a1d136e5f54
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
index fdd114a61..738c57eba 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/cpp.py
@@ -7,9 +7,9 @@ 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 range-``for``
(``for (auto& v : xs)``) and the C-style ``for`` initializer. A ``catch``
-clause's exception variable is deliberately NOT a def: the CFG never records a
-handler binder as a head in any language, so it stays an unmatched *use* — the
-conservative direction, matching the Java and Python dialects.
+clause's exception variable (``catch (const std::exception& e)``) is a def
+scoped to the handler block, recorded through ``handler_def_use`` as the
+handler's head; ``catch (...)`` and an unnamed ``catch (int)`` bind nothing.
Field targets (``obj.f = …`` / ``this->f = …``) and subscript targets
(``arr[i] = …``) bind no *local*, so their base identifiers are reads — the
@@ -60,6 +60,8 @@ _ASSIGN_KINDS = frozenset({"assignment_expression"})
_UPDATE_KINDS = frozenset({"update_expression"}) # ``x++`` / ``--x``
_DECL_KINDS = frozenset({"declaration"})
_INIT_DECLARATOR = "init_declarator"
+_CATCH = "catch_clause"
+_CATCH_PARAM = "parameter_declaration" # ``catch (const std::exception& e)``
_RANGE_FOR = "for_range_loop"
_CALL = "call_expression"
@@ -233,7 +235,23 @@ class CppDefUseDialect(BaseDefUseDialect):
return found
return None
- # -- head (loop clause / if condition / catch binder) ---------------------
+ def handler_def_use(self, handler: Node) -> StatementDefUse:
+ """``catch (const std::exception& e)`` binds ``e`` for the handler
+ block only. The binder is read off the parameter's ``declarator``, so
+ the type is never mistaken for it, and ``catch (...)`` or an unnamed
+ ``catch (int)`` (no declarator) binds nothing."""
+ defs: list[Occurrence] = []
+ params = handler.child_by_field_name("parameters")
+ children = params.named_children if params is not None else []
+ decl = next((c for c in children if c.type == _CATCH_PARAM), None)
+ declarator = decl.child_by_field_name("declarator") if decl is not None else None
+ binder = self._binder_identifier(declarator) if declarator is not None else None
+ if decl is not None and binder is not None:
+ defs.append(self._occ(binder))
+ self._declare(defs, 0, decl)
+ return StatementDefUse(defs=tuple(defs), uses=())
+
+ # -- head (loop clause / if condition) ----------------------------------
def _head(
self, node: Node, lmap: LanguageNodeMap, defs: list[Occurrence], uses: list[Occurrence]
@@ -251,11 +269,9 @@ class CppDefUseDialect(BaseDefUseDialect):
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)
- # NB: a C++ ``try`` has no head. The CFG records a try head only for the
- # ``resources`` field (Java's try-with-resources), and a ``catch``
- # clause's binder is never recorded as a head in any language — so an
- # exception variable is an unmatched *use*, the conservative direction,
- # exactly as in the Java and Python dialects.
+ # NB: a C++ ``try`` has no head, and a ``catch`` clause's binder does not
+ # come through here: the CFG records the handler as its own head and
+ # ``handler_def_use`` answers for it.
else:
self._process(node, defs, uses)
@@ -265,6 +281,12 @@ class CppDefUseDialect(BaseDefUseDialect):
if node is None:
return
t = node.type
+ if t == _CATCH: # a handler walked whole (inside a lambda or a ``switch`` arm)
+ sdu = self.handler_def_use(node)
+ defs.extend(sdu.defs)
+ uses.extend(sdu.uses)
+ self._process(node.child_by_field_name("body"), defs, uses)
+ return
if t in _ASSIGN_KINDS:
left = node.child_by_field_name("left")
self._targets(left, defs, uses)
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
index e1bd9ce1e..34c7ce276 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/csharp.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/csharp.py
@@ -10,10 +10,10 @@ 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.
+...``). A ``catch (Exception e)`` clause binds ``e`` as a def scoped to the
+handler block, and its ``when (...)`` filter is read as part of the head. 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
@@ -44,6 +44,9 @@ _ARGUMENT = "argument"
_DECLARATION_EXPR = "declaration_expression"
_DECLARATION_PATTERN = "declaration_pattern"
_IS_PATTERN = "is_pattern_expression"
+_CATCH = "catch_clause"
+_CATCH_DECL = "catch_declaration" # ``catch (Exception e)``; ``e`` is optional
+_CATCH_FILTER = "catch_filter_clause" # ``catch (E e) when (cond)``
# Field (``obj.f``, ``this.f``) and indexer (``arr[i]``) targets bind no local.
_MEMBER_ACCESS = "member_access_expression"
@@ -108,6 +111,23 @@ class CSharpDefUseDialect(BaseDefUseDialect):
kind = decl.child_by_field_name("type") if decl is not None else None
return ((node_text(kind),) if kind is not None else None), bound
+ def handler_def_use(self, handler: Node) -> StatementDefUse:
+ """``catch (Exception e)`` binds ``e`` for the handler block only; the
+ name is optional (``catch (IOException)``, bare ``catch``). A ``when
+ (...)`` filter runs before the block, so what it reads belongs to the
+ head. The exception type is a bare ``identifier`` in this grammar but
+ sits under the declaration's ``type`` field, which is never walked."""
+ defs: list[Occurrence] = []
+ uses: list[Occurrence] = []
+ decl = next((c for c in handler.named_children if c.type == _CATCH_DECL), None)
+ name = decl.child_by_field_name("name") if decl is not None else None
+ if decl is not None and name is not None:
+ defs.append(self._occ(name))
+ self._declare(defs, 0, decl)
+ flt = next((c for c in handler.named_children if c.type == _CATCH_FILTER), None)
+ self.collect_reads(flt, uses)
+ return StatementDefUse(defs=tuple(defs), uses=tuple(uses))
+
def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
"""Collect variable reads under *node*.
@@ -212,6 +232,12 @@ class CSharpDefUseDialect(BaseDefUseDialect):
if node is None:
return
t = node.type
+ if t == _CATCH: # a handler walked whole (inside a lambda or a ``switch`` arm)
+ sdu = self.handler_def_use(node)
+ defs.extend(sdu.defs)
+ uses.extend(sdu.uses)
+ self._process(node.child_by_field_name("body"), defs, uses)
+ return
if t in _ASSIGN_KINDS:
self._assignment(node, defs, uses)
return
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
index 1d8b15922..0a2eac331 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/java.py
@@ -6,10 +6,12 @@ Java's write sites are: ``local_variable_declaration`` (each nested
are an ``assignment_expression`` -- told apart by the operator token, ``=`` vs
``+=``, as in Go), update expressions (``x++`` / ``--x``, read-modify-write),
the binder of an enhanced ``for`` (``for (T v : xs)``), the C-style ``for``
-initializer, and the resource clause of try-with-resources. Field targets
-(``obj.f = ...`` / ``this.f = ...``) and array targets (``arr[i] = ...``) bind
-no *local*, so their base identifiers are reads -- the precision-first choice
-that keeps reaching definitions sound for the locals they actually track.
+initializer, the resource clause of try-with-resources, and the exception
+variable of a ``catch`` clause (``catch (IOException | RuntimeException e)``,
+a def scoped to the handler block). Field targets (``obj.f = ...`` /
+``this.f = ...``) and array targets (``arr[i] = ...``) bind no *local*, so
+their base identifiers are reads -- the precision-first choice that keeps
+reaching definitions sound for the locals they actually track.
A ``method_invocation``'s ``name`` is the called method, not a variable, so
the walk processes only its ``object`` and ``arguments``; the same for a
@@ -47,6 +49,8 @@ _UPDATE_KINDS = frozenset({"update_expression"}) # ``x++`` / ``--x``
_DECL_KINDS = frozenset({"local_variable_declaration"})
_DECLARATOR = "variable_declarator"
_RESOURCE = "resource" # ``try (var res = open())``
+_CATCH = "catch_clause"
+_CATCH_PARAM = "catch_formal_parameter" # ``catch (IOException e)``
_ENHANCED_FOR = "enhanced_for_statement"
_METHOD_INVOCATION = "method_invocation"
_METHOD_REFERENCE = "method_reference" # ``Integer::parseInt``
@@ -84,6 +88,18 @@ class JavaDefUseDialect(BaseDefUseDialect):
name = param.child_by_field_name("name")
return types, node_text(name) if name is not None else None
+ def handler_def_use(self, handler: Node) -> StatementDefUse:
+ """``catch (IOException | RuntimeException e)`` binds ``e`` for the
+ handler block only. The exception types are ``type_identifier`` nodes,
+ never variable reads, so the head reads nothing."""
+ defs: list[Occurrence] = []
+ param = next((c for c in handler.named_children if c.type == _CATCH_PARAM), None)
+ name = param.child_by_field_name("name") if param is not None else None
+ if param is not None and name is not None:
+ defs.append(self._occ(name))
+ self._declare(defs, 0, param)
+ return StatementDefUse(defs=tuple(defs), uses=())
+
def collect_reads(self, node: Node | None, out: list[Occurrence]) -> None:
"""Like the base collector, but a ``method_invocation`` / ``method_reference``
contributes only its receiver and arguments -- never the method name."""
@@ -180,6 +196,12 @@ class JavaDefUseDialect(BaseDefUseDialect):
if node is None:
return
t = node.type
+ if t == _CATCH: # a handler walked whole (inside a lambda or a ``switch`` arm)
+ sdu = self.handler_def_use(node)
+ defs.extend(sdu.defs)
+ uses.extend(sdu.uses)
+ self._process(node.child_by_field_name("body"), defs, uses)
+ return
if t in _ASSIGN_KINDS:
left = node.child_by_field_name("left")
self._targets(left, defs, uses)
diff --git a/tests/unit/health/test_extract_method_span_interface.py b/tests/unit/health/test_extract_method_span_interface.py
index f617073e7..fc14a2796 100644
--- a/tests/unit/health/test_extract_method_span_interface.py
+++ b/tests/unit/health/test_extract_method_span_interface.py
@@ -397,6 +397,194 @@ def test_typescript_catch_binds_its_parameter_pattern():
assert spans and all("message" in x.params for x in spans)
+_JAVA_CATCH = """class A {
+ void f(java.util.List<Object> items, boolean flag) {
+ for (Object it : items) {
+ try {
+ run(it);
+ } catch (IOException | RuntimeException e) {
+ if (flag && it.big) {
+ log(e);
+ if (it.small || flag) {
+ warn(e, it);
+ }
+ }
+ report(e);
+ }
+ }
+ }
+}
+"""
+
+_CSHARP_CATCH = """class A {
+ void f(List<Item> items, bool flag) {
+ foreach (var it in items) {
+ try {
+ run(it);
+ } catch (Exception e) {
+ if (flag && it.big) {
+ log(e);
+ if (it.small || flag) {
+ warn(e, it);
+ }
+ }
+ report(e);
+ }
+ }
+ }
+}
+"""
+
+_CPP_CATCH = """void f(std::vector<Item>& items, bool flag) {
+ for (auto& it : items) {
+ try {
+ run(it);
+ } catch (const std::exception& e) {
+ if (flag && it.big) {
+ log(e);
+ if (it.small || flag) {
+ warn(e, it);
+ }
+ }
+ report(e);
+ }
+ }
+}
+"""
+
+
+ ("src", "language", "ext", "catch_line"),
+ [
+ (_JAVA_CATCH, "java", "java", 6),
+ (_CSHARP_CATCH, "csharp", "cs", 6),
+ (_CPP_CATCH, "cpp", "cpp", 5),
+ ],
+ ids=["java", "csharp", "cpp"],
+)
+def test_a_catch_clause_binds_its_exception_variable(src, language, ext, catch_line):
+ # The issue-3396 fixture: ``e`` is defined by the clause head and read twice
+ # inside the handler. Without a ``handler_def_use`` override the read was
+ # unmatched, so a span holding both reads never took ``e`` in as an input.
+ fn = _functions(src, language, ext)[0]
+ assert [(d.var, d.line, d.declares) for d in fn.def_use.definitions if d.var == "e"] == [
+ ("e", catch_line, True)
+ ]
+ spans = _spans(src, "f", language, ext)
+ assert spans and all("e" in x.params for x in spans)
+
+
+ ("src", "language", "ext"),
+ [
+ ("class A { void f() { try { run(); } catch (Exception e) { log(e); } } }", "java", "java"),
+ ("class A { void f() { try { run(); } catch (Exception e) { log(e); } } }", "csharp", "cs"),
+ ("void f() { try { run(); } catch (const E& e) { log(e); } }", "cpp", "cpp"),
+ ],
+ ids=["java", "csharp", "cpp"],
+)
+def test_a_catch_variable_is_not_defined_outside_its_handler_head(src, language, ext):
+ fn = _functions(src, language, ext)[0]
+ assert len([d for d in fn.def_use.definitions if d.var == "e"]) == 1
+
+
+ ("src", "language", "ext"),
+ [
+ ("void f() { try { run(); } catch (...) { x(); } }", "cpp", "cpp"),
+ ("void f() { try { run(); } catch (int) { x(); } }", "cpp", "cpp"),
+ ("void f() { try { run(); } catch (const std::exception&) { x(); } }", "cpp", "cpp"),
+ ("class A { void f() { try { run(); } catch (IOException) { x(); } } }", "csharp", "cs"),
+ ("class A { void f() { try { run(); } catch { x(); } } }", "csharp", "cs"),
+ ],
+ ids=["cpp-ellipsis", "cpp-type-only", "cpp-ref-type-only", "cs-type-only", "cs-bare"],
+)
+def test_an_unnamed_catch_binds_nothing(src, language, ext):
+ fn = _functions(src, language, ext)[0]
+ assert [
+ d for d in fn.def_use.definitions if d.var in ("e", "IOException", "std", "exception")
+ ] == []
+
+
+def test_a_csharp_catch_filter_reads_into_the_handler_head():
+ fn = _functions(
+ """class A {
+ void f(int limit) {
+ try { run(); } catch (Exception e) when (e.Code > limit) { }
+ }
+}
+""",
+ "csharp",
+ "cs",
+ )[0]
+ handler = next(
+ b for b in fn.cfg.blocks if b.statements and b.statements[0].kind == "catch_clause"
+ )
+ head = fn.def_use.block(handler.id)
+ assert [d.var for d in head.defs] == ["e"]
+ assert {u.name for u in head.uses} == {"e", "limit"}
+
+
+ ("src", "language", "ext"),
+ [
+ (
+ """class A {
+ void f(Runnable r) {
+ try { r.run(); } catch (Exception err) { log(err); }
+ Runnable g = () -> {
+ try {
+ r.run();
+ } catch (Exception err) {
+ log(err);
+ }
+ };
+ }
+}
+""",
+ "java",
+ "java",
+ ),
+ (
+ """class A {
+ void f(Action r) {
+ try { r(); } catch (Exception err) { log(err); }
+ Action g = () => {
+ try {
+ r();
+ } catch (Exception err) {
+ log(err);
+ }
+ };
+ }
+}
+""",
+ "csharp",
+ "cs",
+ ),
+ (
+ """void f(std::function<void()> r) {
+ try { r(); } catch (const std::exception& err) { log(err); }
+ auto g = [&]() {
+ try {
+ r();
+ } catch (const std::exception& err) {
+ log(err);
+ }
+ };
+}
+""",
+ "cpp",
+ "cpp",
+ ),
+ ],
+ ids=["java", "csharp", "cpp"],
+)
+def test_a_lambda_catch_variable_is_its_own(src, language, ext):
+ captured = _functions(src, language, ext)[0].def_use.captured
+ assert "err" not in {o.name for o in (*captured.reads, *captured.shared, *captured.writes)}
+
+
def test_a_closure_catch_parameter_is_its_own():
fn = _functions(
"""function f(xs) {
@@ -444,18 +632,35 @@ def test_except_star_and_nested_handlers_get_heads():
@pytest.mark.parametrize(
("language", "ext", "src"),
[
- ("java", "java", "class A { int f(int x) { try { g(x); } catch (Exception e) { h(e); } return x; } }"),
- ("csharp", "cs", "class A { int F(int x) { try { G(x); } catch (Exception e) { H(e); } return x; } }"),
+ (
+ "java",
+ "java",
+ "class A { int f(int x) { try { g(x); } catch (Exception e) { h(e); } return x; } }",
+ ),
+ (
+ "csharp",
+ "cs",
+ "class A { int F(int x) { try { G(x); } catch (Exception e) { H(e); } return x; } }",
+ ),
+ (
+ "cpp",
+ "cpp",
+ "int f(int x) { try { g(x); } catch (const std::exception& e) { h(e); } return x; }",
+ ),
],
)
-def test_other_languages_read_nothing_new_at_a_handler_head(language, ext, src):
+def test_other_languages_bind_the_name_at_a_handler_head_but_read_no_type(language, ext, src):
+ # The head defines ``e``; the exception *type* is not a variable, so it is
+ # never a read (Python reads its ``except E`` type because there it is an
+ # expression; these grammars keep it under a type node).
fn = _functions(src, language, ext)[0]
handler = next(b for b in fn.cfg.blocks if b.kind == "handler")
head = handler.statements[0]
assert head.is_head
bdu = fn.def_use.block(handler.id)
- assert [d for d in bdu.defs if d.line == head.start_line] == []
- assert [u for u in bdu.uses if u.line == head.start_line and u.name == "Exception"] == []
+ assert [d.var for d in bdu.defs if d.line == head.start_line] == ["e"]
+ type_names = {"Exception", "exception", "std"}
+ assert [u for u in bdu.uses if u.line == head.start_line and u.name in type_names] == []
def test_a_handler_rebinding_a_name_in_a_loop_carries_nothing():