diff --git a/.gitignore b/.gitignore index cdcf1617..e23fe5a7 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ docs/superpowers/ # Docs build output docs/_build/ +docs/autoapi/ # Downloaded schemas for the docx and gpx examples # (fetch on demand; too large to commit) diff --git a/AGENTS.md b/AGENTS.md index b2f1cd3e..86927043 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,15 @@ # Agent guidance for pyxsd +## Python API documentation + +- Write public docstrings in Sphinx-compatible reStructuredText. Record + behavior, limits, and errors that signatures do not convey. +- Add new exports to `__all__` where the module uses it. AutoAPI picks up + public members of covered modules; add new supported import paths to + `PUBLIC_API_MODULES` in `docs/conf.py`. +- Check reference changes with + `uv run sphinx-build -E -n -W -b html docs docs/_build/html`. + ## Example outputs carry no library markers - Rendered artifacts (SVG, HTML, PDF, PNG, WAV, console output) must not diff --git a/docs/_templates/autoapi/python/package.rst b/docs/_templates/autoapi/python/package.rst new file mode 100644 index 00000000..253ee0bc --- /dev/null +++ b/docs/_templates/autoapi/python/package.rst @@ -0,0 +1,18 @@ +{% extends "python/module.rst" %} + +{% block content %} +{{ super() }} +{% if obj.id == "pyxsd" %} +Public exports +-------------- + +{% for name, kind in lazy_exports if name not in obj.children|map(attribute="short_name")|list %} +.. auto{{ kind }}:: pyxsd.{{ name }} +{% if kind == "class" %} + :members: + :undoc-members: +{% endif %} + +{% endfor %} +{% endif %} +{% endblock %} diff --git a/docs/api.md b/docs/api.md index 8d08bdc2..3567ba8d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -8,6 +8,14 @@ Use {doc}`quickstart` for a complete first example. This page documents public entry points; {doc}`data-model` describes node storage and export behavior. +For generated signatures and docstrings by module, browse the +{doc}`Python API `. + +```{contents} On this page +:local: +:depth: 1 +``` + ## Schema and documents `Schema.compile(source, ...)` generates binding classes once; diff --git a/docs/conf.py b/docs/conf.py index bd6c8326..b6bc3a93 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,9 +2,14 @@ from __future__ import annotations +import logging import sys from pathlib import Path +from sphinx.domains.python import PythonDomain +from sphinx.ext import viewcode +from sphinx.util.nodes import make_refnode + SRC = Path(__file__).resolve().parent.parent / "src" if str(SRC) not in sys.path: sys.path.insert(0, str(SRC)) @@ -13,10 +18,10 @@ copyright = "2026, the pyxsd contributors" author = "the pyxsd contributors" -from pyxsd import __version__ # noqa: E402 +import pyxsd # noqa: E402 #: Full version (MAJOR.MINOR.MICRO) shown in the docs header and search. -release = __version__ +release = pyxsd.__version__ #: Short form (MAJOR.MINOR) Sphinx uses for the version banner. version = ".".join(release.split(".")[:2]) @@ -26,6 +31,8 @@ "sphinx.ext.autosummary", "sphinx.ext.napoleon", "sphinx.ext.intersphinx", + # Load viewcode after AutoAPI so existing source links use Sphinx's analyzer. + "autoapi.extension", "sphinx.ext.viewcode", "sphinx_copybutton", "sphinx_llms_txt", @@ -95,6 +102,161 @@ autodoc_member_order = "bysource" autodoc_typehints = "description" +# Scan implementation modules so AutoAPI can resolve facade re-exports. +# Publish only supported import paths, not the entire implementation tree. +autoapi_dirs = ["../src/pyxsd"] +autoapi_python_use_implicit_namespaces = True +autoapi_add_toctree_entry = False +autoapi_template_dir = "_templates/autoapi" +# These optional adapters are not needed to resolve the public facades. +autoapi_ignore = ["*/pyxsd/mcp/*", "*/pyxsd/relaxng/pydantic_adapter.py"] +autoapi_options = ["members", "undoc-members", "imported-members", "show-module-summary"] +PUBLIC_API_MODULES = frozenset( + { + "pyxsd", + "pyxsd.batch", + "pyxsd.integrations", + "pyxsd.introspection", + "pyxsd.relaxng", + "pyxsd.resource_policy", + "pyxsd.schemaless", + "pyxsd.stubs", + "pyxsd.transforms", + "pyxsd.validation", + "pyxsd.xdm", + "pyxsd.xpath", + "pyxsd.xslt", + } +) + + +def skip_api_member(app, what, name, obj, skip, options): + if what in {"module", "package"} and name not in PUBLIC_API_MODULES: + return True + return None + + +def is_generated_api(docname): + return docname.startswith("autoapi/") + + +class ReferencePythonDomain(PythonDomain): + """Keep both pages' anchors, but prefer hand-authored cross-reference targets.""" + + def note_object(self, name, objtype, node_id, aliased=False, location=None): + generated = is_generated_api(self.env.current_document.docname) + if previous := self.objects.get(name): + was_generated = is_generated_api(previous.docname) + if generated and not was_generated: + return + if was_generated and not generated: + del self.objects[name] + # Autodoc's short annotation names would otherwise match both public + # paths for these classes, which the guide already documents by module. + if generated and name in {"pyxsd.XmlLimits", "pyxsd.XmlParserPolicy"}: + aliased = True + super().note_object(name, objtype, node_id, aliased, location) + + def note_module(self, name, node_id, synopsis, platform, deprecated): + previous = self.modules.get(name) + if not ( + is_generated_api(self.env.current_document.docname) + and previous + and not is_generated_api(previous.docname) + ): + super().note_module(name, node_id, synopsis, platform, deprecated) + + +class StaticImportFilter(logging.Filter): + """Ignore internal registry cycles regardless of which module is scanned first.""" + + def filter(self, record): + if getattr(record, "subtype", None) != "python_import_resolution": + return True + prefix = "Cannot resolve cyclic import: " + message = record.getMessage() + if not message.startswith(prefix): + return True + modules = message.removeprefix(prefix).split(", ") + # The final module repeats at the start of the cycle. Ignore only + # cycles involving the XSD registry, not unrelated import warnings. + cycle = modules[modules.index(modules[-1]) :] + return ( + "pyxsd.element_representatives.element_representative" not in cycle + or not PUBLIC_API_MODULES.isdisjoint(cycle) + ) + + +def prepare_api_templates(env): + # AutoAPI cannot see imports guarded by TYPE_CHECKING. Autodoc can + # resolve these exports directly through the package's lazy __getattr__. + env.globals["lazy_exports"] = [ + (name, "class" if isinstance(getattr(pyxsd, name), type) else "function") + for name in pyxsd.__all__ + if not name.startswith("_") + ] + + +autoapi_prepare_jinja_env = prepare_api_templates + + +def resolve_generated_type(app, env, node, content): + """Link implementation names to their public re-exports where possible.""" + if node.get("refdomain") != "py": + return None + + docname = node["refdoc"] + target = node["reftarget"] + domain = env.get_domain("py") + parent, _, member = target.rpartition(".") + for symbol in getattr(env, "autoapi_all_objects", {}).values(): + origin = symbol.obj.get("original_path") + if origin and origin in (target, parent): + public_name = symbol.id if origin == target else f"{symbol.id}.{member}" + if entry := domain.objects.get(public_name): + return make_refnode(app.builder, docname, entry.docname, entry.node_id, content) + + # AutoAPI signatures also describe types that have no public reference + # page. Keep inferred annotations readable; explicit roles stay checked. + if is_generated_api(docname) and ( + "refexplicit" not in node or (node.get("reftype") == "class" and not node.get("refwarn")) + ): + return content + return None + + +def isolate_api_annotations(app, docname, source): + # AutoAPI's type fields must not replace autodoc's on the existing pages. + if not is_generated_api(docname): + app.env.temp_data.pop("annotations", None) + + +def reference_viewcode(app, doctree): + # Viewcode builds backlinks using defining modules, not the public + # aliases used by AutoAPI. Keep source links on the existing pages. + if not is_generated_api(app.env.current_document.docname): + viewcode.doctree_read(app, doctree) + + +def finish_api_build(app, exception): + logging.getLogger("sphinx.autoapi._mapper").removeFilter(app._static_import_filter) + + +def setup(app): + app.add_domain(ReferencePythonDomain, override=True) + for listener in app.events.listeners["doctree-read"]: + if listener.handler is viewcode.doctree_read: + app.disconnect(listener.id) + app.connect("doctree-read", reference_viewcode, priority=listener.priority) + break + app.connect("autoapi-skip-member", skip_api_member) + app.connect("source-read", isolate_api_annotations, priority=600) + app.connect("missing-reference", resolve_generated_type) + app._static_import_filter = StaticImportFilter() + logging.getLogger("sphinx.autoapi._mapper").addFilter(app._static_import_filter) + app.connect("build-finished", finish_api_build) + + # Strict cross-references: repair public targets in the docs, not broad ignores. nitpicky = True nitpick_ignore = [ diff --git a/docs/index.md b/docs/index.md index d6ced6e1..768c0a8a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -88,6 +88,7 @@ skills :caption: Reference and limits api +Python API cli supported xml-security diff --git a/pyproject.toml b/pyproject.toml index 543d5149..adbd23a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -79,6 +79,7 @@ docs = [ "furo>=2025.7", "sphinx-copybutton>=0.5.2", "sphinx-llms-txt>=0.7.1", + "sphinx-autoapi>=3.9", ] # Runnable consumer examples are examples-only environments; these are not # published extras and must never be installed by library users implicitly. diff --git a/src/pyxsd/binding.py b/src/pyxsd/binding.py index 3bf7c690..910ff51c 100644 --- a/src/pyxsd/binding.py +++ b/src/pyxsd/binding.py @@ -89,7 +89,7 @@ class ParseModes: #: for callers that need the pre-namespaced behavior. STRICT = BindingPolicy(namespaces="legacy") - #: Keep the report strict, but bind best-effort values: invalid + #: Keep the report strict while binding best-effort values. Invalid #: lexical values become raw strings, and unresolved or undeclared #: subtrees are bound generically instead of dropped. Kept explicitly #: for callers that need the pre-namespaced behavior. diff --git a/src/pyxsd/schema.py b/src/pyxsd/schema.py index 62abd401..0d4970ec 100644 --- a/src/pyxsd/schema.py +++ b/src/pyxsd/schema.py @@ -419,8 +419,7 @@ def compile( ``xs:import`` without a ``schemaLocation``. - ``overlay`` - an optional overlay class file, loaded after - class generation (experimental; see - :func:`load_overlay_classes`). + class generation (experimental). - ``namespace_context`` - an existing prefix-to-URI binding context for the schema documents' bindings to accumulate diff --git a/src/pyxsd/schemaless/nodes.py b/src/pyxsd/schemaless/nodes.py index 62416c5b..73d8d7bc 100644 --- a/src/pyxsd/schemaless/nodes.py +++ b/src/pyxsd/schemaless/nodes.py @@ -38,7 +38,7 @@ def attribute(name: str, *, type: TypeRef | None = None) -> Any: """Declare one expanded-name attribute field. - Reads call :meth:`~pyxsd.schemaless.tree.SchemalessElement.attribute_value` + Reads call ``SchemalessElement.attribute_value`` and therefore follow the document's effective scalar policy; a missing attribute reads as ``None``. Writes format the value through that same adapter and replace only that attribute. *name* is an expanded (Clark) @@ -51,7 +51,7 @@ def attribute(name: str, *, type: TypeRef | None = None) -> Any: def text(*, type: TypeRef | None = None, default: Any = None) -> Any: """Declare the element's leading character data as a scalar field. - Reads call :meth:`~pyxsd.schemaless.tree.SchemalessElement.scalar_value` + Reads call ``SchemalessElement.scalar_value`` for present leading text and return *default* when there is none. Mixed content stays mixed content: child tails are never concatenated into this value. Writes replace only the leading text. diff --git a/src/pyxsd/stubs.py b/src/pyxsd/stubs.py index e4d61085..7bd7b7c3 100644 --- a/src/pyxsd/stubs.py +++ b/src/pyxsd/stubs.py @@ -17,7 +17,7 @@ an error-bearing schema still compiles classes, and a stub may still be requested for it. -On top of the inventory, :func:`_members` resolves one class's +On top of the inventory, ``_members`` resolves one class's renderable members: its own element and attribute descriptors in declaration order, members attributed from a base class the inventory does not list (an overlay's generated base), and public functions and diff --git a/src/pyxsd/validation.py b/src/pyxsd/validation.py index be725442..ec3a0e36 100644 --- a/src/pyxsd/validation.py +++ b/src/pyxsd/validation.py @@ -45,7 +45,7 @@ class CompileContextProtocol(Protocol): Annotation-only structural view of :class:`~pyxsd.schema_composition.CompositionContext`, which satisfies it without inheriting from it: the declaration and - derivation checks in :mod:`pyxsd.schema_checks` accept this + derivation checks in ``pyxsd.schema_checks`` accept this protocol, so they depend on the attributes they actually touch rather than on the concrete pipeline context. diff --git a/src/pyxsd/xdm/values.py b/src/pyxsd/xdm/values.py index 4691c339..cd8a1fa9 100644 --- a/src/pyxsd/xdm/values.py +++ b/src/pyxsd/xdm/values.py @@ -48,7 +48,7 @@ class XdmItem: """Base class for one XDM item. Concrete items are immutable. Nodes extend this class in - :mod:`pyxsd.xdm.nodes`; they are not value items and are never compared by + ``pyxsd.xdm.nodes``; they are not value items and are never compared by value here. """ diff --git a/src/pyxsd/xslt/__init__.py b/src/pyxsd/xslt/__init__.py index 13f21d24..4998aeca 100644 --- a/src/pyxsd/xslt/__init__.py +++ b/src/pyxsd/xslt/__init__.py @@ -1,7 +1,7 @@ """XSLT 3.0 compilation, invocation, and optional advisory inspection. The normative processor, compiled stylesheet, and result views are the public -entry points. :mod:`pyxsd.xslt.inspection` remains a separate, non-normative +entry points. :func:`inspect_stylesheet` provides a separate, non-normative binding of the packaged XSLT schemas; it never decides acceptance or compiles the stylesheet. """ diff --git a/src/pyxsd/xslt/processor.py b/src/pyxsd/xslt/processor.py index 9f53a82d..b466d73a 100644 --- a/src/pyxsd/xslt/processor.py +++ b/src/pyxsd/xslt/processor.py @@ -936,7 +936,7 @@ def as_transform( complete transformation result; the callback only observes. This method constructs the adapter only: conversion, validation, - and result handling live in :mod:`pyxsd.xslt.adapter`. + and result handling live in ``pyxsd.xslt.adapter``. """ from pyxsd.xslt.adapter import XsltDocumentTransform diff --git a/tests/test_sphinx_site.py b/tests/test_sphinx_site.py index 66b9af79..37381b3c 100644 --- a/tests/test_sphinx_site.py +++ b/tests/test_sphinx_site.py @@ -1,5 +1,6 @@ """Rendered documentation contracts; install the docs group to run these tests.""" +import logging import os import re import runpy @@ -7,11 +8,14 @@ import sys from html import unescape from pathlib import Path +from urllib.parse import urljoin import pytest pytest.importorskip("sphinx") +from sphinx.util.inventory import InventoryFile + ROOT = Path(__file__).resolve().parents[1] @@ -164,6 +168,39 @@ def test_conf_has_no_regex_suppression(): assert not conf.get("nitpick_ignore_regex") +@pytest.mark.parametrize( + ("subtype", "message", "visible"), + [ + ( + "python_import_resolution", + "Cannot resolve cyclic import: pyxsd.identity, pyxsd.schema_base, " + "pyxsd.element_representatives.attribute, " + "pyxsd.element_representatives.element_representative, " + "pyxsd.element_representatives.attribute", + False, + ), + ( + "python_import_resolution", + "Cannot resolve cyclic import: pyxsd.batch, " + "pyxsd.element_representatives.element_representative, pyxsd.batch", + True, + ), + ( + "python_import_resolution", + "Cannot resolve cyclic import: " + "pyxsd.element_representatives.element_representative, x, y, x", + True, + ), + ("python_import_resolution", "Cannot resolve import of unknown module x", True), + ("other", "Other AutoAPI warning", True), + ], +) +def test_autoapi_filters_only_internal_registry_cycles(subtype, message, visible): + conf = runpy.run_path(str(ROOT / "docs/conf.py")) + record = logging.makeLogRecord({"msg": message, "subtype": subtype}) + assert conf["StaticImportFilter"]().filter(record) is visible + + def test_api_summary_links_resolve_to_unique_anchors(docs_build): html = (docs_build / "api.html").read_text(encoding="utf-8") tables = re.findall(r']*class="[^"]*autosummary[^"]*".*?', html, re.S) @@ -192,6 +229,50 @@ def test_api_summary_links_resolve_to_unique_anchors(docs_build): assert f'href="#{anchor}"' in "".join(tables), anchor +def test_generated_python_api(docs_build): + for page in ("index.html", "api.html"): + html = (docs_build / page).read_text(encoding="utf-8") + assert 'href="autoapi/pyxsd/index.html"' in html + + for module, symbols in ( + ("pyxsd", ("parse", "Schema", "Schema.parse")), + ("pyxsd.relaxng", ("compile", "RelaxNGSchema.compile")), + ("pyxsd.schemaless", ("from_json",)), + ("pyxsd.xslt", ("XsltProcessor",)), + ): + page = docs_build / "autoapi" / module.replace(".", "/") / "index.html" + html = page.read_text(encoding="utf-8") + for symbol in symbols: + assert f'id="{module}.{symbol}"' in html + + assert not (docs_build / "autoapi/pyxsd/xslt/compiler/index.html").exists() + assert not (docs_build / "autoapi/pyxsd/_lexical/index.html").exists() + + with (docs_build / "objects.inv").open("rb") as stream: + inventory = InventoryFile.load(stream, "", urljoin) + functions = inventory["py:function"] + assert functions["pyxsd.schemaless.from_json"].uri == "api.html#pyxsd.schemaless.from_json" + assert inventory["py:method"]["pyxsd.relaxng.RelaxNGSchema.compile"].uri == ( + "autoapi/pyxsd/relaxng/index.html#pyxsd.relaxng.RelaxNGSchema.compile" + ) + modules = inventory["py:module"] + assert modules["pyxsd.introspection"].uri == "api.html#module-pyxsd.introspection" + + +def test_existing_api_page_has_contents(docs_build): + html = (docs_build / "api.html").read_text(encoding="utf-8") + contents = re.search(r']+class="[^"]*\bcontents\b[^"]*"[^>]*>.*?', html, re.S) + assert contents is not None + for target in ( + "schema-and-documents", + "relax-ng", + "schemaless-xml-and-native-json", + "transforms", + ): + assert f'href="#{target}"' in contents[0] + assert f'id="{target}"' in html + + def test_real_site_channel_banner(docs_build): from pyxsd import __version__ diff --git a/uv.lock b/uv.lock index 95b318aa..01f210d1 100644 --- a/uv.lock +++ b/uv.lock @@ -125,6 +125,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5e/b5/08e2f643feb9e4d72d42a484949ad51238b18262a01c7036196c201cc330/ast_serialize-0.11.1-cp39-abi3-win_arm64.whl", hash = "sha256:a579ea6f473aab3958a64734194b22fbaec108ec45d994c28d3bd721e1e1da32", size = 1137533, upload-time = "2026-09-09T16:05:26.095Z" }, ] +[[package]] +name = "astroid" +version = "4.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/87/5732fa68bf100a095cfcbd108f919220d995db99e1a7502b8119a869fd62/astroid-4.3.4.tar.gz", hash = "sha256:d515a105722b72098bbe82d430d65e635f742b6cbac3bdfaf8b7c188b87c5e39", size = 444627, upload-time = "2026-10-08T09:36:44.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/d4/f23c0ac6e6de33ba5686cb21c672c95e0c2d3d4c9351f16d3b5fed818652/astroid-4.3.4-py3-none-any.whl", hash = "sha256:2bcd0d02648a443a4b818c952c3550091989daefac3c12d3b83b2289482e0818", size = 288310, upload-time = "2026-10-08T09:36:42.284Z" }, +] + [[package]] name = "attrs" version = "26.1.0" @@ -2479,6 +2488,7 @@ docs = [ { name = "myst-parser" }, { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "sphinx", version = "9.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "sphinx-autoapi" }, { name = "sphinx-copybutton" }, { name = "sphinx-llms-txt" }, ] @@ -2535,6 +2545,7 @@ docs = [ { name = "furo", specifier = ">=2025.7" }, { name = "myst-parser", specifier = ">=4.1" }, { name = "sphinx", specifier = ">=8.2" }, + { name = "sphinx-autoapi", specifier = ">=3.9" }, { name = "sphinx-copybutton", specifier = ">=0.5.2" }, { name = "sphinx-llms-txt", specifier = ">=0.7.1" }, ] @@ -2905,6 +2916,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/73/f7/b1884cb3188ab181fc81fa00c266699dab600f927a964df02ec3d5d1916a/sphinx-9.1.0-py3-none-any.whl", hash = "sha256:c84fdd4e782504495fe4f2c0b3413d6c2bf388589bb352d439b2a3bb99991978", size = 3921742, upload-time = "2025-12-31T15:09:25.561Z" }, ] +[[package]] +name = "sphinx-autoapi" +version = "3.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "astroid" }, + { name = "jinja2" }, + { name = "pyyaml" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "sphinx", version = "9.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4b/e8/12412b8c25b7e22fc6677ce84aceb278e856a688478e0a3c6eb211281c75/sphinx_autoapi-3.9.0.tar.gz", hash = "sha256:0b2a47beac401c5fe437fbcd41c650c6cdc072234e576f56ef04456805bddabf", size = 61311, upload-time = "2026-10-31T03:00:41.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3a/c4/d08333f57470065ca1e551d907f7cdd7ee873da436f6f352b773276e7720/sphinx_autoapi-3.9.0-py3-none-any.whl", hash = "sha256:8ecba31815322b00e9fb01973c210ba651522d25f92705a4384fd6c429c5a28f", size = 36448, upload-time = "2026-10-31T03:00:39.818Z" }, +] + [[package]] name = "sphinx-basic-ng" version = "1.0.0b2"