xref: /openbmc/qemu/docs/sphinx/qapidoc.py (revision 69430111)
1# coding=utf-8
2#
3# QEMU qapidoc QAPI file parsing extension
4#
5# Copyright (c) 2020 Linaro
6#
7# This work is licensed under the terms of the GNU GPLv2 or later.
8# See the COPYING file in the top-level directory.
9
10"""
11qapidoc is a Sphinx extension that implements the qapi-doc directive
12
13The purpose of this extension is to read the documentation comments
14in QAPI schema files, and insert them all into the current document.
15
16It implements one new rST directive, "qapi-doc::".
17Each qapi-doc:: directive takes one argument, which is the
18pathname of the schema file to process, relative to the source tree.
19
20The docs/conf.py file must set the qapidoc_srctree config value to
21the root of the QEMU source tree.
22
23The Sphinx documentation on writing extensions is at:
24https://www.sphinx-doc.org/en/master/development/index.html
25"""
26
27import os
28import re
29
30from docutils import nodes
31from docutils.statemachine import ViewList
32from docutils.parsers.rst import directives, Directive
33from sphinx.errors import ExtensionError
34from sphinx.util.nodes import nested_parse_with_titles
35import sphinx
36from qapi.gen import QAPISchemaVisitor
37from qapi.schema import QAPIError, QAPISemError, QAPISchema
38
39
40# Sphinx up to 1.6 uses AutodocReporter; 1.7 and later
41# use switch_source_input. Check borrowed from kerneldoc.py.
42Use_SSI = sphinx.__version__[:3] >= '1.7'
43if Use_SSI:
44    from sphinx.util.docutils import switch_source_input
45else:
46    from sphinx.ext.autodoc import AutodocReporter
47
48
49__version__ = '1.0'
50
51
52# Function borrowed from pydash, which is under the MIT license
53def intersperse(iterable, separator):
54    """Yield the members of *iterable* interspersed with *separator*."""
55    iterable = iter(iterable)
56    yield next(iterable)
57    for item in iterable:
58        yield separator
59        yield item
60
61
62class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
63    """A QAPI schema visitor which generates docutils/Sphinx nodes
64
65    This class builds up a tree of docutils/Sphinx nodes corresponding
66    to documentation for the various QAPI objects. To use it, first
67    create a QAPISchemaGenRSTVisitor object, and call its
68    visit_begin() method.  Then you can call one of the two methods
69    'freeform' (to add documentation for a freeform documentation
70    chunk) or 'symbol' (to add documentation for a QAPI symbol). These
71    will cause the visitor to build up the tree of document
72    nodes. Once you've added all the documentation via 'freeform' and
73    'symbol' method calls, you can call 'get_document_nodes' to get
74    the final list of document nodes (in a form suitable for returning
75    from a Sphinx directive's 'run' method).
76    """
77    def __init__(self, sphinx_directive):
78        self._cur_doc = None
79        self._sphinx_directive = sphinx_directive
80        self._top_node = nodes.section()
81        self._active_headings = [self._top_node]
82
83    def _make_dlitem(self, term, defn):
84        """Return a dlitem node with the specified term and definition.
85
86        term should be a list of Text and literal nodes.
87        defn should be one of:
88        - a string, which will be handed to _parse_text_into_node
89        - a list of Text and literal nodes, which will be put into
90          a paragraph node
91        """
92        dlitem = nodes.definition_list_item()
93        dlterm = nodes.term('', '', *term)
94        dlitem += dlterm
95        if defn:
96            dldef = nodes.definition()
97            if isinstance(defn, list):
98                dldef += nodes.paragraph('', '', *defn)
99            else:
100                self._parse_text_into_node(defn, dldef)
101            dlitem += dldef
102        return dlitem
103
104    def _make_section(self, title):
105        """Return a section node with optional title"""
106        section = nodes.section(ids=[self._sphinx_directive.new_serialno()])
107        if title:
108            section += nodes.title(title, title)
109        return section
110
111    def _nodes_for_ifcond(self, ifcond, with_if=True):
112        """Return list of Text, literal nodes for the ifcond
113
114        Return a list which gives text like ' (If: cond1, cond2, cond3)', where
115        the conditions are in literal-text and the commas are not.
116        If with_if is False, we don't return the "(If: " and ")".
117        """
118        condlist = intersperse([nodes.literal('', c) for c in ifcond],
119                               nodes.Text(', '))
120        if not with_if:
121            return condlist
122
123        nodelist = [nodes.Text(' ('), nodes.strong('', 'If: ')]
124        nodelist.extend(condlist)
125        nodelist.append(nodes.Text(')'))
126        return nodelist
127
128    def _nodes_for_one_member(self, member):
129        """Return list of Text, literal nodes for this member
130
131        Return a list of doctree nodes which give text like
132        'name: type (optional) (If: ...)' suitable for use as the
133        'term' part of a definition list item.
134        """
135        term = [nodes.literal('', member.name)]
136        if member.type.doc_type():
137            term.append(nodes.Text(': '))
138            term.append(nodes.literal('', member.type.doc_type()))
139        if member.optional:
140            term.append(nodes.Text(' (optional)'))
141        if member.ifcond:
142            term.extend(self._nodes_for_ifcond(member.ifcond))
143        return term
144
145    def _nodes_for_variant_when(self, variants, variant):
146        """Return list of Text, literal nodes for variant 'when' clause
147
148        Return a list of doctree nodes which give text like
149        'when tagname is variant (If: ...)' suitable for use in
150        the 'variants' part of a definition list.
151        """
152        term = [nodes.Text(' when '),
153                nodes.literal('', variants.tag_member.name),
154                nodes.Text(' is '),
155                nodes.literal('', '"%s"' % variant.name)]
156        if variant.ifcond:
157            term.extend(self._nodes_for_ifcond(variant.ifcond))
158        return term
159
160    def _nodes_for_members(self, doc, what, base=None, variants=None):
161        """Return list of doctree nodes for the table of members"""
162        dlnode = nodes.definition_list()
163        for section in doc.args.values():
164            term = self._nodes_for_one_member(section.member)
165            # TODO drop fallbacks when undocumented members are outlawed
166            if section.text:
167                defn = section.text
168            elif (variants and variants.tag_member == section.member
169                  and not section.member.type.doc_type()):
170                values = section.member.type.member_names()
171                defn = [nodes.Text('One of ')]
172                defn.extend(intersperse([nodes.literal('', v) for v in values],
173                                        nodes.Text(', ')))
174            else:
175                defn = [nodes.Text('Not documented')]
176
177            dlnode += self._make_dlitem(term, defn)
178
179        if base:
180            dlnode += self._make_dlitem([nodes.Text('The members of '),
181                                         nodes.literal('', base.doc_type())],
182                                        None)
183
184        if variants:
185            for v in variants.variants:
186                if v.type.is_implicit():
187                    assert not v.type.base and not v.type.variants
188                    for m in v.type.local_members:
189                        term = self._nodes_for_one_member(m)
190                        term.extend(self._nodes_for_variant_when(variants, v))
191                        dlnode += self._make_dlitem(term, None)
192                else:
193                    term = [nodes.Text('The members of '),
194                            nodes.literal('', v.type.doc_type())]
195                    term.extend(self._nodes_for_variant_when(variants, v))
196                    dlnode += self._make_dlitem(term, None)
197
198        if not dlnode.children:
199            return []
200
201        section = self._make_section(what)
202        section += dlnode
203        return [section]
204
205    def _nodes_for_enum_values(self, doc):
206        """Return list of doctree nodes for the table of enum values"""
207        seen_item = False
208        dlnode = nodes.definition_list()
209        for section in doc.args.values():
210            termtext = [nodes.literal('', section.member.name)]
211            if section.member.ifcond:
212                termtext.extend(self._nodes_for_ifcond(section.member.ifcond))
213            # TODO drop fallbacks when undocumented members are outlawed
214            if section.text:
215                defn = section.text
216            else:
217                defn = [nodes.Text('Not documented')]
218
219            dlnode += self._make_dlitem(termtext, defn)
220            seen_item = True
221
222        if not seen_item:
223            return []
224
225        section = self._make_section('Values')
226        section += dlnode
227        return [section]
228
229    def _nodes_for_arguments(self, doc, boxed_arg_type):
230        """Return list of doctree nodes for the arguments section"""
231        if boxed_arg_type:
232            assert not doc.args
233            section = self._make_section('Arguments')
234            dlnode = nodes.definition_list()
235            dlnode += self._make_dlitem(
236                [nodes.Text('The members of '),
237                 nodes.literal('', boxed_arg_type.name)],
238                None)
239            section += dlnode
240            return [section]
241
242        return self._nodes_for_members(doc, 'Arguments')
243
244    def _nodes_for_features(self, doc):
245        """Return list of doctree nodes for the table of features"""
246        seen_item = False
247        dlnode = nodes.definition_list()
248        for section in doc.features.values():
249            dlnode += self._make_dlitem([nodes.literal('', section.name)],
250                                        section.text)
251            seen_item = True
252
253        if not seen_item:
254            return []
255
256        section = self._make_section('Features')
257        section += dlnode
258        return [section]
259
260    def _nodes_for_example(self, exampletext):
261        """Return list of doctree nodes for a code example snippet"""
262        return [nodes.literal_block(exampletext, exampletext)]
263
264    def _nodes_for_sections(self, doc):
265        """Return list of doctree nodes for additional sections"""
266        nodelist = []
267        for section in doc.sections:
268            snode = self._make_section(section.name)
269            if section.name and section.name.startswith('Example'):
270                snode += self._nodes_for_example(section.text)
271            else:
272                self._parse_text_into_node(section.text, snode)
273            nodelist.append(snode)
274        return nodelist
275
276    def _nodes_for_if_section(self, ifcond):
277        """Return list of doctree nodes for the "If" section"""
278        nodelist = []
279        if ifcond:
280            snode = self._make_section('If')
281            snode += self._nodes_for_ifcond(ifcond, with_if=False)
282            nodelist.append(snode)
283        return nodelist
284
285    def _add_doc(self, typ, sections):
286        """Add documentation for a command/object/enum...
287
288        We assume we're documenting the thing defined in self._cur_doc.
289        typ is the type of thing being added ("Command", "Object", etc)
290
291        sections is a list of nodes for sections to add to the definition.
292        """
293
294        doc = self._cur_doc
295        snode = nodes.section(ids=[self._sphinx_directive.new_serialno()])
296        snode += nodes.title('', '', *[nodes.literal(doc.symbol, doc.symbol),
297                                       nodes.Text(' (' + typ + ')')])
298        self._parse_text_into_node(doc.body.text, snode)
299        for s in sections:
300            if s is not None:
301                snode += s
302        self._add_node_to_current_heading(snode)
303
304    def visit_enum_type(self, name, info, ifcond, features, members, prefix):
305        doc = self._cur_doc
306        self._add_doc('Enum',
307                      self._nodes_for_enum_values(doc)
308                      + self._nodes_for_features(doc)
309                      + self._nodes_for_sections(doc)
310                      + self._nodes_for_if_section(ifcond))
311
312    def visit_object_type(self, name, info, ifcond, features,
313                          base, members, variants):
314        doc = self._cur_doc
315        if base and base.is_implicit():
316            base = None
317        self._add_doc('Object',
318                      self._nodes_for_members(doc, 'Members', base, variants)
319                      + self._nodes_for_features(doc)
320                      + self._nodes_for_sections(doc)
321                      + self._nodes_for_if_section(ifcond))
322
323    def visit_alternate_type(self, name, info, ifcond, features, variants):
324        doc = self._cur_doc
325        self._add_doc('Alternate',
326                      self._nodes_for_members(doc, 'Members')
327                      + self._nodes_for_features(doc)
328                      + self._nodes_for_sections(doc)
329                      + self._nodes_for_if_section(ifcond))
330
331    def visit_command(self, name, info, ifcond, features, arg_type,
332                      ret_type, gen, success_response, boxed, allow_oob,
333                      allow_preconfig, coroutine):
334        doc = self._cur_doc
335        self._add_doc('Command',
336                      self._nodes_for_arguments(doc,
337                                                arg_type if boxed else None)
338                      + self._nodes_for_features(doc)
339                      + self._nodes_for_sections(doc)
340                      + self._nodes_for_if_section(ifcond))
341
342    def visit_event(self, name, info, ifcond, features, arg_type, boxed):
343        doc = self._cur_doc
344        self._add_doc('Event',
345                      self._nodes_for_arguments(doc,
346                                                arg_type if boxed else None)
347                      + self._nodes_for_features(doc)
348                      + self._nodes_for_sections(doc)
349                      + self._nodes_for_if_section(ifcond))
350
351    def symbol(self, doc, entity):
352        """Add documentation for one symbol to the document tree
353
354        This is the main entry point which causes us to add documentation
355        nodes for a symbol (which could be a 'command', 'object', 'event',
356        etc). We do this by calling 'visit' on the schema entity, which
357        will then call back into one of our visit_* methods, depending
358        on what kind of thing this symbol is.
359        """
360        self._cur_doc = doc
361        entity.visit(self)
362        self._cur_doc = None
363
364    def _start_new_heading(self, heading, level):
365        """Start a new heading at the specified heading level
366
367        Create a new section whose title is 'heading' and which is placed
368        in the docutils node tree as a child of the most recent level-1
369        heading. Subsequent document sections (commands, freeform doc chunks,
370        etc) will be placed as children of this new heading section.
371        """
372        if len(self._active_headings) < level:
373            raise QAPISemError(self._cur_doc.info,
374                               'Level %d subheading found outside a '
375                               'level %d heading'
376                               % (level, level - 1))
377        snode = self._make_section(heading)
378        self._active_headings[level - 1] += snode
379        self._active_headings = self._active_headings[:level]
380        self._active_headings.append(snode)
381
382    def _add_node_to_current_heading(self, node):
383        """Add the node to whatever the current active heading is"""
384        self._active_headings[-1] += node
385
386    def freeform(self, doc):
387        """Add a piece of 'freeform' documentation to the document tree
388
389        A 'freeform' document chunk doesn't relate to any particular
390        symbol (for instance, it could be an introduction).
391
392        If the freeform document starts with a line of the form
393        '= Heading text', this is a section or subsection heading, with
394        the heading level indicated by the number of '=' signs.
395        """
396
397        # QAPIDoc documentation says free-form documentation blocks
398        # must have only a body section, nothing else.
399        assert not doc.sections
400        assert not doc.args
401        assert not doc.features
402        self._cur_doc = doc
403
404        text = doc.body.text
405        if re.match(r'=+ ', text):
406            # Section/subsection heading (if present, will always be
407            # the first line of the block)
408            (heading, _, text) = text.partition('\n')
409            (leader, _, heading) = heading.partition(' ')
410            self._start_new_heading(heading, len(leader))
411            if text == '':
412                return
413
414        node = self._make_section(None)
415        self._parse_text_into_node(text, node)
416        self._add_node_to_current_heading(node)
417        self._cur_doc = None
418
419    def _parse_text_into_node(self, doctext, node):
420        """Parse a chunk of QAPI-doc-format text into the node
421
422        The doc comment can contain most inline rST markup, including
423        bulleted and enumerated lists.
424        As an extra permitted piece of markup, @var will be turned
425        into ``var``.
426        """
427
428        # Handle the "@var means ``var`` case
429        doctext = re.sub(r'@([\w-]+)', r'``\1``', doctext)
430
431        rstlist = ViewList()
432        for line in doctext.splitlines():
433            # The reported line number will always be that of the start line
434            # of the doc comment, rather than the actual location of the error.
435            # Being more precise would require overhaul of the QAPIDoc class
436            # to track lines more exactly within all the sub-parts of the doc
437            # comment, as well as counting lines here.
438            rstlist.append(line, self._cur_doc.info.fname,
439                           self._cur_doc.info.line)
440        # Append a blank line -- in some cases rST syntax errors get
441        # attributed to the line after one with actual text, and if there
442        # isn't anything in the ViewList corresponding to that then Sphinx
443        # 1.6's AutodocReporter will then misidentify the source/line location
444        # in the error message (usually attributing it to the top-level
445        # .rst file rather than the offending .json file). The extra blank
446        # line won't affect the rendered output.
447        rstlist.append("", self._cur_doc.info.fname, self._cur_doc.info.line)
448        self._sphinx_directive.do_parse(rstlist, node)
449
450    def get_document_nodes(self):
451        """Return the list of docutils nodes which make up the document"""
452        return self._top_node.children
453
454
455class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
456    """A QAPI schema visitor which adds Sphinx dependencies each module
457
458    This class calls the Sphinx note_dependency() function to tell Sphinx
459    that the generated documentation output depends on the input
460    schema file associated with each module in the QAPI input.
461    """
462    def __init__(self, env, qapidir):
463        self._env = env
464        self._qapidir = qapidir
465
466    def visit_module(self, name):
467        if name is not None:
468            qapifile = self._qapidir + '/' + name
469            self._env.note_dependency(os.path.abspath(qapifile))
470        super().visit_module(name)
471
472
473class QAPIDocDirective(Directive):
474    """Extract documentation from the specified QAPI .json file"""
475    required_argument = 1
476    optional_arguments = 1
477    option_spec = {
478        'qapifile': directives.unchanged_required
479    }
480    has_content = False
481
482    def new_serialno(self):
483        """Return a unique new ID string suitable for use as a node's ID"""
484        env = self.state.document.settings.env
485        return 'qapidoc-%d' % env.new_serialno('qapidoc')
486
487    def run(self):
488        env = self.state.document.settings.env
489        qapifile = env.config.qapidoc_srctree + '/' + self.arguments[0]
490        qapidir = os.path.dirname(qapifile)
491
492        try:
493            schema = QAPISchema(qapifile)
494
495            # First tell Sphinx about all the schema files that the
496            # output documentation depends on (including 'qapifile' itself)
497            schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
498
499            vis = QAPISchemaGenRSTVisitor(self)
500            vis.visit_begin(schema)
501            for doc in schema.docs:
502                if doc.symbol:
503                    vis.symbol(doc, schema.lookup_entity(doc.symbol))
504                else:
505                    vis.freeform(doc)
506            return vis.get_document_nodes()
507        except QAPIError as err:
508            # Launder QAPI parse errors into Sphinx extension errors
509            # so they are displayed nicely to the user
510            raise ExtensionError(str(err))
511
512    def do_parse(self, rstlist, node):
513        """Parse rST source lines and add them to the specified node
514
515        Take the list of rST source lines rstlist, parse them as
516        rST, and add the resulting docutils nodes as children of node.
517        The nodes are parsed in a way that allows them to include
518        subheadings (titles) without confusing the rendering of
519        anything else.
520        """
521        # This is from kerneldoc.py -- it works around an API change in
522        # Sphinx between 1.6 and 1.7. Unlike kerneldoc.py, we use
523        # sphinx.util.nodes.nested_parse_with_titles() rather than the
524        # plain self.state.nested_parse(), and so we can drop the saving
525        # of title_styles and section_level that kerneldoc.py does,
526        # because nested_parse_with_titles() does that for us.
527        if Use_SSI:
528            with switch_source_input(self.state, rstlist):
529                nested_parse_with_titles(self.state, rstlist, node)
530        else:
531            save = self.state.memo.reporter
532            self.state.memo.reporter = AutodocReporter(
533                rstlist, self.state.memo.reporter)
534            try:
535                nested_parse_with_titles(self.state, rstlist, node)
536            finally:
537                self.state.memo.reporter = save
538
539
540def setup(app):
541    """ Register qapi-doc directive with Sphinx"""
542    app.add_config_value('qapidoc_srctree', None, 'env')
543    app.add_directive('qapi-doc', QAPIDocDirective)
544
545    return dict(
546        version=__version__,
547        parallel_read_safe=True,
548        parallel_write_safe=True
549    )
550