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
49 changes: 42 additions & 7 deletions great_docs/_apiref/introspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,30 @@ def _split_path(path: str) -> tuple[str, str | None]:
return module_path, object_path or None


def shadowing_reexport(module: gf.Module) -> gf.Alias | None:
"""
Recover a function re-exported under its own submodule's name

The static model keeps the submodule at that path. The parent still records
the import of the function, which can be documented as a separate binding.
"""
parent = module.parent
if not isinstance(parent, gf.Module):
return None
imported = parent.imports.get(module.name, "")
if not imported.startswith(f"{module.path}."):
return None
name = imported.removeprefix(f"{module.path}.")
member = module.members.get(name)
if member is not None:
try:
if member.kind is gf.Kind.FUNCTION:
return gf.Alias(module.name, member, parent=parent)
except (gf.AliasResolutionError, gf.CyclicAliasError, KeyError):
return None
return None


def _static_object(
module_path: str,
object_path: str | None,
Expand All @@ -290,7 +314,7 @@ def _static_object(
:
The node at the path. An imported name comes back as an alias, and a
function or attribute reached through an aliased parent keeps that
parent.
parent. An object path can name a function that shadows its submodule.

Raises
------
Expand All @@ -301,6 +325,10 @@ def _static_object(
# griffe uses only periods for the path
griffe_path = f"{module_path}.{object_path}" if object_path else module_path
obj = loader.modules_collection[griffe_path]
if object_path is not None and isinstance(obj, gf.Module):
alias = shadowing_reexport(obj)
if alias is not None:
return alias
parent = loader.modules_collection[griffe_path.rsplit(".", 1)[0]]

if isinstance(parent, gf.Alias) and isinstance(obj, (gf.Function, gf.Attribute)):
Expand Down Expand Up @@ -778,14 +806,21 @@ def _locate_runtime_attr(
raise
else:
continue
if isinstance(value, ModuleType) and loader is not None:
modelled_module, remaining = _split_path(
_dynamic_path(path.replace(":", "."), loader)
)
if modelled_module not in (module_path, value.__name__):
if loader is not None and (isinstance(value, ModuleType) or callable(value)):
replacement_path = _dynamic_path(path.replace(":", "."), loader)
modelled_module, remaining = _split_path(replacement_path)
if isinstance(value, ModuleType):
retry = modelled_module not in (module_path, value.__name__)
else:
# Only retry below the module whose binding the callable displaced.
binding_path = f"{module_path}.{'.'.join(names[:index])}"
retry = modelled_module == binding_path or modelled_module.startswith(
f"{binding_path}."
)
if retry:
replacement = import_project_module(modelled_module)
return _locate_runtime_attr(
replacement, modelled_module, remaining, path, loader
replacement, modelled_module, remaining, replacement_path, loader
)
return _locate_declaration(canonical_path or path, name, path, loader)

Expand Down
52 changes: 43 additions & 9 deletions great_docs/_reference/discovery.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"""
Export discovery and categorisation for the generated API reference

Every function reads a package that griffe has already loaded, so none of them imports the
package. A caller that needs to know whether the renderer can document a path passes that check
in.
Read a package that Griffe has already loaded. A caller can check whether the renderer can
document a path and resolve functions that the package exports under a submodule's name.
"""

from __future__ import annotations
Expand All @@ -16,7 +15,7 @@

from .._apiref._exports import declared_exports
from .._apiref._type_checks import ClassKind, attribute_kind, class_kind, function_kind
from .._apiref.introspect import get_object
from .._apiref.introspect import get_object, shadowing_reexport
from .._build.steps import BuildError

if TYPE_CHECKING:
Expand Down Expand Up @@ -332,7 +331,11 @@ def _drop_excluded(names: list[str], config: Config, *, report: Callable[[str],


def discover_exports(
package: gf.Module, config: Config, *, report: Callable[[str], None]
package: gf.Module,
config: Config,
*,
report: Callable[[str], None],
runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None,
) -> list[str] | None:
"""
Find the names a package exports that the reference can document
Expand All @@ -356,6 +359,8 @@ def discover_exports(
The configuration whose `exclude`, `auto_include` and `no_auto_exclude` settings apply.
report
A callback that receives a line for each group of dropped names.
runtime_function
Recover a function at a name that static analysis assigns to a submodule.

Returns
-------
Expand All @@ -376,8 +381,8 @@ def discover_exports(
if package.exports is None and "__all__" not in members:
submodules: dict[str, bool] = {}
for name in candidates:
member = members[name]
try:
member = _export_binding(members[name], runtime_function)
if member.kind is gf.Kind.MODULE:
submodules[name] = member.exports is not None or "__all__" in member.members
except (gf.CyclicAliasError, gf.AliasResolutionError, KeyError):
Expand Down Expand Up @@ -448,6 +453,7 @@ def categorise_exports(
*,
renderable: Callable[[str], bool],
report: Callable[[str], None],
runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None,
) -> Categories:
"""
Sort a package's exports into the groups of the API reference
Expand All @@ -474,6 +480,8 @@ def categorise_exports(
`package:Class.method`.
report
A callback that receives a line for each class and for each name left out.
runtime_function
Recover a function at a name that static analysis assigns to a submodule.

Returns
-------
Expand All @@ -494,8 +502,9 @@ def categorise_exports(
unresolved.append(name)
continue
try:
obj = _export_binding(package.members[name], runtime_function)
_categorise_export(
package, name, exported, categories, renderable=renderable, report=report
package, name, obj, exported, categories, renderable=renderable, report=report
)
except gf.CyclicAliasError:
report(f" Warning: Cyclic alias detected for '{name}', excluding from docs")
Expand All @@ -512,9 +521,29 @@ def categorise_exports(
return categories


def _export_binding(
member: gf.Object | gf.Alias,
runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None,
) -> gf.Object | gf.Alias:
"""
Use the function binding when the static model gives its name to a submodule
"""
if member.kind is not gf.Kind.MODULE:
return member
if isinstance(member, gf.Module) and (alias := shadowing_reexport(member)) is not None:
return alias
if runtime_function is not None:
module = member.final_target if isinstance(member, gf.Alias) else member
candidate = module.members.get(module.name)
if candidate is not None and candidate.kind is gf.Kind.FUNCTION:
return runtime_function(member.name) or member
return member


def _categorise_export(
package: gf.Module,
name: str,
obj: gf.Object | gf.Alias,
exported: set[str],
categories: Categories,
*,
Expand All @@ -530,6 +559,8 @@ def _categorise_export(
The loaded package.
name
The export, which the package defines.
obj
The object exposed under the export name.
exported
All the package's exports, whose names an exported module does not repeat.
categories
Expand All @@ -539,7 +570,6 @@ def _categorise_export(
report
A callback that receives the line describing a class.
"""
obj = package.members[name]
kind = obj.kind
if kind is gf.Kind.CLASS:
categories[_class_group(obj)].append(name)
Expand Down Expand Up @@ -850,6 +880,8 @@ def _found_statically(path: str) -> bool:
def categorise_references(
package: gf.Module,
reference: Iterable[object],
*,
runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None,
) -> Categories:
"""
Sort the names a `reference:` setting lists into the groups of the API reference
Expand All @@ -866,6 +898,8 @@ def categorise_references(
The loaded package.
reference
The sections of the `reference:` setting. Items other than mappings are ignored.
runtime_function
Recover a function at a name that static analysis assigns to a submodule.

Returns
-------
Expand Down Expand Up @@ -898,8 +932,8 @@ def categorise_references(
if name not in package.members:
missing.append(name)
continue
obj = package.members[name]
try:
obj = _export_binding(package.members[name], runtime_function)
kind = obj.kind
except _ALIAS_ERRORS:
categories["other"].append(name)
Expand Down
19 changes: 16 additions & 3 deletions great_docs/_reference/exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,13 @@ def names(self, name: str) -> list[str] | None:
file=sys.stderr,
)
else:
exports = discovery.discover_exports(package, self.config, report=print)
check = probe.RendererCheck(normalized, report=print)
exports = discovery.discover_exports(
package,
self.config,
report=print,
runtime_function=check.exported_function if self.config.dynamic else None,
)

if exports is None:
exports = self._dunder_all(name, normalized)
Expand Down Expand Up @@ -208,11 +214,13 @@ def categorise(self, name: str, exports: list[str]) -> Categories:
]
return categories

check = probe.RendererCheck(normalized, report=print)
return discovery.categorise_exports(
package,
exports,
renderable=probe.RendererCheck(normalized, report=print),
renderable=check,
report=print,
runtime_function=check.exported_function if self.config.dynamic else None,
)

def sections(self, name: str) -> list[dict[str, Any]] | None:
Expand Down Expand Up @@ -246,7 +254,12 @@ def sections(self, name: str) -> list[dict[str, Any]] | None:
categories = discovery.empty_categories()
else:
try:
categories = discovery.categorise_references(package, reference_config)
check = probe.RendererCheck(package.path, report=print)
categories = discovery.categorise_references(
package,
reference_config,
runtime_function=check.exported_function if self.config.dynamic else None,
)
except BuildError as error:
print(f"ERROR: {error}", file=sys.stderr)
raise
Expand Down
32 changes: 24 additions & 8 deletions great_docs/_reference/probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from __future__ import annotations

import inspect
import re
from typing import TYPE_CHECKING, Literal

Expand Down Expand Up @@ -176,7 +177,7 @@ def detect_dynamic_mode(
cycles += 1
except ImportError as error:
report(f"Warning: {_import_warning(f'{package.path}:{name}', error)}")
except USER_CODE_ERRORS:
except (KeyError, *USER_CODE_ERRORS):
pass

if cycles:
Expand Down Expand Up @@ -226,8 +227,6 @@ def __call__(self, path: str) -> bool:
"""
if self._imports is None:
self._imports = self._import_package()
# Static analysis raises `KeyError` for a path it models nothing at.
errors = USER_CODE_ERRORS if self._imports else (KeyError, *USER_CODE_ERRORS)
try:
try:
obj = get_object(path, dynamic=self._imports, loader=self._loader)
Expand All @@ -237,16 +236,33 @@ def __call__(self, path: str) -> bool:
self._report(
f"Warning: {_import_warning(path, error)}; checking with static analysis instead"
)
try:
obj = get_object(path, loader=self._loader)
except KeyError:
return False
obj = get_object(path, loader=self._loader)
_ = obj.members
_ = obj.kind
except errors:
except (KeyError, *USER_CODE_ERRORS):
return False
return True

def exported_function(self, name: str) -> gf.Object | gf.Alias | None:
"""
Read a function the package exposes under a submodule's name

Only inspect bindings in the package that already exist at runtime.
A missing binding does not require importing the candidate submodule.
"""
if self._imports is None:
self._imports = self._import_package()
if not self._imports:
return None
try:
package = import_project_module(self._module_name)
if not inspect.isroutine(getattr(package, name, None)):
return None
obj = get_object(f"{self._module_name}:{name}", dynamic=True, loader=self._loader)
return obj if obj.kind is gf.Kind.FUNCTION else None
except (KeyError, *USER_CODE_ERRORS):
return None

def _import_package(self) -> bool:
"""
Import the package, reporting a failure
Expand Down
12 changes: 6 additions & 6 deletions tests/test_reference_exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def test_finds_the_names_once(self, tmp_path, monkeypatch):
exports = make_exports(_make_gd(tmp_path))
searches: list[str] = []

def discover_exports(package, config, report):
def discover_exports(package, config, report, runtime_function):
searches.append(package)
return ["X"]

Expand All @@ -63,7 +63,7 @@ def test_searches_again_after_finding_nothing(self, tmp_path, monkeypatch):
monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock())
monkeypatch.setattr(
"great_docs._reference.exports.discovery.discover_exports",
lambda package, config, report: next(found),
lambda package, config, report, runtime_function: next(found),
)
monkeypatch.setattr(
"great_docs._reference.exports.discovery.parse_dunder_all",
Expand All @@ -83,7 +83,7 @@ def test_reads_the_project_package_init_when_discovery_finds_nothing(
monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock())
monkeypatch.setattr(
"great_docs._reference.exports.discovery.discover_exports",
lambda package, config, report: None,
lambda package, config, report, runtime_function: None,
)

assert exports.names("mypkg") == ["Y"]
Expand Down Expand Up @@ -128,7 +128,7 @@ def test_include_inherited_on_explicit_members(self, tmp_path, monkeypatch):
monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock())
monkeypatch.setattr(
"great_docs._reference.exports.discovery.categorise_references",
lambda package, reference: empty_categories(),
lambda package, reference, runtime_function: empty_categories(),
)
result = make_exports(gd).sections("mypkg")
assert result is not None
Expand Down Expand Up @@ -158,7 +158,7 @@ def test_include_inherited_on_default_entry(self, tmp_path, monkeypatch):
monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock())
monkeypatch.setattr(
"great_docs._reference.exports.discovery.categorise_references",
lambda package, reference: empty_categories(),
lambda package, reference, runtime_function: empty_categories(),
)
result = make_exports(gd).sections("mypkg")
assert result is not None
Expand Down Expand Up @@ -187,7 +187,7 @@ def test_plain_string_when_no_include_inherited(self, tmp_path, monkeypatch):
monkeypatch.setattr(Exports, "package", lambda self, name: MagicMock())
monkeypatch.setattr(
"great_docs._reference.exports.discovery.categorise_references",
lambda package, reference: empty_categories(),
lambda package, reference, runtime_function: empty_categories(),
)
result = make_exports(gd).sections("mypkg")
assert result is not None
Expand Down
Loading
Loading