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
31 ##########################################################################
33 ##########################################################################
34 def format_xml_paragraph(xmlnode):
35 """Format an Doxygen XML segment (principally a detaileddescription)
36 as a paragraph for inclusion in the rst document
47 return [l.rstrip() for l in _DoxygenXmlParagraphFormatter().generic_visit(xmlnode).lines]
50 class _DoxygenXmlParagraphFormatter(object):
51 # This class follows the model of the stdlib's ast.NodeVisitor for tree traversal
52 # where you dispatch on the element type to a different method for each node
53 # during the traverse.
55 # It's supposed to handle paragraphs, references, preformatted text (code blocks), and lists.
59 self.continue_line = False
61 def visit(self, node):
62 method = 'visit_' + node.tag
63 visitor = getattr(self, method, self.generic_visit)
66 def generic_visit(self, node):
67 for child in node.getchildren():
71 def visit_ref(self, node):
72 ref = get_doxygen_root().findall('.//*[@id="%s"]' % node.get('refid'))
75 if ref.tag == 'memberdef':
76 parent = ref.xpath('./ancestor::compounddef/compoundname')[0].text
77 name = ref.find('./name').text
78 real_name = parent + '::' + name
79 elif ref.tag in ('compounddef', 'enumvalue'):
80 name_node = ref.find('./name')
81 real_name = name_node.text if name_node is not None else ''
83 raise NotImplementedError(ref.tag)
87 val = [':cpp:any:`', node.text]
89 val.extend((' <', real_name, '>`'))
92 if node.tail is not None:
95 self.lines[-1] += ''.join(val)
97 def visit_para(self, node):
98 if node.text is not None:
99 if self.continue_line:
100 self.lines[-1] += node.text
102 self.lines.append(node.text)
103 self.generic_visit(node)
104 self.lines.append('')
105 self.continue_line = False
107 def visit_verbatim(self, node):
108 if node.text is not None:
109 # remove the leading ' *' of any lines
110 lines = [re.sub('^\s*\*','', l) for l in node.text.split('\n')]
111 # Merge each paragraph together
112 text = re.sub("\n\n", "PaRaGrraphSplit", '\n'.join(lines))
113 text = re.sub('\n', '', text)
114 lines = text.split('PaRaGrraphSplit')
116 # merge content to the built doc
117 if self.continue_line:
118 self.lines[-1] += lines[0]
121 self.lines.append('')
123 self.generic_visit(node)
124 self.lines.append('')
125 self.continue_line = False
127 def visit_parametername(self, node):
128 if 'direction' in node.attrib:
129 direction = '[%s] ' % node.get('direction')
133 self.lines.append('**%s** -- %s' % (
134 node.text, direction))
135 self.continue_line = True
137 def visit_parameterlist(self, node):
138 lines = [l for l in type(self)().generic_visit(node).lines if l != '']
139 self.lines.extend([':parameters:', ''] + ['* %s' % l for l in lines] + [''])
141 def visit_simplesect(self, node):
142 if node.get('kind') == 'return':
143 self.lines.append(':returns: ')
144 self.continue_line = True
145 self.generic_visit(node)
147 def visit_listitem(self, node):
148 self.lines.append(' - ')
149 self.continue_line = True
150 self.generic_visit(node)
152 def visit_preformatted(self, node):
153 segment = [node.text if node.text is not None else '']
154 for n in node.getchildren():
155 segment.append(n.text)
156 if n.tail is not None:
157 segment.append(n.tail)
159 lines = ''.join(segment).split('\n')
160 self.lines.extend(('.. code-block:: C++', ''))
161 self.lines.extend([' ' + l for l in lines])
163 def visit_computeroutput(self, node):
164 c = node.find('preformatted')
166 return self.visit_preformatted(c)
167 return self.visit_preformatted(node)
169 def visit_xrefsect(self, node):
170 if node.find('xreftitle').text == 'Deprecated':
171 sublines = type(self)().generic_visit(node).lines
172 self.lines.extend(['.. admonition:: Deprecated'] + [' ' + s for s in sublines])
174 raise ValueError(node)
176 def visit_subscript(self, node):
177 self.lines[-1] += '\ :sub:`%s` %s' % (node.text, node.tail)
180 ##########################################################################
182 ##########################################################################
185 class DoxygenDocumenter(Documenter):
186 # Variables to store the names of the object being documented. modname and fullname are redundant,
187 # and objpath is always the empty list. This is inelegant, but we need to work with the superclass.
189 fullname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
190 modname = None # example: "OpenMM::NonbondedForce" or "OpenMM::NonbondedForce::methodName""
191 objname = None # example: "NonbondedForce" or "methodName"
192 objpath = [] # always the empty list
193 object = None # the xml node for the object
196 'members': members_option,
199 def __init__(self, directive, name, indent=u'', my_id = None):
200 super(DoxygenDocumenter, self).__init__(directive, name, indent)
201 if my_id is not None:
204 def parse_id(self, id_to_parse):
207 def parse_name(self):
208 """Determine what module to import and what attribute to document.
209 Returns True and sets *self.modname*, *self.objname*, *self.fullname*,
210 if parsing and resolving was successful.
212 # To view the context and order in which all of these methods get called,
213 # See, Documenter.generate(). That's the main "entry point" that first
214 # calls parse_name(), follwed by import_object(), format_signature(),
215 # add_directive_header(), and then add_content() (which calls get_doc())
217 # If we were provided a prototype, that must be an overloaded function. Save it.
218 self.argsstring = None
220 (self.name, self.argsstring) = self.name.split('(', 1)
221 self.argsstring = "({}".format(self.argsstring)
223 # methods in the superclass sometimes use '.' to join namespace/class
224 # names with method names, and we don't want that.
225 self.name = self.name.replace('.', '::')
226 self.fullname = self.name
227 self.modname = self.fullname
230 if '::' in self.name:
231 parts = self.name.split('::')
232 self.klassname = parts[-2]
233 self.objname = parts[-1]
235 self.objname = self.name
240 def add_directive_header(self, sig):
241 """Add the directive header and options to the generated content."""
242 domain = getattr(self, 'domain', 'cpp')
243 directive = getattr(self, 'directivetype', self.objtype)
244 name = self.format_name()
245 sourcename = self.get_sourcename()
246 #print('.. %s:%s:: %s%s' % (domain, directive, name, sig))
247 self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
250 def document_members(self, all_members=False):
251 """Generate reST for member documentation.
252 If *all_members* is True, do all members, else those given by
253 *self.options.members*.
255 want_all = all_members or self.options.inherited_members or \
256 self.options.members is ALL
257 # find out which members are documentable
258 members_check_module, members = self.get_object_members(want_all)
260 # remove members given by exclude-members
261 if self.options.exclude_members:
262 members = [(membername, member) for (membername, member) in members
263 if membername not in self.options.exclude_members]
265 # document non-skipped members
266 memberdocumenters = []
267 for (mname, member, isattr) in self.filter_members(members, want_all):
268 if sphinxVersion >= 2:
269 classes = [cls for cls in itervalues(self.env.app.registry.documenters)
270 if cls.can_document_member(member, mname, isattr, self)]
272 classes = [cls for cls in itervalues(AutoDirective._registry)
273 if cls.can_document_member(member, mname, isattr, self)]
275 # don't know how to document this member
278 # prefer the documenter with the highest priority
279 classes.sort(key=lambda cls: cls.priority)
281 documenter = classes[-1](self.directive, mname, indent=self.indent, id=member.get('id'))
282 memberdocumenters.append((documenter, isattr))
284 for documenter, isattr in memberdocumenters:
286 all_members=True, real_modname=self.real_modname,
287 check_module=members_check_module and not isattr)
289 # reset current objects
290 self.env.temp_data['autodoc:module'] = None
291 self.env.temp_data['autodoc:class'] = None
294 class DoxygenClassDocumenter(DoxygenDocumenter):
295 objtype = 'doxyclass'
296 directivetype = 'class'
301 'members': members_option,
305 def can_document_member(cls, member, membername, isattr, parent):
306 # this method is only called from Documenter.document_members
307 # when a higher level documenter (module or namespace) is trying
308 # to choose the appropriate documenter for each of its lower-level
309 # members. Currently not implemented since we don't have a higher-level
310 # doumenter like a DoxygenNamespaceDocumenter.
313 def import_object(self):
314 """Import the object and set it as *self.object*. In the call sequence, this
315 is executed right after parse_name(), so it can use *self.fullname*, *self.objname*,
318 Returns True if successful, False if an error occurred.
320 xpath_query = './/compoundname[text()="%s"]/..' % self.fullname
321 match = get_doxygen_root().xpath(xpath_query)
323 raise ExtensionError('[autodoxy] could not find class (fullname="%s"). I tried '
324 'the following xpath: "%s"' % (self.fullname, xpath_query))
326 self.object = match[0]
329 def format_signature(self):
332 def format_name(self):
335 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
336 detaileddescription = self.object.find('detaileddescription')
337 doc = [format_xml_paragraph(detaileddescription)]
340 def get_object_members(self, want_all):
341 all_members = self.object.xpath('.//sectiondef[@kind="public-func" '
342 'or @kind="public-static-func"]/memberdef[@kind="function"]')
345 return False, ((m.find('name').text, m) for m in all_members)
346 if not self.options.members:
348 return False, ((m.find('name').text, m) for m in all_members if m.find('name').text in self.options.members)
350 def filter_members(self, members, want_all):
352 for (membername, member) in members:
353 ret.append((membername, member, False))
356 def document_members(self, all_members=False):
357 super(DoxygenClassDocumenter, self).document_members(all_members=all_members)
358 # Uncomment to view the generated rst for the class.
359 # print('\n'.join(self.directive.result))
361 autodoxy_requalified_identifiers = []
362 def fix_namespaces(str):
363 for unqualified,fullyqualif in autodoxy_requalified_identifiers:
364 p = re.compile("(^| ){:s}".format(unqualified))
365 str = p.sub(' {:s}'.format(fullyqualif), str)
368 class DoxygenMethodDocumenter(DoxygenDocumenter):
369 objtype = 'doxymethod'
370 directivetype = 'function'
375 def can_document_member(cls, member, membername, isattr, parent):
376 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'function':
380 def parse_id(self, id_to_parse):
381 xp = './/*[@id="%s"]' % id_to_parse
382 match = get_doxygen_root().xpath(xp)
385 self.fullname = match.find('./definition').text.split()[-1]
386 self.modname = self.fullname
387 self.objname = match.find('./name').text
391 def import_object(self):
392 if ET.iselement(self.object):
393 # self.object already set from DoxygenDocumenter.parse_name(),
394 # caused by passing in the `id` of the node instead of just a
395 # classname or method name
398 if '::' in self.fullname:
399 (obj, meth) = self.fullname.rsplit('::', 1)
400 # 'public-func' and 'public-static-func' are for classes while 'func' alone is for namespaces
401 prefix = './/compoundname[text()="{:s}"]/../sectiondef[@kind="public-func" or @kind="public-static-func" or @kind="func"]'.format(obj)
402 obj = "{:s}::".format(obj)
408 xpath_query_noparam = ('{:s}/memberdef[@kind="function"]/name[text()="{:s}"]/..').format(prefix, meth)
410 if self.argsstring != None:
411 xpath_query = ('{:s}/memberdef[@kind="function" and argsstring/text()="{:s}"]/name[text()="{:s}"]/..').format(prefix,self.argsstring,meth)
413 xpath_query = xpath_query_noparam
414 match = get_doxygen_root().xpath(xpath_query)
416 logger = logging.getLogger(__name__)
418 if self.argsstring != None:
419 candidates = get_doxygen_root().xpath(xpath_query_noparam)
420 if len(candidates) == 1:
421 logger.warning("[autodoxy] Using method '{}{}{}' instead of '{}{}{}'. You may want to drop your specification of the signature, or to fix it."
422 .format(obj, meth, candidates[0].find('argsstring').text, obj, meth, self.argsstring))
423 self.object = candidates[0]
425 logger.warning("[autodoxy] WARNING: Could not find method {}{}{}".format(obj, meth, self.argsstring))
427 logger.warning("[autodoxy] WARNING: (no candidate found)")
428 for cand in candidates:
429 logger.warning("[autodoxy] WARNING: Existing candidate: {}{}{}".format(obj, meth, cand.find('argsstring').text))
431 logger.warning("[autodoxy] WARNING: Could not find method {}{} in Doxygen files\nQuery: {}".format(obj, meth, xpath_query))
433 self.object = match[0]
436 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
437 detaileddescription = self.object.find('detaileddescription')
438 doc = [format_xml_paragraph(detaileddescription)]
441 def format_name(self):
443 if el.text is not None:
448 if el.tail is not None:
452 rtype_el = self.object.find('type')
453 rtype_el_ref = rtype_el.find('ref')
454 if rtype_el_ref is not None:
455 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
457 rtype = rtype_el.text
459 # print("rtype: {}".format(rtype))
460 signame = fix_namespaces((rtype and (rtype + ' ') or '') + self.klassname + "::"+ self.objname )
461 # print("signame: '{}'".format(signame))
462 return self.format_template_name() + signame
464 def format_template_name(self):
465 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
468 ret = 'template <%s>' % ','.join(types)
469 # print ("template: {}".format(ret))
472 def format_signature(self):
473 args = fix_namespaces(self.object.find('argsstring').text)
474 # print ("signature: {}".format(args))
477 def document_members(self, all_members=False):
480 class DoxygenVariableDocumenter(DoxygenDocumenter):
482 directivetype = 'var'
487 def can_document_member(cls, member, membername, isattr, parent):
488 if ET.iselement(member) and member.tag == 'memberdef' and member.get('kind') == 'variable':
492 def import_object(self):
493 if ET.iselement(self.object):
494 # self.object already set from DoxygenDocumenter.parse_name(),
495 # caused by passing in the `id` of the node instead of just a
496 # classname or method name
499 (obj, var) = self.fullname.rsplit('::', 1)
501 xpath_query = ('.//compoundname[text()="{:s}"]/../sectiondef[@kind="public-attrib" or @kind="public-static-attrib"]'
502 '/memberdef[@kind="variable"]/name[text()="{:s}"]/..').format(obj, var)
503 # print("fullname {}".format(self.fullname))
504 match = get_doxygen_root().xpath(xpath_query)
506 logger = logging.getLogger(__name__)
508 logger.warning("[autodoxy] WARNING: could not find variable {}::{} in Doxygen files".format(obj, var))
510 self.object = match[0]
513 def parse_id(self, id_to_parse):
514 xp = './/*[@id="%s"]' % id_to_parse
515 match = get_doxygen_root().xpath(xp)
518 self.fullname = match.find('./definition').text.split()[-1]
519 self.modname = self.fullname
520 self.objname = match.find('./name').text
524 def format_name(self):
526 if el.text is not None:
531 if el.tail is not None:
535 rtype_el = self.object.find('type')
536 rtype_el_ref = rtype_el.find('ref')
537 if rtype_el_ref is not None:
538 rtype = text(rtype_el) + text(rtype_el_ref) + tail(rtype_el_ref)
540 rtype = rtype_el.text
542 # print("rtype: {}".format(rtype))
543 signame = (rtype and (rtype + ' ') or '') + self.klassname + "::" + self.objname
544 return fix_namespaces(self.format_template_name() + signame)
546 def get_doc(self, encoding=None): # This method is called with 1 parameter in Sphinx 2.x and 2 parameters in Sphinx 1.x
547 detaileddescription = self.object.find('detaileddescription')
548 doc = [format_xml_paragraph(detaileddescription)]
551 def format_template_name(self):
552 types = [e.text for e in self.object.findall('templateparamlist/param/type')]
555 ret = 'template <%s>' % ','.join(types)
556 # print ("template: {}".format(ret))
559 def document_members(self, all_members=False):
563 ##########################################################################
564 # Setup the extension
565 ##########################################################################
566 def set_doxygen_xml(app):
567 """Load all doxygen XML files from the app config variable
568 `app.config.doxygen_xml` which should be a path to a directory
569 containing doxygen xml output
571 err = ExtensionError(
572 '[autodoxy] No doxygen xml output found in doxygen_xml="%s"' % app.config.doxygen_xml)
574 if not os.path.isdir(app.config.doxygen_xml):
577 files = [os.path.join(app.config.doxygen_xml, f)
578 for f in os.listdir(app.config.doxygen_xml)
579 if f.lower().endswith('.xml') and not f.startswith('._')]
583 setup.DOXYGEN_ROOT = ET.ElementTree(ET.Element('root')).getroot()
584 for current_file in files:
585 root = ET.parse(current_file).getroot()
587 setup.DOXYGEN_ROOT.append(node)
589 if app.config.autodoxy_requalified_identifiers is not None:
590 global autodoxy_requalified_identifiers
591 autodoxy_requalified_identifiers = app.config.autodoxy_requalified_identifiers
593 def get_doxygen_root():
594 """Get the root element of the doxygen XML document.
596 if not hasattr(setup, 'DOXYGEN_ROOT'):
597 setup.DOXYGEN_ROOT = ET.Element("root") # dummy
598 return setup.DOXYGEN_ROOT
602 import sphinx.ext.autosummary
604 app.connect("builder-inited", set_doxygen_xml)
605 # app.connect("builder-inited", process_generate_options)
607 app.setup_extension('sphinx.ext.autodoc')
608 # app.setup_extension('sphinx.ext.autosummary')
610 app.add_autodocumenter(DoxygenClassDocumenter)
611 app.add_autodocumenter(DoxygenMethodDocumenter)
612 app.add_autodocumenter(DoxygenVariableDocumenter)
613 app.add_config_value("doxygen_xml", "", True)
614 app.add_config_value("autodoxy_requalified_identifiers", [], True)
616 # app.add_directive('autodoxysummary', DoxygenAutosummary)
617 # app.add_directive('autodoxyenum', DoxygenAutoEnum)
619 return {'version': sphinx.__display_version__, 'parallel_read_safe': True}