Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(dataflow): build try regions and match error exits inside switch arms (#3494) (#3694)
Rishabh Mishra0a43bbc39341
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.pyindex 762c5ad8f..03c1a1335 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py@@ -432,19 +432,55 @@ class _CFGBuilder:self._raises.append(RaiseSite(st.start_point[0] + 1, kind, exc, caught))def _record_arm_raises(self, switch: Node) -> None:- """The raises in a ``switch`` / ``match`` the graph keeps whole. The- statement is one graph node, so its arms are walked here, once, and- only within it: nested functions and lambdas are not entered."""+ """The raises and nested try regions in a ``switch`` / ``match`` the+ graph keeps whole. The statement is one graph node, so its arms are+ walked here, once, and only within it: nested functions and lambdas are+ not entered."""+ for child in switch.named_children:+ self._walk_arm_node(child)++ def _walk_arm_node(self, node: Node) -> None:scopes = self.lmap.function_kinds | self.lmap.lambda_kinds- stack = list(reversed(switch.named_children))- while stack:- node = stack.pop()- if node.type in self.lmap.raise_kinds:- self._record_exit(node)- elif node.type not in scopes:- stack.extend(reversed(node.named_children))+ if node.type in self.lmap.raise_kinds:+ self._record_exit(node)+ elif node.type in self.lmap.try_kinds:+ clauses = [c for c in node.children if c.type in self.lmap.catch_kinds]+ heads = [self._handler(c) for c in clauses]+ body = node.child_by_field_name("body")+ else_clause = next((c for c in node.children if c.type == "else_clause"), None)+ finally_clause = next((c for c in node.children if c.type == "finally_clause"), None)++ self._guards.append(tuple(heads))+ if body is not None:+ for child in body.children:+ self._walk_arm_node(child)+ self._guards.pop()++ if else_clause is not None:+ for child in else_clause.children:+ self._walk_arm_node(child)++ handlers = []+ for clause, head in zip(clauses, heads, strict=True):+ self._handling.append(head)+ handler_entry = self._new("handler")+ handler_out = self._process_seq(+ self._body_stmts(self._block_of(clause)), handler_entry+ )+ self._handling.pop()+ handlers.append(replace(head, completes=handler_out is not None))++ if finally_clause is not None:+ for child in finally_clause.children:+ self._walk_arm_node(child)++ parts = (body, else_clause, clauses, finally_clause)+ self._regions.append(_try_region(node, parts, tuple(handlers)))+ elif node.type not in scopes:+ for child in node.named_children:+ self._walk_arm_node(child)- def _build_if(self, if_node: Node, cur: BasicBlock) -> BasicBlock:+ def _build_if(self, if_node: Node, cur: BasicBlock) -> BasicBlock | None:cur.kind = "branch"self._record_head(cur, if_node)join = self._new("join")@@ -470,7 +506,7 @@ class _CFGBuilder:self._build_py_else_chain(alts, cur, join)else:self._build_c_alternative(if_node, cur, join)- return join+ return join if join.predecessors else Nonedef _build_py_else_chain(self, alts: list[Node], cur: BasicBlock, join: BasicBlock) -> None:"""Python ``elif`` / ``else`` clause chain off *cur*'s false edge."""diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/raises.py b/packages/core/src/repowise/core/analysis/health/dataflow/raises.pyindex bf9fbc8e4..2bbc984ce 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/raises.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/raises.py@@ -282,6 +282,9 @@ def _followed(cfg: CFG, line: int, s: int, e: int) -> bool:if at is None:return Trueblock, k = at+ st = cfg.block(block).statements[k]+ if st.start_line < s or e < st.end_line:+ return Truerest = cfg.block(block).statements[k + 1 :]if rest:return s <= rest[0].start_line <= ediff --git a/tests/unit/health/test_dataflow_raises.py b/tests/unit/health/test_dataflow_raises.pyindex d93774121..99645eb89 100644--- a/tests/unit/health/test_dataflow_raises.py+++ b/tests/unit/health/test_dataflow_raises.py@@ -110,6 +110,102 @@ def test_a_raise_in_a_switch_arm_is_recorded_and_a_closure_raise_is_not():assert _facts("typescript", src) == [(6, "raise", "RangeError", 10)]+def test_try_inside_switch_arm_in_typescript_and_java():+ ts = """+ function f(k) {+ switch (k) {+ case 1:+ try {+ throw new RangeError("a");+ } catch (e) {+ throw e;+ }+ default:+ break;+ }+ }+ """+ assert _facts("typescript", ts) == [+ (6, "raise", "RangeError", 7),+ (8, "rethrow", None, None),+ ]+ (ts_region,) = _cfg("typescript", ts).try_regions+ assert ts_region.start_line == 5 and ts_region.end_line == 9++ java = """+ class A {+ void f(int k) {+ switch (k) {+ case 1:+ try {+ throw new IllegalArgumentException();+ } catch (IllegalArgumentException e) {+ throw e;+ }+ }+ }+ }+ """+ assert _facts("java", java) == [+ (7, "raise", "IllegalArgumentException", 8),+ (9, "rethrow", "IllegalArgumentException", None),+ ]+ (java_region,) = _cfg("java", java).try_regions+ assert java_region.start_line == 6 and java_region.end_line == 10+++def test_try_inside_switch_arm_handler_with_if_else_exits():+ ts = """+ function f(k, c) {+ switch (k) {+ case 1:+ try {+ throw new RangeError("a");+ } catch (e) {+ if (c) {+ return 1;+ } else {+ throw e;+ }+ }+ default:+ break;+ }+ }+ """+ cfg = _cfg("typescript", ts)+ (region,) = cfg.try_regions+ (handler,) = region.handlers+ assert handler.completes is False++++def test_try_inside_match_arm_in_python_and_extract_method_refusal():+ src = """+ def f(k):+ x = 0+ match k:+ case 1:+ try:+ x = g(k)+ if x:+ x = h(x)+ note(x)+ log(x)+ send(k)+ except Exception:+ return x+ case _:+ pass+ return x+ """+ cfg = _cfg("python", src)+ (region,) = cfg.try_regions+ assert (region.start_line, region.end_line) == (6, 14)+ assert _refusal(src, 7, 12) == EXCEPTION_STATE+ assert _refusal(src, 6, 7) == TRY_SPLIT++def test_java_union_catch_and_csharp_bare_rethrow():java = """class A { void f() {