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)
337 if not self.options.members:
340 return False, ((m.find('name').text, m) for m in all_members
341 if m.find('name').text in self.options.members)
343 def filter_members(self, members, want_all):
345 for (membername, member) in members:
346 ret.append((membername, member, False))
349 def document_members(self, all_members=False):
350 super(DoxygenClassDocumenter, self).document_members(all_members=all_members)
351 # Uncomment to view the generated rst for the class.
352 # print('\n'.join(self.directive.result))
354 class DoxygenMethodDocumenter(DoxygenDocumenter):
355 objtype = 'doxymethod'
356 directivetype = 'function'
361 def can_document_member(cls, member, membername, isattr, parent):
362 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'function':
366 def parse_id(self, id):
367 xp = './/*[@id="%s"]' % id
368 match = get_doxygen_root().xpath(xp)
371 self.fullname = match.find('./definition').text.split()[-1]
372 self.modname = self.fullname
373 self.objname = match.find('./name').text
377 def import_object(self):
378 if ET.iselement(self.object):
379 # self.object already set from DoxygenDocumenter.parse_name(),
380 # caused by passing in the `id` of the node instead of just a
381 # classname or method name
384 (obj, meth) = self.fullname.rsplit('::', 1)
386 xpath_query_noparam = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func"]'
387 '/memberdef[@kind="function"]/name[text()="{:s}"]/..').format(obj, meth)
389 # print("fullname {}".format(self.fullname))
390 if self.argsstring != None:
391 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func"]'
392 '/memberdef[@kind="function" and argsstring/text()="{:s}"]/name[text()="{:s}"]/..').format(obj,self.argsstring,meth)
394 xpath_query = xpath_query_noparam
395 match = get_doxygen_root().xpath(xpath_query)
397 logger = logging.getLogger(__name__)
399 if self.argsstring != None:
400 candidates = get_doxygen_root().xpath(xpath_query_noparam)
401 if len(candidates) == 1:
402 logger.warning("[autodoxy] Using method '{}::{}{}' instead of '{}::{}{}'. You may want to drop your specification of the signature, or to fix it."
403 .format(obj, meth, candidates[0].find('argsstring').text, obj, meth, self.argsstring))
404 self.object = candidates[0]
406 logger.warning("[autodoxy] WARNING: Could not find method {}::{}{}".format(obj, meth, self.argsstring))
407 for cand in candidates:
408 logger.warning("[autodoxy] WARNING: Existing candidate: {}::{}{}".format(obj, meth, cand.find('argsstring').text))
410 logger.warning("[autodoxy] WARNING: could not find method {}::{} in Doxygen files".format(obj, meth))
412 self.object = match[0]
415 def get_doc(self, encoding):
416 detaileddescription = self.object.find('detaileddescription')
417 doc = [format_xml_paragraph(detaileddescription)]
420 def format_name(self):
422 if el.text is not None:
427 if el.tail is not None:
431 rtype_el = self.object.find('type')
432 rtype_el_ref = rtype_el.find('ref')
433 if rtype_el_ref is not None:
434 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
436 rtype = rtype_el.text
438 # print("rtype: {}".format(rtype))
439 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::"+ self.objname
440 return self.format_template_name() + signame
442 def format_template_name(self):
443 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
446 ret = 'template <%s>' % ','.join(types)
447 # print ("template: {}".format(ret))
450 def format_signature(self):
451 args = self.object.find('argsstring').text
454 def document_members(self, all_members=False):
457 class DoxygenVariableDocumenter(DoxygenDocumenter):
459 directivetype = 'var'
464 def can_document_member(cls, member, membername, isattr, parent):
465 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'variable':
469 def import_object(self):
470 if ET.iselement(self.object):
471 # self.object already set from DoxygenDocumenter.parse_name(),
472 # caused by passing in the `id` of the node instead of just a
473 # classname or method name
476 (obj, var) = self.fullname.rsplit('::', 1)
478 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-attrib" or @kind="public-static-attrib"]'
479 '/memberdef[@kind="variable"]/name[text()="{:s}"]/..').format(obj, var)
480 # print("fullname {}".format(self.fullname))
481 match = get_doxygen_root().xpath(xpath_query)
483 logger = logging.getLogger(__name__)
485 logger.warning("[autodoxy] WARNING: could not find variable {}::{} in Doxygen files".format(obj, var))
487 self.object = match[0]
490 def parse_id(self, id):
491 xp = './/*[@id="%s"]' % id
492 match = get_doxygen_root().xpath(xp)
495 self.fullname = match.find('./definition').text.split()[-1]
496 self.modname = self.fullname
497 self.objname = match.find('./name').text
501 def format_name(self):
503 if el.text is not None:
508 if el.tail is not None:
512 rtype_el = self.object.find('type')
513 rtype_el_ref = rtype_el.find('ref')
514 if rtype_el_ref is not None:
515 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
517 rtype = rtype_el.text
519 # print("rtype: {}".format(rtype))
520 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::" + self.objname
521 return self.format_template_name() + signame
523 def get_doc(self, encoding):
524 detaileddescription = self.object.find('detaileddescription')
525 doc = [format_xml_paragraph(detaileddescription)]
528 def format_template_name(self):
529 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
532 ret = 'template <%s>' % ','.join(types)
533 # print ("template: {}".format(ret))
536 def document_members(self, all_members=False):
540 ##########################################################################
541 # Setup the extension
542 ##########################################################################
543 def set_doxygen_xml(app):
544 """Load all doxygen XML files from the app config variable
545 `app.config.doxygen_xml` which should be a path to a directory
546 containing doxygen xml output
548 err = ExtensionError(
549 '[autodoxy] No doxygen xml output found in doxygen_xml="%s"' % app.config.doxygen_xml)
551 if not os.path.isdir(app.config.doxygen_xml):
554 files = [os.path.join(app.config.doxygen_xml, f)
555 for f in os.listdir(app.config.doxygen_xml)
556 if f.lower().endswith('.xml') and not f.startswith('._')]
560 setup.DOXYGEN_ROOT = ET.ElementTree(ET.Element('root')).getroot()
562 root = ET.parse(file).getroot()
564 setup.DOXYGEN_ROOT.append(node)
567 def get_doxygen_root():
568 """Get the root element of the doxygen XML document.
570 if not hasattr(setup, 'DOXYGEN_ROOT'):
571 setup.DOXYGEN_ROOT = ET.Element("root") # dummy
572 return setup.DOXYGEN_ROOT
576 import sphinx.ext.autosummary
578 app.connect("builder-inited", set_doxygen_xml)
579 # app.connect("builder-inited", process_generate_options)
581 app.setup_extension('sphinx.ext.autodoc')
582 # app.setup_extension('sphinx.ext.autosummary')
584 app.add_autodocumenter(DoxygenClassDocumenter)
585 app.add_autodocumenter(DoxygenMethodDocumenter)
586 app.add_autodocumenter(DoxygenVariableDocumenter)
587 app.add_config_value("doxygen_xml", "", True)
589 # app.add_directive('autodoxysummary', DoxygenAutosummary)
590 # app.add_directive('autodoxyenum', DoxygenAutoEnum)
592 return {'version': sphinx.__display_version__, 'parallel_read_safe': True}