-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
sphinxrenderer.py
2413 lines (2048 loc) · 94.6 KB
/
sphinxrenderer.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
import sphinx
from breathe.parser import compound, compoundsuper, DoxygenCompoundParser
from breathe.project import ProjectInfo
from breathe.renderer import RenderContext
from breathe.renderer.filter import Filter
from breathe.renderer.target import TargetHandler
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.directives import ObjectDescription
from sphinx.domains import cpp, c, python
from sphinx.util.nodes import nested_parse_with_titles
from docutils import nodes
from docutils.nodes import Element, Node, TextElement # noqa
from docutils.statemachine import StringList, UnexpectedIndentationError
from docutils.parsers.rst.states import Text
try:
from sphinxcontrib import phpdomain as php # type: ignore
except ImportError:
php = None
try:
from sphinx_csharp import csharp as cs # type: ignore
except ImportError:
cs = None
import re
import textwrap
from typing import Callable, cast, Dict, List, Optional, Tuple, Type, Union # noqa
ContentCallback = Callable[[addnodes.desc_content], None]
Declarator = Union[addnodes.desc_signature, addnodes.desc_signature_line]
DeclaratorCallback = Callable[[Declarator], None]
_debug_indent = 0
class WithContext:
def __init__(self, parent: "SphinxRenderer", context: RenderContext):
self.context = context
self.parent = parent
self.previous = None
def __enter__(self):
assert self.previous is None
self.previous = self.parent.context
self.parent.set_context(self.context)
return self
def __exit__(self, et, ev, bt):
self.parent.context = self.previous
self.previous = None
class BaseObject:
# Use this class as the first base class to make sure the overrides are used.
# Set the content_callback attribute to a function taking a docutils node.
def transform_content(self, contentnode: addnodes.desc_content) -> None:
super().transform_content(contentnode) # type: ignore
callback = getattr(self, "breathe_content_callback", None)
if callback is None:
return
callback(contentnode)
# ----------------------------------------------------------------------------
class CPPClassObject(BaseObject, cpp.CPPClassObject):
pass
class CPPUnionObject(BaseObject, cpp.CPPUnionObject):
pass
class CPPFunctionObject(BaseObject, cpp.CPPFunctionObject):
pass
class CPPMemberObject(BaseObject, cpp.CPPMemberObject):
pass
class CPPTypeObject(BaseObject, cpp.CPPTypeObject):
pass
class CPPEnumObject(BaseObject, cpp.CPPEnumObject):
pass
class CPPEnumeratorObject(BaseObject, cpp.CPPEnumeratorObject):
pass
# ----------------------------------------------------------------------------
class CStructObject(BaseObject, c.CStructObject):
pass
class CUnionObject(BaseObject, c.CUnionObject):
pass
class CFunctionObject(BaseObject, c.CFunctionObject):
pass
class CMemberObject(BaseObject, c.CMemberObject):
pass
class CTypeObject(BaseObject, c.CTypeObject):
pass
class CEnumObject(BaseObject, c.CEnumObject):
pass
class CEnumeratorObject(BaseObject, c.CEnumeratorObject):
pass
class CMacroObject(BaseObject, c.CMacroObject):
pass
# ----------------------------------------------------------------------------
class PyFunction(BaseObject, python.PyFunction):
pass
class PyAttribute(BaseObject, python.PyAttribute):
pass
class PyClasslike(BaseObject, python.PyClasslike):
pass
# ----------------------------------------------------------------------------
# Create multi-inheritance classes to merge BaseObject from Breathe with
# classes from phpdomain.
# We use capitalization (and the namespace) to differentiate between the two
if php is not None:
class PHPNamespaceLevel(BaseObject, php.PhpNamespacelevel):
"""Description of a PHP item *in* a namespace (not the space itself)."""
pass
class PHPClassLike(BaseObject, php.PhpClasslike):
pass
class PHPClassMember(BaseObject, php.PhpClassmember):
pass
class PHPGlobalLevel(BaseObject, php.PhpGloballevel):
pass
# ----------------------------------------------------------------------------
if cs is not None:
class CSharpCurrentNamespace(BaseObject, cs.CSharpCurrentNamespace):
pass
class CSharpNamespacePlain(BaseObject, cs.CSharpNamespacePlain):
pass
class CSharpClass(BaseObject, cs.CSharpClass):
pass
class CSharpStruct(BaseObject, cs.CSharpStruct):
pass
class CSharpInterface(BaseObject, cs.CSharpInterface):
pass
class CSharpInherits(BaseObject, cs.CSharpInherits):
pass
class CSharpMethod(BaseObject, cs.CSharpMethod):
pass
class CSharpVariable(BaseObject, cs.CSharpVariable):
pass
class CSharpProperty(BaseObject, cs.CSharpProperty):
pass
class CSharpEvent(BaseObject, cs.CSharpEvent):
pass
class CSharpEnum(BaseObject, cs.CSharpEnum):
pass
class CSharpEnumValue(BaseObject, cs.CSharpEnumValue):
pass
class CSharpAttribute(BaseObject, cs.CSharpAttribute):
pass
class CSharpIndexer(BaseObject, cs.CSharpIndexer):
pass
class CSharpXRefRole(BaseObject, cs.CSharpXRefRole):
pass
# ----------------------------------------------------------------------------
class DomainDirectiveFactory:
# A mapping from node kinds to domain directives and their names.
cpp_classes = {
"variable": (CPPMemberObject, "var"),
"class": (CPPClassObject, "class"),
"struct": (CPPClassObject, "struct"),
"interface": (CPPClassObject, "class"),
"function": (CPPFunctionObject, "function"),
"friend": (CPPFunctionObject, "function"),
"signal": (CPPFunctionObject, "function"),
"slot": (CPPFunctionObject, "function"),
"enum": (CPPEnumObject, "enum"),
"typedef": (CPPTypeObject, "type"),
"using": (CPPTypeObject, "type"),
"union": (CPPUnionObject, "union"),
"namespace": (CPPTypeObject, "type"),
"enumvalue": (CPPEnumeratorObject, "enumerator"),
"define": (CMacroObject, "macro"),
}
c_classes = {
"variable": (CMemberObject, "var"),
"function": (CFunctionObject, "function"),
"define": (CMacroObject, "macro"),
"struct": (CStructObject, "struct"),
"union": (CUnionObject, "union"),
"enum": (CEnumObject, "enum"),
"enumvalue": (CEnumeratorObject, "enumerator"),
"typedef": (CTypeObject, "type"),
}
python_classes = {
# TODO: PyFunction is meant for module-level functions
# and PyAttribute is meant for class attributes, not module-level variables.
# Somehow there should be made a distinction at some point to get the correct
# index-text and whatever other things are different.
"function": (PyFunction, "function"),
"variable": (PyAttribute, "attribute"),
"class": (PyClasslike, "class"),
"namespace": (PyClasslike, "class"),
}
if php is not None:
php_classes = {
"function": (PHPNamespaceLevel, "function"),
"class": (PHPClassLike, "class"),
"attr": (PHPClassMember, "attr"),
"method": (PHPClassMember, "method"),
"global": (PHPGlobalLevel, "global"),
}
php_classes_default = php_classes["class"] # Directive when no matching ones were found
if cs is not None:
cs_classes = {
# 'doxygen-name': (CSharp class, key in CSharpDomain.object_types)
"namespace": (CSharpNamespacePlain, "namespace"),
"class": (CSharpClass, "class"),
"struct": (CSharpStruct, "struct"),
"interface": (CSharpInterface, "interface"),
"function": (CSharpMethod, "function"),
"method": (CSharpMethod, "method"),
"variable": (CSharpVariable, "var"),
"property": (CSharpProperty, "property"),
"event": (CSharpEvent, "event"),
"enum": (CSharpEnum, "enum"),
"enumvalue": (CSharpEnumValue, "enumerator"),
"attribute": (CSharpAttribute, "attr"),
# Fallback to cpp domain
"typedef": (CPPTypeObject, "type"),
}
@staticmethod
def create(domain: str, args) -> ObjectDescription:
cls = cast(Type[ObjectDescription], None)
name = cast(str, None)
# TODO: remove the 'type: ignore's below at some point
# perhaps something to do with the mypy version
if domain == "c":
cls, name = DomainDirectiveFactory.c_classes[args[0]] # type: ignore
elif domain == "py":
cls, name = DomainDirectiveFactory.python_classes[args[0]] # type: ignore
elif php is not None and domain == "php":
separators = php.separators
arg_0 = args[0]
if any([separators["method"] in n for n in args[1]]):
if any([separators["attr"] in n for n in args[1]]):
arg_0 = "attr"
else:
arg_0 = "method"
else:
if arg_0 in ["variable"]:
arg_0 = "global"
if arg_0 in DomainDirectiveFactory.php_classes:
cls, name = DomainDirectiveFactory.php_classes[arg_0] # type: ignore
else:
cls, name = DomainDirectiveFactory.php_classes_default # type: ignore
elif cs is not None and domain == "cs":
cls, name = DomainDirectiveFactory.cs_classes[args[0]] # type: ignore
else:
domain = "cpp"
cls, name = DomainDirectiveFactory.cpp_classes[args[0]] # type: ignore
# Replace the directive name because domain directives don't know how to handle
# Breathe's "doxygen" directives.
assert ":" not in name
args = [domain + ":" + name] + args[1:]
return cls(*args)
class NodeFinder(nodes.SparseNodeVisitor):
"""Find the Docutils desc_signature declarator and desc_content nodes."""
def __init__(self, document):
super().__init__(document)
self.declarator = None
self.content = None
def visit_desc_signature(self, node):
# Find the last signature node because it contains the actual declarator
# rather than "template <...>". In Sphinx 1.4.1 we'll be able to use sphinx_cpp_tagname:
# https://github.com/michaeljones/breathe/issues/242
self.declarator = node
def visit_desc_signature_line(self, node):
# In sphinx 1.5, there is now a desc_signature_line node within the desc_signature
# This should be used instead
self.declarator = node
def visit_desc_content(self, node):
self.content = node
def intersperse(iterable, delimiter):
it = iter(iterable)
yield next(it)
for x in it:
yield delimiter
yield x
def get_param_decl(param):
def to_string(node):
"""Convert Doxygen node content to a string."""
result = []
if node is not None:
for p in node.content_:
value = p.value
if not isinstance(value, str):
value = value.valueOf_
result.append(value)
return " ".join(result)
param_type = to_string(param.type_)
param_name = param.declname if param.declname else param.defname
if not param_name:
param_decl = param_type
else:
param_decl, number_of_subs = re.subn(
r"(\((?:\w+::)*[*&]+)(\))", r"\g<1>" + param_name + r"\g<2>", param_type
)
if number_of_subs == 0:
param_decl = param_type + " " + param_name
if param.array:
param_decl += param.array
if param.defval:
param_decl += " = " + to_string(param.defval)
return param_decl
def get_definition_without_template_args(data_object):
"""
Return data_object.definition removing any template arguments from the class name in the member
function. Otherwise links to classes defined in the same template are not generated correctly.
For example in 'Result<T> A< B<C> >::f' we want to remove the '< B<C> >' part.
"""
definition = data_object.definition
if len(data_object.bitfield) > 0:
definition += " : " + data_object.bitfield
qual_name = "::" + data_object.name
if definition.endswith(qual_name):
qual_name_start = len(definition) - len(qual_name)
pos = qual_name_start - 1
if definition[pos] == ">":
bracket_count = 0
# Iterate back through the characters of the definition counting matching braces and
# then remove all braces and everything between
while pos > 0:
if definition[pos] == ">":
bracket_count += 1
elif definition[pos] == "<":
bracket_count -= 1
if bracket_count == 0:
definition = definition[:pos] + definition[qual_name_start:]
break
pos -= 1
return definition
class InlineText(Text):
"""
Add a custom docutils class to allow parsing inline text. This is to be
used inside a @verbatim/@endverbatim block but only the first line is
consumed and a inline element is generated as the parent, instead of the
paragraph used by Text.
"""
patterns = {"inlinetext": r""}
initial_transitions = [("inlinetext",)]
def indent(self, match, context, next_state):
"""
Avoid Text's indent from detecting space prefixed text and
doing "funny" stuff; always rely on inlinetext for parsing.
"""
return self.inlinetext(match, context, next_state)
def eof(self, context):
"""
Text.eof() inserts a paragraph, so override it to skip adding elements.
"""
return []
def inlinetext(self, match, context, next_state):
"""
Called by the StateMachine when an inline element is found (which is
any text when this class is added as the single transition.
"""
startline = self.state_machine.abs_line_number() - 1
msg = None
try:
block = self.state_machine.get_text_block()
except UnexpectedIndentationError as err:
block, src, srcline = err.args
msg = self.reporter.error("Unexpected indentation.", source=src, line=srcline)
lines = context + list(block)
text, _ = self.inline_text(lines[0], startline)
self.parent += text
self.parent += msg
return [], next_state, []
class SphinxRenderer:
"""
Doxygen node visitor that converts input into Sphinx/RST representation.
Each visit method takes a Doxygen node as an argument and returns a list of RST nodes.
"""
def __init__(
self,
app: Sphinx,
project_info: ProjectInfo,
node_stack,
state,
document: nodes.document,
target_handler: TargetHandler,
compound_parser: DoxygenCompoundParser,
filter_: Filter,
):
self.app = app
self.project_info = project_info
self.qualification_stack = node_stack
self.nesting_level = 0
self.state = state
self.document = document
self.target_handler = target_handler
self.compound_parser = compound_parser
self.filter_ = filter_
self.context = None # type: Optional[RenderContext]
self.output_defname = True
# Nesting level for lists.
self.nesting_level = 0
def set_context(self, context: RenderContext) -> None:
self.context = context
if self.context.domain == "":
self.context.domain = self.get_domain()
# XXX: fix broken links in XML generated by Doxygen when Doxygen's
# SEPARATE_MEMBER_PAGES is set to YES; this function should be harmless
# when SEPARATE_MEMBER_PAGES is NO!
#
# The issue was discussed here: https://github.com/doxygen/doxygen/pull/7971
#
# A Doxygen anchor consists of a 32-byte string version of the results of
# passing in the stringified identifier or prototype that is being "hashed".
# An "a" character is then prefixed to mark it as an anchor. Depending on how
# the identifier is linked, it can also get a "g" prefix to mean it is part
# of a Doxygen group. This results in an id having either 33 or 34 bytes
# (containing a "g" or not). Some identifiers, eg enumerators, get twice that
# length to have both a unique enum + unique enumerator, and sometimes they
# get two "g" characters as prefix instead of one.
def _fixup_separate_member_pages(self, refid: str) -> str:
if refid:
parts = refid.rsplit("_", 1)
if len(parts) == 2 and parts[1].startswith("1"):
anchorid = parts[1][1:]
if len(anchorid) in set([33, 34]) and parts[0].endswith(anchorid):
return parts[0][: -len(anchorid)] + parts[1]
elif len(anchorid) > 34:
index = 0
if anchorid.startswith("gg"):
index = 1
_len = 35
elif anchorid.startswith("g"):
_len = 34
else:
_len = 33
if parts[0].endswith(anchorid[index:_len]):
return parts[0][: -(_len - index)] + parts[1]
return refid
def get_refid(self, refid: str) -> str:
if self.app.config.breathe_separate_member_pages: # type: ignore
refid = self._fixup_separate_member_pages(refid)
if self.app.config.breathe_use_project_refids: # type: ignore
return "%s%s" % (self.project_info.name(), refid)
else:
return refid
def get_domain(self) -> str:
"""Returns the domain for the current node."""
def get_filename(node) -> Optional[str]:
"""Returns the name of a file where the declaration represented by node is located."""
try:
return node.location.file
except AttributeError:
return None
self.context = cast(RenderContext, self.context)
node_stack = self.context.node_stack
node = node_stack[0]
# An enumvalue node doesn't have location, so use its parent node for detecting
# the domain instead.
if isinstance(node, str) or node.node_type == "enumvalue":
node = node_stack[1]
filename = get_filename(node)
if not filename and node.node_type == "compound":
file_data = self.compound_parser.parse(node.refid)
filename = get_filename(file_data.compounddef)
return self.project_info.domain_for_file(filename) if filename else ""
def join_nested_name(self, names: List[str]) -> str:
dom = self.get_domain()
sep = "::" if not dom or dom == "cpp" else "."
return sep.join(names)
def run_directive(
self, obj_type: str, declaration: str, contentCallback: ContentCallback, options={}
) -> List[Node]:
self.context = cast(RenderContext, self.context)
args = [obj_type, [declaration]] + self.context.directive_args[2:]
directive = DomainDirectiveFactory.create(self.context.domain, args)
assert issubclass(type(directive), BaseObject)
directive.breathe_content_callback = contentCallback # type: ignore
# Translate Breathe's no-link option into the standard noindex option.
if "no-link" in self.context.directive_args[2]:
directive.options["noindex"] = True
for k, v in options.items():
directive.options[k] = v
assert self.app.env is not None
config = self.app.env.config
if config.breathe_debug_trace_directives:
global _debug_indent
print(
"{}Running directive: .. {}:: {}".format(
" " * _debug_indent, directive.name, declaration
)
)
_debug_indent += 1
self.nesting_level += 1
nodes = directive.run()
self.nesting_level -= 1
# TODO: the directive_args seems to be reused between different run_directives
# so for now, reset the options.
# Remove this once the args are given in a different manner.
for k, v in options.items():
del directive.options[k]
if config.breathe_debug_trace_directives:
_debug_indent -= 1
# Filter out outer class names if we are rendering a member as a part of a class content.
# In some cases of errors with a declaration there are no nodes
# (e.g., variable in function), so perhaps skip (see #671).
# If there are nodes, there should be at least 2.
if len(nodes) != 0:
assert len(nodes) >= 2, nodes
rst_node = nodes[1]
finder = NodeFinder(rst_node.document)
rst_node.walk(finder)
signode = finder.declarator
if self.context.child:
signode.children = [n for n in signode.children if not n.tagname == "desc_addname"]
return nodes
def handle_declaration(
self,
node,
declaration: str,
*,
obj_type: str = None,
content_callback: ContentCallback = None,
display_obj_type: str = None,
declarator_callback: DeclaratorCallback = None,
options={}
) -> List[Node]:
if obj_type is None:
obj_type = node.kind
if content_callback is None:
def content(contentnode):
contentnode.extend(self.description(node))
content_callback = content
declaration = declaration.replace("\n", " ")
nodes_ = self.run_directive(obj_type, declaration, content_callback, options)
assert self.app.env is not None
if self.app.env.config.breathe_debug_trace_doxygen_ids:
target = self.create_doxygen_target(node)
if len(target) == 0:
print("{}Doxygen target: (none)".format(" " * _debug_indent))
else:
print("{}Doxygen target: {}".format(" " * _debug_indent, target[0]["ids"]))
# <desc><desc_signature> and then one or more <desc_signature_line>
# each <desc_signature_line> has a sphinx_line_type which hints what is present in that line
# In some cases of errors with a declaration there are no nodes
# (e.g., variable in function), so perhaps skip (see #671).
if len(nodes_) == 0:
return []
assert len(nodes_) >= 2, nodes_
desc = nodes_[1]
assert isinstance(desc, addnodes.desc)
assert len(desc) >= 1
sig = desc[0]
assert isinstance(sig, addnodes.desc_signature)
# if may or may not be a multiline signature
isMultiline = sig.get("is_multiline", False)
declarator = None # type: Optional[Declarator]
if isMultiline:
for line in sig:
assert isinstance(line, addnodes.desc_signature_line)
if line.sphinx_line_type == "declarator":
declarator = line
else:
declarator = sig
assert declarator is not None
if display_obj_type is not None:
n = declarator[0]
newStyle = True
# the new style was introduced in Sphinx v4
if sphinx.version_info[0] < 4:
newStyle = False
# but only for the C and C++ domains
if self.get_domain() and self.get_domain() not in ("c", "cpp"):
newStyle = False
if newStyle:
# TODO: remove the "type: ignore" when Sphinx >= 4 is required
assert isinstance(n, addnodes.desc_sig_keyword) # type: ignore
declarator[0] = addnodes.desc_sig_keyword( # type: ignore
display_obj_type, display_obj_type
)
else:
assert isinstance(n, addnodes.desc_annotation)
assert n.astext()[-1] == " "
txt = display_obj_type + " "
declarator[0] = addnodes.desc_annotation(txt, txt)
if not self.app.env.config.breathe_debug_trace_doxygen_ids:
target = self.create_doxygen_target(node)
declarator.insert(0, target)
if declarator_callback:
declarator_callback(declarator)
return nodes_
def get_qualification(self) -> List[str]:
if self.nesting_level > 0:
return []
assert self.app.env is not None
config = self.app.env.config
if config.breathe_debug_trace_qualification:
def debug_print_node(n):
return "node_type={}".format(n.node_type)
global _debug_indent
print(
"{}{}".format(_debug_indent * " ", debug_print_node(self.qualification_stack[0]))
)
_debug_indent += 1
names = [] # type: List[str]
for node in self.qualification_stack[1:]:
if config.breathe_debug_trace_qualification:
print("{}{}".format(_debug_indent * " ", debug_print_node(node)))
if node.node_type == "ref" and len(names) == 0:
if config.breathe_debug_trace_qualification:
print("{}{}".format(_debug_indent * " ", "res="))
return []
if (
node.node_type == "compound" and node.kind not in ["file", "namespace", "group"]
) or node.node_type == "memberdef":
# We skip the 'file' entries because the file name doesn't form part of the
# qualified name for the identifier. We skip the 'namespace' entries because if we
# find an object through the namespace 'compound' entry in the index.xml then we'll
# also have the 'compounddef' entry in our node stack and we'll get it from that. We
# need the 'compounddef' entry because if we find the object through the 'file'
# entry in the index.xml file then we need to get the namespace name from somewhere
names.append(node.name)
if node.node_type == "compounddef" and node.kind == "namespace":
# Nested namespaces include their parent namespace(s) in compoundname. ie,
# compoundname is 'foo::bar' instead of just 'bar' for namespace 'bar' nested in
# namespace 'foo'. We need full compoundname because node_stack doesn't necessarily
# include parent namespaces and we stop here in case it does.
names.extend(reversed(node.compoundname.split("::")))
break
names.reverse()
if config.breathe_debug_trace_qualification:
print("{}res={}".format(_debug_indent * " ", names))
_debug_indent -= 1
return names
# ===================================================================================
def get_fully_qualified_name(self):
names = []
node_stack = self.context.node_stack
node = node_stack[0]
# If the node is a namespace, use its name because namespaces are skipped in the main loop.
if node.node_type == "compound" and node.kind == "namespace":
names.append(node.name)
for node in node_stack:
if node.node_type == "ref" and len(names) == 0:
return node.valueOf_
if (
node.node_type == "compound" and node.kind not in ["file", "namespace", "group"]
) or node.node_type == "memberdef":
# We skip the 'file' entries because the file name doesn't form part of the
# qualified name for the identifier. We skip the 'namespace' entries because if we
# find an object through the namespace 'compound' entry in the index.xml then we'll
# also have the 'compounddef' entry in our node stack and we'll get it from that. We
# need the 'compounddef' entry because if we find the object through the 'file'
# entry in the index.xml file then we need to get the namespace name from somewhere
names.insert(0, node.name)
if node.node_type == "compounddef" and node.kind == "namespace":
# Nested namespaces include their parent namespace(s) in compoundname. ie,
# compoundname is 'foo::bar' instead of just 'bar' for namespace 'bar' nested in
# namespace 'foo'. We need full compoundname because node_stack doesn't necessarily
# include parent namespaces and we stop here in case it does.
names.insert(0, node.compoundname)
break
return "::".join(names)
def create_template_prefix(self, decl) -> str:
if not decl.templateparamlist:
return ""
nodes = self.render(decl.templateparamlist)
return "template<" + "".join(n.astext() for n in nodes) + ">" # type: ignore
def run_domain_directive(self, kind, names):
domain_directive = DomainDirectiveFactory.create(
self.context.domain, [kind, names] + self.context.directive_args[2:]
)
# Translate Breathe's no-link option into the standard noindex option.
if "no-link" in self.context.directive_args[2]:
domain_directive.options["noindex"] = True
config = self.app.env.config
if config.breathe_debug_trace_directives:
global _debug_indent
print(
"{}Running directive (old): .. {}:: {}".format(
" " * _debug_indent, domain_directive.name, "".join(names)
)
)
_debug_indent += 1
nodes = domain_directive.run()
if config.breathe_debug_trace_directives:
_debug_indent -= 1
# Filter out outer class names if we are rendering a member as a part of a class content.
rst_node = nodes[1]
finder = NodeFinder(rst_node.document)
rst_node.walk(finder)
signode = finder.declarator
if len(names) > 0 and self.context.child:
signode.children = [n for n in signode.children if not n.tagname == "desc_addname"]
return nodes
def create_doxygen_target(self, node) -> List[Element]:
"""Can be overridden to create a target node which uses the doxygen refid information
which can be used for creating links between internal doxygen elements.
The default implementation should suffice most of the time.
"""
refid = self.get_refid(node.id)
return self.target_handler.create_target(refid)
def title(self, node) -> List[Node]:
nodes_ = []
# Variable type or function return type
nodes_.extend(self.render_optional(node.type_))
if nodes_:
nodes_.append(nodes.Text(" "))
nodes_.append(addnodes.desc_name(text=node.name))
return nodes_
def description(self, node) -> List[Node]:
brief = self.render_optional(node.briefdescription)
detailedCand = self.render_optional(node.detaileddescription)
# all field_lists must be at the top-level of the desc_content, so pull them up
fieldLists = [] # type: List[nodes.field_list]
admonitions = [] # type: List[Union[nodes.warning, nodes.note]]
def pullup(node, typ, dest):
for n in node.traverse(typ):
del n.parent[n.parent.index(n)]
dest.append(n)
detailed = []
for candNode in detailedCand:
pullup(candNode, nodes.field_list, fieldLists)
pullup(candNode, nodes.note, admonitions)
pullup(candNode, nodes.warning, admonitions)
# and collapse paragraphs
for para in candNode.traverse(nodes.paragraph):
if (
para.parent
and len(para.parent) == 1
and isinstance(para.parent, nodes.paragraph)
):
para.replace_self(para.children)
# and remove empty top-level paragraphs
if isinstance(candNode, nodes.paragraph) and len(candNode) == 0:
continue
detailed.append(candNode)
# make one big field list instead to the Sphinx transformer can make it pretty
if len(fieldLists) > 1:
fieldList = nodes.field_list()
for fl in fieldLists:
fieldList.extend(fl)
fieldLists = [fieldList]
# collapse retvals into a single return field
if len(fieldLists) != 0 and sphinx.version_info[0:2] < (4, 3):
others: nodes.field = []
retvals: nodes.field = []
for f in fieldLists[0]:
fn, fb = f
assert len(fn) == 1
if fn.astext().startswith("returns "):
retvals.append(f)
else:
others.append(f)
if len(retvals) != 0:
items: List[nodes.paragraph] = []
for fn, fb in retvals:
# we created the retvals before, so we made this prefix
assert fn.astext().startswith("returns ")
val = nodes.strong("", fn.astext()[8:])
# assumption from visit_docparamlist: fb is a single paragraph or nothing
assert len(fb) <= 1, fb
bodyNodes = [val, nodes.Text(" -- ")]
if len(fb) == 1:
assert isinstance(fb[0], nodes.paragraph)
bodyNodes.extend(fb[0])
items.append(nodes.paragraph("", "", *bodyNodes))
# only make a bullet list if there are multiple retvals
if len(items) == 1:
body = items[0]
else:
body = nodes.bullet_list()
for i in items:
body.append(nodes.list_item("", i))
fRetvals = nodes.field(
"", nodes.field_name("", "returns"), nodes.field_body("", body)
)
fl = nodes.field_list("", *others, fRetvals)
fieldLists = [fl]
if self.app.config.breathe_order_parameters_first: # type: ignore
return brief + detailed + fieldLists + admonitions
else:
return brief + detailed + admonitions + fieldLists
def update_signature(self, signature, obj_type):
"""Update the signature node if necessary, e.g. add qualifiers."""
prefix = obj_type + " "
annotation = addnodes.desc_annotation(prefix, prefix)
if signature[0].tagname != "desc_name":
signature[0] = annotation
else:
signature.insert(0, annotation)
def render_declaration(self, node, declaration=None, description=None, **kwargs):
if declaration is None:
declaration = self.get_fully_qualified_name()
obj_type = kwargs.get("objtype", None)
if obj_type is None:
obj_type = node.kind
nodes = self.run_domain_directive(obj_type, [declaration.replace("\n", " ")])
if self.app.env.config.breathe_debug_trace_doxygen_ids:
target = self.create_doxygen_target(node)
if len(target) == 0:
print("{}Doxygen target (old): (none)".format(" " * _debug_indent))
else:
print("{}Doxygen target (old): {}".format(" " * _debug_indent, target[0]["ids"]))
rst_node = nodes[1]
finder = NodeFinder(rst_node.document)
rst_node.walk(finder)
signode = finder.declarator
contentnode = finder.content
update_signature = kwargs.get("update_signature", None)
if update_signature is not None:
update_signature(signode, obj_type)
if description is None:
description = self.description(node)
if not self.app.env.config.breathe_debug_trace_doxygen_ids:
target = self.create_doxygen_target(node)
signode.insert(0, target)
contentnode.extend(description)
return nodes
def visit_doxygen(self, node) -> List[Node]:
nodelist = []
# Process all the compound children
for n in node.get_compound():
nodelist.extend(self.render(n))
return nodelist
def visit_doxygendef(self, node) -> List[Node]:
return self.render(node.compounddef)
def visit_union(self, node) -> List[Node]:
# Read in the corresponding xml file and process
file_data = self.compound_parser.parse(node.refid)
nodeDef = file_data.compounddef
self.context = cast(RenderContext, self.context)
parent_context = self.context.create_child_context(file_data)
new_context = parent_context.create_child_context(nodeDef)