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 != '']
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'', my_id = None):
195 super(DoxygenDocumenter, self).__init__(directive, name, indent)
196 if my_id is not None:
199 def parse_id(self, id_to_parse):
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 #print('.. %s:%s:: %s%s' % (domain, directive, name, sig))
242 self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
245 def document_members(self, all_members=False):
246 """Generate reST for member documentation.
247 If *all_members* is True, do all members, else those given by
248 *self.options.members*.
250 want_all = all_members or self.options.inherited_members or \
251 self.options.members is ALL
252 # find out which members are documentable
253 members_check_module, members = self.get_object_members(want_all)
255 # remove members given by exclude-members
256 if self.options.exclude_members:
257 members = [(membername, member) for (membername, member) in members
258 if membername not in self.options.exclude_members]
260 # document non-skipped members
261 memberdocumenters = []
262 for (mname, member, isattr) in self.filter_members(members, want_all):
263 classes = [cls for cls in itervalues(AutoDirective._registry)
264 if cls.can_document_member(member, mname, isattr, self)]
266 # don't know how to document this member
269 # prefer the documenter with the highest priority
270 classes.sort(key=lambda cls: cls.priority)
272 documenter = classes[-1](self.directive, mname, indent=self.indent, id=member.get('id'))
273 memberdocumenters.append((documenter, isattr))
275 for documenter, isattr in memberdocumenters:
277 all_members=True, real_modname=self.real_modname,
278 check_module=members_check_module and not isattr)
280 # reset current objects
281 self.env.temp_data['autodoc:module'] = None
282 self.env.temp_data['autodoc:class'] = None
285 class DoxygenClassDocumenter(DoxygenDocumenter):
286 objtype = 'doxyclass'
287 directivetype = 'class'
292 'members': members_option,
296 def can_document_member(cls, member, membername, isattr, parent):
297 # this method is only called from Documenter.document_members
298 # when a higher level documenter (module or namespace) is trying
299 # to choose the appropriate documenter for each of its lower-level
300 # members. Currently not implemented since we don't have a higher-level
301 # doumenter like a DoxygenNamespaceDocumenter.
304 def import_object(self):
305 """Import the object and set it as *self.object*. In the call sequence, this
306 is executed right after parse_name(), so it can use *self.fullname*, *self.objname*,
309 Returns True if successful, False if an error occurred.
311 xpath_query = './/compoundname[text()="%s"]/..' % self.fullname
312 match = get_doxygen_root().xpath(xpath_query)
314 raise ExtensionError('[autodoxy] could not find class (fullname="%s"). I tried'
315 'the following xpath: "%s"' % (self.fullname, xpath_query))
317 self.object = match[0]
320 def format_signature(self):
323 def format_name(self):
326 def get_doc(self, encoding):
327 detaileddescription = self.object.find('detaileddescription')
328 doc = [format_xml_paragraph(detaileddescription)]
331 def get_object_members(self, want_all):
332 all_members = self.object.xpath('.//sectiondef[@kind="public-func" '
333 'or @kind="public-static-func"]/memberdef[@kind="function"]')
336 return False, ((m.find('name').text, m) for m in all_members)
337 if not self.options.members:
339 return False, ((m.find('name').text, m) for m in all_members if m.find('name').text in self.options.members)
341 def filter_members(self, members, want_all):
343 for (membername, member) in members:
344 ret.append((membername, member, False))
347 def document_members(self, all_members=False):
348 super(DoxygenClassDocumenter, self).document_members(all_members=all_members)
349 # Uncomment to view the generated rst for the class.
350 # print('\n'.join(self.directive.result))
352 class DoxygenMethodDocumenter(DoxygenDocumenter):
353 objtype = 'doxymethod'
354 directivetype = 'function'
359 def can_document_member(cls, member, membername, isattr, parent):
360 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'function':
364 def parse_id(self, id_to_parse):
365 xp = './/*[@id="%s"]' % id_to_parse
366 match = get_doxygen_root().xpath(xp)
369 self.fullname = match.find('./definition').text.split()[-1]
370 self.modname = self.fullname
371 self.objname = match.find('./name').text
375 def import_object(self):
376 if ET.iselement(self.object):
377 # self.object already set from DoxygenDocumenter.parse_name(),
378 # caused by passing in the `id` of the node instead of just a
379 # classname or method name
382 if '::' in self.fullname:
383 (obj, meth) = self.fullname.rsplit('::', 1)
384 prefix = './/compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func"]'.format(obj)
385 obj = "{:s}::".format(obj)
391 xpath_query_noparam = ('{:s}/memberdef[@kind="function"]/name[text()="{:s}"]/..').format(prefix, meth)
393 if self.argsstring != None:
394 xpath_query = ('{:s}/memberdef[@kind="function" and argsstring/text()="{:s}"]/name[text()="{:s}"]/..').format(prefix,self.argsstring,meth)
396 xpath_query = xpath_query_noparam
397 match = get_doxygen_root().xpath(xpath_query)
399 logger = logging.getLogger(__name__)
401 if self.argsstring != None:
402 candidates = get_doxygen_root().xpath(xpath_query_noparam)
403 if len(candidates) == 1:
404 logger.warning("[autodoxy] Using method '{}{}{}' instead of '{}{}{}'. You may want to drop your specification of the signature, or to fix it."
405 .format(obj, meth, candidates[0].find('argsstring').text, obj, meth, self.argsstring))
406 self.object = candidates[0]
408 logger.warning("[autodoxy] WARNING: Could not find method {}{}{}".format(obj, meth, self.argsstring))
409 for cand in candidates:
410 logger.warning("[autodoxy] WARNING: Existing candidate: {}{}{}".format(obj, meth, cand.find('argsstring').text))
412 logger.warning("[autodoxy] WARNING: could not find method {}{} in Doxygen files\nQuery: {}".format(obj, meth, xpath_query))
414 self.object = match[0]
417 def get_doc(self, encoding):
418 detaileddescription = self.object.find('detaileddescription')
419 doc = [format_xml_paragraph(detaileddescription)]
422 def format_name(self):
424 if el.text is not None:
429 if el.tail is not None:
433 rtype_el = self.object.find('type')
434 rtype_el_ref = rtype_el.find('ref')
435 if rtype_el_ref is not None:
436 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
438 rtype = rtype_el.text
440 # print("rtype: {}".format(rtype))
441 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::"+ self.objname
442 return self.format_template_name() + signame
444 def format_template_name(self):
445 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
448 ret = 'template <%s>' % ','.join(types)
449 # print ("template: {}".format(ret))
452 def format_signature(self):
453 args = self.object.find('argsstring').text
456 def document_members(self, all_members=False):
459 class DoxygenVariableDocumenter(DoxygenDocumenter):
461 directivetype = 'var'
466 def can_document_member(cls, member, membername, isattr, parent):
467 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'variable':
471 def import_object(self):
472 if ET.iselement(self.object):
473 # self.object already set from DoxygenDocumenter.parse_name(),
474 # caused by passing in the `id` of the node instead of just a
475 # classname or method name
478 (obj, var) = self.fullname.rsplit('::', 1)
480 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-attrib" or @kind="public-static-attrib"]'
481 '/memberdef[@kind="variable"]/name[text()="{:s}"]/..').format(obj, var)
482 # print("fullname {}".format(self.fullname))
483 match = get_doxygen_root().xpath(xpath_query)
485 logger = logging.getLogger(__name__)
487 logger.warning("[autodoxy] WARNING: could not find variable {}::{} in Doxygen files".format(obj, var))
489 self.object = match[0]
492 def parse_id(self, id_to_parse):
493 xp = './/*[@id="%s"]' % id_to_parse
494 match = get_doxygen_root().xpath(xp)
497 self.fullname = match.find('./definition').text.split()[-1]
498 self.modname = self.fullname
499 self.objname = match.find('./name').text
503 def format_name(self):
505 if el.text is not None:
510 if el.tail is not None:
514 rtype_el = self.object.find('type')
515 rtype_el_ref = rtype_el.find('ref')
516 if rtype_el_ref is not None:
517 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
519 rtype = rtype_el.text
521 # print("rtype: {}".format(rtype))
522 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::" + self.objname
523 return self.format_template_name() + signame
525 def get_doc(self, encoding):
526 detaileddescription = self.object.find('detaileddescription')
527 doc = [format_xml_paragraph(detaileddescription)]
530 def format_template_name(self):
531 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
534 ret = 'template <%s>' % ','.join(types)
535 # print ("template: {}".format(ret))
538 def document_members(self, all_members=False):
542 ##########################################################################
543 # Setup the extension
544 ##########################################################################
545 def set_doxygen_xml(app):
546 """Load all doxygen XML files from the app config variable
547 `app.config.doxygen_xml` which should be a path to a directory
548 containing doxygen xml output
550 err = ExtensionError(
551 '[autodoxy] No doxygen xml output found in doxygen_xml="%s"' % app.config.doxygen_xml)
553 if not os.path.isdir(app.config.doxygen_xml):
556 files = [os.path.join(app.config.doxygen_xml, f)
557 for f in os.listdir(app.config.doxygen_xml)
558 if f.lower().endswith('.xml') and not f.startswith('._')]
562 setup.DOXYGEN_ROOT = ET.ElementTree(ET.Element('root')).getroot()
563 for current_file in files:
564 root = ET.parse(current_file).getroot()
566 setup.DOXYGEN_ROOT.append(node)
569 def get_doxygen_root():
570 """Get the root element of the doxygen XML document.
572 if not hasattr(setup, 'DOXYGEN_ROOT'):
573 setup.DOXYGEN_ROOT = ET.Element("root") # dummy
574 return setup.DOXYGEN_ROOT
578 import sphinx.ext.autosummary
580 app.connect("builder-inited", set_doxygen_xml)
581 # app.connect("builder-inited", process_generate_options)
583 app.setup_extension('sphinx.ext.autodoc')
584 # app.setup_extension('sphinx.ext.autosummary')
586 app.add_autodocumenter(DoxygenClassDocumenter)
587 app.add_autodocumenter(DoxygenMethodDocumenter)
588 app.add_autodocumenter(DoxygenVariableDocumenter)
589 app.add_config_value("doxygen_xml", "", True)
591 # app.add_directive('autodoxysummary', DoxygenAutosummary)
592 # app.add_directive('autodoxyenum', DoxygenAutoEnum)
594 return {'version': sphinx.__display_version__, 'parallel_read_safe': True}