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
refactor(health): split the walker helpers this week made too complex (#3546)
Raghav Chamadiyaf451d020c3d2
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.pyindex dad3e34db..a1776cb8b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py@@ -295,6 +295,48 @@ def _eh_node_kinds(language: str, lmap: LanguageNodeMap) -> frozenset[str]:return frozenset(kinds)+def _eh_swallow_allowed(noqa_codes: set[str] | None) -> bool:+ """Whether the clause's noqa codes leave a swallowed catch reportable."""+ return noqa_codes is None or (len(noqa_codes) > 0 and "S110" not in noqa_codes)+++def _eh_broad_except_hit(node: Node, noqa_codes: set[str] | None) -> ErrorHandlingHit | None:+ """The bare/broad except hit for a Python clause that does not re-raise,+ unless its noqa codes suppress that kind."""+ # ``except:`` / ``except BaseException:`` also swallow+ # KeyboardInterrupt & SystemExit; ``except Exception:`` cannot.+ is_base = _eh_catches_base(node)+ kind = "bare_except" if is_base else "broad_except"+ suppress = noqa_codes is not None and (+ len(noqa_codes) == 0+ or (kind == "broad_except" and "BLE001" in noqa_codes)+ or (kind == "bare_except" and bool(noqa_codes & {"BLE001", "E722"}))+ )+ return None if suppress else ErrorHandlingHit(kind, node.start_point[0] + 1)+++def _eh_catch_visit(node: Node, language: str, hits: list[ErrorHandlingHit]) -> None:+ """Append the swallowed-catch and bare/broad-except hits of one catch clause."""+ noqa_codes = _eh_noqa_codes(node) if language == "python" else None+ block = _eh_find_body_block(node)+ swallowed_unsuppressed = _eh_swallow_allowed(noqa_codes)+ if (+ block is not None+ and _eh_body_is_swallowed(block, language)+ and swallowed_unsuppressed+ and not (language == "java" and _eh_java_try_ends_in_fail(node, language))+ ):+ hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))+ if (+ language == "python"+ and _eh_is_bare_except(node)+ and not _eh_body_ends_in_raise(block, language)+ ):+ hit = _eh_broad_except_hit(node, noqa_codes)+ if hit is not None:+ hits.append(hit)++def _eh_visit(node: Node, language: str, lmap: LanguageNodeMap, hits: list[ErrorHandlingHit]) -> None:@@ -309,34 +351,7 @@ def _eh_visit("""catch_kinds = lmap.catch_kindsif catch_kinds and node.type in catch_kinds:- noqa_codes = _eh_noqa_codes(node) if language == "python" else None- block = _eh_find_body_block(node)- swallowed_unsuppressed = noqa_codes is None or (- len(noqa_codes) > 0 and "S110" not in noqa_codes- )- if (- block is not None- and _eh_body_is_swallowed(block, language)- and swallowed_unsuppressed- and not (language == "java" and _eh_java_try_ends_in_fail(node, language))- ):- hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))- if (- language == "python"- and _eh_is_bare_except(node)- and not _eh_body_ends_in_raise(block, language)- ):- # ``except:`` / ``except BaseException:`` also swallow- # KeyboardInterrupt & SystemExit; ``except Exception:`` cannot.- is_base = _eh_catches_base(node)- kind = "bare_except" if is_base else "broad_except"- suppress = noqa_codes is not None and (- len(noqa_codes) == 0- or (kind == "broad_except" and "BLE001" in noqa_codes)- or (kind == "bare_except" and bool(noqa_codes & {"BLE001", "E722"}))- )- if not suppress:- hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))+ _eh_catch_visit(node, language, hits)elif language == "rust" and _eh_rust_hit(node):# A panic-family macro aborts unconditionally; unwrap/expect converts# a Result/Option into a panic. Different claims → different kinds.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/gating.py b/packages/core/src/repowise/core/analysis/health/complexity/gating.pyindex 9a07119a9..a909d2fd7 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/gating.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/gating.py@@ -48,24 +48,27 @@ def _falsy_literal(node: Node | None) -> str | None:return "false" if node.type in _FALSE else "falsy"+def _declared_pairs(stmt: Node, language: str) -> list[tuple[Node | None, Node | None]]:+ """``(name, value)`` of a Python assignment or a TS/JS ``const``; empty otherwise."""+ node = stmt.named_children[0] if stmt.named_children else None+ if language == "python" and node is not None and node.type == "assignment":+ return [(node.child_by_field_name("left"), node.child_by_field_name("right"))]+ if stmt.type == "lexical_declaration" and stmt.children[0].type == "const":+ return [+ (d.child_by_field_name("name"), d.child_by_field_name("value"))+ for d in stmt.named_children+ if d.type == "variable_declarator"+ ]+ return []++def _declared(root: Node, language: str) -> dict[str, str]:"""Module-level ``NAME = <falsy literal>`` (Python) or ``const NAME = ...`` (TS/JS)."""out: dict[str, str] = {}for stmt in root.named_children:if stmt.type == "export_statement":stmt = stmt.child_by_field_name("declaration") or stmt- node = stmt.named_children[0] if stmt.named_children else None- if language == "python" and node is not None and node.type == "assignment":- pairs = [(node.child_by_field_name("left"), node.child_by_field_name("right"))]- elif stmt.type == "lexical_declaration" and stmt.children[0].type == "const":- pairs = [- (d.child_by_field_name("name"), d.child_by_field_name("value"))- for d in stmt.named_children- if d.type == "variable_declarator"- ]- else:- continue- for name, value in pairs:+ for name, value in _declared_pairs(stmt, language):kind = _falsy_literal(value)if name is not None and name.type == "identifier" and kind:out[_text(name)] = kinddiff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.pyindex 44f298978..6bcf8682e 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py@@ -26,7 +26,7 @@ from typing import TYPE_CHECKINGfrom ..perf.dialects import PERF_DIALECTSfrom ..perf.dialects.base import BasePerfDialect as BasePerfDialectClass-from ..perf.loop_facts import LoopFacts, LoopSource, combined_magnitude+from ..perf.loop_facts import BatchForm, LoopFacts, LoopSource, combined_magnitudefrom .ast_utils import (_dart_signature_sibling,_find_function_entry_name,@@ -557,6 +557,12 @@ def _collect_perf_hits(sources[key] = dialect.loop_source(loop, probe) or LoopSource()return sources[key]+ def sink_facts(node: Node, loop: Node, sink: bool) -> tuple[BatchForm | None, str | None]:+ """``(batch, concurrency_bound)`` of *node* in *loop*; both ``None`` off a sink."""+ batch = dialect.batch_form(node, loop, probe) if sink and do_batch else None+ bound = dialect.concurrency_bound(node, loop) if sink and do_bound else None+ return batch, bound+def loop_facts(node: Node, sink: bool, per_call: bool = False) -> LoopFacts | None:"""Facts of *node*'s innermost loop; batch and bound only mean something at a sink.@@ -569,13 +575,14 @@ def _collect_perf_hits(if not loops:return Noneloop = loops[0]+ chunked = do_chunked and dialect.is_chunked_loop(loop)+ magnitude = combined_magnitude([source(lp) for lp in loops]) if do_magnitude else "unknown"+ batch, bound = sink_facts(node, loop, sink)facts = LoopFacts(- chunked=do_chunked and dialect.is_chunked_loop(loop),- magnitude=(- combined_magnitude([source(lp) for lp in loops]) if do_magnitude else "unknown"- ),- batch=dialect.batch_form(node, loop, probe) if sink and do_batch else None,- concurrency_bound=dialect.concurrency_bound(node, loop) if sink and do_bound else None,+ chunked=chunked,+ magnitude=magnitude,+ batch=batch,+ concurrency_bound=bound,# Only a native loop header names its key; a block loop (Ruby# ``each do |row|``) claims nothing, as before it carried loop facts.key_unused=per_call and loop.type in loop_kinds and not _loop_key_feeds(node, loop),diff --git a/packages/core/src/repowise/core/analysis/health/perf/reduction_idioms.py b/packages/core/src/repowise/core/analysis/health/perf/reduction_idioms.pyindex ea6b4fbb1..50eda76ef 100644--- a/packages/core/src/repowise/core/analysis/health/perf/reduction_idioms.py+++ b/packages/core/src/repowise/core/analysis/health/perf/reduction_idioms.py@@ -122,6 +122,23 @@ def _adds_to(stmts: list[Node], container: str, keys: frozenset[str]) -> bool:)+def _stores_value(node: Node, values: frozenset[str]) -> bool:+ """``x.add/append/extend(v)`` or ``x[...] = v`` with *v* reading *values*."""+ call = _method_call(node)+ if call and call[1] in ("add", "append", "extend") and any(+ references(arg, values) for arg in call[2]+ ):+ return True+ left = node.child_by_field_name("left") if node.type == "assignment" else None+ right = node.child_by_field_name("right") if left is not None else None+ return (+ left is not None+ and right is not None+ and left.type == "subscript"+ and references(right, values)+ )++def _keeps_every_row(stmts: list[Node], values: frozenset[str]) -> bool:"""Whether an unguarded statement stores each iterated row."""nested_loops = frozenset({"for_statement", "while_statement"})@@ -132,19 +149,7 @@ def _keeps_every_row(stmts: list[Node], values: frozenset[str]) -> bool:if guarded:continuenode = next((c for c in stmt.children if c.is_named), stmt)- call = _method_call(node)- if call and call[1] in ("add", "append", "extend") and any(- references(arg, values) for arg in call[2]- ):- return True- left = node.child_by_field_name("left") if node.type == "assignment" else None- right = node.child_by_field_name("right") if left is not None else None- if (- left is not None- and right is not None- and left.type == "subscript"- and references(right, values)- ):+ if _stores_value(node, values):return Truereturn False