2 This is autodoxy, a sphinx extension providing autodoc-like directives
3 that are feed with Doxygen files.
5 It is highly inspired from the autodoc_doxygen sphinx extension, but
6 adapted to my own needs in SimGrid.
7 https://github.com/rmcgibbo/sphinxcontrib-autodoc_doxygen
10 Copyright (c) 2015 Robert T. McGibbon
11 Copyright (c) 2019 Martin Quinson
13 from __future__ import print_function, absolute_import, division
19 from six import itervalues
20 from lxml import etree as ET
21 from sphinx.ext.autodoc import Documenter, members_option, ALL
23 from sphinx.ext.autodoc import AutoDirective
27 from sphinx.errors import ExtensionError
28 from sphinx.util import logging
30 ##########################################################################
32 ##########################################################################
33 def format_xml_paragraph(xmlnode):
34 """Format an Doxygen XML segment (principally a detaileddescription)
35 as a paragraph for inclusion in the rst document
46 return [l.rstrip() for l in _DoxygenXmlParagraphFormatter().generic_visit(xmlnode).lines]
49 class _DoxygenXmlParagraphFormatter(object):
50 # This class follows the model of the stdlib's ast.NodeVisitor for tree traversal
51 # where you dispatch on the element type to a different method for each node
52 # during the traverse.
54 # It's supposed to handle paragraphs, references, preformatted text (code blocks), and lists.
58 self.continue_line = False
60 def visit(self, node):
61 method = 'visit_' + node.tag
62 visitor = getattr(self, method, self.generic_visit)
65 def generic_visit(self, node):
66 for child in node.getchildren():
70 def visit_ref(self, node):
71 ref = get_doxygen_root().findall('.//*[@id="%s"]' % node.get('refid'))
74 if ref.tag == 'memberdef':
75 parent = ref.xpath('./ancestor::compounddef/compoundname')[0].text
76 name = ref.find('./name').text
77 real_name = parent + '::' + name
78 elif ref.tag in ('compounddef', 'enumvalue'):
79 name_node = ref.find('./name')
80 real_name = name_node.text if name_node is not None else ''
82 raise NotImplementedError(ref.tag)
86 val = [':cpp:any:`', node.text]
88 val.extend((' <', real_name, '>`'))
91 if node.tail is not None:
94 self.lines[-1] += ''.join(val)
96 def visit_para(self, node):
97 if node.text is not None:
98 if self.continue_line:
99 self.lines[-1] += node.text
101 self.lines.append(node.text)
102 self.generic_visit(node)
103 self.lines.append('')
104 self.continue_line = False
106 def visit_verbatim(self, node):
107 if node.text is not None:
108 # remove the leading ' *' of any lines
109 lines = [re.sub('^\s*\*','', l) for l in node.text.split('\n')]
110 # Merge each paragraph together
111 text = re.sub("\n\n", "PaRaGrraphSplit", '\n'.join(lines))
112 text = re.sub('\n', '', text)
113 lines = text.split('PaRaGrraphSplit')
115 # merge content to the built doc
116 if self.continue_line:
117 self.lines[-1] += lines[0]
120 self.lines.append('')
122 self.generic_visit(node)
123 self.lines.append('')
124 self.continue_line = False
126 def visit_parametername(self, node):
127 if 'direction' in node.attrib:
128 direction = '[%s] ' % node.get('direction')
132 self.lines.append('**%s** -- %s' % (
133 node.text, direction))
134 self.continue_line = True
136 def visit_parameterlist(self, node):
137 lines = [l for l in type(self)().generic_visit(node).lines if l != '']
138 self.lines.extend([':parameters:', ''] + ['* %s' % l for l in lines] + [''])
140 def visit_simplesect(self, node):
141 if node.get('kind') == 'return':
142 self.lines.append(':returns: ')
143 self.continue_line = True
144 self.generic_visit(node)
146 def visit_listitem(self, node):
147 self.lines.append(' - ')
148 self.continue_line = True
149 self.generic_visit(node)
151 def visit_preformatted(self, node):
152 segment = [node.text if node.text is not None else '']
153 for n in node.getchildren():
154 segment.append(n.text)
155 if n.tail is not None:
156 segment.append(n.tail)
158 lines = ''.join(segment).split('\n')
159 self.lines.extend(('.. code-block:: C++', ''))
160 self.lines.extend([' ' + l for l in lines])
162 def visit_computeroutput(self, node):
163 c = node.find('preformatted')
165 return self.visit_preformatted(c)
166 return self.visit_preformatted(node)
168 def visit_xrefsect(self, node):
169 if node.find('xreftitle').text == 'Deprecated':
170 sublines = type(self)().generic_visit(node).lines
171 self.lines.extend(['.. admonition:: Deprecated'] + [' ' + s for s in sublines])
173 raise ValueError(node)
175 def visit_subscript(self, node):
176 self.lines[-1] += '\ :sub:`%s` %s' % (node.text, node.tail)
179 ##########################################################################
181 ##########################################################################
184 class DoxygenDocumenter(Documenter):
185 # Variables to store the names of the object being documented. modname and fullname are redundant,
186 # and objpath is always the empty list. This is inelegant, but we need to work with the superclass.
188 fullname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
189 modname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
190 objname = None # example: "NonbondedForce" or "methodName"
191 objpath = [] # always the empty list
192 object = None # the xml node for the object
195 'members': members_option,
198 def __init__(self, directive, name, indent=u'', my_id = None):
199 super(DoxygenDocumenter, self).__init__(directive, name, indent)
200 if my_id is not None:
203 def parse_id(self, id_to_parse):
206 def parse_name(self):
207 """Determine what module to import and what attribute to document.
208 Returns True and sets *self.modname*, *self.objname*, *self.fullname*,
209 if parsing and resolving was successful.
211 # To view the context and order in which all of these methods get called,
212 # See, Documenter.generate(). That's the main "entry point" that first
213 # calls parse_name(), follwed by import_object(), format_signature(),
214 # add_directive_header(), and then add_content() (which calls get_doc())
216 # If we were provided a prototype, that must be an overloaded function. Save it.
217 self.argsstring = None
219 (self.name, self.argsstring) = self.name.split('(', 1)
220 self.argsstring = "({}".format(self.argsstring)
222 # methods in the superclass sometimes use '.' to join namespace/class
223 # names with method names, and we don't want that.
224 self.name = self.name.replace('.', '::')
225 self.fullname = self.name
226 self.modname = self.fullname
229 if '::' in self.name:
230 parts = self.name.split('::')
231 self.klassname = parts[-2]
232 self.objname = parts[-1]
234 self.objname = self.name
239 def add_directive_header(self, sig):
240 """Add the directive header and options to the generated content."""
241 domain = getattr(self, 'domain', 'cpp')
242 directive = getattr(self, 'directivetype', self.objtype)
243 name = self.format_name()
244 sourcename = self.get_sourcename()
245 #print('.. %s:%s:: %s%s' % (domain, directive, name, sig))
246 self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
249 def document_members(self, all_members=False):
250 """Generate reST for member documentation.
251 If *all_members* is True, do all members, else those given by
252 *self.options.members*.
254 want_all = all_members or self.options.inherited_members or \
255 self.options.members is ALL
256 # find out which members are documentable
257 members_check_module, members = self.get_object_members(want_all)
259 # remove members given by exclude-members
260 if self.options.exclude_members:
261 members = [(membername, member) for (membername, member) in members
262 if membername not in self.options.exclude_members]
264 # document non-skipped members
265 memberdocumenters = []
266 for (mname, member, isattr) in self.filter_members(members, want_all):
267 if sphinxVersion >= 2:
268 classes = [cls for cls in itervalues(self.env.app.registry.documenters)
269 if cls.can_document_member(member, mname, isattr, self)]
271 classes = [cls for cls in itervalues(AutoDirective._registry)
272 if cls.can_document_member(member, mname, isattr, self)]
274 # don't know how to document this member
277 # prefer the documenter with the highest priority
278 classes.sort(key=lambda cls: cls.priority)
280 documenter = classes[-1](self.directive, mname, indent=self.indent, id=member.get('id'))
281 memberdocumenters.append((documenter, isattr))
283 for documenter, isattr in memberdocumenters:
285 all_members=True, real_modname=self.real_modname,
286 check_module=members_check_module and not isattr)
288 # reset current objects
289 self.env.temp_data['autodoc:module'] = None
290 self.env.temp_data['autodoc:class'] = None
293 class DoxygenClassDocumenter(DoxygenDocumenter):
294 objtype = 'doxyclass'
295 directivetype = 'class'
300 'members': members_option,
304 def can_document_member(cls, member, membername, isattr, parent):
305 # this method is only called from Documenter.document_members
306 # when a higher level documenter (module or namespace) is trying
307 # to choose the appropriate documenter for each of its lower-level
308 # members. Currently not implemented since we don't have a higher-level
309 # doumenter like a DoxygenNamespaceDocumenter.
312 def import_object(self):
313 """Import the object and set it as *self.object*. In the call sequence, this
314 is executed right after parse_name(), so it can use *self.fullname*, *self.objname*,
317 Returns True if successful, False if an error occurred.
319 xpath_query = './/compoundname[text()="%s"]/..' % self.fullname
320 match = get_doxygen_root().xpath(xpath_query)
322 raise ExtensionError('[autodoxy] could not find class (fullname="%s"). I tried '
323 'the following xpath: "%s"' % (self.fullname, xpath_query))
325 self.object = match[0]
328 def format_signature(self):
331 def format_name(self):
334 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
335 detaileddescription = self.object.find('detaileddescription')
336 doc = [format_xml_paragraph(detaileddescription)]
339 def get_object_members(self, want_all):
340 all_members = self.object.xpath('.//sectiondef[@kind="public-func" '
341 'or @kind="public-static-func"]/memberdef[@kind="function"]')
344 return False, ((m.find('name').text, m) for m in all_members)
345 if not self.options.members:
347 return False, ((m.find('name').text, m) for m in all_members if m.find('name').text in self.options.members)
349 def filter_members(self, members, want_all):
351 for (membername, member) in members:
352 ret.append((membername, member, False))
355 def document_members(self, all_members=False):
356 super(DoxygenClassDocumenter, self).document_members(all_members=all_members)
357 # Uncomment to view the generated rst for the class.
358 # print('\n'.join(self.directive.result))
360 autodoxy_requalified_identifiers = []
361 def fix_namespaces(str):
362 for unqualified,fullyqualif in autodoxy_requalified_identifiers:
363 p = re.compile("(^| ){:s}".format(unqualified))
364 str = p.sub(' {:s}'.format(fullyqualif), str)
367 class DoxygenMethodDocumenter(DoxygenDocumenter):
368 objtype = 'doxymethod'
369 directivetype = 'function'
374 def can_document_member(cls, member, membername, isattr, parent):
375 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'function':
379 def parse_id(self, id_to_parse):
380 xp = './/*[@id="%s"]' % id_to_parse
381 match = get_doxygen_root().xpath(xp)
384 self.fullname = match.find('./definition').text.split()[-1]
385 self.modname = self.fullname
386 self.objname = match.find('./name').text
390 def import_object(self):
391 if ET.iselement(self.object):
392 # self.object already set from DoxygenDocumenter.parse_name(),
393 # caused by passing in the `id` of the node instead of just a
394 # classname or method name
397 if '::' in self.fullname:
398 (obj, meth) = self.fullname.rsplit('::', 1)
399 # 'public-func' and 'public-static-func' are for classes while 'func' alone is for namespaces
400 prefix = './/compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func" or @kind="func"]'.format(obj)
401 obj = "{:s}::".format(obj)
407 xpath_query_noparam = ('{:s}/memberdef[@kind="function"]/name[text()="{:s}"]/..').format(prefix, meth)
409 if self.argsstring is not None:
410 xpath_query = ('{:s}/memberdef[@kind="function" and argsstring/text()="{:s}"]/name[text()="{:s}"]/..').format(prefix,self.argsstring,meth)
412 xpath_query = xpath_query_noparam
413 match = get_doxygen_root().xpath(xpath_query)
415 logger = logging.getLogger(__name__)
417 if self.argsstring is not None:
418 candidates = get_doxygen_root().xpath(xpath_query_noparam)
419 if len(candidates) == 1:
420 logger.warning("[autodoxy] Using method '{}{}{}' instead of '{}{}{}'. You may want to drop your specification of the signature, or to fix it."
421 .format(obj, meth, candidates[0].find('argsstring').text, obj, meth, self.argsstring))
422 self.object = candidates[0]
424 logger.warning("[autodoxy] WARNING: Could not find method {}{}{}".format(obj, meth, self.argsstring))
426 logger.warning("[autodoxy] WARNING: (no candidate found)")
427 for cand in candidates:
428 logger.warning("[autodoxy] WARNING: Existing candidate: {}{}{}".format(obj, meth, cand.find('argsstring').text))
430 logger.warning("[autodoxy] WARNING: Could not find method {}{} in Doxygen files\nQuery: {}".format(obj, meth, xpath_query))
432 self.object = match[0]
435 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
436 detaileddescription = self.object.find('detaileddescription')
437 doc = [format_xml_paragraph(detaileddescription)]
440 def format_name(self):
442 if el.text is not None:
447 if el.tail is not None:
451 rtype_el = self.object.find('type')
452 rtype_el_ref = rtype_el.find('ref')
453 if rtype_el_ref is not None:
454 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
456 rtype = rtype_el.text
458 # print("rtype: {}".format(rtype))
459 signame = fix_namespaces((rtype and (rtype + ' ') or '') + self.klassname + "::"+ self.objname )
460 # print("signame: '{}'".format(signame))
461 return self.format_template_name() + signame
463 def format_template_name(self):
464 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
467 ret = 'template <%s>' % ','.join(types)
468 # print ("template: {}".format(ret))
471 def format_signature(self):
472 args = fix_namespaces(self.object.find('argsstring').text)
473 # print ("signature: {}".format(args))
476 def document_members(self, all_members=False):
480 """Return the unparsed form of the element"""
481 res = '<{}'.format(xelm.tag)
482 for key in xelm.keys():
483 res += ' {}="{}"'.format(key, xelm.attrib[key])
485 if xelm.text is not None: # Text before the first child
487 for i in xelm.getchildren(): # serialize every subtag
489 if xelm.tail is not None: # Text after last child
491 res += '</{}>'.format(xelm.tag)
494 """Return the content of the element, with all tags removed. Only the text remains"""
496 if xelm.text is not None: # Text before the first child
498 for i in xelm.getchildren(): # serialize every subtag
500 if xelm.tail is not None: # Text after last child
504 class DoxygenVariableDocumenter(DoxygenDocumenter):
506 directivetype = 'var'
511 def can_document_member(cls, member, membername, isattr, parent):
512 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'variable':
516 def import_object(self):
517 if ET.iselement(self.object):
518 # self.object already set from DoxygenDocumenter.parse_name(),
519 # caused by passing in the `id` of the node instead of just a
520 # classname or method name
523 (obj, var) = self.fullname.rsplit('::', 1)
525 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-attrib" or @kind="public-static-attrib"]'
526 '/memberdef[@kind="variable"]/name[text()="{:s}"]/..').format(obj, var)
527 # print("fullname {}".format(self.fullname))
528 match = get_doxygen_root().xpath(xpath_query)
530 logger = logging.getLogger(__name__)
532 logger.warning("[autodoxy] WARNING: could not find variable {}::{} in Doxygen files".format(obj, var))
534 self.object = match[0]
537 def parse_id(self, id_to_parse):
538 xp = './/*[@id="%s"]' % id_to_parse
539 match = get_doxygen_root().xpath(xp)
542 self.fullname = match.find('./definition').text.split()[-1]
543 self.modname = self.fullname
544 self.objname = match.find('./name').text
548 def format_name(self):
550 if el.text is not None:
554 # Remove all tags (such as refs) but keep the text of the element's type
555 rtype = elm2txt(self.object.find('type')).replace("\n", " ")
556 rtype = re.sub(" +", " ", rtype) # s/ +/ /
557 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::" + self.objname
558 res = fix_namespaces(self.format_template_name() + signame)
559 # print("formatted name: {}".format(res))
562 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
563 detaileddescription = self.object.find('detaileddescription')
564 doc = [format_xml_paragraph(detaileddescription)]
565 # print ("doc: {}".format(doc))
568 def format_template_name(self):
569 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
572 ret = 'template <%s>' % ','.join(types)
573 # print ("template: {}".format(ret))
576 def document_members(self, all_members=False):
580 ##########################################################################
581 # Setup the extension
582 ##########################################################################
583 def set_doxygen_xml(app):
584 """Load all doxygen XML files from the app config variable
585 `app.config.doxygen_xml` which should be a path to a directory
586 containing doxygen xml output
588 err = ExtensionError(
589 '[autodoxy] No doxygen xml output found in doxygen_xml="%s"' % app.config.doxygen_xml)
591 if not os.path.isdir(app.config.doxygen_xml):
594 files = [os.path.join(app.config.doxygen_xml, f)
595 for f in os.listdir(app.config.doxygen_xml)
596 if f.lower().endswith('.xml') and not f.startswith('._')]
600 setup.DOXYGEN_ROOT = ET.ElementTree(ET.Element('root')).getroot()
601 for current_file in files:
602 root = ET.parse(current_file).getroot()
604 setup.DOXYGEN_ROOT.append(node)
606 if app.config.autodoxy_requalified_identifiers is not None:
607 global autodoxy_requalified_identifiers
608 autodoxy_requalified_identifiers = app.config.autodoxy_requalified_identifiers
610 def get_doxygen_root():
611 """Get the root element of the doxygen XML document.
613 if not hasattr(setup, 'DOXYGEN_ROOT'):
614 setup.DOXYGEN_ROOT = ET.Element("root") # dummy
615 return setup.DOXYGEN_ROOT
619 import sphinx.ext.autosummary
621 app.connect("builder-inited", set_doxygen_xml)
622 # app.connect("builder-inited", process_generate_options)
624 app.setup_extension('sphinx.ext.autodoc')
625 # app.setup_extension('sphinx.ext.autosummary')
627 app.add_autodocumenter(DoxygenClassDocumenter)
628 app.add_autodocumenter(DoxygenMethodDocumenter)
629 app.add_autodocumenter(DoxygenVariableDocumenter)
630 app.add_config_value("doxygen_xml", "", True)
631 app.add_config_value("autodoxy_requalified_identifiers", [], True)
633 # app.add_directive('autodoxysummary', DoxygenAutosummary)
634 # app.add_directive('autodoxyenum', DoxygenAutoEnum)
636 return {'version': sphinx.__display_version__, 'parallel_read_safe': True}