Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 11 additions & 3 deletions docs/python-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion src/trailmark/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
151 changes: 140 additions & 11 deletions src/trailmark/parsers/python/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
]:
Expand All @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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")
Expand Down
3 changes: 3 additions & 0 deletions tests/test_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
Loading
Loading