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.

feat(graph): record functions passed as values so registrations show as callers (#3197)

Raghav Chamadiyac6d8dbb46a50
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/base.py b/packages/core/src/repowise/core/ingestion/framework_edges/base.py
index c431316a8..7e48e6dca 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/base.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/base.py
@@ -95,8 +95,12 @@ def add_symbol_edge(graph: nx.DiGraph, source: str, target: str) -> bool:
data = graph.nodes.get(node)
if data is None or data.get("node_type") != "symbol":
return False
- if graph.has_edge(source, target):
- return False
+ existing = graph.get_edge_data(source, target)
+ if existing is not None:
+ # A binding says the target runs, which outranks a bare mention of it.
+ if existing.get("edge_type") != "references":
+ return False
+ graph.remove_edge(source, target)
graph.add_edge(
source,
target,
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 9c6974b80..e136e3bc0 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -23,9 +23,11 @@ log = structlog.get_logger(__name__)
_MIN_REFERENCE_CONFIDENCE = 0.85
#: Symbol kinds a resolved reference may land on, by how the name was spelled.
-#: See ``_add_reference_edges`` for why a bare name is restricted to functions.
-_BARE_REFERENCE_KINDS = frozenset({"function"})
-_QUALIFIED_REFERENCE_KINDS = frozenset({"function", "method"})
+#: See ``_add_reference_edges`` for why a bare name never reaches a method. A
+#: class is admitted: handing one over (``[FooService]``, ``isinstance(x, Foo)``)
+#: is a use, and no grammar lets a bare class name stand for a local.
+_BARE_REFERENCE_KINDS = frozenset({"function", "class"})
+_QUALIFIED_REFERENCE_KINDS = frozenset({"function", "method", "class"})
#: Languages that share the MSBuild project graph, so the namespace and
#: partial-class passes below serve both. Call resolution and receiver typing
@@ -717,7 +719,7 @@ class ResolveMixin:
**What may be named depends on how it was written, not on the
language.** A receiver-less name produces an edge only to a free
- function: a bare identifier cannot name a member in the languages that
+ function or a class: a bare identifier cannot name a member in the languages that
spell a reference that way, so a plain name resolving to a method is a
collision rather than a reference, and C++ names its getters exactly
like the locals that feed them. Measured on leveldb, admitting methods
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index b37e8ddf9..fd1d3343e 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -151,8 +151,29 @@ _TS_JS_LANGUAGES = ("typescript", "javascript", "svelte", "vue")
# Languages whose query defines the ``@reference.*`` captures. Every other
# language would only scan the whole match list to find nothing, so the check
-# is here rather than inside ``_extract_references``.
-_REFERENCE_LANGUAGES = ("cpp", "c", "go", "rust", "kotlin")
+# is here rather than inside ``_extract_references``. The SFC tags reuse the
+# TS captures but stay out: resolution has no local-shadow scan for them.
+_REFERENCE_LANGUAGES = ("cpp", "c", "go", "rust", "kotlin", "typescript", "javascript", "python")
+
+# Languages where a bare name resolves only through the file's own symbols or
+# a name it imports, so any other bare name cannot pass the reference floor.
+_NAMED_BINDING_LANGUAGES = frozenset({"typescript", "javascript", "python"})
+
+
+def _bare_reference_names(
+ language: str, symbols: list[Symbol], imports: list[Import]
+) -> frozenset[str] | None:
+ """Names a receiver-less reference in this file could resolve to, or None for any.
+
+ Most bare identifiers in a value position are locals; dropping them here
+ skips their per-site work. A wildcard import keeps every name.
+ """
+ if language not in _NAMED_BINDING_LANGUAGES:
+ return None
+ imported = {name for imp in imports for name in imp.local_names}
+ if "*" in imported:
+ return None
+ return frozenset(imported.union(s.name for s in symbols))
def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
@@ -1448,7 +1469,7 @@ class ASTParser:
# every non-SFC language.
calls.extend(component_call_sites(lang, original_source, symbols))
references = (
- self._extract_references(matches, file_info, src, symbols)
+ self._extract_references(matches, file_info, src, symbols, imports)
if lang in _REFERENCE_LANGUAGES
else []
)
@@ -2008,6 +2029,7 @@ class ASTParser:
file_info: FileInfo,
src: str,
symbols: list[Symbol],
+ imports: list[Import],
) -> list[CallSite]:
"""Extract sites that name a function without calling it.
@@ -2017,6 +2039,8 @@ class ASTParser:
initialiser, and a ``::`` callable reference. Each leaves the named
function with no inbound edge, which read as a ``safe_to_delete``
unused export and took out whole handler and interop layers (#1602).
+ TS/JS and Python capture any value position: an argument, a list or
+ object entry, a return, an assignment and a default export.
``@reference.receiver`` is optional; capturing it is what lets
``_add_reference_edges`` restrict a bare name to free functions and
@@ -2051,6 +2075,7 @@ class ASTParser:
key=lambda t: (t[0], -t[1]),
)
callable_ids = {s.id for s in symbols if s.kind in ("function", "method")}
+ bindable = _bare_reference_names(file_info.language, symbols, imports)
references: list[CallSite] = []
seen: set[tuple[int, str, str | None]] = set()
@@ -2081,6 +2106,8 @@ class ASTParser:
name = _node_text(name_node, src).strip()
if not name or name in builtins:
continue
+ if bindable is not None and receiver is None and name not in bindable:
+ continue
line = name_node.start_point[0] + 1
enclosing = _find_enclosing_symbol(line, symbol_ranges)
if is_table and enclosing in callable_ids:
diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
index fe2a0c4bf..a9c7ebb38 100644
--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
@@ -243,3 +243,39 @@
(#match? @call.target "^[A-Z]")
) @call.site
+
+; Handler passed as a JSX attribute value: onClick={handle} / {this.handle}
+(jsx_expression (identifier) @reference.name)
+(jsx_expression (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+
+; ---------------------------------------------------------------------------
+; Value references: a function or class handed over by name, not called
+; ---------------------------------------------------------------------------
+; See typescript.scm for the shapes and why they are two alternations.
+[
+ (arguments (identifier) @reference.name)
+ (array (identifier) @reference.name)
+ (pair value: (identifier) @reference.name)
+ (shorthand_property_identifier) @reference.name
+ (return_statement (identifier) @reference.name)
+ (variable_declarator value: (identifier) @reference.name)
+ (assignment_expression right: (identifier) @reference.name)
+ (export_statement value: (identifier) @reference.name)
+]
+
+[
+ (arguments (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (array (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (pair value: (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (assignment_expression right: (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+]
diff --git a/packages/core/src/repowise/core/ingestion/queries/python.scm b/packages/core/src/repowise/core/ingestion/queries/python.scm
index 81ffc2f35..c2d55d9f1 100644
--- a/packages/core/src/repowise/core/ingestion/queries/python.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/python.scm
@@ -103,3 +103,42 @@
; Constructor call via class name: MyClass(args)
; (captured by the simple function call pattern above — class names are identifiers)
+
+; ---------------------------------------------------------------------------
+; Value references: a function or class handed over by name, not called
+; ---------------------------------------------------------------------------
+; register(fn), callback=fn, map(fn, xs), [fn], (fn,), {"k": fn}, return fn,
+; x = fn. Each becomes a ``references`` edge once the name resolves to a
+; function or class; one alternation per spelling keeps it to two patterns.
+[
+ (argument_list (identifier) @reference.name)
+ (keyword_argument value: (identifier) @reference.name)
+ (list (identifier) @reference.name)
+ (tuple (identifier) @reference.name)
+ (set (identifier) @reference.name)
+ (pair value: (identifier) @reference.name)
+ (return_statement (identifier) @reference.name)
+ (assignment right: (identifier) @reference.name)
+]
+
+; The same positions holding mod.fn or self.handle
+[
+ (argument_list (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+ (keyword_argument value: (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+ (list (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+ (tuple (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+ (pair value: (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+ (assignment right: (attribute
+ object: (identifier) @reference.receiver
+ attribute: (identifier) @reference.name))
+]
diff --git a/packages/core/src/repowise/core/ingestion/queries/tsx.scm b/packages/core/src/repowise/core/ingestion/queries/tsx.scm
index 6fa8f7985..bf33f5d84 100644
--- a/packages/core/src/repowise/core/ingestion/queries/tsx.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/tsx.scm
@@ -42,3 +42,9 @@
(#match? @call.target "^[A-Z]")
) @call.site
+
+; Handler passed as a JSX attribute value: onClick={handle} / {this.handle}
+(jsx_expression (identifier) @reference.name)
+(jsx_expression (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
index 5f953542f..bb305be00 100644
--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
@@ -291,6 +291,39 @@
arguments: (arguments) @call.arguments
) @call.site
+; ---------------------------------------------------------------------------
+; Value references: a function or class handed over by name, not called
+; ---------------------------------------------------------------------------
+; register(fn), [fn], { handler: fn }, { fn }, return fn, x = fn, export default fn.
+; Each becomes a ``references`` edge once the name resolves to a function or
+; class; one alternation per spelling keeps it to two query patterns.
+[
+ (arguments (identifier) @reference.name)
+ (array (identifier) @reference.name)
+ (pair value: (identifier) @reference.name)
+ (shorthand_property_identifier) @reference.name
+ (return_statement (identifier) @reference.name)
+ (variable_declarator value: (identifier) @reference.name)
+ (assignment_expression right: (identifier) @reference.name)
+ (export_statement value: (identifier) @reference.name)
+]
+
+; The same positions holding mod.fn or this.handle
+[
+ (arguments (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (array (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (pair value: (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+ (assignment_expression right: (member_expression
+ object: [(identifier) (this)] @reference.receiver
+ property: (property_identifier) @reference.name))
+]
+
; ---------------------------------------------------------------------------
; Type references (non-import positions)
;
diff --git a/tests/unit/ingestion/test_cpp_reference_edges.py b/tests/unit/ingestion/test_cpp_reference_edges.py
index 2a20f9e45..6105236b3 100644
--- a/tests/unit/ingestion/test_cpp_reference_edges.py
+++ b/tests/unit/ingestion/test_cpp_reference_edges.py
@@ -150,9 +150,11 @@ class TestPrecision:
assert not [e for e in _reference_edges(graph) if e[1].endswith("::Add")]
def test_other_languages_emit_no_reference_edges(self, tmp_path: Path) -> None:
- # Only the C/C++ queries define ``@reference.name``; everything else
- # pays a dict lookup and produces nothing.
- (tmp_path / "mod.py").write_text("def handler():\n pass\n\nTABLE = [handler]\n")
+ # A language whose query defines no ``@reference.name`` pays a dict
+ # lookup and produces nothing.
+ (tmp_path / "App.java").write_text(
+ "class App {\n static void handler() {}\n static Runnable[] T = { handler };\n}\n"
+ )
graph = _build(tmp_path)
assert _reference_edges(graph) == []
diff --git a/tests/unit/ingestion/test_express_framework_edges.py b/tests/unit/ingestion/test_express_framework_edges.py
index e4d8b9b1c..da5e880f4 100644
--- a/tests/unit/ingestion/test_express_framework_edges.py
+++ b/tests/unit/ingestion/test_express_framework_edges.py
@@ -152,6 +152,32 @@ class TestExpressLocalMiddlewareReads:
assert graph.has_edge("mw.ts::__module__", "mw.ts::authGuard")
assert graph["mw.ts::__module__"]["mw.ts::authGuard"]["edge_type"] == "framework_binds"
+ def test_upgraded_reference_carries_a_fresh_bindings_attributes(self) -> None:
+ """``app.use(fn)`` is first a ``references`` edge; the binding replaces it whole."""
+ from repowise.core.ingestion.framework_edges.base import (
+ FRAMEWORK_BIND_CONFIDENCE,
+ add_symbol_edge,
+ )
+
+ graph = nx.DiGraph()
+ for node in ("m::__module__", "m::guard", "m::called"):
+ graph.add_node(node, node_type="symbol")
+ graph.add_edge(
+ "m::__module__", "m::guard",
+ edge_type="references", confidence=0.95, resolution_origin="same_file",
+ )
+ graph.add_edge("m::__module__", "m::called", edge_type="calls", confidence=0.95)
+
+ assert add_symbol_edge(graph, "m::__module__", "m::guard")
+ assert graph["m::__module__"]["m::guard"] == {
+ "edge_type": "framework_binds",
+ "confidence": FRAMEWORK_BIND_CONFIDENCE,
+ "imported_names": [],
+ }
+ # Any other existing edge is the stronger or equal claim and stays.
+ assert not add_symbol_edge(graph, "m::__module__", "m::called")
+ assert graph["m::__module__"]["m::called"]["edge_type"] == "calls"
+
def test_defines_edge_preserved(self, tmp_path: Path) -> None:
(tmp_path / "routes.ts").write_text(
"import { Router } from 'express';\n"
@@ -208,7 +234,9 @@ class TestExpressLocalMiddlewareReads:
"const app = express();\n"
)
graph = _build_graph_with_framework_edges(tmp_path)
- assert not graph.has_edge("svc.ts::__module__", "svc.ts::cleanup")
+ # Passing it as a value is still a ``references`` edge; only the wiring is absent.
+ edge = graph.get_edge_data("svc.ts::__module__", "svc.ts::cleanup") or {}
+ assert edge.get("edge_type") != "framework_binds"
def test_non_express_file_no_reads_edge(self, tmp_path: Path) -> None:
(tmp_path / "app.ts").write_text(
@@ -220,7 +248,9 @@ class TestExpressLocalMiddlewareReads:
"store.get(helper);\n"
)
graph = _build_graph_with_framework_edges(tmp_path)
- assert not graph.has_edge("cache.ts::__module__", "cache.ts::helper")
+ # Passing it as a value is still a ``references`` edge; only the wiring is absent.
+ edge = graph.get_edge_data("cache.ts::__module__", "cache.ts::helper") or {}
+ assert edge.get("edge_type") != "framework_binds"
class TestExpressDeadCodeRegression:
diff --git a/tests/unit/ingestion/test_value_reference_edges.py b/tests/unit/ingestion/test_value_reference_edges.py
index a8a428614..e317c545b 100644
--- a/tests/unit/ingestion/test_value_reference_edges.py
+++ b/tests/unit/ingestion/test_value_reference_edges.py
@@ -1,4 +1,4 @@
-"""A method or function passed as a value, in Go, Rust and Kotlin.
+"""A method, function or class passed as a value, in Go, Rust, Kotlin, TS/JS and Python.
``list.map(Foo::bar)``, ``register(pkg.Handler)`` and ``Config { on_tick:
my_func }`` all name something callable and never call it. Go and Rust already
@@ -332,7 +332,7 @@ class TestRustMacroInvocations:
class TestReceiverDecidesWhatMayBeNamed:
- """A bare identifier admits only functions; a qualified name admits methods.
+ """A bare identifier never reaches a method; a qualified name may.
This is what keeps the C/C++ rule that bought #1602's precision — there a
plain name resolving to a method is a collision, since naming a member
@@ -417,23 +417,246 @@ class TestKotlinCeilings:
class TestControls:
+ def test_languages_without_the_captures_gain_nothing(self, tmp_path: Path) -> None:
+ """The pass is self-gating on the captures, not on a language list."""
+ (tmp_path / "App.java").write_text(
+ "class App {\n"
+ " static void handler() {}\n"
+ " static void setup() { register(handler); }\n"
+ "}\n"
+ )
+ graph = _build(tmp_path)
+ assert not _edges_of_type(graph, "references")
+
+
+def _write(root: Path, files: dict[str, str]) -> None:
+ for name, body in files.items():
+ (root / name).write_text(body)
+
+
+class TestTypeScriptValueReferences:
+ """A function or class handed over by name: registered, passed, exported."""
+
@pytest.mark.parametrize(
- ("name", "body"),
+ ("body", "caller"),
[
- (
- "app.py",
- "def handler():\n pass\n\ndef setup():\n register(handler)\n",
- ),
- (
- "app.ts",
- "function handler() {}\nfunction setup() { register(handler); }\n",
- ),
+ ("export function setup() { register(handler); }\n", "setup"),
+ ('export function setup(e: any) { e.on("x", handler); }\n', "setup"),
+ ("export function setup() { setTimeout(handler, 10); }\n", "setup"),
+ ("export function setup() { return { extensions: [handler] }; }\n", "setup"),
+ ("export function setup() { return { onMessage: handler }; }\n", "setup"),
+ ("export function setup() { return { handler }; }\n", "setup"),
+ ("export function setup() { return handler; }\n", "setup"),
+ ("export function setup() { let h; h = handler; return h; }\n", "setup"),
+ ("export default handler;\n", "__module__"),
],
)
- def test_languages_without_the_captures_gain_nothing(
- self, tmp_path: Path, name: str, body: str
+ def test_value_positions_reference_an_imported_function(
+ self, tmp_path: Path, body: str, caller: str
) -> None:
- """The pass is self-gating on the captures, not on a language list."""
- (tmp_path / name).write_text(body)
+ _write(
+ tmp_path,
+ {
+ "handler.ts": "export function handler() {}\n",
+ "setup.ts": 'import { handler } from "./handler";\n' + body,
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "handler.ts::handler", "references") == {f"setup.ts::{caller}"}
+ assert not _inbound(graph, "handler.ts::handler", "calls")
+
+ def test_default_export_registered_by_an_importer(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {
+ "ext.ts": "function safeguard() {}\nexport default safeguard;\n",
+ "runner.ts": (
+ 'import safeguard from "./ext";\n'
+ "export function build() { return { extensions: [safeguard] }; }\n"
+ ),
+ },
+ )
+ graph = _build(tmp_path)
+ assert "runner.ts::build" in _inbound(graph, "ext.ts::safeguard", "references")
+
+ def test_class_and_method_values(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {
+ "svc.ts": "export class FooService {}\n",
+ "mod.ts": (
+ 'import { FooService } from "./svc";\n'
+ "export class Panel {\n"
+ " onClick() {}\n"
+ " mount(el: any) { el.listen(this.onClick); }\n"
+ "}\n"
+ "export function providers() { return [FooService]; }\n"
+ ),
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "svc.ts::FooService", "references") == {"mod.ts::providers"}
+ assert _inbound(graph, "mod.ts::Panel::onClick", "references") == {
+ "mod.ts::Panel::mount"
+ }
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ # A local of the same name hides the function.
+ "export function setup() { const handler = 1; register(handler); }\n",
+ # So does a parameter.
+ "export function setup(handler: any) { register(handler); }\n",
+ # A string names nothing.
+ 'export function setup() { register("handler"); }\n',
+ # A property on an untyped object is not the method of that name.
+ "export function setup(cfg: any) { register(cfg.handler); }\n",
+ ],
+ )
+ def test_negatives_produce_no_reference(self, tmp_path: Path, body: str) -> None:
+ _write(
+ tmp_path,
+ {
+ "lib.ts": "export function handler() {}\nexport class Store {\n handler() {}\n}\n",
+ "setup.ts": 'import { handler } from "./lib";\n' + body,
+ },
+ )
+ graph = _build(tmp_path)
+ assert not _edges_of_type(graph, "references")
+
+ def test_a_call_stays_a_call(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {
+ "handler.ts": "export function handler() { return 1; }\n",
+ "setup.ts": (
+ 'import { handler } from "./handler";\n'
+ "export function setup() { register(handler()); }\n"
+ ),
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "handler.ts::handler", "calls") == {"setup.ts::setup"}
+ assert not _edges_of_type(graph, "references")
+
+
+class TestJavaScriptValueReferences:
+ @pytest.mark.parametrize(
+ ("body", "caller"),
+ [
+ ("function setup() { app.use(handler); }\n", "setup"),
+ ("function setup() { return [handler]; }\n", "setup"),
+ ("module.exports.handler = handler;\n", "__module__"),
+ ("function View() { return <button onClick={handler} />; }\n", "View"),
+ ],
+ )
+ def test_value_positions_reference_a_same_file_function(
+ self, tmp_path: Path, body: str, caller: str
+ ) -> None:
+ _write(tmp_path, {"app.jsx": "function handler() {}\n" + body})
+ graph = _build(tmp_path)
+ assert _inbound(graph, "app.jsx::handler", "references") == {f"app.jsx::{caller}"}
+
+ def test_a_shadowing_parameter_produces_no_reference(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {"app.js": "function handler() {}\nfunction setup(handler) { app.use(handler); }\n"},
+ )
+ graph = _build(tmp_path)
+ assert not _edges_of_type(graph, "references")
+
+
+class TestPythonValueReferences:
+ @pytest.mark.parametrize(
+ ("body", "caller"),
+ [
+ ("def setup(bus):\n bus.subscribe(callback=on_message)\n", "setup"),
+ ("def setup(xs):\n return list(map(on_message, xs))\n", "setup"),
+ ('def setup():\n return {"msg": on_message}\n', "setup"),
+ ("def setup():\n return [on_message]\n", "setup"),
+ ("def setup():\n return (on_message,)\n", "setup"),
+ ("def setup():\n return on_message\n", "setup"),
+ ("def setup():\n h = on_message\n return h\n", "setup"),
+ ("def setup(bus):\n bus.subscribe(handlers.on_message)\n", "setup"),
+ ],
+ )
+ def test_value_positions_reference_an_imported_function(
+ self, tmp_path: Path, body: str, caller: str
+ ) -> None:
+ _write(
+ tmp_path,
+ {
+ "handlers.py": "def on_message(m):\n return m\n",
+ "setup.py": "import handlers\nfrom handlers import on_message\n\n" + body,
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "handlers.py::on_message", "references") == {f"setup.py::{caller}"}
+ assert not _inbound(graph, "handlers.py::on_message", "calls")
+
+ def test_a_wildcard_import_still_reaches_its_names(self, tmp_path: Path) -> None:
+ """The per-file name prefilter must not drop a name only ``*`` binds."""
+ _write(
+ tmp_path,
+ {
+ "handlers.py": "def on_message(m):\n return m\n",
+ "setup.py": "from handlers import *\n\ndef setup(bus):\n bus.subscribe(on_message)\n",
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "handlers.py::on_message", "references") == {"setup.py::setup"}
+
+ def test_class_and_bound_method_values(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {
+ "app.py": (
+ "class NotFound(Exception):\n pass\n\n"
+ "class Panel:\n"
+ " def on_click(self):\n pass\n\n"
+ " def mount(self, el):\n el.listen(self.on_click)\n\n"
+ "def setup(app):\n app.register_error_handler(404, NotFound)\n"
+ ),
+ },
+ )
+ graph = _build(tmp_path)
+ assert _inbound(graph, "app.py::NotFound", "references") == {"app.py::setup"}
+ assert _inbound(graph, "app.py::Panel::on_click", "references") == {"app.py::Panel::mount"}
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ "def setup(on_message):\n register(on_message)\n",
+ "def setup():\n on_message = 1\n register(on_message)\n",
+ 'def setup():\n register("on_message")\n',
+ "def setup(cfg):\n register(cfg.on_message)\n",
+ ],
+ )
+ def test_negatives_produce_no_reference(self, tmp_path: Path, body: str) -> None:
+ _write(
+ tmp_path,
+ {
+ "lib.py": (
+ "def on_message(m):\n return m\n\n"
+ "class Store:\n def on_message(self):\n pass\n"
+ ),
+ "setup.py": "from lib import on_message\n\n" + body,
+ },
+ )
+ graph = _build(tmp_path)
+ assert not _edges_of_type(graph, "references")
+
+ def test_a_call_stays_a_call(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ {
+ "lib.py": "def on_message(m):\n return m\n",
+ "setup.py": (
+ "from lib import on_message\n\n"
+ "def setup():\n register(on_message(1))\n"
+ ),
+ },
+ )
graph = _build(tmp_path)
+ assert _inbound(graph, "lib.py::on_message", "calls") == {"setup.py::setup"}
assert not _edges_of_type(graph, "references")