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