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, AutoDirective, members_option, ALL
22 from sphinx.errors import ExtensionError
23 from sphinx.util import logging
26 ##########################################################################
28 ##########################################################################
29 def format_xml_paragraph(xmlnode):
30 """Format an Doxygen XML segment (principally a detaileddescription)
31 as a paragraph for inclusion in the rst document
42 return [l.rstrip() for l in _DoxygenXmlParagraphFormatter().generic_visit(xmlnode).lines]
45 class _DoxygenXmlParagraphFormatter(object):
46 # This class follows the model of the stdlib's ast.NodeVisitor for tree traversal
47 # where you dispatch on the element type to a different method for each node
48 # during the traverse.
50 # It's supposed to handle paragraphs, references, preformatted text (code blocks), and lists.
54 self.continue_line = False
56 def visit(self, node):
57 method = 'visit_' + node.tag
58 visitor = getattr(self, method, self.generic_visit)
61 def generic_visit(self, node):
62 for child in node.getchildren():
66 def visit_ref(self, node):
67 ref = get_doxygen_root().findall('.//*[@id="%s"]' % node.get('refid'))
70 if ref.tag == 'memberdef':
71 parent = ref.xpath('./ancestor::compounddef/compoundname')[0].text
72 name = ref.find('./name').text
73 real_name = parent + '::' + name
74 elif ref.tag in ('compounddef', 'enumvalue'):
75 name_node = ref.find('./name')
76 real_name = name_node.text if name_node is not None else ''
78 raise NotImplementedError(ref.tag)
82 val = [':cpp:any:`', node.text]
84 val.extend((' <', real_name, '>`'))
87 if node.tail is not None:
90 self.lines[-1] += ''.join(val)
92 def visit_para(self, node):
93 if node.text is not None:
94 if self.continue_line:
95 self.lines[-1] += node.text
97 self.lines.append(node.text)
98 self.generic_visit(node)
100 self.continue_line = False
102 def visit_verbatim(self, node):
103 if node.text is not None:
104 # remove the leading ' *' of any lines
105 lines = [re.sub('^\s*\*','', l) for l in node.text.split('\n')]
106 # Merge each paragraph together
107 text = re.sub("\n\n", "PaRaGrraphSplit", '\n'.join(lines))
108 text = re.sub('\n', '', text)
109 lines = text.split('PaRaGrraphSplit')
111 # merge content to the built doc
112 if self.continue_line:
113 self.lines[-1] += lines[0]
116 self.lines.append('')
118 self.generic_visit(node)
119 self.lines.append('')
120 self.continue_line = False
122 def visit_parametername(self, node):
123 if 'direction' in node.attrib:
124 direction = '[%s] ' % node.get('direction')
128 self.lines.append('**%s** -- %s' % (
129 node.text, direction))
130 self.continue_line = True
132 def visit_parameterlist(self, node):
133 lines = [l for l in type(self)().generic_visit(node).lines if l is not '']
134 self.lines.extend([':parameters:', ''] + ['* %s' % l for l in lines] + [''])
136 def visit_simplesect(self, node):
137 if node.get('kind') == 'return':
138 self.lines.append(':returns: ')
139 self.continue_line = True
140 self.generic_visit(node)
142 def visit_listitem(self, node):
143 self.lines.append(' - ')
144 self.continue_line = True
145 self.generic_visit(node)
147 def visit_preformatted(self, node):
148 segment = [node.text if node.text is not None else '']
149 for n in node.getchildren():
150 segment.append(n.text)
151 if n.tail is not None:
152 segment.append(n.tail)
154 lines = ''.join(segment).split('\n')
155 self.lines.extend(('.. code-block:: C++', ''))
156 self.lines.extend([' ' + l for l in lines])
158 def visit_computeroutput(self, node):
159 c = node.find('preformatted')
161 return self.visit_preformatted(c)
162 return self.visit_preformatted(node)
164 def visit_xrefsect(self, node):
165 if node.find('xreftitle').text == 'Deprecated':
166 sublines = type(self)().generic_visit(node).lines
167 self.lines.extend(['.. admonition:: Deprecated'] + [' ' + s for s in sublines])
169 raise ValueError(node)
171 def visit_subscript(self, node):
172 self.lines[-1] += '\ :sub:`%s` %s' % (node.text, node.tail)
175 ##########################################################################
177 ##########################################################################
180 class DoxygenDocumenter(Documenter):
181 # Variables to store the names of the object being documented. modname and fullname are redundant,
182 # and objpath is always the empty list. This is inelegant, but we need to work with the superclass.
184 fullname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
185 modname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
186 objname = None # example: "NonbondedForce" or "methodName"
187 objpath = [] # always the empty list
188 object = None # the xml node for the object
191 'members': members_option,
194 def __init__(self, directive, name, indent=u'', id=None):
195 super(DoxygenDocumenter, self).__init__(directive, name, indent)
199 def parse_id(self, id):
202 def parse_name(self):
203 """Determine what module to import and what attribute to document.
204 Returns True and sets *self.modname*, *self.objname*, *self.fullname*,
205 if parsing and resolving was successful.
207 # To view the context and order in which all of these methods get called,
208 # See, Documenter.generate(). That's the main "entry point" that first
209 # calls parse_name(), follwed by import_object(), format_signature(),
210 # add_directive_header(), and then add_content() (which calls get_doc())
212 # If we were provided a prototype, that must be an overloaded function. Save it.
213 self.argsstring = None
215 (self.name, self.argsstring) = self.name.split('(', 1)
216 self.argsstring = "({}".format(self.argsstring)
218 # methods in the superclass sometimes use '.' to join namespace/class
219 # names with method names, and we don't want that.
220 self.name = self.name.replace('.', '::')
221 self.fullname = self.name
222 self.modname = self.fullname
225 if '::' in self.name:
226 parts = self.name.split('::')
227 self.klassname = parts[-2]
228 self.objname = parts[-1]
230 self.objname = self.name
235 def add_directive_header(self, sig):
236 """Add the directive header and options to the generated content."""
237 domain = getattr(self, 'domain', 'cpp')
238 directive = getattr(self, 'directivetype', self.objtype)
239 name = self.format_name()
240 sourcename = self.get_sourcename()
241 self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
244 def document_members(self, all_members=False):
245 """Generate reST for member documentation.
246 If *all_members* is True, do all members, else those given by
247 *self.options.members*.
249 want_all = all_members or self.options.inherited_members or \
250 self.options.members is ALL
251 # find out which members are documentable
252 members_check_module, members = self.get_object_members(want_all)
254 # remove members given by exclude-members
255 if self.options.exclude_members:
256 members = [(membername, member) for (membername, member) in members
257 if membername not in self.options.exclude_members]
259 # document non-skipped members
260 memberdocumenters = []
261 for (mname, member, isattr) in self.filter_members(members, want_all):
262 classes = [cls for cls in itervalues(AutoDirective._registry)
263 if cls.can_document_member(member, mname, isattr, self)]
265 # don't know how to document this member
268 # prefer the documenter with the highest priority
269 classes.sort(key=lambda cls: cls.priority)
271 documenter = classes[-1](self.directive, mname, indent=self.indent, id=member.get('id'))
272 memberdocumenters.append((documenter, isattr))
274 for documenter, isattr in memberdocumenters:
276 all_members=True, real_modname=self.real_modname,
277 check_module=members_check_module and not isattr)
279 # reset current objects
280 self.env.temp_data['autodoc:module'] = None
281 self.env.temp_data['autodoc:class'] = None
284 class DoxygenClassDocumenter(DoxygenDocumenter):
285 objtype = 'doxyclass'
286 directivetype = 'class'
291 'members': members_option,
295 def can_document_member(cls, member, membername, isattr, parent):
296 # this method is only called from Documenter.document_members
297 # when a higher level documenter (module or namespace) is trying
298 # to choose the appropriate documenter for each of its lower-level
299 # members. Currently not implemented since we don't have a higher-level
300 # doumenter like a DoxygenNamespaceDocumenter.
303 def import_object(self):
304 """Import the object and set it as *self.object*. In the call sequence, this
305 is executed right after parse_name(), so it can use *self.fullname*, *self.objname*,
308 Returns True if successful, False if an error occurred.
310 xpath_query = './/compoundname[text()="%s"]/..' % self.fullname
311 match = get_doxygen_root().xpath(xpath_query)
313 raise ExtensionError('[autodoxy] could not find class (fullname="%s"). I tried'
314 'the following xpath: "%s"' % (self.fullname, xpath_query))
316 self.object = match[0]
319 def format_signature(self):
322 def format_name(self):
325 def get_doc(self, encoding):
326 detaileddescription = self.object.find('detaileddescription')
327 doc = [format_xml_paragraph(detaileddescription)]
330 def get_object_members(self, want_all):
331 all_members = self.object.xpath('.//sectiondef[@kind="public-func" '
332 'or @kind="public-static-func"]/memberdef[@kind="function"]')
335 return False, ((m.find('name').text, m) for m in all_members)
336 if not self.options.members:
338 return False, ((m.find('name').text, m) for m in all_members if m.find('name').text in self.options.members)
340 def filter_members(self, members, want_all):
342 for (membername, member) in members:
343 ret.append((membername, member, False))
346 def document_members(self, all_members=False):
347 super(DoxygenClassDocumenter, self).document_members(all_members=all_members)
348 # Uncomment to view the generated rst for the class.
349 # print('\n'.join(self.directive.result))
351 class DoxygenMethodDocumenter(DoxygenDocumenter):
352 objtype = 'doxymethod'
353 directivetype = 'function'
358 def can_document_member(cls, member, membername, isattr, parent):
359 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'function':
363 def parse_id(self, id):
364 xp = './/*[@id="%s"]' % id
365 match = get_doxygen_root().xpath(xp)
368 self.fullname = match.find('./definition').text.split()[-1]
369 self.modname = self.fullname
370 self.objname = match.find('./name').text
374 def import_object(self):
375 if ET.iselement(self.object):
376 # self.object already set from DoxygenDocumenter.parse_name(),
377 # caused by passing in the `id` of the node instead of just a
378 # classname or method name
381 (obj, meth) = self.fullname.rsplit('::', 1)
383 xpath_query_noparam = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func"]'
384 '/memberdef[@kind="function"]/name[text()="{:s}"]/..').format(obj, meth)
386 # print("fullname {}".format(self.fullname))
387 if self.argsstring != None:
388 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func"]'
389 '/memberdef[@kind="function" and argsstring/text()="{:s}"]/name[text()="{:s}"]/..').format(obj,self.argsstring,meth)
391 xpath_query = xpath_query_noparam
392 match = get_doxygen_root().xpath(xpath_query)
394 logger = logging.getLogger(__name__)
396 if self.argsstring != None:
397 candidates = get_doxygen_root().xpath(xpath_query_noparam)
398 if len(candidates) == 1:
399 logger.warning("[autodoxy] Using method '{}::{}{}' instead of '{}::{}{}'. You may want to drop your specification of the signature, or to fix it."
400 .format(obj, meth, candidates[0].find('argsstring').text, obj, meth, self.argsstring))
401 self.object = candidates[0]
403 logger.warning("[autodoxy] WARNING: Could not find method {}::{}{}".format(obj, meth, self.argsstring))
404 for cand in candidates:
405 logger.warning("[autodoxy] WARNING: Existing candidate: {}::{}{}".format(obj, meth, cand.find('argsstring').text))
407 logger.warning("[autodoxy] WARNING: could not find method {}::{} in Doxygen files".format(obj, meth))
409 self.object = match[0]
412 def get_doc(self, encoding):
413 detaileddescription = self.object.find('detaileddescription')
414 doc = [format_xml_paragraph(detaileddescription)]
417 def format_name(self):
419 if el.text is not None:
424 if el.tail is not None:
428 rtype_el = self.object.find('type')
429 rtype_el_ref = rtype_el.find('ref')
430 if rtype_el_ref is not None:
431 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
433 rtype = rtype_el.text
435 # print("rtype: {}".format(rtype))
436 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::"+ self.objname
437 return self.format_template_name() + signame
439 def format_template_name(self):
440 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
443 ret = 'template <%s>' % ','.join(types)
444 # print ("template: {}".format(ret))
447 def format_signature(self):
448 args = self.object.find('argsstring').text
451 def document_members(self, all_members=False):
454 class DoxygenVariableDocumenter(DoxygenDocumenter):
456 directivetype = 'var'
461 def can_document_member(cls, member, membername, isattr, parent):
462 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'variable':
466 def import_object(self):
467 if ET.iselement(self.object):
468 # self.object already set from DoxygenDocumenter.parse_name(),
469 # caused by passing in the `id` of the node instead of just a
470 # classname or method name
473 (obj, var) = self.fullname.rsplit('::', 1)
475 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-attrib" or @kind="public-static-attrib"]'
476 '/memberdef[@kind="variable"]/name[text()="{:s}"]/..').format(obj, var)
477 # print("fullname {}".format(self.fullname))
478 match = get_doxygen_root().xpath(xpath_query)
480 logger = logging.getLogger(__name__)
482 logger.warning("[autodoxy] WARNING: could not find variable {}::{} in Doxygen files".format(obj, var))
484 self.object = match[0]
487 def parse_id(self, id):
488 xp = './/*[@id="%s"]' % id
489 match = get_doxygen_root().xpath(xp)
492 self.fullname = match.find('./definition').text.split()[-1]
493 self.modname = self.fullname
494 self.objname = match.find('./name').text
498 def format_name(self):
500 if el.text is not None:
505 if el.tail is not None:
509 rtype_el = self.object.find('type')
510 rtype_el_ref = rtype_el.find('ref')
511 if rtype_el_ref is not None:
512 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
514 rtype = rtype_el.text
516 # print("rtype: {}".format(rtype))
517 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::" + self.objname
518 return self.format_template_name() + signame
520 def get_doc(self, encoding):
521 detaileddescription = self.object.find('detaileddescription')
522 doc = [format_xml_paragraph(detaileddescription)]
525 def format_template_name(self):
526 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
529 ret = 'template <%s>' % ','.join(types)
530 # print ("template: {}".format(ret))
533 def document_members(self, all_members=False):
537 ##########################################################################
538 # Setup the extension
539 ##########################################################################
540 def set_doxygen_xml(app):
541 """Load all doxygen XML files from the app config variable
542 `app.config.doxygen_xml` which should be a path to a directory
543 containing doxygen xml output
545 err = ExtensionError(
546 '[autodoxy] No doxygen xml output found in doxygen_xml="%s"' % app.config.doxygen_xml)
548 if not os.path.isdir(app.config.doxygen_xml):
551 files = [os.path.join(app.config.doxygen_xml, f)
552 for f in os.listdir(app.config.doxygen_xml)
553 if f.lower().endswith('.xml') and not f.startswith('._')]
557 setup.DOXYGEN_ROOT = ET.ElementTree(ET.Element('root')).getroot()
559 root = ET.parse(file).getroot()
561 setup.DOXYGEN_ROOT.append(node)
564 def get_doxygen_root():
565 """Get the root element of the doxygen XML document.
567 if not hasattr(setup, 'DOXYGEN_ROOT'):
568 setup.DOXYGEN_ROOT = ET.Element("root") # dummy
569 return setup.DOXYGEN_ROOT
573 import sphinx.ext.autosummary
575 app.connect("builder-inited", set_doxygen_xml)
576 # app.connect("builder-inited", process_generate_options)
578 app.setup_extension('sphinx.ext.autodoc')
579 # app.setup_extension('sphinx.ext.autosummary')
581 app.add_autodocumenter(DoxygenClassDocumenter)
582 app.add_autodocumenter(DoxygenMethodDocumenter)
583 app.add_autodocumenter(DoxygenVariableDocumenter)
584 app.add_config_value("doxygen_xml", "", True)
586 # app.add_directive('autodoxysummary', DoxygenAutosummary)
587 # app.add_directive('autodoxyenum', DoxygenAutoEnum)
589 return {'version': sphinx.__display_version__, 'parallel_read_safe': True}