Debian Codegraph @

src/mkdocstrings_handlers/python/_internal/rendering.py

raw
1 # This module implements rendering utilities.
2
3 from __future__ import annotations
4
5 import random
6 import re
7 import string
8 import subprocess
9 import sys
10 from collections import defaultdict
11 from contextlib import suppress
12 from dataclasses import replace
13 from functools import lru_cache
14 from pathlib import Path
15 from re import Pattern
16 from typing import TYPE_CHECKING, Any, Callable, ClassVar, Literal, TypeVar
17
18 from griffe import (
19 Alias,
20 AliasResolutionError,
21 CyclicAliasError,
22 DocstringAttribute,
23 DocstringClass,
24 DocstringFunction,
25 DocstringModule,
26 DocstringSectionAttributes,
27 DocstringSectionClasses,
28 DocstringSectionFunctions,
29 DocstringSectionModules,
30 DocstringSectionTypeAliases,
31 DocstringTypeAlias,
32 Object,
33 TypeAlias,
34 )
35 from jinja2 import pass_context
36 from markupsafe import Markup
37 from mkdocs_autorefs import AutorefsHookInterface, Backlink, BacklinkCrumb
38 from mkdocstrings import get_logger
39
40 if TYPE_CHECKING:
41 from collections.abc import Iterable, Iterator, Sequence
42
43 from griffe import Attribute, Class, Function, Module
44 from jinja2.runtime import Context
45 from mkdocstrings import CollectorItem
46
47 _logger = get_logger(__name__)
48
49
50 def _sort_key_alphabetical(item: CollectorItem) -> str:
51 # `chr(sys.maxunicode)` is a string that contains the final unicode character,
52 # so if `name` isn't found on the object, the item will go to the end of the list.
53 return item.name or chr(sys.maxunicode)
54
55
56 def _sort_key_source(item: CollectorItem) -> float:
57 # If `lineno` is none, the item will go to the end of the list.
58 if item.is_alias:
59 return item.alias_lineno if item.alias_lineno is not None else float("inf")
60 return item.lineno if item.lineno is not None else float("inf")
61
62
63 def _sort__all__(item: CollectorItem) -> float:
64 if item.parent.exports is not None:
65 try:
66 return item.parent.exports.index(item.name)
67 except ValueError:
68 # If the item is not in `__all__`, it will go to the end of the list.
69 return float("inf")
70 # No exports declared, refuse to sort (try other methods or return members as they are).
71 raise ValueError(f"Parent object {item.parent.path} doesn't declare exports")
72
73
74 Order = Literal["__all__", "alphabetical", "source"]
75 """Ordering methods.
76
77 - `__all__`: order members according to `__all__` module attributes, if declared;
78 - `alphabetical`: order members alphabetically;
79 - `source`: order members as they appear in the source file.
80 """
81
82 _order_map: dict[str, Callable[[Object | Alias], str | float]] = {
83 "alphabetical": _sort_key_alphabetical,
84 "source": _sort_key_source,
85 "__all__": _sort__all__,
86 }
87
88
89 def do_format_code(code: str, line_length: int) -> str:
90 """Format code.
91
92 Parameters:
93 code: The code to format.
94 line_length: The line length.
95
96 Returns:
97 The same code, formatted.
98 """
99 code = code.strip()
100 if len(code) < line_length:
101 return code
102 formatter = _get_formatter()
103 return formatter(code, line_length)
104
105
106 class _StashCrossRefFilter:
107 stash: ClassVar[dict[str, str]] = {}
108
109 @staticmethod
110 def _gen_key(length: int) -> str:
111 return "_" + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(max(2, length - 1))) # noqa: S311
112
113 def _gen_stash_key(self, length: int) -> str:
114 key = self._gen_key(length)
115 while key in self.stash:
116 key = self._gen_key(length)
117 return key
118
119 def __call__(self, crossref: str, *, length: int) -> str:
120 key = self._gen_stash_key(length)
121 self.stash[key] = crossref
122 return key
123
124
125 do_stash_crossref = _StashCrossRefFilter()
126 """Filter to stash cross-references (and restore them after formatting and highlighting)."""
127
128
129 def _format_signature(name: Markup, signature: str, line_length: int) -> str:
130 name = str(name).strip() # type: ignore[assignment]
131 signature = signature.strip()
132 if len(name + signature) < line_length:
133 return name + signature
134
135 # Black cannot format names with dots, so we replace
136 # the whole name with a string of equal length
137 name_length = len(name)
138 formatter = _get_formatter()
139 formatable = f"def {'x' * name_length}{signature}: pass"
140 formatted = formatter(formatable, line_length)
141
142 # We put back the original name
143 # and remove starting `def ` and trailing `: pass`
144 return name + formatted[4:-5].strip()[name_length:-1]
145
146
147 @pass_context
148 def do_format_signature(
149 context: Context,
150 callable_path: Markup,
151 function: Function,
152 line_length: int,
153 *,
154 annotations: bool | None = None,
155 crossrefs: bool = False, # noqa: ARG001
156 ) -> str:
157 """Format a signature.
158
159 Parameters:
160 context: Jinja context, passed automatically.
161 callable_path: The path of the callable we render the signature of.
162 function: The function we render the signature of.
163 line_length: The line length.
164 annotations: Whether to show type annotations.
165 crossrefs: Whether to cross-reference types in the signature.
166
167 Returns:
168 The same code, formatted.
169 """
170 env = context.environment
171 type_params_template = env.get_template("type_parameters.html.jinja")
172 signature_template = env.get_template("signature.html.jinja")
173
174 if annotations is None:
175 new_context = context.parent
176 else:
177 new_context = dict(context.parent)
178 new_context["config"] = replace(new_context["config"], show_signature_annotations=annotations)
179
180 signature = type_params_template.render(context.parent, obj=function, signature=True)
181 signature += signature_template.render(new_context, function=function, signature=True)
182
183 signature = _format_signature(callable_path, signature, line_length)
184 signature = str(
185 env.filters["highlight"](
186 Markup.escape(signature),
187 language="python",
188 inline=False,
189 classes=["doc-signature"],
190 linenums=False,
191 ),
192 )
193
194 # Since we highlight the signature without `def`,
195 # Pygments sees it as a function call and not a function definition.
196 # The result is that the function name is not parsed as such,
197 # but instead as a regular name: `n` CSS class instead of `nf`.
198 # When the function name is a known special name like `__exit__`,
199 # Pygments will set an `fm` (function -> magic) CSS class.
200 # To fix this, we replace the CSS class in the first span with `nf`,
201 # unless we already found an `nf` span.
202 if not re.search(r'<span class="nf">', signature):
203 signature = re.sub(r'<span class="[a-z]{1,2}">', '<span class="nf">', signature, count=1)
204
205 if stash := env.filters["stash_crossref"].stash:
206 for key, value in stash.items():
207 signature = re.sub(rf"\b{key}\b", value, signature)
208 stash.clear()
209
210 return signature
211
212
213 @pass_context
214 def do_format_attribute(
215 context: Context,
216 attribute_path: Markup,
217 attribute: Attribute,
218 line_length: int,
219 *,
220 crossrefs: bool = False, # noqa: ARG001
221 show_value: bool = True,
222 ) -> str:
223 """Format an attribute.
224
225 Parameters:
226 context: Jinja context, passed automatically.
227 attribute_path: The path of the callable we render the signature of.
228 attribute: The attribute we render the signature of.
229 line_length: The line length.
230 crossrefs: Whether to cross-reference types in the signature.
231
232 Returns:
233 The same code, formatted.
234 """
235 env = context.environment
236 template = env.get_template("expression.html.jinja")
237 annotations = context.parent["config"].show_signature_annotations
238
239 signature = str(attribute_path).strip()
240 if annotations and attribute.annotation:
241 annotation = template.render(
242 context.parent,
243 expression=attribute.annotation,
244 signature=True,
245 backlink_type="returned-by",
246 )
247 signature += f": {annotation}"
248 if show_value and attribute.value:
249 value = template.render(
250 context.parent,
251 expression=attribute.value,
252 signature=True,
253 annotations_path="source",
254 backlink_type="used-by",
255 )
256 signature += f" = {value}"
257
258 signature = do_format_code(signature, line_length)
259 signature = str(
260 env.filters["highlight"](
261 Markup.escape(signature),
262 language="python",
263 inline=False,
264 classes=["doc-signature"],
265 linenums=False,
266 ),
267 )
268
269 if stash := env.filters["stash_crossref"].stash:
270 for key, value in stash.items():
271 signature = re.sub(rf"\b{key}\b", value, signature)
272 stash.clear()
273
274 return signature
275
276
277 @pass_context
278 def do_format_type_alias(
279 context: Context,
280 type_alias_path: Markup,
281 type_alias: TypeAlias,
282 line_length: int,
283 *,
284 crossrefs: bool = False, # noqa: ARG001
285 ) -> str:
286 """Format a type alias.
287
288 Parameters:
289 context: Jinja context, passed automatically.
290 type_alias_path: The path of the type alias we render the signature of.
291 type_alias: The type alias we render the signature of.
292 line_length: The line length.
293 crossrefs: Whether to cross-reference types in the signature.
294
295 Returns:
296 The same code, formatted.
297 """
298 env = context.environment
299 type_params_template = env.get_template("type_parameters.html.jinja")
300 expr_template = env.get_template("expression.html.jinja")
301
302 signature = str(type_alias_path).strip()
303 signature += type_params_template.render(context.parent, obj=type_alias, signature=True)
304 value = expr_template.render(context.parent, expression=type_alias.value, signature=True)
305 signature += f" = {value}"
306
307 signature = do_format_code(signature, line_length)
308 signature = str(
309 env.filters["highlight"](
310 Markup.escape(signature),
311 language="python",
312 inline=False,
313 classes=["doc-signature"],
314 linenums=False,
315 ),
316 )
317
318 # Since we highlight the signature without `type`,
319 # Pygments sees only an assignment, not a type alias definition
320 # (at the moment it does not understand type alias definitions anyway).
321 # The result is that the type alias name is not parsed as such,
322 # but instead as a regular name: `n` CSS class instead of `nc`.
323 # To fix it, we replace the first occurrence of an `n` CSS class
324 # with an `nc` one, unless we found `nc` already.
325 if not re.search(r'<span class="nc">', signature):
326 signature = re.sub(r'<span class="[a-z]{1,2}">', '<span class="nc">', signature, count=1)
327
328 if stash := env.filters["stash_crossref"].stash:
329 for key, value in stash.items():
330 signature = re.sub(rf"\b{key}\b", value, signature)
331 stash.clear()
332
333 return signature
334
335
336 def do_order_members(
337 members: Sequence[Object | Alias],
338 order: Order | list[Order],
339 members_list: bool | list[str] | None, # noqa: FBT001
340 ) -> Sequence[Object | Alias]:
341 """Order members given an ordering method.
342
343 Parameters:
344 members: The members to order.
345 order: The ordering method.
346 members_list: An optional member list (manual ordering).
347
348 Returns:
349 The same members, ordered.
350 """
351 if isinstance(members_list, list) and members_list:
352 sorted_members = []
353 members_dict = {member.name: member for member in members}
354 for name in members_list:
355 if name in members_dict:
356 sorted_members.append(members_dict[name])
357 return sorted_members
358 if isinstance(order, str):
359 order = [order]
360 for method in order:
361 with suppress(ValueError):
362 return sorted(members, key=_order_map[method])
363 return members
364
365
366 _split_path_re = re.compile(r"([.(]?)([\w]+)(\))?")
367 _splitable_re = re.compile(r"[().]")
368
369
370 def do_split_path(path: str, full_path: str) -> Iterator[tuple[str, str, str, str]]:
371 """Split object paths for building cross-references.
372
373 Parameters:
374 path: The path to split.
375 full_path: The full path, used to compute correct paths for each part of the path.
376
377 Yields:
378 4-tuples: prefix, word, full path, suffix.
379 """
380 # Path is a single word, yield full path directly.
381 if not _splitable_re.search(path):
382 yield ("", path, full_path, "")
383 return
384
385 current_path = ""
386 if path == full_path:
387 # Split full path and yield directly without storing data in a dict.
388 for match in _split_path_re.finditer(full_path):
389 prefix, word, suffix = match.groups()
390 current_path = f"{current_path}{prefix}{word}{suffix or ''}" if current_path else word
391 yield prefix or "", word, current_path, suffix or ""
392 return
393
394 # Split full path first to store tuples in a dict.
395 elements = {}
396 for match in _split_path_re.finditer(full_path):
397 prefix, word, suffix = match.groups()
398 current_path = f"{current_path}{prefix}{word}{suffix or ''}" if current_path else word
399 elements[word] = (prefix or "", word, current_path, suffix or "")
400
401 # Then split path and pick tuples from the dict.
402 first = True
403 for match in _split_path_re.finditer(path):
404 prefix, word, current_path, suffix = elements[match.group(2)]
405 yield "" if first else prefix, word, current_path, suffix
406 first = False
407
408
409 def _keep_object(name: str, filters: Sequence[tuple[Pattern, bool]]) -> bool:
410 keep = None
411 rules = set()
412 for regex, exclude in filters:
413 rules.add(exclude)
414 if regex.search(name):
415 keep = not exclude
416 if keep is None:
417 # When we only include stuff, no match = reject.
418 # When we only exclude stuff, or include and exclude stuff, no match = keep.
419 return rules != {False}
420 return keep
421
422
423 def _parents(obj: Alias) -> set[str]:
424 parents = {obj.path}
425 parent = obj.parent
426 while parent is not None:
427 parents.add(parent.path)
428 if isinstance(parent, Alias):
429 parents.add(parent.final_target.path)
430 parent = parent.parent
431 return parents
432
433
434 def _remove_cycles(objects: list[Object | Alias]) -> Iterator[Object | Alias]:
435 suppress_errors = suppress(AliasResolutionError, CyclicAliasError)
436 for obj in objects:
437 if isinstance(obj, Alias):
438 with suppress_errors:
439 if obj.final_target.path in _parents(obj):
440 continue
441 yield obj
442
443
444 def do_filter_objects(
445 objects_dictionary: dict[str, Object | Alias],
446 *,
447 filters: Sequence[tuple[Pattern, bool]] | Literal["public"] | None = None,
448 members_list: bool | list[str] | None = None,
449 inherited_members: bool | list[str] = False,
450 keep_no_docstrings: bool = True,
451 ) -> list[Object | Alias]:
452 """Filter a dictionary of objects based on their docstrings.
453
454 Parameters:
455 objects_dictionary: The dictionary of objects.
456 filters: Filters to apply, based on members' names, or `"public"`.
457 Each element is a tuple: a pattern, and a boolean indicating whether
458 to reject the object if the pattern matches.
459 members_list: An optional, explicit list of members to keep.
460 When given and empty, return an empty list.
461 When given and not empty, ignore filters and docstrings presence/absence.
462 inherited_members: Whether to keep inherited members or exclude them.
463 keep_no_docstrings: Whether to keep objects with no/empty docstrings (recursive check).
464
465 Returns:
466 A list of objects.
467 """
468 inherited_members_specified = False
469 if inherited_members is True:
470 # Include all inherited members.
471 objects = list(objects_dictionary.values())
472 elif inherited_members is False:
473 # Include no inherited members.
474 objects = [obj for obj in objects_dictionary.values() if not obj.inherited]
475 else:
476 # Include specific inherited members.
477 inherited_members_specified = True
478 objects = [
479 obj for obj in objects_dictionary.values() if not obj.inherited or obj.name in set(inherited_members)
480 ]
481
482 if members_list is True:
483 # Return all pre-selected members.
484 return objects
485
486 if members_list is False or members_list == []:
487 # Return selected inherited members, if any.
488 return [obj for obj in objects if obj.inherited]
489
490 if members_list is not None:
491 # Return selected members (keeping any pre-selected inherited members).
492 return [
493 obj for obj in objects if obj.name in set(members_list) or (inherited_members_specified and obj.inherited)
494 ]
495
496 # Use filters and docstrings.
497 if filters == "public":
498 objects = [obj for obj in objects if obj.is_public]
499 elif filters:
500 objects = [
501 obj for obj in objects if _keep_object(obj.name, filters) or (inherited_members_specified and obj.inherited)
502 ]
503 if not keep_no_docstrings:
504 objects = [obj for obj in objects if obj.has_docstrings or (inherited_members_specified and obj.inherited)]
505
506 # Prevent infinite recursion.
507 if objects:
508 objects = list(_remove_cycles(objects))
509
510 return objects
511
512
513 @lru_cache(maxsize=1)
514 def _get_formatter() -> Callable[[str, int], str]:
515 for formatter_function in [
516 _get_black_formatter,
517 _get_ruff_formatter,
518 ]:
519 if (formatter := formatter_function()) is not None:
520 return formatter
521
522 _logger.info("Formatting signatures requires either Black or Ruff to be installed.")
523 return lambda text, _: text
524
525
526 def _get_ruff_formatter() -> Callable[[str, int], str] | None:
527 try:
528 from ruff.__main__ import find_ruff_bin # noqa: PLC0415
529 except ImportError:
530 return None
531
532 try:
533 ruff_bin = find_ruff_bin()
534 except FileNotFoundError:
535 ruff_bin = "ruff"
536
537 def formatter(code: str, line_length: int) -> str:
538 try:
539 completed_process = subprocess.run( # noqa: S603
540 [
541 ruff_bin,
542 "format",
543 "--config",
544 f"line-length={line_length}",
545 "--stdin-filename",
546 "file.py",
547 "-",
548 ],
549 check=True,
550 capture_output=True,
551 text=True,
552 input=code,
553 )
554 except subprocess.CalledProcessError:
555 return code
556 else:
557 return completed_process.stdout
558
559 return formatter
560
561
562 def _get_black_formatter() -> Callable[[str, int], str] | None:
563 try:
564 from black import InvalidInput, Mode, format_str # noqa: PLC0415
565 except ModuleNotFoundError:
566 return None
567
568 def formatter(code: str, line_length: int) -> str:
569 mode = Mode(line_length=line_length)
570 try:
571 return format_str(code, mode=mode)
572 except InvalidInput:
573 return code
574
575 return formatter
576
577
578 def do_get_template(obj: Object | Alias) -> str:
579 """Get the template name used to render an object.
580
581 Parameters:
582 obj: A Griffe object.
583
584 Returns:
585 A template name.
586 """
587 extra_data = getattr(obj, "extra", {}).get("mkdocstrings", {})
588 if name := extra_data.get("template", ""):
589 return name
590 name = obj.kind.value.replace(" ", "_")
591 return f"{name}.html.jinja"
592
593
594 def do_source_location(obj: Object | Alias) -> Path:
595 """Get the file path displayed in an object's source block label.
596
597 Environment paths are never displayed: when the object's file lives in
598 a `site-packages` directory (for example a virtual environment inside
599 the current working directory), the path below `site-packages` is
600 returned instead.
601
602 Parameters:
603 obj: A Griffe object.
604
605 Returns:
606 The file path to display.
607 """
608 relative_filepath = obj.relative_filepath
609 parts = relative_filepath.parts
610 if "site-packages" in parts:
611 anchor = len(parts) - 1 - parts[::-1].index("site-packages")
612 return Path(*parts[anchor + 1 :])
613 if relative_filepath.is_absolute():
614 return obj.relative_package_filepath
615 return relative_filepath
616
617
618 @pass_context
619 def do_as_attributes_section(
620 context: Context, # noqa: ARG001
621 attributes: Sequence[Attribute],
622 *,
623 check_public: bool = True,
624 ) -> DocstringSectionAttributes:
625 """Build an attributes section from a list of attributes.
626
627 Parameters:
628 attributes: The attributes to build the section from.
629 check_public: Whether to check if the attribute is public.
630
631 Returns:
632 An attributes docstring section.
633 """
634
635 def _parse_docstring_summary(attribute: Attribute) -> str:
636 if attribute.docstring is None:
637 return ""
638 line = attribute.docstring.value.split("\n", 1)[0]
639 if ":" in line and attribute.docstring.parser_options.get("returns_type_in_property_summary", False):
640 _, line = line.split(":", 1)
641 return line
642
643 return DocstringSectionAttributes(
644 [
645 DocstringAttribute(
646 name=attribute.name,
647 description=_parse_docstring_summary(attribute),
648 annotation=attribute.annotation,
649 value=attribute.value,
650 )
651 for attribute in attributes
652 if not check_public or attribute.is_public
653 ],
654 )
655
656
657 @pass_context
658 def do_as_functions_section(
659 context: Context,
660 functions: Sequence[Function],
661 *,
662 check_public: bool = True,
663 ) -> DocstringSectionFunctions:
664 """Build a functions section from a list of functions.
665
666 Parameters:
667 functions: The functions to build the section from.
668 check_public: Whether to check if the function is public.
669
670 Returns:
671 A functions docstring section.
672 """
673 keep_init_method = not context.parent["config"].merge_init_into_class
674 return DocstringSectionFunctions(
675 [
676 DocstringFunction(
677 name=function.name,
678 description=function.docstring.value.split("\n", 1)[0] if function.docstring else "",
679 )
680 for function in functions
681 if (not check_public or function.is_public) and (function.name != "__init__" or keep_init_method)
682 ],
683 )
684
685
686 @pass_context
687 def do_as_classes_section(
688 context: Context, # noqa: ARG001
689 classes: Sequence[Class],
690 *,
691 check_public: bool = True,
692 ) -> DocstringSectionClasses:
693 """Build a classes section from a list of classes.
694
695 Parameters:
696 classes: The classes to build the section from.
697 check_public: Whether to check if the class is public.
698
699 Returns:
700 A classes docstring section.
701 """
702 return DocstringSectionClasses(
703 [
704 DocstringClass(
705 name=cls.name,
706 description=cls.docstring.value.split("\n", 1)[0] if cls.docstring else "",
707 )
708 for cls in classes
709 if not check_public or cls.is_public
710 ],
711 )
712
713
714 @pass_context
715 def do_as_modules_section(
716 context: Context, # noqa: ARG001
717 modules: Sequence[Module],
718 *,
719 check_public: bool = True,
720 ) -> DocstringSectionModules:
721 """Build a modules section from a list of modules.
722
723 Parameters:
724 modules: The modules to build the section from.
725 check_public: Whether to check if the module is public.
726
727 Returns:
728 A modules docstring section.
729 """
730 return DocstringSectionModules(
731 [
732 DocstringModule(
733 name=module.name,
734 description=module.docstring.value.split("\n", 1)[0] if module.docstring else "",
735 )
736 for module in modules
737 if not check_public or module.is_public
738 ],
739 )
740
741
742 @pass_context
743 def do_as_type_aliases_section(
744 context: Context, # noqa: ARG001
745 type_aliases: Sequence[TypeAlias],
746 *,
747 check_public: bool = True,
748 ) -> DocstringSectionTypeAliases:
749 """Build a type aliases section from a list of type aliases.
750
751 Parameters:
752 type_aliases: The type aliases to build the section from.
753 check_public: Whether to check if the type_alias is public.
754
755 Returns:
756 A type aliases docstring section.
757 """
758 return DocstringSectionTypeAliases(
759 [
760 DocstringTypeAlias(
761 name=type_alias.name,
762 description=type_alias.docstring.value.split("\n", 1)[0] if type_alias.docstring else "",
763 )
764 for type_alias in type_aliases
765 if not check_public or type_alias.is_public
766 ],
767 )
768
769
770 class AutorefsHook(AutorefsHookInterface):
771 """Autorefs hook.
772
773 With this hook, we're able to add context to autorefs (cross-references),
774 such as originating file path and line number, to improve error reporting.
775 """
776
777 def __init__(self, current_object: Object | Alias, config: dict[str, Any]) -> None:
778 """Initialize the hook.
779
780 Parameters:
781 current_object: The object being rendered.
782 config: The configuration dictionary.
783 """
784 self.current_object = current_object
785 """The current object being rendered."""
786 self.config = config
787 """The configuration options."""
788
789 def expand_identifier(self, identifier: str) -> str:
790 """Expand an identifier.
791
792 Parameters:
793 identifier: The identifier to expand.
794
795 Returns:
796 The expanded identifier.
797 """
798 # Handle leading dots in the identifier:
799 # - `.name` is a reference to the current object's `name` member.
800 # - `..name` is a reference to the parent object's `name` member.
801 # - etc.
802 # TODO: We should update the protocol to allow modifying the title too.
803 # In this case it would likely be better to strip dots from the title,
804 # when it's not explicitly specified.
805 if self.config.relative_crossrefs and identifier.startswith("."): # type: ignore[attr-defined]
806 identifier = identifier[1:]
807 obj = self.current_object
808 while identifier and identifier[0] == ".":
809 identifier = identifier[1:]
810 if obj.parent is None:
811 break
812 obj = obj.parent
813 identifier = f"{obj.path}.{identifier}" if identifier else obj.path
814
815 # We resolve the identifier to its full path.
816 # For this we take out the first name, resolve it, and then append the rest.
817 if self.config.scoped_crossrefs: # type: ignore[attr-defined]
818 if "." in identifier:
819 identifier, remaining = identifier.split(".", 1)
820 else:
821 remaining = ""
822 with suppress(Exception):
823 identifier = self.current_object.resolve(identifier)
824 if remaining:
825 identifier = f"{identifier}.{remaining}"
826
827 return identifier
828
829 def get_context(self) -> AutorefsHookInterface.Context:
830 """Get the context for the current object.
831
832 Returns:
833 The context.
834 """
835 role = {
836 "attribute": "data" if self.current_object.parent and self.current_object.parent.is_module else "attr",
837 "class": "class",
838 "function": "meth" if self.current_object.parent and self.current_object.parent.is_class else "func",
839 "module": "mod",
840 }.get(self.current_object.kind.value.lower(), "obj")
841 origin = self.current_object.path
842 docstring = self.current_object.docstring
843 if docstring is None or docstring.parent is None:
844 filepath = self.current_object.filepath
845 lineno = 0
846 else:
847 filepath = docstring.parent.filepath
848 lineno = docstring.lineno or 0
849
850 return AutorefsHookInterface.Context(
851 domain="py",
852 role=role,
853 origin=origin,
854 filepath=str(filepath),
855 lineno=lineno,
856 )
857
858
859 _T = TypeVar("_T")
860 _Tree = dict[_T, "_Tree"]
861 _rtree = lambda: defaultdict(_rtree) # type: ignore[has-type,var-annotated] # noqa: E731
862
863 Tree = dict[tuple[_T, ...], "Tree"]
864 """A tree type. Each node holds a tuple of items."""
865
866
867 def _tree(data: Iterable[tuple[_T, ...]]) -> _Tree:
868 new_tree = _rtree()
869 for nav in data:
870 *path, leaf = nav
871 node = new_tree
872 for key in path:
873 node = node[key]
874 node[leaf] = _rtree()
875 return new_tree
876
877
878 def _compact_tree(tree: _Tree) -> Tree:
879 new_tree = _rtree()
880 for key, value in tree.items():
881 child = _compact_tree(value)
882 if len(child) == 1:
883 child_key, child_value = next(iter(child.items()))
884 new_key = (key, *child_key)
885 new_tree[new_key] = child_value
886 else:
887 new_tree[(key,)] = child
888 return new_tree
889
890
891 def do_backlink_tree(backlinks: list[Backlink]) -> Tree[BacklinkCrumb]:
892 """Build a tree of backlinks.
893
894 Parameters:
895 backlinks: The list of backlinks.
896
897 Returns:
898 A tree of backlinks.
899 """
900 return _compact_tree(_tree(backlink.crumbs for backlink in backlinks))