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(dataflow): a write overwritten later in a try body reaches its handler (#3413)

Raghav Chamadiyaf0c8e48e6c4b
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
index 004b7571e..b8db9b9c3 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
@@ -36,12 +36,9 @@ children, while the C-family (Go / TS / Java / Rust) hangs the else arm off an
silence), the same precision-first default as the def/use dialect.
**Exceptions.** A ``try`` body, ``else`` clause or handler is joined to the
-handlers / ``finally`` it can raise into from the state before it and at the
-end of each of its blocks, not between two statements of one block: a write
-that a later statement of the same block overwrites never reaches the handler
-(a ``try`` body ``x = 1; y = g(); x = 2`` hides ``x = 1`` from an
-``except`` that reads ``x``). Splitting every protected statement into its own block would close
-that gap at the cost of a much larger graph.
+handlers / ``finally`` it can raise into from the state before it and from each
+of its blocks. Those block edges are ``raise_edges``, since an exception can
+leave a block mid-way: in ``x = 1; y = g(); x = 2`` the handler sees ``x = 1``.
"""
from __future__ import annotations
@@ -145,6 +142,8 @@ class CFG:
exit_id: int
function_name: str = ""
function_start_line: int = 0
+ # ``(src, dst)`` edges an exception can take from inside *src*, mid-block.
+ raise_edges: frozenset[tuple[int, int]] = frozenset()
def __post_init__(self) -> None:
self._by_id: dict[int, BasicBlock] = {b.id: b for b in self.blocks}
@@ -211,6 +210,7 @@ class _CFGBuilder:
self._next_id = 0
self._loops: list[_LoopCtx] = []
self.exit_block: BasicBlock | None = None
+ self._raise_edges: set[tuple[int, int]] = set()
# -- low-level graph ops --------------------------------------------------
@@ -235,6 +235,15 @@ class _CFGBuilder:
for src in sources:
self._edge(src, dst)
+ def _raises_to(self, sources: list[BasicBlock], dst: BasicBlock) -> None:
+ self._edges_to(sources, dst)
+ self._raise_edges.update((src.id, dst.id) for src in sources)
+
+ def _protect(self, cur: BasicBlock, region: list[BasicBlock], dst: BasicBlock) -> None:
+ """*cur* reaches *dst* by its end state, *region*'s blocks from mid-block."""
+ self._edge(cur, dst)
+ self._raises_to(region, dst)
+
def _record_stmt(self, block: BasicBlock, node: Node) -> None:
block.statements.append(
Statement(node.type, node.start_point[0] + 1, node.end_point[0] + 1, node=node)
@@ -293,7 +302,12 @@ class _CFGBuilder:
out = self._process_seq(self._body_stmts(body), first)
if out is not None:
self._edge(out, self.exit_block)
- return CFG(blocks=self.blocks, entry_id=entry.id, exit_id=self.exit_block.id)
+ return CFG(
+ blocks=self.blocks,
+ entry_id=entry.id,
+ exit_id=self.exit_block.id,
+ raise_edges=frozenset(self._raise_edges),
+ )
def _process_seq(self, stmts: list[Node], cur: BasicBlock | None) -> BasicBlock | None:
"""Thread *stmts* onto *cur*, returning the fall-through block.
@@ -504,9 +518,9 @@ class _CFGBuilder:
body_out = self._process_seq(
self._body_stmts(try_node.child_by_field_name("body")), body_entry
)
- protected = [cur, *self.blocks[first:]]
+ protected = self.blocks[first:]
if finally_clause is not None:
- self._edges_to(protected, normal_join)
+ self._protect(cur, protected, normal_join)
# ``else`` runs only when the body completed without an exception; one
# raised inside it skips the handlers but still runs the ``finally``.
@@ -519,14 +533,14 @@ class _CFGBuilder:
if else_out is not None:
self._edge(else_out, normal_join)
if finally_clause is not None:
- self._edges_to(self.blocks[first:], normal_join)
+ self._raises_to(self.blocks[first:], normal_join)
elif body_out is not None:
self._edge(body_out, normal_join)
for handler in (c for c in try_node.children if c.type in self.lmap.catch_kinds):
first = len(self.blocks)
handler_entry = self._new("handler")
- self._edges_to(protected, handler_entry)
+ self._protect(cur, protected, handler_entry)
handler_out = self._process_seq(
self._body_stmts(self._block_of(handler)), handler_entry
)
@@ -534,7 +548,7 @@ class _CFGBuilder:
self._edge(handler_out, normal_join)
# A handler that returns or raises part-way still runs ``finally``.
if finally_clause is not None:
- self._edges_to(self.blocks[first:], normal_join)
+ self._raises_to(self.blocks[first:], normal_join)
return join
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/reaching.py b/packages/core/src/repowise/core/analysis/health/dataflow/reaching.py
index 9988adb2a..753707793 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/reaching.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/reaching.py
@@ -10,6 +10,7 @@ Per block ``b`` with predecessors ``pred(b)``::
GEN[b] = the last definition of each variable written in b
KILL[b] = every definition of any variable b writes, except GEN[b]
IN[b] = union over p in pred(b) of OUT[p]
+ (IN[p] union every def in p, on a raise edge p -> b)
OUT[b] = GEN[b] union (IN[b] minus KILL[b])
Definition sets are integer sets keyed by :attr:`defuse.Definition.index`, so
@@ -62,13 +63,10 @@ class ReachingDefinitions:
return [self.definitions[i] for i in sorted(idx)]
-def compute_reaching(
- cfg: CFG,
- fdu: FunctionDefUse,
- *,
- max_iterations: int | None = None,
-) -> ReachingDefinitions:
- """Run the reaching-definitions fixpoint over *cfg* with *fdu*'s def facts."""
+def _block_facts(
+ cfg: CFG, fdu: FunctionDefUse
+) -> tuple[dict[int, frozenset[int]], dict[int, frozenset[int]], dict[int, frozenset[int]]]:
+ """GEN, KILL and every definition written, per block."""
# All definitions of each variable -> the KILL sets.
defs_by_var: dict[str, set[int]] = {}
for d in fdu.definitions:
@@ -76,6 +74,7 @@ def compute_reaching(
gen: dict[int, frozenset[int]] = {}
kill: dict[int, frozenset[int]] = {}
+ every: dict[int, frozenset[int]] = {}
for block in cfg.blocks:
bdu = fdu.block(block.id)
block_defs = bdu.defs if bdu is not None else []
@@ -88,7 +87,20 @@ def compute_reaching(
for var in last_per_var:
killed |= defs_by_var.get(var, set())
gen[block.id] = gen_b
+ every[block.id] = frozenset(d.index for d in block_defs)
kill[block.id] = frozenset(killed) - gen_b
+ return gen, kill, every
+
+
+def compute_reaching(
+ cfg: CFG,
+ fdu: FunctionDefUse,
+ *,
+ max_iterations: int | None = None,
+) -> ReachingDefinitions:
+ """Run the reaching-definitions fixpoint over *cfg* with *fdu*'s def facts."""
+ gen, kill, every = _block_facts(cfg, fdu)
+ raise_srcs = {src for src, _dst in cfg.raise_edges}
in_sets: dict[int, frozenset[int]] = {b.id: frozenset() for b in cfg.blocks}
out_sets: dict[int, frozenset[int]] = {b.id: gen[b.id] for b in cfg.blocks}
@@ -112,11 +124,17 @@ def compute_reaching(
in_b: frozenset[int] = frozenset()
for pred in block.predecessors:
- in_b |= out_sets[pred]
+ # OUT[pred] is a subset of IN[pred] | every[pred].
+ if (pred, bid) in cfg.raise_edges:
+ in_b |= in_sets[pred] | every[pred]
+ else:
+ in_b |= out_sets[pred]
+ # A raise edge carries IN, so its target moves even when OUT does not.
+ in_moved = bid in raise_srcs and in_b != in_sets[bid]
in_sets[bid] = in_b
out_b = gen[bid] | (in_b - kill[bid])
- if out_b != out_sets[bid]:
+ if out_b != out_sets[bid] or in_moved:
out_sets[bid] = out_b
for succ in block.successors:
if succ not in queued:
diff --git a/tests/unit/health/test_dataflow_reaching.py b/tests/unit/health/test_dataflow_reaching.py
index e423eec86..474ecf1fd 100644
--- a/tests/unit/health/test_dataflow_reaching.py
+++ b/tests/unit/health/test_dataflow_reaching.py
@@ -338,6 +338,94 @@ def test_handler_assignment_reaches_finally_on_reraise():
assert 7 in reaching_lines
+def test_a_write_overwritten_later_in_the_try_body_reaches_the_handler():
+ cfg, def_use, reaching = _analyze(
+ """
+ def f():
+ try:
+ x = 1
+ y = g()
+ x = 2
+ except Exception:
+ return x
+ return x + y
+ """
+ )
+ (handler,) = [b for b in cfg.blocks if b.kind == "handler"]
+ # g() can raise after x = 1 and before x = 2.
+ assert {d.line for d in reaching.reaching_in(handler.id) if d.var == "x"} == {4, 6}
+ # The normal path still sees only the last write.
+ after = next(bid for bid, bdu in def_use.blocks.items() if any(u.line == 9 for u in bdu.uses))
+ assert {d.line for d in reaching.reaching_in(after) if d.var == "x"} == {6}
+
+
+def _lines_at(def_use, reaching, var: str, use_line: int) -> set[int]:
+ """Lines of the *var* definitions reaching the block that reads it at *use_line*."""
+ bid = next(b for b, bdu in def_use.blocks.items() if any(u.line == use_line for u in bdu.uses))
+ return {d.line for d in reaching.reaching_in(bid) if d.var == var}
+
+
+def test_handler_and_else_writes_overwritten_mid_block_reach_finally():
+ cfg, def_use, reaching = _analyze(
+ """
+ def f():
+ try:
+ a = g()
+ except Exception:
+ s = 1
+ s = h()
+ s = 2
+ raise
+ else:
+ e = 1
+ e = k()
+ e = 2
+ finally:
+ use(s, e)
+ """
+ )
+ assert cfg.raise_edges
+ assert {6, 8} <= _lines_at(def_use, reaching, "s", 15)
+ assert {11, 13} <= _lines_at(def_use, reaching, "e", 15)
+
+
+def test_an_inner_try_body_write_reaches_the_outer_handler():
+ cfg, def_use, reaching = _analyze(
+ """
+ def f():
+ try:
+ try:
+ x = 1
+ g()
+ x = 2
+ except ValueError:
+ pass
+ except Exception:
+ return x
+ return x
+ """
+ )
+ assert cfg.raise_edges
+ assert _lines_at(def_use, reaching, "x", 11) == {5, 7}
+
+
+def test_a_write_overwritten_before_the_try_does_not_reach_the_handler():
+ cfg, def_use, reaching = _analyze(
+ """
+ def f():
+ x = 0
+ x = 5
+ try:
+ g()
+ except Exception:
+ return x
+ return x
+ """
+ )
+ assert cfg.raise_edges
+ assert _lines_at(def_use, reaching, "x", 8) == {4}
+
+
def test_redefinition_kills_earlier_def():
cfg, _du, reaching = _analyze(
"""