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): recurse into with-statement bodies (#836)
SK4483b0f6aab6
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 613d592ec..0318b81ee 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -186,6 +186,7 @@ class LanguageNodeMap:raise_kinds: frozenset[str] = frozenset()break_kinds: frozenset[str] = frozenset()continue_kinds: frozenset[str] = frozenset()+ with_kinds: 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@@ -230,6 +231,7 @@ _PY = LanguageNodeMap(raise_kinds=frozenset({"raise_statement"}),break_kinds=frozenset({"break_statement"}),continue_kinds=frozenset({"continue_statement"}),+ with_kinds=frozenset({"with_statement"}),)_TS = LanguageNodeMap(diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.pyindex 6a953b786..3a5b747e6 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py@@ -308,6 +308,8 @@ class _CFGBuilder:cur = self._build_loop(st, cur)elif t in self.lmap.try_kinds:cur = self._build_try(st, cur)+ elif t in self.lmap.with_kinds:+ cur = self._build_with(st, cur)elif t in self.lmap.return_kinds or t in self.lmap.raise_kinds:self._record_stmt(cur, st)self._edge(cur, self.exit_block)@@ -430,6 +432,28 @@ class _CFGBuilder:self._edge(body_out, header) # back-edgereturn after+ def _build_with(self, with_node: Node, cur: BasicBlock) -> BasicBlock | None:+ """Process a context-manager head and recurse into its body.++ A with-body always executes. If every path in the body terminates,+ statements following the with-statement cannot fall through.+ """+ self._record_head(cur, with_node)++ body_entry = self._new()+ self._edge(cur, body_entry)++ body_out = self._process_seq(+ self._body_stmts(with_node.child_by_field_name("body")),+ body_entry,+ )+ if body_out is None:+ return None++ join = self._new("join")+ self._edge(body_out, join)+ return join+def _build_try(self, try_node: Node, cur: BasicBlock) -> BasicBlock:# try-with-resources (Java) binds locals in its resource clause; record# a head so the def/use dialect sees those bindings. A plain ``try``@@ -480,6 +504,10 @@ class _CFGBuilder:for handler in (c for c in try_node.children if c.type in self.lmap.catch_kinds):handler_entry = self._new("handler")self._edge(body_entry, handler_entry)+ if finally_clause is not None:+ # Finally also runs when a handler returns or re-raises. This+ # edge lets handler definitions reach reads in the finally body.+ self._edge(handler_entry, normal_join)handler_out = self._process_seq(self._body_stmts(self._block_of(handler)), handler_entry)diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.pyindex 703ca3c48..09a3e44b6 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/python.py@@ -88,6 +88,12 @@ class PythonDefUseDialect(BaseDefUseDialect):self._process(node.child_by_field_name("condition"), defs, uses)elif node.type in lmap.branch_kinds:self._process(node.child_by_field_name("condition"), defs, uses)+ elif node.type in lmap.with_kinds:+ clause = next(+ (child for child in node.named_children if child.type == "with_clause"),+ None,+ )+ self._process(clause, defs, uses)else:self._process(node, defs, uses)diff --git a/tests/unit/health/test_dataflow_cfg.py b/tests/unit/health/test_dataflow_cfg.pyindex 294f983fb..3548b6ec5 100644--- a/tests/unit/health/test_dataflow_cfg.py+++ b/tests/unit/health/test_dataflow_cfg.py@@ -192,6 +192,49 @@ def test_for_loop_shape():assert cfg.back_edges()+# -- with statements -----------------------------------------------------------+++def test_with_body_recurses_into_nested_control_flow():+ cfg = _cfg(+ """+ def f(ctx, cond):+ with ctx.push():+ if cond:+ result = 1+ else:+ result = 2+ return result+ """+ )++ assert len(_by_kind(cfg, "branch")) == 1+ assert len(_by_kind(cfg, "join")) == 2+ assert any(+ statement.kind == "with_statement" and statement.is_head+ for block in cfg.blocks+ for statement in block.statements+ )+ assert cfg.exit_id in cfg.reachable_ids()+++def test_return_inside_with_makes_following_code_unreachable():+ cfg = _cfg(+ """+ def f(path):+ with open(path) as handle:+ return handle.read()+ dead = 1+ """+ )++ unreachable = _by_kind(cfg, "unreachable")+ assert len(unreachable) == 1+ assert unreachable[0].statements[0].start_line == 5+ assert unreachable[0].predecessors == []+ assert unreachable[0].id not in cfg.reachable_ids()++def test_break_and_continue_targets():cfg = _cfg("""diff --git a/tests/unit/health/test_dataflow_facts.py b/tests/unit/health/test_dataflow_facts.pyindex 239f44db1..b8a086124 100644--- a/tests/unit/health/test_dataflow_facts.py+++ b/tests/unit/health/test_dataflow_facts.py@@ -55,6 +55,26 @@ def test_dead_store_overwritten_before_use():assert "y" in facts.flows_out+def test_with_branch_assignments_are_both_live():+ facts = _facts(+ """+ def f(ctx, cond):+ with ctx.push():+ if cond:+ result = 1+ else:+ result = 2+ return result+ """,+ 2,+ )++ dead_result_lines = {+ definition.line for definition in facts.dead_stores if definition.var == "result"+ }+ assert dead_result_lines.isdisjoint({5, 7})++def test_unreachable_lines_after_return():facts = _facts("""diff --git a/tests/unit/health/test_dataflow_reaching.py b/tests/unit/health/test_dataflow_reaching.pyindex b41d7b0ca..d7ddda8d6 100644--- a/tests/unit/health/test_dataflow_reaching.py+++ b/tests/unit/health/test_dataflow_reaching.py@@ -129,6 +129,33 @@ def test_with_as_alias_is_def():assert "path" in uses # the context expression is a use+def test_with_body_branch_defs_both_reach_return():+ _cfg_result, def_use, reaching = _analyze(+ """+ def f(ctx, cond):+ with ctx.push():+ if cond:+ result = 1+ else:+ result = 2+ return result+ """+ )++ return_block = next(+ block_id+ for block_id, block_def_use in def_use.blocks.items()+ if any(use.name == "result" and use.line == 8 for use in block_def_use.uses)+ )+ reaching_lines = {+ definition.line+ for definition in reaching.reaching_in(return_block)+ if definition.var == "result"+ }++ assert reaching_lines == {5, 7}++def test_walrus_is_def():defs, _uses = _def_use_names("""@@ -218,6 +245,36 @@ def test_both_branch_defs_reach_join():assert len(reaching_y) == 2+def test_handler_assignment_reaches_finally_on_reraise():+ _cfg_result, def_use, reaching = _analyze(+ """+ def f():+ failed = False+ try:+ run()+ except Exception:+ failed = True+ raise+ finally:+ if not failed:+ cleanup()+ """+ )++ finally_block = next(+ block_id+ for block_id, block_def_use in def_use.blocks.items()+ if any(use.name == "failed" and use.line == 10 for use in block_def_use.uses)+ )+ reaching_lines = {+ definition.line+ for definition in reaching.reaching_in(finally_block)+ if definition.var == "failed"+ }++ assert 7 in reaching_lines++def test_redefinition_kills_earlier_def():cfg, _du, reaching = _analyze("""