From 08f4fe7f55f6f777b583f13b0b5d5ccb13104af4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:49:18 +0000 Subject: [PATCH] Stop the Python lowering dropping the sub-expressions that read names Many Python visitors built their IR node without visiting what was inside it: list/tuple/dict/set literals, f-string slots, `*xs`, the index of a subscript, the receiver of a method call, the target of `xs[i] = v`, `del d[k]`, `assert`, `raise`, `yield`, `match` subjects, `while ... else`, and the decorators, defaults and bases of a definition. Every name read only in one of those places was reported as "Assigned but never read", including `start` in the Python sample the web UI loads by default, `logger` in `logger.info(msg)`, `i` in `return xs[i]`, `name` in `f"hi {name}"`, and every callback parameter called as `fn(x)`. Calls in the same places were missing from the call graph, and `memo[n] = ...` was read as a new local shadowing `memo`. The visitors now descend into those children. Decorators, defaults and base classes are emitted before the definition, since they run in the enclosing scope, so `@app.route(...)` is not a call `index` makes. A subscript store no longer counts as a binding, and a plain call counts as a read of its callee. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UigC7feaY8NkAy9oay3GDW --- explain_my_code/adapters/python.py | 152 ++++++++++++++++++---------- explain_my_code/analysis/symbols.py | 11 +- tests/test_analysis.py | 71 +++++++++++++ 3 files changed, 180 insertions(+), 54 deletions(-) diff --git a/explain_my_code/adapters/python.py b/explain_my_code/adapters/python.py index 02a287d..c44265b 100644 --- a/explain_my_code/adapters/python.py +++ b/explain_my_code/adapters/python.py @@ -212,6 +212,36 @@ def generic(self, node: ast.AST) -> list[Node]: def children_of(self, node: ast.AST) -> list[Node]: return self.generic(node) + def target_reads(self, target: ast.AST) -> list[Node]: + """What an assignment target reads, as opposed to binds. + + `xs[i] = v` binds nothing: it reads `xs` and `i`. `obj.x = v` reads `obj`. A bare + name, or a name inside a tuple being unpacked, is a binding and is skipped. + """ + if isinstance(target, (ast.Tuple, ast.List)): + return [n for element in target.elts for n in self.target_reads(element)] + if isinstance(target, ast.Starred): + return self.target_reads(target.value) + if isinstance(target, (ast.Subscript, ast.Attribute)): + return self.visit(target) + return [] + + def definition_time_reads(self, node: ast.AST) -> list[Node]: + """Expressions a `def` or `class` statement evaluates where it stands. + + Decorators, parameter defaults and base classes run in the enclosing scope when + the definition executes, not inside the body. They come back as siblings that + precede the definition, so `@app.get(...)` reads `app` at module level instead + of looking like a call made by the decorated function. + """ + expressions: list[ast.AST] = list(getattr(node, "decorator_list", [])) + if isinstance(node, ast.ClassDef): + expressions += [*node.bases, *(k.value for k in node.keywords)] + else: + arguments = node.args # type: ignore[attr-defined] + expressions += [*arguments.defaults, *(d for d in arguments.kw_defaults if d)] + return [n for expression in expressions for n in self.visit(expression)] + # -- definitions ---------------------------------------------------------- def _function(self, node: ast.FunctionDef | ast.AsyncFunctionDef, is_async: bool) -> list[Node]: @@ -265,7 +295,7 @@ def _function(self, node: ast.FunctionDef | ast.AsyncFunctionDef, is_async: bool ) ) fn.extend(self.visit_body(node.body, owns_docstring=True)) - return [fn] + return [*self.definition_time_reads(node), fn] def visit_FunctionDef(self, node: ast.FunctionDef) -> list[Node]: return self._function(node, is_async=False) @@ -309,7 +339,7 @@ def visit_ClassDef(self, node: ast.ClassDef) -> list[Node]: if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)): stmt._emc_in_class = True # type: ignore[attr-defined] cls.extend(self.visit_body(node.body, owns_docstring=True)) - return [cls] + return [*self.definition_time_reads(node), cls] def visit_Lambda(self, node: ast.Lambda) -> list[Node]: params = _params(node.args) @@ -429,6 +459,8 @@ def visit_While(self, node: ast.While) -> list[Node]: ) loop.extend(self.visit(node.test)) loop.extend(self.visit_body(node.body)) + if node.orelse: + loop.extend(self.visit_body(node.orelse)) return [loop] def visit_Break(self, node: ast.Break) -> list[Node]: @@ -452,14 +484,14 @@ def visit_Return(self, node: ast.Return) -> list[Node]: return [ret] def _yield(self, node: ast.Yield | ast.YieldFrom, delegated: bool) -> list[Node]: - return [ - Node( - kind=Kind.YIELD, - span=_span(node), - name="yield", - meta={"value": _repr(node.value), "delegated": delegated}, - ) - ] + yielded = Node( + kind=Kind.YIELD, + span=_span(node), + name="yield", + meta={"value": _repr(node.value), "delegated": delegated}, + ) + yielded.extend(self.children_of(node)) + return [yielded] def visit_Yield(self, node: ast.Yield) -> list[Node]: return self._yield(node, delegated=False) @@ -469,16 +501,16 @@ def visit_YieldFrom(self, node: ast.YieldFrom) -> list[Node]: def visit_Raise(self, node: ast.Raise) -> list[Node]: exc = _callee_name(node.exc.func) if isinstance(node.exc, ast.Call) else _repr(node.exc, 32) - return [ - Node( - kind=Kind.THROW, - span=_span(node), - name="raise", - meta={"exception": exc, "reraises": node.exc is None, - "message": _repr(node.exc.args[0], 48) - if isinstance(node.exc, ast.Call) and node.exc.args else ""}, - ) - ] + throw = Node( + kind=Kind.THROW, + span=_span(node), + name="raise", + meta={"exception": exc, "reraises": node.exc is None, + "message": _repr(node.exc.args[0], 48) + if isinstance(node.exc, ast.Call) and node.exc.args else ""}, + ) + throw.extend(self.children_of(node)) + return [throw] def visit_Try(self, node: ast.Try) -> list[Node]: try_node = Node( @@ -557,6 +589,7 @@ def visit_Match(self, node: ast.Match) -> list[Node]: name="match", meta={"subject": _repr(node.subject, 40), "case_count": len(node.cases)}, ) + match_node.extend(self.visit(node.subject)) for case in node.cases: case_node = Node( kind=Kind.CASE, @@ -567,6 +600,8 @@ def visit_Match(self, node: ast.Match) -> list[Node]: "has_guard": case.guard is not None, }, ) + if case.guard is not None: + case_node.extend(self.visit(case.guard)) case_node.extend(self.visit_body(case.body)) match_node.add(case_node) return [match_node] @@ -595,6 +630,8 @@ def visit_Assign(self, node: ast.Assign) -> list[Node]: }, ) assign.extend(self.visit(node.value)) + for target in node.targets: + assign.extend(self.target_reads(target)) return [assign] def visit_AnnAssign(self, node: ast.AnnAssign) -> list[Node]: @@ -610,6 +647,7 @@ def visit_AnnAssign(self, node: ast.AnnAssign) -> list[Node]: ) if node.value is not None: decl.extend(self.visit(node.value)) + decl.extend(self.target_reads(node.target)) return [decl] def visit_AugAssign(self, node: ast.AugAssign) -> list[Node]: @@ -626,6 +664,7 @@ def visit_AugAssign(self, node: ast.AugAssign) -> list[Node]: }, ) aug.extend(self.visit(node.value)) + aug.extend(self.target_reads(node.target)) return [aug] def visit_Call(self, node: ast.Call) -> list[Node]: @@ -646,6 +685,12 @@ def visit_Call(self, node: ast.Call) -> list[Node]: "qualified": _repr(node.func, 48), }, ) + # The callee itself is this node's name, but whatever it hangs off is a real + # read: the receiver in `logger.info(...)`, the inner call in `helper().strip()`. + if isinstance(node.func, ast.Attribute): + call.extend(self.visit(node.func.value)) + elif not isinstance(node.func, ast.Name): + call.extend(self.visit(node.func)) for arg in [*node.args, *[k.value for k in node.keywords]]: call.extend(self.visit(arg)) return [call] @@ -717,6 +762,7 @@ def visit_Subscript(self, node: ast.Subscript) -> list[Node]: }, ) sub.extend(self.visit(node.value)) + sub.extend(self.visit(node.slice)) return [sub] def visit_Attribute(self, node: ast.Attribute) -> list[Node]: @@ -792,15 +838,15 @@ def visit_UnaryOp(self, node: ast.UnaryOp) -> list[Node]: return [unop] def _collection(self, node: ast.AST, coll_type: str, size: int) -> list[Node]: - return [ - Node( - kind=Kind.COLLECTION, - span=_span(node), - name=coll_type, - meta={"collection_type": coll_type, "size": size, - "is_empty": size == 0, "value": _repr(node, 40)}, - ) - ] + collection = Node( + kind=Kind.COLLECTION, + span=_span(node), + name=coll_type, + meta={"collection_type": coll_type, "size": size, + "is_empty": size == 0, "value": _repr(node, 40)}, + ) + collection.extend(self.children_of(node)) + return [collection] def visit_List(self, node: ast.List) -> list[Node]: return self._collection(node, "list", len(node.elts)) @@ -816,27 +862,29 @@ def visit_Dict(self, node: ast.Dict) -> list[Node]: def visit_JoinedStr(self, node: ast.JoinedStr) -> list[Node]: slots = [f for f in node.values if isinstance(f, ast.FormattedValue)] - return [ - Node( - kind=Kind.FSTRING, - span=_span(node), - name="f-string", - meta={"slot_count": len(slots), - "slots": [_repr(s.value, 24) for s in slots]}, - ) - ] + fstring = Node( + kind=Kind.FSTRING, + span=_span(node), + name="f-string", + meta={"slot_count": len(slots), + "slots": [_repr(s.value, 24) for s in slots]}, + ) + for slot in slots: + fstring.extend(self.visit(slot.value)) + return [fstring] def visit_Starred(self, node: ast.Starred) -> list[Node]: - return [ - Node(kind=Kind.SPREAD, span=_span(node), name="*", - meta={"value": _repr(node.value, 32)}) - ] + spread = Node(kind=Kind.SPREAD, span=_span(node), name="*", + meta={"value": _repr(node.value, 32)}) + spread.extend(self.visit(node.value)) + return [spread] def visit_Delete(self, node: ast.Delete) -> list[Node]: - return [ - Node(kind=Kind.DELETE, span=_span(node), name="del", - meta={"targets": [_repr(t, 24) for t in node.targets]}) - ] + delete = Node(kind=Kind.DELETE, span=_span(node), name="del", + meta={"targets": [_repr(t, 24) for t in node.targets]}) + for target in node.targets: + delete.extend(self.target_reads(target)) + return [delete] def visit_Global(self, node: ast.Global) -> list[Node]: return [ @@ -851,12 +899,12 @@ def visit_Nonlocal(self, node: ast.Nonlocal) -> list[Node]: ] def visit_Assert(self, node: ast.Assert) -> list[Node]: - return [ - Node(kind=Kind.THROW, span=_span(node), name="assert", - meta={"exception": "AssertionError", "is_assert": True, - "condition": _repr(node.test, 40), - "message": _repr(node.msg, 40)}) - ] + check = Node(kind=Kind.THROW, span=_span(node), name="assert", + meta={"exception": "AssertionError", "is_assert": True, + "condition": _repr(node.test, 40), + "message": _repr(node.msg, 40)}) + check.extend(self.children_of(node)) + return [check] # -- module system ----------------------------------------------------------- diff --git a/explain_my_code/analysis/symbols.py b/explain_my_code/analysis/symbols.py index 877c8cf..29a6332 100644 --- a/explain_my_code/analysis/symbols.py +++ b/explain_my_code/analysis/symbols.py @@ -139,8 +139,9 @@ def _bindings_of(node: Node) -> list[tuple[str, str]]: targets = node.meta.get("targets") or ([node.meta["name"]] if node.meta.get("name") else []) for target in targets: base = str(target).split("[")[0].split(".")[0].strip("()* ") - # `self.x = 1` binds an attribute, not a local; skip the receiver. - if base and base.isidentifier() and "." not in str(target): + # `self.x = 1` binds an attribute and `memo[n] = 1` stores into a container + # that already exists: neither introduces a new local. + if base and base.isidentifier() and not any(c in str(target) for c in ".["): out.append((base, "variable")) return out @@ -199,6 +200,12 @@ def visit(node: Node, scope: Scope) -> None: symbol = inner.lookup(child.name or "") if symbol is not None: symbol.used_at.append(child.span) + elif child.kind is Kind.CALL and not child.meta.get("receiver"): + # A plain call `fn(x)` reads `fn`. Python keeps the callee only as the + # call's name, so a callback parameter would otherwise look unused. + symbol = inner.lookup(str(child.meta.get("callee") or "")) + if symbol is not None: + symbol.used_at.append(child.span) visit(child, inner) visit(root, root_scope) diff --git a/tests/test_analysis.py b/tests/test_analysis.py index 87d8b2c..bbb65a9 100644 --- a/tests/test_analysis.py +++ b/tests/test_analysis.py @@ -247,6 +247,77 @@ def test_unused_local_is_reported(): assert "unused" in {symbol.name for symbol in analysis.symbols.unused} +@pytest.mark.parametrize( + "source", + [ + "def log(msg):\n logger = get_logger()\n logger.info(msg)\n", + "def get(xs, i):\n return xs[i]\n", + "def head(xs, n):\n return xs[:n]\n", + "def fill(xs, i, v):\n xs[i] = v\n", + "def setx(obj, v):\n obj.x = v\n", + "def bump(d, k):\n d[k] += 1\n", + "def drop(d, k):\n del d[k]\n", + "def pair(a, b):\n return [a, b]\n", + "def pair(a, b):\n return a, b\n", + "def entry(k, v):\n return {k: v}\n", + "def copy(xs):\n return [*xs]\n", + 'def greet(name):\n return f"hi {name}"\n', + "def apply(fn, x):\n return fn(x)\n", + "def dispatch(handlers, name, x):\n return handlers[name](x)\n", + "def check(x, why):\n assert x > 0, why\n", + "def fail(err, msg):\n raise ValueError(msg) from err\n", + "def gen(x):\n yield x\n", + 'def route(cmd, verbose):\n match cmd:\n case "go" if verbose:\n return 1\n', + "LIMIT = 5\n\ndef take(n=LIMIT):\n return n\n", + 'app = Flask(__name__)\n\n@app.route("/")\ndef index():\n return "hi"\n', + "Base = make_base()\n\nclass Model(Base):\n pass\n", + ], + ids=["method-receiver", "index", "slice", "index-store", "attribute-store", "index-augassign", + "del-index", "list", "tuple", "dict", "starred", "f-string", "callback", "subscript-call", + "assert", "raise-from", "yield", "match", "default-value", "decorator", "base-class"], +) +def test_python_reads_are_not_reported_as_unused(source): + """Each of these reads every name it binds. The Python lowering used to drop the + sub-expression doing the reading, which made the name look assigned-but-unread.""" + assert [symbol.name for symbol in analyze(source).symbols.unused] == [] + + +def test_storing_into_a_container_does_not_shadow_it(): + analysis = analyze(""" +memo = {} + +def fib(n): + if n in memo: + return memo[n] + memo[n] = fib(n - 1) + fib(n - 2) + return memo[n] +""") + assert "shadowed-name" not in rules(analysis) + + +@pytest.mark.parametrize( + "source,caller,callee", + [ + ("def go():\n return helper().strip()\n\ndef helper():\n return ''\n", "go", "helper"), + ("def go(x):\n return [helper(x)]\n\ndef helper(x):\n return x\n", "go", "helper"), + ("def go(xs):\n while xs:\n xs.pop()\n else:\n helper()\n\n" + "def helper():\n return 1\n", "go", "helper"), + ("def go():\n raise make_error()\n\ndef make_error():\n return ValueError()\n", + "go", "make_error"), + ], + ids=["chained-call", "call-in-list", "while-else", "raised-call"], +) +def test_python_call_graph_sees_nested_calls(source, caller, callee): + graph = analyze(source).call_graph + assert f"module.{callee}" in graph.edges[f"module.{caller}"] + + +def test_decorator_calls_belong_to_the_enclosing_scope(): + """`@app.route(...)` runs at definition time, so it is not a call `index` makes.""" + analysis = analyze('app = Flask(__name__)\n\n@app.route("/")\ndef index():\n return "hi"\n') + assert analysis.call_graph.edges["module.index"] == [] + + def test_underscore_prefixed_names_are_left_alone(): analysis = analyze("def go():\n _ignored = 1\n return 2\n") assert "_ignored" not in {symbol.name for symbol in analysis.symbols.unused}