From 1ad18d137fdecde2239a336eff8eccdbf80ed77b Mon Sep 17 00:00:00 2001 From: Alexis Date: Tue, 24 Nov 2026 14:13:56 +0100 Subject: [PATCH] Link Python imports and calls across explicit source roots --- README.md | 1 + docs/python-api.md | 14 ++- src/trailmark/parse.py | 13 ++- src/trailmark/parsers/python/parser.py | 151 +++++++++++++++++++++++-- tests/test_docs.py | 3 + tests/test_python_import_resolution.py | 126 ++++++++++++++++++++- 6 files changed, 291 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 0fe6756..d7a5778 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ that are reachable from user input. - **Entrypoint evidence.** Inspect callable and declarative references, executable file bodies, and unresolved candidates with source provenance. References stay separate from execution. Select additional source roots with explicit exclusions. + Python import bindings can link calls across explicitly selected roots. - **Reachability.** Direct callers and callees, transitive slices, and bounded call paths from entrypoints to a target. - **Reusable analysis.** Save and reload complete, versioned analysis snapshots diff --git a/docs/python-api.md b/docs/python-api.md index 82e888b..42c5303 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -78,9 +78,17 @@ parse. The supplied root's absolute lexical path is preserved in source location canonicalization is used only for containment and deduplication. Source selection does not prove deployment or external reachability. -Ordinary calls are linked within each selected root. Cross-root execution needs -explicit linking evidence; qualified declarative references and anchored PHP -includes can span selected roots without assuming an import search path. +Ordinary calls are linked within each selected root. With multiple explicit +roots, Python also links absolute imports and calls with existing lexical import +bindings to uniquely matching Python definitions in other selected roots. Supply +the directory that contains the importable modules or packages, such as a +dependency checkout's `src/` directory. Existing within-root links retain +precedence. Relative imports stay within their root, and ambiguous matches +remain unresolved. The analysis uses the selected files as source evidence and +leaves runtime import precedence and package re-exports unresolved. + +Qualified declarative references and anchored PHP includes can also span +selected roots. `parse_directory(..., source_policy=policy)` and `QueryEngine.from_directory(..., source_policy=policy)` use the policy's roots diff --git a/src/trailmark/parse.py b/src/trailmark/parse.py index b7b37d3..addc8db 100644 --- a/src/trailmark/parse.py +++ b/src/trailmark/parse.py @@ -345,7 +345,14 @@ def parse_roots( languages = _resolve_directory_languages( selected.path, language, allow_empty=True, selected_files=paths ) - sub = _parse_and_merge(os.path.abspath(selected.path), languages, paths) + path = os.path.abspath(selected.path) + if len(policy.roots) > 1 and "python" in languages: + from trailmark.parsers.python.parser import collect_cross_root_imports + + with collect_cross_root_imports(): + sub = _parse_and_merge(path, languages, paths) + else: + sub = _parse_and_merge(path, languages, paths) if len(policy.roots) == 1: merged.language = sub.language if len(policy.roots) > 1: @@ -356,6 +363,10 @@ def parse_roots( from trailmark.parsers.php._includes import link_php_includes link_php_includes(merged) + if len(policy.roots) > 1 and merged.source_file_counts.get("python"): + from trailmark.parsers.python.parser import link_cross_root_imports + + link_cross_root_imports(merged) if not allow_empty and not sum(merged.source_file_counts.values()): raise ValueError("No source files inspected under the selected source policy") _check_diagnostics(merged, strict=strict) diff --git a/src/trailmark/parsers/python/parser.py b/src/trailmark/parsers/python/parser.py index c75d1c9..b97726c 100644 --- a/src/trailmark/parsers/python/parser.py +++ b/src/trailmark/parsers/python/parser.py @@ -2,7 +2,8 @@ from __future__ import annotations -from collections.abc import Generator +from collections import defaultdict +from collections.abc import Generator, Iterator from contextlib import contextmanager from contextvars import ContextVar from dataclasses import replace @@ -63,6 +64,9 @@ _CALL_SITES: ContextVar[dict[SourceLocation, Node] | None] = ContextVar( "_PYTHON_CALL_SITES", default=None ) +_CROSS_ROOT_IMPORTS: ContextVar[bool] = ContextVar("_CROSS_ROOT_IMPORTS", default=False) +_CROSS_ROOT_IMPORT = "_python_cross_root_import" + _EAGER_SITES: ContextVar[set[int] | None] = ContextVar("_PYTHON_EAGER_SITES", default=None) _OVERLOAD_NAMES: ContextVar[frozenset[str]] = ContextVar( "_PYTHON_OVERLOAD_NAMES", @@ -692,13 +696,15 @@ def _record_imports( module = node.child_by_field_name("module_name") if node.type == "import_from_statement" and module is None: continue - prefix = _absolute_import(node_text(module), module_id, file_path) if module else "" + raw_module = node_text(module) if module is not None else "" + prefix = _absolute_import(raw_module, module_id, file_path) if module is not None and not prefix: continue names = [ node_text(name.child_by_field_name("name") or name) for name in node.children_by_field_name("name") ] + attributes = (("python_import", True), *_cross_root_import_attributes(raw_module)) for name in ([prefix] if prefix else []) + [ f"{prefix}.{name}" if prefix else name for name in names ]: @@ -709,11 +715,127 @@ def _record_imports( EdgeKind.IMPORTS, EdgeConfidence.INFERRED, location=make_location(node, file_path), - attributes=(("python_import", True),), + attributes=attributes, ) ) +@contextmanager +def collect_cross_root_imports() -> Generator[None]: + """Keep absolute import bindings available until explicit roots are merged.""" + token = _CROSS_ROOT_IMPORTS.set(True) + try: + yield + finally: + _CROSS_ROOT_IMPORTS.reset(token) + + +def _cross_root_import_attributes(import_path: str) -> tuple[tuple[str, bool], ...]: + if _CROSS_ROOT_IMPORTS.get() and not import_path.startswith("."): + return ((_CROSS_ROOT_IMPORT, True),) + return () + + +def _import_prefixes(path: str) -> Iterator[tuple[str, str]]: + parts = path.split(".") + for index in range(1, len(parts) + 1): + yield ".".join(parts[:index]), ".".join(parts[index:]) + + +def _without_pending_import(edge: CodeEdge) -> CodeEdge: + return replace( + edge, attributes=tuple(item for item in edge.attributes if item[0] != _CROSS_ROOT_IMPORT) + ) + + +def link_cross_root_imports(graph: CodeGraph) -> None: + """Resolve absolute Python import bindings against explicitly selected roots.""" + modules: dict[str, list[str]] = defaultdict(list) + for node_id, unit in graph.nodes.items(): + root, _, module = node_id.partition("::") + if ( + module + and unit.kind == NodeKind.MODULE + and Path(unit.location.file_path).suffix == ".py" + ): + modules[module].append(root) + + linked: list[CodeEdge] = [] + imports: set[CodeEdge] = set() + replaced_proxies: set[str] = set() + for edge in graph.edges: + attrs = dict(edge.attributes) + if not attrs.get(_CROSS_ROOT_IMPORT): + linked.append(edge) + continue + edge = _without_pending_import(edge) + root = edge.source_id.partition("::")[0] + if edge.kind == EdgeKind.IMPORTS: + candidates, _ = _cross_root_modules(modules, edge.target_id) + for owner, module, _ in candidates: + if owner != root: + imported = replace(edge, target_id=f"{owner}::{module}") + if imported not in imports: + imports.add(imported) + linked.append(imported) + continue + raw = attrs.get("raw_target") + if edge.kind == EdgeKind.CALLS and isinstance(raw, str): + target = _cross_root_call_target(graph, modules, root, raw) + if target is not None: + replaced_proxies.add(edge.target_id) + edge = replace( + edge, + target_id=target, + attributes=tuple(item for item in edge.attributes if item[0] != "raw_target"), + ) + linked.append(edge) + + graph.edges[:] = linked + if replaced_proxies: + used = {node for edge in linked for node in (edge.source_id, edge.target_id)} + for proxy in replaced_proxies - used: + del graph.nodes[proxy] + + +def _cross_root_modules( + modules: dict[str, list[str]], path: str +) -> tuple[list[tuple[str, str, str]], bool]: + """Find module prefixes without assuming precedence or mixing package roots.""" + candidates: list[tuple[str, str, str]] = [] + owner: str | None = None + for module, member in _import_prefixes(path): + owners = modules.get(module) + if not owners: + continue + if len(owners) > 1 or (owner is not None and owners[0] != owner): + return candidates, False + owner = owners[0] + candidates.append((owner, module, member)) + return candidates, True + + +def _cross_root_call_target( + graph: CodeGraph, modules: dict[str, list[str]], root: str, path: str +) -> str | None: + candidates, unambiguous = _cross_root_modules(modules, path) + if not unambiguous: + return None + targets = [] + for owner, module, member in candidates: + if owner == root or not member: + continue + target_id = f"{owner}::{module}:{member}" + target = graph.nodes.get(target_id) + if target is not None and target.kind in { + NodeKind.FUNCTION, + NodeKind.METHOD, + NodeKind.CLASS, + }: + targets.append(target_id) + return targets[0] if len(targets) == 1 else None + + def _link_python_imports(graph: CodeGraph) -> None: """Resolve only imported paths with a unique Python source candidate.""" from trailmark.parsers._common import link_cross_file_calls @@ -722,20 +844,22 @@ def _link_python_imports(graph: CodeGraph) -> None: for edge in graph.edges: attributes = dict(edge.attributes) if attributes.get("import_binding"): - parts = edge.target_id.split(".") candidates = [ - f"{'.'.join(parts[:i])}:{'.'.join(parts[i:])}" for i in range(1, len(parts)) + f"{module}:{member}" + for module, member in _import_prefixes(edge.target_id) + if member ] targets = [target for target in candidates if target in graph.nodes] if len(targets) == 1: edge = replace(edge, target_id=targets[0]) elif attributes.get("python_import"): - parts = edge.target_id.split(".") - for i in range(1, len(parts) + 1): - target = ".".join(parts[:i]) + local = _without_pending_import(edge) if attributes.get(_CROSS_ROOT_IMPORT) else edge + for target, _ in _import_prefixes(edge.target_id): unit = graph.nodes.get(target) if unit is not None and unit.kind == NodeKind.MODULE and target != edge.source_id: - linked.append(replace(edge, target_id=target)) + linked.append(replace(local, target_id=target)) + if attributes.get(_CROSS_ROOT_IMPORT): + linked.append(edge) continue linked.append(edge) graph.edges[:] = list(dict.fromkeys(linked)) @@ -765,13 +889,18 @@ def _bind_complete_calls( for edge in graph.edges: call = calls.get(edge.location) if edge.kind == EdgeKind.CALLS else None if call is not None: - target = _absolute_import(imported.get(call, ""), module_id, file_path) + imported_path = imported.get(call, "") + target = _absolute_import(imported_path, module_id, file_path) if target: edge = replace( edge, target_id=target, confidence=EdgeConfidence.INFERRED, - attributes=(*edge.attributes, ("import_binding", True)), + attributes=( + *edge.attributes, + ("import_binding", True), + *_cross_root_import_attributes(imported_path), + ), ) else: callee = call.child_by_field_name("function") diff --git a/tests/test_docs.py b/tests/test_docs.py index 764842e..82bb7bb 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -341,6 +341,9 @@ def pyproject_data() -> dict[str, object]: ("CONTRIBUTING.md", "tests.benchmark_analysis /path/to/corpus --language python --repeat 7"), ("CONTRIBUTING.md", "complete graph output with `graph_sha256`"), ("docs/cli.md", "`--source-root`, `--include`, and `--exclude` options, were added in 0.7.1."), + ("README.md", "Python import bindings can link calls across explicitly selected roots."), + ("docs/python-api.md", "calls with existing lexical import bindings"), + ("docs/python-api.md", "Relative imports stay within their root"), ("docs/python-api.md", "| 0.7.1 | `SourceRoot`, `SourcePolicy`, `parse_roots`"), ("CONTRIBUTING.md", "tests.run_mutations --reviewed --workers=4"), ("CONTRIBUTING.md", "tests.run_mutations --workers=4"), diff --git a/tests/test_python_import_resolution.py b/tests/test_python_import_resolution.py index 1cc76ea..5c71539 100644 --- a/tests/test_python_import_resolution.py +++ b/tests/test_python_import_resolution.py @@ -1,8 +1,9 @@ from pathlib import Path -from trailmark.models.edges import EdgeKind -from trailmark.parse import parse_directory +from trailmark.models.edges import EdgeConfidence, EdgeKind +from trailmark.parse import parse_directory, parse_roots from trailmark.query.api import QueryEngine +from trailmark.source_policy import SourcePolicy, SourceRoot def test_package_import_edges_and_lexical_aliases(tmp_path: Path) -> None: @@ -83,3 +84,124 @@ def test_unavailable_conditional_and_shadowed_bases_never_use_name_fallback(tmp_ assert all(e.target_id not in graph.nodes for e in bases) assert next(e.target_id for e in bases if e.source_id == "child:External") == "unavailable.Base" assert QueryEngine.from_graph(graph).callees_of("child:factory") == [] + + +def test_explicit_roots_link_python_import_and_call_aliases(tmp_path: Path) -> None: + app, dependency = tmp_path / "app", tmp_path / "dependency" + app.mkdir() + package = dependency / "extpkg" + package.mkdir(parents=True) + (package / "__init__.py").write_text("") + (package / "api.py").write_text("def start(): pass\ndef stop(): pass\n") + source = app / "app.py" + source.write_text( + "from extpkg.api import start as boot\n" + "import extpkg.api as api\n" + "def run():\n" + " boot()\n" + " api.stop()\n" + ) + policy = SourcePolicy( + (SourceRoot(str(app), "app"), SourceRoot(str(dependency), "dep", "dependency")) + ) + + graph = parse_roots(policy, "python") + imports = [edge for edge in graph.edges if edge.kind == EdgeKind.IMPORTS] + assert {(edge.source_id, edge.target_id) for edge in imports} == { + ("app::app", "dep::extpkg"), + ("app::app", "dep::extpkg.api"), + } + assert {edge.location.start_line for edge in imports if edge.location} == {1, 2} + calls = [edge for edge in graph.edges if edge.kind == EdgeKind.CALLS] + assert [(edge.source_id, edge.target_id) for edge in calls] == [ + ("app::app:run", "dep::extpkg.api:start"), + ("app::app:run", "dep::extpkg.api:stop"), + ] + assert all(edge.confidence == EdgeConfidence.INFERRED for edge in calls) + assert [edge.location.start_line for edge in calls if edge.location] == [4, 5] + assert graph.unresolved_calls() == [] + assert all(unit.kind.value != "proxy" for unit in graph.nodes.values()) + engine = QueryEngine.from_graph(graph) + assert engine.paths_between("app::app:run", "dep::extpkg.api:start") == [ + ["app::app:run", "dep::extpkg.api:start"] + ] + + +def test_python_imports_with_ambiguous_cross_root_modules_stay_unresolved(tmp_path: Path) -> None: + app, first, second = (tmp_path / name for name in ("app", "first", "second")) + for root in (app, first, second): + root.mkdir() + (app / "app.py").write_text("from vendor import start as boot\ndef run(): boot()\n") + (first / "vendor.py").write_text("def start(): pass\n") + (second / "vendor.py").write_text("def other(): pass\n") + roots = tuple(SourceRoot(str(root), root.name) for root in (app, first, second)) + + for policy in (SourcePolicy(roots), SourcePolicy(roots[::-1])): + graph = parse_roots(policy, "python") + assert all(edge.kind != EdgeKind.IMPORTS for edge in graph.edges) + (call,) = graph.unresolved_calls() + assert call.source_id == "app::app:run" + assert dict(call.attributes)["raw_target"] == "vendor.start" + + +def test_cross_root_linking_preserves_local_shadowing_and_relative_imports(tmp_path: Path) -> None: + app, dependency = tmp_path / "app", tmp_path / "dep" + (app / "pkg").mkdir(parents=True) + (dependency / "pkg").mkdir(parents=True) + (dependency / "pkg" / "api.py").write_text("def start(): pass\n") + (app / "pkg" / "app.py").write_text( + "from pkg.api import start as boot\n" + "from .api import start as relative_boot\n" + "def bound(): boot()\n" + "def shadow(boot): boot()\n" + "def bare(): start()\n" + "def relative(): relative_boot()\n" + ) + graph = parse_roots( + SourcePolicy((SourceRoot(str(app), "app"), SourceRoot(str(dependency), "dep"))), + "python", + ) + + linked = [ + edge + for edge in graph.edges + if edge.kind == EdgeKind.CALLS and edge.target_id == "dep::pkg.api:start" + ] + assert [edge.source_id for edge in linked] == ["app::pkg.app:bound"] + assert {edge.source_id for edge in graph.unresolved_calls()} == { + "app::pkg.app:bare", + "app::pkg.app:relative", + "app::pkg.app:shadow", + } + assert [ + edge.location.start_line + for edge in graph.edges + if edge.kind == EdgeKind.IMPORTS and edge.location is not None + ] == [1] + + +def test_local_python_package_keeps_its_imports_within_the_root(tmp_path: Path) -> None: + app, dependency = tmp_path / "app", tmp_path / "dep" + for root in (app, dependency): + (root / "widgets").mkdir(parents=True) + (app / "widgets/__init__.py").write_text("def start(): pass\n") + (dependency / "widgets/api.py").write_text("def stop(): pass\n") + (app / "main.py").write_text( + "from widgets import start\n" + "from widgets.api import stop\n" + "def run():\n" + " start()\n" + " stop()\n" + ) + graph = parse_roots( + SourcePolicy((SourceRoot(str(app), "app"), SourceRoot(str(dependency), "dep"))), + "python", + ) + + calls = [edge for edge in graph.edges if edge.kind == EdgeKind.CALLS] + assert calls[0].target_id == "app::widgets:start" + assert graph.unresolved_calls() == calls[1:] + assert dict(calls[1].attributes)["raw_target"] == "widgets.api.stop" + assert {edge.target_id for edge in graph.edges if edge.kind == EdgeKind.IMPORTS} == { + "app::widgets" + }