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