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(dead-code): avoid false JSX prop guard findings (#2534)
Just One More Night8db3800d0d73
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 4e3a2fe89..c4ac684ff 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -1772,7 +1772,11 @@ class DeadCodeAnalyzer:}def _get_unsatisfied_prop_guard(- self, sym_id: str, sym_name: str, visited: set[str] | None = None+ self,+ sym_id: str,+ sym_name: str,+ visited: set[str] | None = None,+ memo: dict[str, tuple[str, str] | None] | None = None,) -> tuple[str, str] | None:"""Check if a symbol is rendered behind a prop guard that is never supplied."""if not self.graph.has_node(sym_id):@@ -1780,6 +1784,10 @@ class DeadCodeAnalyzer:if visited is None:visited = set()+ if memo is None:+ memo = {}+ if sym_id in memo:+ return memo[sym_id]if sym_id in visited:return Nonevisited.add(sym_id)@@ -1791,8 +1799,10 @@ class DeadCodeAnalyzer:if self.graph[pred][sym_id].get("edge_type") in REACHABILITY_USE_EDGE_TYPES]if not predecessors:+ memo[sym_id] = Nonereturn None+ resolved_guards: list[tuple[str, str]] = []for pred in predecessors:pred_file = pred.split("::")[0] if "::" in pred else predif not pred_file.endswith((".tsx", ".jsx", ".ts", ".js")):@@ -1828,14 +1838,28 @@ class DeadCodeAnalyzer:all_missing = Falsebreakif all_missing:- return (prop_name, parent_name)+ resolved_guards.append((prop_name, parent_name))+ continuepred_name = pred.split("::")[-1]- parent_guard = self._get_unsatisfied_prop_guard(pred, pred_name, visited)- if parent_guard is not None:- return parent_guard-- return None+ parent_guard = self._get_unsatisfied_prop_guard(+ pred, pred_name, set(visited), memo+ )+ if parent_guard is None:+ memo[sym_id] = None+ return None+ resolved_guards.append(parent_guard)++ # One blocked route is insufficient: any unguarded or satisfied route+ # keeps the symbol reachable. Report only when every predecessor path+ # resolves to an unsatisfied guard.+ result = (+ resolved_guards[0]+ if resolved_guards and len(resolved_guards) == len(predecessors)+ else None+ )+ memo[sym_id] = result+ return resultdef _file_line_count(self, file_path: str) -> int | None:"""Physical line count of an indexed file, or ``None`` when unread.diff --git a/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.pyindex 6a55fa9eb..97d8666d4 100644--- a/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py+++ b/packages/core/src/repowise/core/analysis/dead_code/jsx_prop_guards.py@@ -57,8 +57,7 @@ def extract_guarded_jsx_renders(if c.type == "property_identifier":prop_text = _node_text(c)if (- obj_text in ("props", "this.props", "self.props")- or obj_text.endswith(".props")+ obj_text in ("props", "this.props", "self.props") or obj_text.endswith(".props")) and prop_text:return [prop_text]elif n.type == "identifier":@@ -151,6 +150,11 @@ def extract_guarded_jsx_renders("pair_pattern","variable_declarator","rest_pattern",+ "formal_parameters",+ "parameters",+ "required_parameter",+ "optional_parameter",+ "assignment_pattern",):for c in n.children:if c.type not in (":", "=", ",", "[", "]", "{", "}", "...", "var", "let", "const"):@@ -210,8 +214,26 @@ def extract_guarded_jsx_renders(return param_props if has_destructured_param else None- def _collect_function_local_vars(fn_node: Any) -> set[str]:+ def _collect_function_param_names(fn_node: Any) -> set[str]:+ for c in fn_node.children:+ if c.type in ("formal_parameters", "parameters"):+ return set(_extract_bound_names(c))+ single_param = fn_node.child_by_field_name("parameter")+ if single_param is not None:+ return set(_extract_bound_names(single_param))+ return set()++ def _collect_function_local_vars(+ fn_node: Any, inherited_vars: set[str] | None = None+ ) -> set[str]:+ # A nested callback closes over the variables in its enclosing+ # component. Keep those names in scope while adding declarations from+ # the callback itself; otherwise ``show && <Child />`` inside a+ # callback is mistaken for a prop guard even when ``show`` is local+ # state in the component.local_vars: set[str] = set(module_vars)+ if inherited_vars:+ local_vars.update(inherited_vars)def _scan(n: Any) -> None:if n != fn_node and n.type in (@@ -237,6 +259,7 @@ def extract_guarded_jsx_renders(current_fn: str | None = None,local_vars: set[str] | None = None,param_props: set[str] | None = None,+ function_depth: int = 0,) -> None:current_local_vars = local_varscurrent_param_props = param_props@@ -258,8 +281,15 @@ def extract_guarded_jsx_renders(fn_name = _node_text(c)breakcurrent_fn = fn_name or "Anonymous"- current_local_vars = _collect_function_local_vars(n)- current_param_props = _collect_function_param_props(n)+ current_local_vars = _collect_function_local_vars(n, local_vars)+ current_param_props = set(param_props or ())+ current_param_props.update(_collect_function_param_props(n) or ())+ if function_depth > 0:+ # A callback parameter can shadow an outer destructured prop.+ # Treat only the callback's own bindings as locals; the outer+ # component's destructured props remain eligible guards.+ current_local_vars.update(_collect_function_param_names(n))+ function_depth += 1if n.type == "binary_expression":op = None@@ -298,7 +328,13 @@ def extract_guarded_jsx_renders(results.append((current_fn, target, prop_name))for child in n.children:- _walk(child, current_fn, current_local_vars, current_param_props)+ _walk(+ child,+ current_fn,+ current_local_vars,+ current_param_props,+ function_depth,+ )_walk(tree.root_node)return resultsdiff --git a/tests/unit/dead_code/test_jsx_prop_guard_dead_code.py b/tests/unit/dead_code/test_jsx_prop_guard_dead_code.pyindex 97404de7c..c2d860b6f 100644--- a/tests/unit/dead_code/test_jsx_prop_guard_dead_code.py+++ b/tests/unit/dead_code/test_jsx_prop_guard_dead_code.py@@ -9,6 +9,66 @@ from repowise.core.analysis.dead_code import (from tests.unit.dead_code._helpers import _build_graph+def test_jsx_prop_guard_keeps_outer_scope_inside_callbacks():+ from repowise.core.analysis.dead_code.jsx_prop_guards import (+ extract_guarded_jsx_renders,+ )++ local_state = """+function A() {+ const [show] = useState(false);+ return items.map(() => show && <Child />);+}+"""+ outer_prop = """+function A({ show }) {+ return items.map(() => show && <Child />);+}+"""+ shadowed_callback_param = """+function A({ show }) {+ return items.map(show => show && <Child />);+}+"""+ assert extract_guarded_jsx_renders("A.tsx", local_state) == []+ assert ("A", "Child", "show") in extract_guarded_jsx_renders("A.tsx", outer_prop)+ assert extract_guarded_jsx_renders("A.tsx", shadowed_callback_param) == []+++def test_jsx_prop_guard_does_not_hide_an_unguarded_use(tmp_path):+ a_file = tmp_path / "A.tsx"+ c_file = tmp_path / "C.tsx"+ child_file = tmp_path / "Child.tsx"+ app_file = tmp_path / "App.tsx"+ a_file.write_text("function A(props) { return props.flag && <Child />; }")+ c_file.write_text("function C() { return <Child />; }")+ child_file.write_text("export function Child() { return null; }")+ graph = _build_graph(+ nodes={+ str(a_file): {"is_test": False, "symbols": [{"name": "A", "kind": "function"}]},+ str(c_file): {"is_test": False, "symbols": [{"name": "C", "kind": "function"}]},+ str(child_file): {"is_test": False, "symbols": [{"name": "Child", "kind": "function"}]},+ str(app_file): {"is_test": False, "symbols": [{"name": "App", "kind": "function"}]},+ },+ edges=[+ (f"{a_file}::A", f"{child_file}::Child", {"edge_type": "calls"}),+ (f"{c_file}::C", f"{child_file}::Child", {"edge_type": "calls"}),+ (+ f"{app_file}::App",+ f"{a_file}::A",+ {"edge_type": "calls", "supplied_props": frozenset()},+ ),+ (+ f"{app_file}::App",+ f"{c_file}::C",+ {"edge_type": "calls", "supplied_props": frozenset()},+ ),+ ],+ )+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})+ assert analyzer._get_unsatisfied_prop_guard(f"{child_file}::Child", "Child") is None++def test_jsx_prop_guard_unsatisfied_reported(tmp_path):"""Component B behind flag in Component A should be reported when A is rendered without flag."""a_content = """