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): include Python loop else branches in CFG (#3424)
goudan99b4d06f9121
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.pyindex b8db9b9c3..7e85a1f44 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py@@ -453,7 +453,6 @@ class _CFGBuilder:body_entry = self._new()self._edge(header, body_entry) # enter the loop body- self._edge(header, after) # skip / exhaust the loopself._loops.append(_LoopCtx(continue_target=header, break_target=after))body_out = self._process_seq(@@ -463,6 +462,19 @@ class _CFGBuilder:if body_out is not None:self._edge(body_out, header) # back-edge++ # Python's for/while else runs on exhaustion, but not on break. Keep+ # break targeting ``after`` while routing the header's exhaustion edge+ # through the else body. Loops without an alternative keep their direct edge.+ alternative = loop_node.child_by_field_name("alternative")+ if alternative is None:+ self._edge(header, after)+ else:+ else_entry = self._new()+ self._edge(header, else_entry)+ else_out = self._process_seq(self._body_stmts(self._block_of(alternative)), else_entry)+ if else_out is not None:+ self._edge(else_out, after)return afterdef _build_with(self, with_node: Node, cur: BasicBlock) -> BasicBlock | None:diff --git a/tests/fixtures/refactoring_corpus/golden_extractions.json b/tests/fixtures/refactoring_corpus/golden_extractions.jsonindex 616cc7d22..9acf3100f 100644--- a/tests/fixtures/refactoring_corpus/golden_extractions.json+++ b/tests/fixtures/refactoring_corpus/golden_extractions.json@@ -484,6 +484,7 @@"ccn_removed": 2,"end_line": 173,"params": [+ "limit","rows"],"returns": [@@ -496,6 +497,7 @@"ccn_removed": 2,"end_line": 173,"params": [+ "limit","rows"],"returns": [@@ -505,28 +507,28 @@"start_line": 160},{- "ccn_removed": 2,+ "ccn_removed": 1,"end_line": 173,"params": [- "rows"+ "limit",+ "total"+ ],+ "returns": [+ "flag"],- "returns": [],- "slice_nloc": 12,- "start_line": 161- },- {- "ccn_removed": 1,- "end_line": 173,- "params": [],- "returns": [],"slice_nloc": 8,"start_line": 166},{"ccn_removed": 1,"end_line": 172,- "params": [],- "returns": [],+ "params": [+ "limit",+ "total"+ ],+ "returns": [+ "flag"+ ],"slice_nloc": 7,"start_line": 166}diff --git a/tests/unit/health/test_dataflow_cfg.py b/tests/unit/health/test_dataflow_cfg.pyindex d6e2ebfef..2c17a7e86 100644--- a/tests/unit/health/test_dataflow_cfg.py+++ b/tests/unit/health/test_dataflow_cfg.py@@ -223,6 +223,70 @@ def test_for_loop_shape():assert cfg.back_edges()[email protected]("loop_head", ["for item in items:", "while items:"])+def test_python_loop_else_runs_on_exhaustion(loop_head):+ cfg = _cfg(+ f"""+ def f(items):+ {loop_head}+ process(items)+ else:+ completed = finish()+ return completed+ """+ )+ header = _by_kind(cfg, "loop_header")[0]+ after = _by_kind(cfg, "loop_exit")[0]+ else_blocks = [+ block+ for block in cfg.blocks+ if any(+ not statement.is_head+ and statement.node is not None+ and b"completed = finish()" in statement.node.text+ for statement in block.statements+ )+ ]+ assert len(else_blocks) == 1+ else_block = else_blocks[0]+ assert else_block.id in header.successors+ assert after.id in else_block.successors+ assert after.id not in header.successors+++def test_python_loop_break_skips_else():+ cfg = _cfg(+ """+ def f(items):+ for item in items:+ if item:+ break+ else:+ completed = finish()+ return 0+ """+ )+ header = _by_kind(cfg, "loop_header")[0]+ after = _by_kind(cfg, "loop_exit")[0]+ break_block = next(+ block+ for block in cfg.blocks+ if any(statement.kind == "break_statement" for statement in block.statements)+ )+ else_block = next(+ block+ for block in cfg.blocks+ if any(+ statement.node is not None and b"completed = finish()" in statement.node.text+ for statement in block.statements+ if not statement.is_head+ )+ )+ assert else_block.predecessors == [header.id]+ assert break_block.successors == [after.id]+ assert else_block.id not in break_block.successors++# -- with statements -----------------------------------------------------------diff --git a/tests/unit/health/test_dataflow_reaching.py b/tests/unit/health/test_dataflow_reaching.pyindex 474ecf1fd..f7976eabe 100644--- a/tests/unit/health/test_dataflow_reaching.py+++ b/tests/unit/health/test_dataflow_reaching.py@@ -17,6 +17,7 @@ from repowise.core.analysis.health.dataflow import (analyze_function,compute_def_use,compute_reaching,+ find_extractions,)from repowise.core.analysis.health.dataflow.dialects.base import get_defuse_dialect@@ -74,6 +75,61 @@ def test_simple_assignment():assert "a" in uses[email protected]("loop_head", ["for item in items:", "while items:"])+def test_python_loop_else_body_contributes_to_dataflow(loop_head):+ cfg, def_use, reaching = _analyze(+ f"""+ def f(items):+ {loop_head}+ consume(items)+ else:+ done = flush()+ return done+ """+ )+ assert "done" in {definition.var for definition in def_use.definitions}+ assert "flush" in {use.name for block in def_use.blocks.values() for use in block.uses}+ return_block = next(+ block+ for block in cfg.blocks+ if any(statement.kind == "return_statement" for statement in block.statements)+ )+ assert "done" in {definition.var for definition in reaching.reaching_in(return_block.id)}+++def test_loop_else_read_is_returned_by_extract_method():+ source = """def pick(items, limit, extra):+ bound = 0+ for it in extra:+ if it > limit:+ bound += 1+ if it < 0:+ bound -= 1+ if it == 0:+ bound += 2+ elif it == 1:+ bound += 3+ if bound > 3:+ bound = 3+ if bound < 0:+ bound = 0+ for x in items:+ if x > limit:+ break+ else:+ use(bound)+"""+ result = analyze_file("m.py", "python", source.encode(), flagged_only=False)+ assert result.functions+ candidates = [+ candidate+ for candidate in find_extractions(result.functions[0], get_language_map("python"))+ if candidate.end_line == 15+ ]+ assert candidates+ assert all("bound" in candidate.returns for candidate in candidates)++def test_augmented_assignment_is_def_and_use():defs, uses = _def_use_names("""