| 1 |
"""Transform references to typevars to avoid missing reference errors. |
| 2 |
|
| 3 |
See https://github.com/sphinx-doc/sphinx/issues/7722 also. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import re |
| 9 |
from pathlib import Path |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
import trio |
| 13 |
from sphinx.errors import NoUri |
| 14 |
|
| 15 |
if TYPE_CHECKING: |
| 16 |
from sphinx.addnodes import Element, pending_xref |
| 17 |
from sphinx.application import Sphinx |
| 18 |
from sphinx.environment import BuildEnvironment |
| 19 |
|
| 20 |
|
| 21 |
def identify_typevars(trio_folder: Path) -> None: |
| 22 |
"""Record all typevars in trio.""" |
| 23 |
for filename in trio_folder.rglob("*.py"): |
| 24 |
with open(filename, encoding="utf8") as f: |
| 25 |
for line in f: |
| 26 |
# A simple regex should be sufficient to find them all, no need to actually parse. |
| 27 |
match = re.search( |
| 28 |
r"\b(TypeVar|TypeVarTuple|ParamSpec)\(['\"]([^'\"]+)['\"]", |
| 29 |
line, |
| 30 |
) |
| 31 |
if match is not None: |
| 32 |
relative = "trio" / filename.relative_to(trio_folder) |
| 33 |
relative = relative.with_suffix("") |
| 34 |
if relative.name == "__init__": # Package, remove. |
| 35 |
relative = relative.parent |
| 36 |
kind = match.group(1) |
| 37 |
name = match.group(2) |
| 38 |
typevars_qualified[f'{".".join(relative.parts)}.{name}'] = kind |
| 39 |
existing = typevars_named.setdefault(name, kind) |
| 40 |
if existing != kind: |
| 41 |
print("Mismatch: {} = {}, {}", name, existing, kind) |
| 42 |
|
| 43 |
|
| 44 |
# All our typevars, so we can suppress reference errors for them. |
| 45 |
typevars_qualified: dict[str, str] = {} |
| 46 |
typevars_named: dict[str, str] = {} |
| 47 |
|
| 48 |
|
| 49 |
def lookup_reference( |
| 50 |
app: Sphinx, |
| 51 |
env: BuildEnvironment, |
| 52 |
node: pending_xref, |
| 53 |
contnode: Element, |
| 54 |
) -> Element | None: |
| 55 |
"""Handle missing references.""" |
| 56 |
# If this is a typing_extensions object, redirect to typing. |
| 57 |
# Most things there are backports, so the stdlib docs should have an entry. |
| 58 |
target: str = node["reftarget"] |
| 59 |
if target.startswith("typing_extensions."): |
| 60 |
new_node = node.copy() |
| 61 |
new_node["reftarget"] = f"typing.{target[18:]}" |
| 62 |
# This fires off this same event, with our new modified node in order to fetch the right |
| 63 |
# URL to use. |
| 64 |
return app.emit_firstresult( # type: ignore[no-any-return] |
| 65 |
"missing-reference", |
| 66 |
env, |
| 67 |
new_node, |
| 68 |
contnode, |
| 69 |
allowed_exceptions=(NoUri,), |
| 70 |
) |
| 71 |
|
| 72 |
try: |
| 73 |
typevar_type = typevars_qualified[target] |
| 74 |
except KeyError: |
| 75 |
# Imports might mean the typevar was defined in a different module or something. |
| 76 |
# Fall back to checking just by name. |
| 77 |
dot = target.rfind(".") |
| 78 |
stem = target[dot + 1 :] if dot >= 0 else target |
| 79 |
try: |
| 80 |
typevar_type = typevars_named[stem] |
| 81 |
except KeyError: |
| 82 |
# Let other handlers deal with this name, it's not a typevar. |
| 83 |
return None |
| 84 |
|
| 85 |
# Found a typevar. Redirect to the stdlib docs for that kind of var. |
| 86 |
new_node = node.copy() |
| 87 |
new_node["reftarget"] = f"typing.{typevar_type}" |
| 88 |
new_node = app.emit_firstresult( |
| 89 |
"missing-reference", |
| 90 |
env, |
| 91 |
new_node, |
| 92 |
contnode, |
| 93 |
allowed_exceptions=(NoUri,), |
| 94 |
) |
| 95 |
reftitle = new_node["reftitle"] |
| 96 |
# Is normally "(in Python 3.XX)", make it say typevar/paramspec/etc |
| 97 |
paren = "(" if reftitle.startswith("(") else "" |
| 98 |
new_node["reftitle"] = f"{paren}{typevar_type}, {reftitle.lstrip('(')}" |
| 99 |
# Add a CSS class, for restyling. |
| 100 |
new_node["classes"].append("typevarref") |
| 101 |
return new_node # type: ignore[no-any-return] |
| 102 |
|
| 103 |
|
| 104 |
def setup(app: Sphinx) -> None: |
| 105 |
identify_typevars(Path(trio.__file__).parent) |
| 106 |
app.connect("missing-reference", lookup_reference, -10) |