-
Notifications
You must be signed in to change notification settings - Fork 32
/
apigen.py
1827 lines (1527 loc) · 60.9 KB
/
apigen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Python API documentation generation extension.
A separate page is generated for each class/function/member/constant to be
documented.
As with sphinx.ext.autosummary, we have to physically write a separate rST file
to the source tree for each object to document, as an initial preprocesing step,
since that provides the simplest way to get Sphinx to process those pages. It
is recommended to run the build with the source tree copied to a temporary
directory in order to avoid modifying the real source tree.
Unlike the sphinx.ext.autosummary extension, we use Sphinx Python domain
directives for the "summaries" as well, rather than a plain table, in order to
display the signatures nicely.
"""
import copy
import dataclasses
import importlib
import inspect
import json
import re
from typing import (
List,
Tuple,
Any,
Optional,
Type,
cast,
Dict,
NamedTuple,
Iterator,
Set,
)
import docutils.nodes
import docutils.parsers.rst.states
import docutils.statemachine
import sphinx
import sphinx.addnodes
import sphinx.application
import sphinx.domains.python
import sphinx.environment
import sphinx.ext.autodoc
import sphinx.ext.autodoc.directive
import sphinx.ext.napoleon.docstring
import sphinx.pycode
import sphinx.util.docstrings
import sphinx.util.docutils
import sphinx.util.inspect
import sphinx.util.logging
import sphinx.util.typing
from .. import object_description_options
from ... import sphinx_utils
from .. import apigen_utils
if sphinx.version_info >= (6, 1):
stringify_annotation = sphinx.util.typing.stringify_annotation
else:
stringify_annotation = sphinx.util.typing.stringify # type: ignore[attr-defined]
logger = sphinx.util.logging.getLogger(__name__)
_UNCONDITIONALLY_DOCUMENTED_MEMBERS = frozenset(
[
"__init__",
"__class_getitem__",
"__call__",
"__getitem__",
"__setitem__",
]
)
"""Special members to include even if they have no docstring."""
class ParsedOverload(NamedTuple):
"""Parsed representation of a single overload.
For non-function types and non-overloaded functions, this just represents the
object itself.
Sphinx does not really support pybind11-style overloaded functions directly.
It has minimal support functions with multiple signatures, with a single
docstring. However, pybind11 produces overloaded functions each with their
own docstring. This module adds support for documenting each overload as an
independent function.
Additionally, we need a way to identify each overload, for the purpose of
generating a page name, listing in the table of contents sidebar, and
cross-referencing. Sphinx does not have a native solution to this problem
because it is not designed to support overloads. Doxygen uses some sort of
hash as the identifier, but that means links break with even minor changes to
the signature.
Instead, we require that a unique id be manually assigned to each overload,
and specified as:
Overload:
XXX
in the docstring. Then the overload will be identified as
`module.Class.function(overload)`, and will be documented using the page name
`module.Class.function-overload`. Typically the overload id should be chosen
to be a parameter name that is unique to the overload.
"""
doc: Optional[str]
"""Docstring for individual overload. First line is the signature."""
overload_id: Optional[str] = None
"""Overload id specified in the docstring.
If there is just a single overload, will be `None`. Otherwise, if no overload
id is specified, a warning is produced and the index of the overload,
i.e. "1", "2", etc., is used as the id.
"""
def _extract_field(doc: str, field: str) -> Tuple[str, Optional[str]]:
pattern = f"\n\\s*\n{field}:\\s*\n\\s+([^\n]+)\n"
m = re.search(pattern, doc)
if m is None:
return doc, None
start, end = m.span()
return f"{doc[:start]}\n\n{doc[end:]}", m.group(1).strip()
_OVERLOADED_FUNCTION_RE = "^([^(]+)\\([^\n]*\nOverloaded function.\n"
def _parse_overloaded_function_docstring(doc: Optional[str]) -> List[ParsedOverload]:
"""Parses a pybind11 overloaded function docstring.
If the docstring is not for an overloaded function, just returns the full
docstring as a single "overload".
:param doc: Original docstring.
:returns: List of parsed overloads.
:raises ValueError: If docstring has unexpected format.
"""
if doc is None:
return [ParsedOverload(doc=doc, overload_id=None)]
m = re.match(_OVERLOADED_FUNCTION_RE, doc)
if m is None:
# Non-overloaded function
doc, overload_id = _extract_field(doc, "Overload")
return [ParsedOverload(doc=doc, overload_id=overload_id)]
display_name = m.group(1)
doc = doc[m.end() :]
i = 1
def get_prefix(i: int):
return "\n%d. %s(" % (i, display_name)
prefix = get_prefix(i)
parts: List[ParsedOverload] = []
while doc:
if not doc.startswith(prefix):
raise ValueError(
"Docstring does not contain %r as expected: %r"
% (
prefix,
doc,
)
)
doc = doc[len(prefix) - 1 :]
nl_index = doc.index("\n")
part_sig = doc[:nl_index]
doc = doc[nl_index + 1 :]
i += 1
prefix = get_prefix(i)
end_index = doc.find(prefix)
if end_index == -1:
part = doc
doc = ""
else:
part = doc[:end_index]
doc = doc[end_index:]
part, overload_id = _extract_field(part, "Overload")
if overload_id is None:
overload_id = str(i - 1)
part_doc_with_sig = f"{display_name}{part_sig}\n{part}"
parts.append(
ParsedOverload(
doc=part_doc_with_sig,
overload_id=overload_id,
)
)
return parts
def _get_overloads_from_documenter(
documenter: sphinx.ext.autodoc.Documenter,
) -> List[ParsedOverload]:
docstring = sphinx.util.inspect.getdoc(
documenter.object,
documenter.get_attr,
documenter.env.config.autodoc_inherit_docstrings,
documenter.parent,
documenter.object_name,
)
return _parse_overloaded_function_docstring(docstring)
def _has_default_value(node: sphinx.addnodes.desc_parameter):
for sub_node in node.findall(condition=docutils.nodes.literal):
if "default_value" in sub_node.get("classes"):
return True
return False
def _summarize_signature(
env: sphinx.environment.BuildEnvironment, node: sphinx.addnodes.desc_signature
) -> None:
"""Shortens a signature line to fit within `wrap_signatures_column_limit."""
obj_desc = node.parent
options = object_description_options.get_object_description_options(
env, obj_desc["domain"], obj_desc["objtype"]
)
column_limit = options["wrap_signatures_column_limit"]
def _must_shorten():
return len(node.astext()) > column_limit
parameterlist: Optional[sphinx.addnodes.desc_parameterlist] = None
for parameterlist in node.findall(condition=sphinx.addnodes.desc_parameterlist):
break
if parameterlist is None:
# Can't shorten a signature without a parameterlist
return
# Remove initial `self` parameter
if parameterlist.children and parameterlist.children[0].astext() == "self":
del parameterlist.children[0]
added_ellipsis = False
for next_parameter_index in range(len(parameterlist.children) - 1, -1, -1):
if not _must_shorten():
return
# First remove type annotation of last parameter, but only if it doesn't
# have a default value.
last_parameter = parameterlist.children[next_parameter_index]
if isinstance(
last_parameter, sphinx.addnodes.desc_parameter
) and not _has_default_value(last_parameter):
del last_parameter.children[1:]
if not _must_shorten():
return
# Elide last parameter entirely
del parameterlist.children[next_parameter_index]
if not added_ellipsis:
added_ellipsis = True
ellipsis_node = sphinx.addnodes.desc_sig_punctuation("", "...")
param = sphinx.addnodes.desc_parameter()
param += ellipsis_node
parameterlist += param
class _MemberDocumenterEntry(NamedTuple):
"""Represents a member of some outer scope (module/class) to document."""
documenter: sphinx.ext.autodoc.Documenter
is_attr: bool
name: str
"""Member name within parent, e.g. class member name."""
full_name: str
"""Full name under which to document the member.
For example, "modname.ClassName.method".
"""
parent_canonical_full_name: str
overload: Optional[ParsedOverload] = None
is_inherited: bool = False
"""Indicates whether this is an inherited member."""
subscript: bool = False
"""Whether this is a "subscript" method to be shown with [] instead of ()."""
@property
def overload_suffix(self):
if self.overload and self.overload.overload_id:
return f"({self.overload.overload_id})"
return ""
@property
def toc_title(self):
return self.name + self.overload_suffix
class _ApiEntityMemberReference(NamedTuple):
name: str
canonical_object_name: str
parent_canonical_object_name: str
inherited: bool = False
@dataclasses.dataclass
class _ApiEntity:
canonical_full_name: str
objtype: str
directive: str
overload_id: str
@property
def canonical_object_name(self):
return self.canonical_full_name + self.overload_suffix
@property
def object_name(self):
return self.documented_full_name + self.overload_suffix
@property
def overload_suffix(self) -> str:
overload_id = self.overload_id
return f"({overload_id})" if overload_id else ""
signatures: List[str]
options: Dict[str, str]
content: List[str]
group_name: str
order: Optional[int]
subscript: bool
members: List[_ApiEntityMemberReference]
"""Members of this entity."""
parents: List[_ApiEntityMemberReference]
"""Parents that reference this entity as a member.
Inverse of `members`."""
docname: str = ""
documented_full_name: str = ""
documented_name: str = ""
top_level: bool = False
base_classes: Optional[List[str]] = None
"""List of base classes, as rST cross references."""
def _is_constructor_name(name: str) -> bool:
return name in ("__init__", "__new__", "__class_getitem__")
class _ApiData:
entities: Dict[str, _ApiEntity]
top_level_groups: Dict[str, List[_ApiEntityMemberReference]]
def __init__(self):
self.entities = {}
self.top_level_groups = {}
def get_name_for_signature(
self, entity: _ApiEntity, member: Optional[_ApiEntityMemberReference]
) -> str:
if member is not None:
assert member.canonical_object_name == entity.canonical_object_name
# Get name for summary
if _is_constructor_name(member.name):
parent_entity = self.entities.get(member.parent_canonical_object_name)
if parent_entity is not None and parent_entity.objtype == "class":
# Display as the parent class name.
return parent_entity.documented_name
# Display as the member name
return member.name
full_name = entity.documented_full_name
if _is_constructor_name(entity.documented_name):
full_name = full_name[: -len(entity.documented_name) - 1]
module = entity.options.get("module")
if module is not None and full_name.startswith(module + "."):
# Strip module name, since it is specified separately.
full_name = full_name[len(module) + 1 :]
return full_name
def sort_members(
self, members: List[_ApiEntityMemberReference], alphabetical=False
):
def get_key(member: _ApiEntityMemberReference):
member_entity = self.entities[member.canonical_object_name]
order = member_entity.order or 0
if alphabetical:
return (order, member.name.lower(), member.name)
return order
members.sort(key=get_key)
def _ensure_module_name_in_signature(signode: sphinx.addnodes.desc_signature) -> None:
"""Ensures non-summary objects are documented with the module name.
Sphinx by default excludes the module name from class members, and does not
provide an option to override that. Since we display all objects on separate
pages, we want to include the module name for clarity.
:param signode: Signature to modify in place.
"""
for node in signode.findall(condition=sphinx.addnodes.desc_addname):
modname = signode.get("module")
if modname and not node.astext().startswith(modname + "."):
node.insert(0, docutils.nodes.Text(modname + "."))
break
def _get_group_name(
default_groups: List[Tuple[re.Pattern, str]], entity: _ApiEntity
) -> str:
"""Returns a default group name for an entry.
This is used if the group name is not explicitly specified via "Group:" in the
docstring.
:param default_groups: Default group associations.
:param entity: Entity to document.
:returns: The group name.
"""
s = f"{entity.objtype}:{entity.documented_full_name}"
group = "Public members"
for pattern, default_group in default_groups:
if pattern.fullmatch(s) is not None:
group = default_group
return group
def _get_order(default_order: List[Tuple[re.Pattern, int]], entity: _ApiEntity) -> int:
"""Returns a default order value for an entry.
This is used if the order is not explicitly specified via "Order:" in the
docstring.
:param default_order: Default order associations.
:param entity: Entity to document.
:returns: The order.
"""
s = f"{entity.objtype}:{entity.documented_full_name}"
order = 0
for pattern, order_value in default_order:
if pattern.fullmatch(s) is not None:
order = order_value
return order
def _mark_subscript_parameterlist(signode: sphinx.addnodes.desc_signature) -> None:
"""Modifies an object description to display as a "subscript method".
A "subscript method" is a property that defines __getitem__ and is intended to
be treated as a method invoked using [] rather than (), in order to allow
subscript syntax like ':'.
:param node: Signature to modify in place.
"""
for sub_node in signode.findall(condition=sphinx.addnodes.desc_parameterlist):
sub_node["parens"] = ("[", "]")
def _clean_init_signature(signode: sphinx.addnodes.desc_signature) -> None:
"""Modifies an object description of an __init__ method.
Removes the return type (always None) and the self parameter (since these
methods are displayed as the class name, without showing __init__).
:param node: Signature to modify in place.
"""
# Remove first parameter.
for param in signode.findall(condition=sphinx.addnodes.desc_parameter):
if param.children[0].astext() == "self":
param.parent.remove(param)
break
# Remove return type.
for node in signode.findall(condition=sphinx.addnodes.desc_returns):
node.parent.remove(node)
def _clean_class_getitem_signature(signode: sphinx.addnodes.desc_signature) -> None:
"""Modifies an object description of a __class_getitem__ method.
Removes the `static` prefix since these methods are shown using the class
name (i.e. as "subscript" constructors).
:param node: Signature to modify in place.
"""
# Remove `static` prefix
for prefix in signode.findall(condition=sphinx.addnodes.desc_annotation):
prefix.parent.remove(prefix)
break
def _get_api_data(
env: sphinx.environment.BuildEnvironment,
) -> _ApiData:
return getattr(env, "_sphinx_immaterial_python_apigen_data")
def _generate_entity_desc_node(
env: sphinx.environment.BuildEnvironment,
entity: _ApiEntity,
state: docutils.parsers.rst.states.RSTState,
member: Optional[_ApiEntityMemberReference] = None,
callback=None,
):
api_data = _get_api_data(env)
summary = member is not None
name = api_data.get_name_for_signature(entity, member)
def object_description_transform(
app: sphinx.application.Sphinx,
domain: str,
objtype: str,
contentnode: sphinx.addnodes.desc_content,
) -> None:
env = app.env
assert env is not None
obj_desc = contentnode.parent
assert isinstance(obj_desc, sphinx.addnodes.desc)
signodes = cast(List[sphinx.addnodes.desc_signature], obj_desc[:-1])
if not signodes:
return
for signode in signodes:
fullname = signode["fullname"]
modname = signode["module"]
object_name = (modname + "." if modname else "") + fullname
if object_name != entity.object_name:
# This callback may be invoked for additional members
# documented within the body of `entry`, but we don't want
# to transform them here.
return
assert isinstance(signode, sphinx.addnodes.desc_signature)
if entity.subscript:
_mark_subscript_parameterlist(signode)
if entity.documented_name in ("__init__", "__new__"):
_clean_init_signature(signode)
if entity.documented_name == "__class_getitem__":
_clean_class_getitem_signature(signode)
if summary:
obj_desc["classes"].append("summary")
assert app.env is not None
_summarize_signature(app.env, signode)
base_classes = entity.base_classes
if base_classes:
signode += sphinx.addnodes.desc_sig_punctuation("", "(")
for i, base_class in enumerate(base_classes):
base_entity = api_data.entities.get(base_class)
if base_entity is not None:
base_class = base_entity.object_name
if i != 0:
signode += sphinx.addnodes.desc_sig_punctuation("", ",")
signode += sphinx.addnodes.desc_sig_space()
signode += sphinx.domains.python._parse_annotation(base_class, env)
signode += sphinx.addnodes.desc_sig_punctuation("", ")")
if callback is not None:
callback(contentnode)
listener_id = env.app.connect(
"object-description-transform", object_description_transform, priority=999
)
content = entity.content
options = dict(entity.options)
options["nonodeid"] = ""
options["object-ids"] = json.dumps([entity.object_name] * len(entity.signatures))
if summary:
content = _summarize_rst_content(content)
options["noindex"] = ""
options.pop("canonical", None)
else:
options["canonical"] = entity.canonical_object_name
try:
with apigen_utils.save_rst_defaults(env):
rst_input = docutils.statemachine.StringList()
sphinx_utils.append_multiline_string_to_stringlist(
rst_input,
".. highlight-push::\n\n"
+ env.config.python_apigen_rst_prolog
+ "\n\n",
"<python_apigen_rst_prolog>",
-2,
)
sphinx_utils.append_directive_to_stringlist(
rst_input,
entity.directive,
signatures=[name + sig for sig in entity.signatures],
content="\n".join(content),
source_path=entity.object_name,
source_line=0,
options=options,
)
sphinx_utils.append_multiline_string_to_stringlist(
rst_input,
"\n\n"
+ env.config.python_apigen_rst_epilog
+ "\n\n.. highlight-pop::\n\n",
"<python_apigen_rst_epilog>",
-2,
)
nodes = [
x
for x in sphinx_utils.parse_rst(
state=state,
text=rst_input,
)
if isinstance(x, sphinx.addnodes.desc)
]
finally:
env.app.disconnect(listener_id)
if len(nodes) != 1:
raise ValueError("Failed to document entity: %r" % (entity.object_name,))
node = nodes[0]
return node
def _generate_entity_summary(
env: sphinx.environment.BuildEnvironment,
member: _ApiEntityMemberReference,
state: docutils.parsers.rst.states.RSTState,
include_in_toc: bool,
) -> sphinx.addnodes.desc:
api_data = _get_api_data(env)
entity = api_data.entities[member.canonical_object_name]
objdesc = _generate_entity_desc_node(
env=env, entity=entity, member=member, state=state
)
for sig_node in cast(List[sphinx.addnodes.desc_signature], objdesc.children[:-1]):
# Insert a link around the `desc_name` field
for sub_node in sig_node.findall(condition=sphinx.addnodes.desc_name):
if include_in_toc:
sub_node["classes"].append("pseudo-toc-entry")
xref_node = sphinx.addnodes.pending_xref(
"",
sub_node.deepcopy(),
refdomain="py",
reftype="obj",
reftarget=entity.object_name,
refwarn=True,
refexplicit=True,
)
sub_node.replace_self(xref_node)
break
# Only mark first signature as a `pseudo-toc-entry`.
include_in_toc = False
return objdesc
def _generate_group_summary(
env: sphinx.environment.BuildEnvironment,
members: List[_ApiEntityMemberReference],
state: docutils.parsers.rst.states.RSTState,
notoc: Optional[bool] = None,
):
data = _get_api_data(env)
nodes: List[docutils.nodes.Node] = []
toc_entries: List[Tuple[str, str]] = []
for member in members:
member_entity = data.entities[member.canonical_object_name]
include_in_toc = True
if notoc is True:
include_in_toc = False
elif member is not member_entity.parents[0]:
include_in_toc = False
node = _generate_entity_summary(
env=env, member=member, state=state, include_in_toc=include_in_toc
)
if node is None:
continue
nodes.append(node)
if include_in_toc:
toc_entries.append(
(member.name + member_entity.overload_suffix, member_entity.docname)
)
nodes.extend(
sphinx_utils.make_toctree_node(
state,
toc_entries,
options={"hidden": True},
source_path=__name__,
)
)
return nodes
def _add_group_summary(
env: sphinx.environment.BuildEnvironment,
contentnode: docutils.nodes.Element,
sections: Dict[str, docutils.nodes.section],
group_name: str,
members: List[_ApiEntityMemberReference],
state: docutils.parsers.rst.states.RSTState,
) -> None:
group_id = docutils.nodes.make_id(group_name)
section = sections.get(group_id)
if section is None:
section = docutils.nodes.section()
section["ids"].append(group_id)
title = docutils.nodes.title("", group_name)
section += title
contentnode += section
sections[group_id] = section
section.extend(_generate_group_summary(env=env, members=members, state=state))
def _merge_summary_nodes_into(
env: sphinx.environment.BuildEnvironment,
entity: _ApiEntity,
contentnode: docutils.nodes.Element,
state: docutils.parsers.rst.states.RSTState,
) -> None:
"""Merges the member summary into `contentnode`.
Members are organized into groups. The group is either specified explicitly
by a `Group:` field in the docstring, or determined automatically by
`_get_group_name`. If there is an existing section, the member summary is
appended to it. Otherwise, a new section is created.
:param contentnode: The existing container to which the member summaries will be
added. If `contentnode` contains sections, those sections correspond to
group names.
"""
sections: Dict[str, docutils.nodes.section] = {}
for section in contentnode.findall(condition=docutils.nodes.section):
if section["ids"]:
sections[section["ids"][0]] = section
# Maps group name to the list of members.
groups: Dict[str, List[_ApiEntityMemberReference]] = {}
entities = _get_api_data(env).entities
for member in entity.members:
member_entity = entities[member.canonical_object_name]
groups.setdefault(member_entity.group_name, []).append(member)
for group_name, members in groups.items():
_add_group_summary(
env=env,
contentnode=contentnode,
sections=sections,
group_name=group_name,
members=members,
state=state,
)
class PythonApigenEntityPageDirective(sphinx.util.docutils.SphinxDirective):
"""Documents an entity and summarizes its members, if applicable."""
has_content = False
final_argument_whitespace = True
required_arguments = 1
optional_arguments = 0
def run(self) -> List[docutils.nodes.Node]:
entities = _get_api_data(self.env).entities
object_name = self.arguments[0]
entity = entities.get(object_name)
if entity is None:
logger.error(
"Undefined Python entity: %r", object_name, location=self.get_location()
)
return []
objtype = entity.objtype
objdesc = _generate_entity_desc_node(
self.env,
entity,
state=self.state,
callback=lambda contentnode: _merge_summary_nodes_into(
env=self.env,
entity=entity,
contentnode=contentnode,
state=self.state,
),
)
if objdesc is None:
return []
for signode in objdesc.children[:-1]:
signode = cast(sphinx.addnodes.desc_signature, signode)
_ensure_module_name_in_signature(signode)
# Wrap in a section
section = docutils.nodes.section()
section["ids"].append("")
# Sphinx treates the first child of a `section` node as the title,
# regardless of its type. We use a comment node to avoid adding a title
# that would be redundant with the object description.
section += docutils.nodes.comment("", entity.object_name)
section += objdesc
return [section]
class PythonApigenTopLevelGroupDirective(sphinx.util.docutils.SphinxDirective):
"""Summarizes the members of a top-level group."""
has_content = False
final_argument_whitespace = True
required_arguments = 1
optional_arguments = 0
option_spec = {
"notoc": docutils.parsers.rst.directives.flag,
}
def run(self) -> List[docutils.nodes.Node]:
env = self.env
data = _get_api_data(env)
top_level_groups = data.top_level_groups
group_id = docutils.nodes.make_id(self.arguments[0])
members = data.top_level_groups.get(group_id)
if members is None:
logger.warning(
"No top-level Python API group named: %r, valid groups are: %r",
group_id,
list(data.top_level_groups.keys()),
location=self.state_machine.get_source_and_line(self.lineno),
)
return []
return _generate_group_summary(
env=env, members=members, state=self.state, notoc="notoc" in self.options
)
class PythonApigenEntitySummaryDirective(sphinx.util.docutils.SphinxDirective):
"""Generates a summary/link to a Python entity."""
has_content = False
final_argument_whitespace = True
required_arguments = 1
optional_arguments = 0
option_spec = {
"notoc": docutils.parsers.rst.directives.flag,
}
def run(self) -> List[docutils.nodes.Node]:
env = self.env
data = _get_api_data(env)
object_name = self.arguments[0]
entity = data.entities.get(object_name)
if entity is None:
logger.warning(
"No Python entity named: %r",
object_name,
location=self.state_machine.get_source_and_line(self.lineno),
)
return []
return _generate_group_summary(
env=env,
members=[entity.parents[0]],
state=self.state,
notoc="notoc" in self.options,
)
class _FakeBridge(sphinx.ext.autodoc.directive.DocumenterBridge):
def __init__(
self,
env: sphinx.environment.BuildEnvironment,
tab_width: int,
extra_options: dict,
) -> None:
settings = docutils.parsers.rst.states.Struct(tab_width=tab_width)
document = docutils.parsers.rst.states.Struct(settings=settings)
state = docutils.parsers.rst.states.Struct(document=document)
options = sphinx.ext.autodoc.Options()
options["undoc-members"] = True
options["class-doc-from"] = "class"
options.update(extra_options)
super().__init__(
env=env,
reporter=sphinx.util.docutils.NullReporter(),
options=options,
lineno=0,
state=state,
)
_EXCLUDED_SPECIAL_MEMBERS = frozenset(
[
"__module__",
"__abstractmethods__",
"__dict__",
"__weakref__",
"__class__",
"__base__",
# Exclude pickling members since they are never documented.
"__getstate__",
"__setstate__",
]
)
def _create_documenter(
env: sphinx.environment.BuildEnvironment,
documenter_cls: Type[sphinx.ext.autodoc.Documenter],
name: str,
tab_width: int = 8,
) -> sphinx.ext.autodoc.Documenter:
"""Creates a documenter for the given full object name.
Since we are using the documenter independent of any autodoc directive, we use
a `_FakeBridge` as the documenter bridge, similar to the strategy used by
`sphinx.ext.autosummary`.
:param env: Sphinx build environment.
:param documenter_cls: Documenter class to use.
:param name: Full object name, e.g. `my_module.MyClass.my_function`.
:param tab_width: Tab width setting to use when parsing docstrings.
:returns: The documenter object.
"""
extra_options = {}
if documenter_cls.objtype == "class":
extra_options["special-members"] = sphinx.ext.autodoc.ALL
bridge = _FakeBridge(env, tab_width=tab_width, extra_options=extra_options)
documenter = documenter_cls(bridge, name)
assert documenter.parse_name()
assert documenter.import_object()
try:
documenter.analyzer = sphinx.pycode.ModuleAnalyzer.for_module(
documenter.get_real_modname()
)
# parse right now, to get PycodeErrors on parsing (results will
# be cached anyway)
documenter.analyzer.find_attr_docs()
except sphinx.pycode.PycodeError:
# no source file -- e.g. for builtin and C modules
documenter.analyzer = None # type: ignore[assignment]
return documenter
def _get_member_documenter(
parent: sphinx.ext.autodoc.Documenter,
member_name: str,
member_value: Any,
is_attr: bool,
) -> Optional[sphinx.ext.autodoc.Documenter]:
"""Creates a documenter for the given member.
:param parent: Parent documenter.
:param member_name: Name of the member.
:param member_value: Value of the member.
:param is_attr: Whether the member is an attribute.
:returns: The documenter object.
"""
classes = [
cls
for cls in parent.documenters.values()
if cls.can_document_member(member_value, member_name, is_attr, parent)
]
if not classes:
return None
# prefer the documenter with the highest priority
classes.sort(key=lambda cls: cls.priority)
full_mname = parent.modname + "::" + ".".join(parent.objpath + [member_name])
documenter = _create_documenter(
env=parent.env,
documenter_cls=classes[-1],
name=full_mname,
tab_width=parent.directive.state.document.settings.tab_width,
)
return documenter
def _include_member(member_name: str, member_value: Any, is_attr: bool) -> bool:
"""Determines whether a member should be documented.
:param member_name: Name of the member.
:param member_value: Value of the member.
:param is_attr: Whether the member is an attribute.
:returns: True if the member should be documented.
"""
del is_attr