3 # QEMU qapidoc QAPI file parsing extension
5 # Copyright (c) 2020 Linaro
7 # This work is licensed under the terms of the GNU GPLv2 or later.
8 # See the COPYING file in the top-level directory.
11 qapidoc is a Sphinx extension that implements the qapi-doc directive
13 The purpose of this extension is to read the documentation comments
14 in QAPI schema files, and insert them all into the current document.
16 It implements one new rST directive, "qapi-doc::".
17 Each qapi-doc:: directive takes one argument, which is the
18 pathname of the schema file to process, relative to the source tree.
20 The docs/conf.py file must set the qapidoc_srctree config value to
21 the root of the QEMU source tree.
23 The Sphinx documentation on writing extensions is at:
24 https://www.sphinx-doc.org/en/master/development/index.html
31 from docutils
import nodes
32 from docutils
.parsers
.rst
import Directive
, directives
33 from docutils
.statemachine
import ViewList
34 from qapi
.error
import QAPIError
, QAPISemError
35 from qapi
.gen
import QAPISchemaVisitor
36 from qapi
.schema
import QAPISchema
39 from sphinx
.errors
import ExtensionError
40 from sphinx
.util
.nodes
import nested_parse_with_titles
43 # Sphinx up to 1.6 uses AutodocReporter; 1.7 and later
44 # use switch_source_input. Check borrowed from kerneldoc.py.
45 USE_SSI
= sphinx
.__version
__[:3] >= "1.7"
47 from sphinx
.util
.docutils
import switch_source_input
49 from sphinx
.ext
.autodoc
import ( # pylint: disable=no-name-in-module
57 def dedent(text
: str) -> str:
58 # Adjust indentation to make description text parse as paragraph.
60 lines
= text
.splitlines(True)
61 if re
.match(r
"\s+", lines
[0]):
62 # First line is indented; description started on the line after
63 # the name. dedent the whole block.
64 return textwrap
.dedent(text
)
66 # Descr started on same line. Dedent line 2+.
67 return lines
[0] + textwrap
.dedent("".join(lines
[1:]))
70 # Disable black auto-formatter until re-enabled:
74 class QAPISchemaGenRSTVisitor(QAPISchemaVisitor
):
75 """A QAPI schema visitor which generates docutils/Sphinx nodes
77 This class builds up a tree of docutils/Sphinx nodes corresponding
78 to documentation for the various QAPI objects. To use it, first
79 create a QAPISchemaGenRSTVisitor object, and call its
80 visit_begin() method. Then you can call one of the two methods
81 'freeform' (to add documentation for a freeform documentation
82 chunk) or 'symbol' (to add documentation for a QAPI symbol). These
83 will cause the visitor to build up the tree of document
84 nodes. Once you've added all the documentation via 'freeform' and
85 'symbol' method calls, you can call 'get_document_nodes' to get
86 the final list of document nodes (in a form suitable for returning
87 from a Sphinx directive's 'run' method).
89 def __init__(self
, sphinx_directive
):
91 self
._sphinx
_directive
= sphinx_directive
92 self
._top
_node
= nodes
.section()
93 self
._active
_headings
= [self
._top
_node
]
95 def _make_dlitem(self
, term
, defn
):
96 """Return a dlitem node with the specified term and definition.
98 term should be a list of Text and literal nodes.
99 defn should be one of:
100 - a string, which will be handed to _parse_text_into_node
101 - a list of Text and literal nodes, which will be put into
104 dlitem
= nodes
.definition_list_item()
105 dlterm
= nodes
.term('', '', *term
)
108 dldef
= nodes
.definition()
109 if isinstance(defn
, list):
110 dldef
+= nodes
.paragraph('', '', *defn
)
112 self
._parse
_text
_into
_node
(defn
, dldef
)
116 def _make_section(self
, title
):
117 """Return a section node with optional title"""
118 section
= nodes
.section(ids
=[self
._sphinx
_directive
.new_serialno()])
120 section
+= nodes
.title(title
, title
)
123 def _nodes_for_ifcond(self
, ifcond
, with_if
=True):
124 """Return list of Text, literal nodes for the ifcond
126 Return a list which gives text like ' (If: condition)'.
127 If with_if is False, we don't return the "(If: " and ")".
130 doc
= ifcond
.docgen()
133 doc
= nodes
.literal('', doc
)
137 nodelist
= [nodes
.Text(' ('), nodes
.strong('', 'If: ')]
139 nodelist
.append(nodes
.Text(')'))
142 def _nodes_for_one_member(self
, member
):
143 """Return list of Text, literal nodes for this member
145 Return a list of doctree nodes which give text like
146 'name: type (optional) (If: ...)' suitable for use as the
147 'term' part of a definition list item.
149 term
= [nodes
.literal('', member
.name
)]
150 if member
.type.doc_type():
151 term
.append(nodes
.Text(': '))
152 term
.append(nodes
.literal('', member
.type.doc_type()))
154 term
.append(nodes
.Text(' (optional)'))
155 if member
.ifcond
.is_present():
156 term
.extend(self
._nodes
_for
_ifcond
(member
.ifcond
))
159 def _nodes_for_variant_when(self
, branches
, variant
):
160 """Return list of Text, literal nodes for variant 'when' clause
162 Return a list of doctree nodes which give text like
163 'when tagname is variant (If: ...)' suitable for use in
164 the 'branches' part of a definition list.
166 term
= [nodes
.Text(' when '),
167 nodes
.literal('', branches
.tag_member
.name
),
169 nodes
.literal('', '"%s"' % variant
.name
)]
170 if variant
.ifcond
.is_present():
171 term
.extend(self
._nodes
_for
_ifcond
(variant
.ifcond
))
174 def _nodes_for_members(self
, doc
, what
, base
=None, branches
=None):
175 """Return list of doctree nodes for the table of members"""
176 dlnode
= nodes
.definition_list()
177 for section
in doc
.args
.values():
178 term
= self
._nodes
_for
_one
_member
(section
.member
)
179 # TODO drop fallbacks when undocumented members are outlawed
181 defn
= dedent(section
.text
)
183 defn
= [nodes
.Text('Not documented')]
185 dlnode
+= self
._make
_dlitem
(term
, defn
)
188 dlnode
+= self
._make
_dlitem
([nodes
.Text('The members of '),
189 nodes
.literal('', base
.doc_type())],
193 for v
in branches
.variants
:
194 if v
.type.name
== 'q_empty':
196 assert not v
.type.is_implicit()
197 term
= [nodes
.Text('The members of '),
198 nodes
.literal('', v
.type.doc_type())]
199 term
.extend(self
._nodes
_for
_variant
_when
(branches
, v
))
200 dlnode
+= self
._make
_dlitem
(term
, None)
202 if not dlnode
.children
:
205 section
= self
._make
_section
(what
)
209 def _nodes_for_enum_values(self
, doc
):
210 """Return list of doctree nodes for the table of enum values"""
212 dlnode
= nodes
.definition_list()
213 for section
in doc
.args
.values():
214 termtext
= [nodes
.literal('', section
.member
.name
)]
215 if section
.member
.ifcond
.is_present():
216 termtext
.extend(self
._nodes
_for
_ifcond
(section
.member
.ifcond
))
217 # TODO drop fallbacks when undocumented members are outlawed
219 defn
= dedent(section
.text
)
221 defn
= [nodes
.Text('Not documented')]
223 dlnode
+= self
._make
_dlitem
(termtext
, defn
)
229 section
= self
._make
_section
('Values')
233 def _nodes_for_arguments(self
, doc
, arg_type
):
234 """Return list of doctree nodes for the arguments section"""
235 if arg_type
and not arg_type
.is_implicit():
237 section
= self
._make
_section
('Arguments')
238 dlnode
= nodes
.definition_list()
239 dlnode
+= self
._make
_dlitem
(
240 [nodes
.Text('The members of '),
241 nodes
.literal('', arg_type
.name
)],
246 return self
._nodes
_for
_members
(doc
, 'Arguments')
248 def _nodes_for_features(self
, doc
):
249 """Return list of doctree nodes for the table of features"""
251 dlnode
= nodes
.definition_list()
252 for section
in doc
.features
.values():
253 dlnode
+= self
._make
_dlitem
(
254 [nodes
.literal('', section
.member
.name
)], dedent(section
.text
))
260 section
= self
._make
_section
('Features')
264 def _nodes_for_example(self
, exampletext
):
265 """Return list of doctree nodes for a code example snippet"""
266 return [nodes
.literal_block(exampletext
, exampletext
)]
268 def _nodes_for_sections(self
, doc
):
269 """Return list of doctree nodes for additional sections"""
271 for section
in doc
.sections
:
272 if section
.tag
and section
.tag
== 'TODO':
273 # Hide TODO: sections
277 # Sphinx cannot handle sectionless titles;
278 # Instead, just append the results to the prior section.
279 container
= nodes
.container()
280 self
._parse
_text
_into
_node
(section
.text
, container
)
281 nodelist
+= container
.children
284 snode
= self
._make
_section
(section
.tag
)
285 if section
.tag
.startswith('Example'):
286 snode
+= self
._nodes
_for
_example
(dedent(section
.text
))
288 self
._parse
_text
_into
_node
(dedent(section
.text
), snode
)
289 nodelist
.append(snode
)
292 def _nodes_for_if_section(self
, ifcond
):
293 """Return list of doctree nodes for the "If" section"""
295 if ifcond
.is_present():
296 snode
= self
._make
_section
('If')
297 snode
+= nodes
.paragraph(
298 '', '', *self
._nodes
_for
_ifcond
(ifcond
, with_if
=False)
300 nodelist
.append(snode
)
303 def _add_doc(self
, typ
, sections
):
304 """Add documentation for a command/object/enum...
306 We assume we're documenting the thing defined in self._cur_doc.
307 typ is the type of thing being added ("Command", "Object", etc)
309 sections is a list of nodes for sections to add to the definition.
313 snode
= nodes
.section(ids
=[self
._sphinx
_directive
.new_serialno()])
314 snode
+= nodes
.title('', '', *[nodes
.literal(doc
.symbol
, doc
.symbol
),
315 nodes
.Text(' (' + typ
+ ')')])
316 self
._parse
_text
_into
_node
(doc
.body
.text
, snode
)
320 self
._add
_node
_to
_current
_heading
(snode
)
322 def visit_enum_type(self
, name
, info
, ifcond
, features
, members
, prefix
):
324 self
._add
_doc
('Enum',
325 self
._nodes
_for
_enum
_values
(doc
)
326 + self
._nodes
_for
_features
(doc
)
327 + self
._nodes
_for
_sections
(doc
)
328 + self
._nodes
_for
_if
_section
(ifcond
))
330 def visit_object_type(self
, name
, info
, ifcond
, features
,
331 base
, members
, branches
):
333 if base
and base
.is_implicit():
335 self
._add
_doc
('Object',
336 self
._nodes
_for
_members
(doc
, 'Members', base
, branches
)
337 + self
._nodes
_for
_features
(doc
)
338 + self
._nodes
_for
_sections
(doc
)
339 + self
._nodes
_for
_if
_section
(ifcond
))
341 def visit_alternate_type(self
, name
, info
, ifcond
, features
,
344 self
._add
_doc
('Alternate',
345 self
._nodes
_for
_members
(doc
, 'Members')
346 + self
._nodes
_for
_features
(doc
)
347 + self
._nodes
_for
_sections
(doc
)
348 + self
._nodes
_for
_if
_section
(ifcond
))
350 def visit_command(self
, name
, info
, ifcond
, features
, arg_type
,
351 ret_type
, gen
, success_response
, boxed
, allow_oob
,
352 allow_preconfig
, coroutine
):
354 self
._add
_doc
('Command',
355 self
._nodes
_for
_arguments
(doc
, arg_type
)
356 + self
._nodes
_for
_features
(doc
)
357 + self
._nodes
_for
_sections
(doc
)
358 + self
._nodes
_for
_if
_section
(ifcond
))
360 def visit_event(self
, name
, info
, ifcond
, features
, arg_type
, boxed
):
362 self
._add
_doc
('Event',
363 self
._nodes
_for
_arguments
(doc
, arg_type
)
364 + self
._nodes
_for
_features
(doc
)
365 + self
._nodes
_for
_sections
(doc
)
366 + self
._nodes
_for
_if
_section
(ifcond
))
368 def symbol(self
, doc
, entity
):
369 """Add documentation for one symbol to the document tree
371 This is the main entry point which causes us to add documentation
372 nodes for a symbol (which could be a 'command', 'object', 'event',
373 etc). We do this by calling 'visit' on the schema entity, which
374 will then call back into one of our visit_* methods, depending
375 on what kind of thing this symbol is.
381 def _start_new_heading(self
, heading
, level
):
382 """Start a new heading at the specified heading level
384 Create a new section whose title is 'heading' and which is placed
385 in the docutils node tree as a child of the most recent level-1
386 heading. Subsequent document sections (commands, freeform doc chunks,
387 etc) will be placed as children of this new heading section.
389 if len(self
._active
_headings
) < level
:
390 raise QAPISemError(self
._cur
_doc
.info
,
391 'Level %d subheading found outside a '
393 % (level
, level
- 1))
394 snode
= self
._make
_section
(heading
)
395 self
._active
_headings
[level
- 1] += snode
396 self
._active
_headings
= self
._active
_headings
[:level
]
397 self
._active
_headings
.append(snode
)
399 def _add_node_to_current_heading(self
, node
):
400 """Add the node to whatever the current active heading is"""
401 self
._active
_headings
[-1] += node
403 def freeform(self
, doc
):
404 """Add a piece of 'freeform' documentation to the document tree
406 A 'freeform' document chunk doesn't relate to any particular
407 symbol (for instance, it could be an introduction).
409 If the freeform document starts with a line of the form
410 '= Heading text', this is a section or subsection heading, with
411 the heading level indicated by the number of '=' signs.
414 # QAPIDoc documentation says free-form documentation blocks
415 # must have only a body section, nothing else.
416 assert not doc
.sections
418 assert not doc
.features
422 if re
.match(r
'=+ ', text
):
423 # Section/subsection heading (if present, will always be
424 # the first line of the block)
425 (heading
, _
, text
) = text
.partition('\n')
426 (leader
, _
, heading
) = heading
.partition(' ')
427 self
._start
_new
_heading
(heading
, len(leader
))
431 node
= self
._make
_section
(None)
432 self
._parse
_text
_into
_node
(text
, node
)
433 self
._add
_node
_to
_current
_heading
(node
)
436 def _parse_text_into_node(self
, doctext
, node
):
437 """Parse a chunk of QAPI-doc-format text into the node
439 The doc comment can contain most inline rST markup, including
440 bulleted and enumerated lists.
441 As an extra permitted piece of markup, @var will be turned
445 # Handle the "@var means ``var`` case
446 doctext
= re
.sub(r
'@([\w-]+)', r
'``\1``', doctext
)
449 for line
in doctext
.splitlines():
450 # The reported line number will always be that of the start line
451 # of the doc comment, rather than the actual location of the error.
452 # Being more precise would require overhaul of the QAPIDoc class
453 # to track lines more exactly within all the sub-parts of the doc
454 # comment, as well as counting lines here.
455 rstlist
.append(line
, self
._cur
_doc
.info
.fname
,
456 self
._cur
_doc
.info
.line
)
457 # Append a blank line -- in some cases rST syntax errors get
458 # attributed to the line after one with actual text, and if there
459 # isn't anything in the ViewList corresponding to that then Sphinx
460 # 1.6's AutodocReporter will then misidentify the source/line location
461 # in the error message (usually attributing it to the top-level
462 # .rst file rather than the offending .json file). The extra blank
463 # line won't affect the rendered output.
464 rstlist
.append("", self
._cur
_doc
.info
.fname
, self
._cur
_doc
.info
.line
)
465 self
._sphinx
_directive
.do_parse(rstlist
, node
)
467 def get_document_nodes(self
):
468 """Return the list of docutils nodes which make up the document"""
469 return self
._top
_node
.children
472 # Turn the black formatter on for the rest of the file.
476 class QAPISchemaGenDepVisitor(QAPISchemaVisitor
):
477 """A QAPI schema visitor which adds Sphinx dependencies each module
479 This class calls the Sphinx note_dependency() function to tell Sphinx
480 that the generated documentation output depends on the input
481 schema file associated with each module in the QAPI input.
484 def __init__(self
, env
, qapidir
):
486 self
._qapidir
= qapidir
488 def visit_module(self
, name
):
489 if name
!= "./builtin":
490 qapifile
= self
._qapidir
+ "/" + name
491 self
._env
.note_dependency(os
.path
.abspath(qapifile
))
492 super().visit_module(name
)
495 class QAPIDocDirective(Directive
):
496 """Extract documentation from the specified QAPI .json file"""
498 required_argument
= 1
499 optional_arguments
= 1
500 option_spec
= {"qapifile": directives
.unchanged_required
}
503 def new_serialno(self
):
504 """Return a unique new ID string suitable for use as a node's ID"""
505 env
= self
.state
.document
.settings
.env
506 return "qapidoc-%d" % env
.new_serialno("qapidoc")
509 env
= self
.state
.document
.settings
.env
510 qapifile
= env
.config
.qapidoc_srctree
+ "/" + self
.arguments
[0]
511 qapidir
= os
.path
.dirname(qapifile
)
514 schema
= QAPISchema(qapifile
)
516 # First tell Sphinx about all the schema files that the
517 # output documentation depends on (including 'qapifile' itself)
518 schema
.visit(QAPISchemaGenDepVisitor(env
, qapidir
))
520 vis
= QAPISchemaGenRSTVisitor(self
)
521 vis
.visit_begin(schema
)
522 for doc
in schema
.docs
:
524 vis
.symbol(doc
, schema
.lookup_entity(doc
.symbol
))
527 return vis
.get_document_nodes()
528 except QAPIError
as err
:
529 # Launder QAPI parse errors into Sphinx extension errors
530 # so they are displayed nicely to the user
531 raise ExtensionError(str(err
)) from err
533 def do_parse(self
, rstlist
, node
):
534 """Parse rST source lines and add them to the specified node
536 Take the list of rST source lines rstlist, parse them as
537 rST, and add the resulting docutils nodes as children of node.
538 The nodes are parsed in a way that allows them to include
539 subheadings (titles) without confusing the rendering of
542 # This is from kerneldoc.py -- it works around an API change in
543 # Sphinx between 1.6 and 1.7. Unlike kerneldoc.py, we use
544 # sphinx.util.nodes.nested_parse_with_titles() rather than the
545 # plain self.state.nested_parse(), and so we can drop the saving
546 # of title_styles and section_level that kerneldoc.py does,
547 # because nested_parse_with_titles() does that for us.
549 with
switch_source_input(self
.state
, rstlist
):
550 nested_parse_with_titles(self
.state
, rstlist
, node
)
552 save
= self
.state
.memo
.reporter
553 self
.state
.memo
.reporter
= AutodocReporter(
554 rstlist
, self
.state
.memo
.reporter
557 nested_parse_with_titles(self
.state
, rstlist
, node
)
559 self
.state
.memo
.reporter
= save
563 """Register qapi-doc directive with Sphinx"""
564 app
.add_config_value("qapidoc_srctree", None, "env")
565 app
.add_directive("qapi-doc", QAPIDocDirective
)
568 "version": __version__
,
569 "parallel_read_safe": True,
570 "parallel_write_safe": True,