qapidoc.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. qapidoc is a Sphinx extension that implements the qapi-doc directive
  11. The purpose of this extension is to read the documentation comments
  12. in QAPI schema files, and insert them all into the current document.
  13. It implements one new rST directive, "qapi-doc::".
  14. Each qapi-doc:: directive takes one argument, which is the
  15. pathname of the schema file to process, relative to the source tree.
  16. The docs/conf.py file must set the qapidoc_srctree config value to
  17. the root of the QEMU source tree.
  18. The Sphinx documentation on writing extensions is at:
  19. https://www.sphinx-doc.org/en/master/development/index.html
  20. """
  21. from __future__ import annotations
  22. from contextlib import contextmanager
  23. import os
  24. import sys
  25. from typing import TYPE_CHECKING
  26. from docutils import nodes
  27. from docutils.parsers.rst import Directive, directives
  28. from docutils.statemachine import StringList
  29. from qapi.error import QAPIError
  30. from qapi.schema import QAPISchema, QAPISchemaVisitor
  31. from qapi.source import QAPISourceInfo
  32. from qapidoc_legacy import QAPISchemaGenRSTVisitor # type: ignore
  33. from sphinx import addnodes
  34. from sphinx.directives.code import CodeBlock
  35. from sphinx.errors import ExtensionError
  36. from sphinx.util.docutils import switch_source_input
  37. from sphinx.util.nodes import nested_parse_with_titles
  38. if TYPE_CHECKING:
  39. from typing import (
  40. Any,
  41. Generator,
  42. List,
  43. Sequence,
  44. )
  45. from sphinx.application import Sphinx
  46. from sphinx.util.typing import ExtensionMetadata
  47. __version__ = "1.0"
  48. class Transmogrifier:
  49. def __init__(self) -> None:
  50. self._result = StringList()
  51. self.indent = 0
  52. # General-purpose rST generation functions
  53. def get_indent(self) -> str:
  54. return " " * self.indent
  55. @contextmanager
  56. def indented(self) -> Generator[None]:
  57. self.indent += 1
  58. try:
  59. yield
  60. finally:
  61. self.indent -= 1
  62. def add_line_raw(self, line: str, source: str, *lineno: int) -> None:
  63. """Append one line of generated reST to the output."""
  64. # NB: Sphinx uses zero-indexed lines; subtract one.
  65. lineno = tuple((n - 1 for n in lineno))
  66. if line.strip():
  67. # not a blank line
  68. self._result.append(
  69. self.get_indent() + line.rstrip("\n"), source, *lineno
  70. )
  71. else:
  72. self._result.append("", source, *lineno)
  73. def add_line(self, content: str, info: QAPISourceInfo) -> None:
  74. # NB: We *require* an info object; this works out OK because we
  75. # don't document built-in objects that don't have
  76. # one. Everything else should.
  77. self.add_line_raw(content, info.fname, info.line)
  78. def add_lines(
  79. self,
  80. content: str,
  81. info: QAPISourceInfo,
  82. ) -> None:
  83. lines = content.splitlines(True)
  84. for i, line in enumerate(lines):
  85. self.add_line_raw(line, info.fname, info.line + i)
  86. def ensure_blank_line(self) -> None:
  87. # Empty document -- no blank line required.
  88. if not self._result:
  89. return
  90. # Last line isn't blank, add one.
  91. if self._result[-1].strip(): # pylint: disable=no-member
  92. fname, line = self._result.info(-1)
  93. assert isinstance(line, int)
  94. # New blank line is credited to one-after the current last line.
  95. # +2: correct for zero/one index, then increment by one.
  96. self.add_line_raw("", fname, line + 2)
  97. class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
  98. """A QAPI schema visitor which adds Sphinx dependencies each module
  99. This class calls the Sphinx note_dependency() function to tell Sphinx
  100. that the generated documentation output depends on the input
  101. schema file associated with each module in the QAPI input.
  102. """
  103. def __init__(self, env: Any, qapidir: str) -> None:
  104. self._env = env
  105. self._qapidir = qapidir
  106. def visit_module(self, name: str) -> None:
  107. if name != "./builtin":
  108. qapifile = self._qapidir + "/" + name
  109. self._env.note_dependency(os.path.abspath(qapifile))
  110. super().visit_module(name)
  111. class NestedDirective(Directive):
  112. def run(self) -> Sequence[nodes.Node]:
  113. raise NotImplementedError
  114. def do_parse(self, rstlist: StringList, node: nodes.Node) -> None:
  115. """
  116. Parse rST source lines and add them to the specified node
  117. Take the list of rST source lines rstlist, parse them as
  118. rST, and add the resulting docutils nodes as children of node.
  119. The nodes are parsed in a way that allows them to include
  120. subheadings (titles) without confusing the rendering of
  121. anything else.
  122. """
  123. with switch_source_input(self.state, rstlist):
  124. nested_parse_with_titles(self.state, rstlist, node)
  125. class QAPIDocDirective(NestedDirective):
  126. """Extract documentation from the specified QAPI .json file"""
  127. required_argument = 1
  128. optional_arguments = 1
  129. option_spec = {
  130. "qapifile": directives.unchanged_required,
  131. "transmogrify": directives.flag,
  132. }
  133. has_content = False
  134. def new_serialno(self) -> str:
  135. """Return a unique new ID string suitable for use as a node's ID"""
  136. env = self.state.document.settings.env
  137. return "qapidoc-%d" % env.new_serialno("qapidoc")
  138. def transmogrify(self, schema: QAPISchema) -> nodes.Element:
  139. raise NotImplementedError
  140. def legacy(self, schema: QAPISchema) -> nodes.Element:
  141. vis = QAPISchemaGenRSTVisitor(self)
  142. vis.visit_begin(schema)
  143. for doc in schema.docs:
  144. if doc.symbol:
  145. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  146. else:
  147. vis.freeform(doc)
  148. return vis.get_document_node() # type: ignore
  149. def run(self) -> Sequence[nodes.Node]:
  150. env = self.state.document.settings.env
  151. qapifile = env.config.qapidoc_srctree + "/" + self.arguments[0]
  152. qapidir = os.path.dirname(qapifile)
  153. transmogrify = "transmogrify" in self.options
  154. try:
  155. schema = QAPISchema(qapifile)
  156. # First tell Sphinx about all the schema files that the
  157. # output documentation depends on (including 'qapifile' itself)
  158. schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
  159. except QAPIError as err:
  160. # Launder QAPI parse errors into Sphinx extension errors
  161. # so they are displayed nicely to the user
  162. raise ExtensionError(str(err)) from err
  163. if transmogrify:
  164. contentnode = self.transmogrify(schema)
  165. else:
  166. contentnode = self.legacy(schema)
  167. return contentnode.children
  168. class QMPExample(CodeBlock, NestedDirective):
  169. """
  170. Custom admonition for QMP code examples.
  171. When the :annotated: option is present, the body of this directive
  172. is parsed as normal rST, but with any '::' code blocks set to use
  173. the QMP lexer. Code blocks must be explicitly written by the user,
  174. but this allows for intermingling explanatory paragraphs with
  175. arbitrary rST syntax and code blocks for more involved examples.
  176. When :annotated: is absent, the directive body is treated as a
  177. simple standalone QMP code block literal.
  178. """
  179. required_argument = 0
  180. optional_arguments = 0
  181. has_content = True
  182. option_spec = {
  183. "annotated": directives.flag,
  184. "title": directives.unchanged,
  185. }
  186. def _highlightlang(self) -> addnodes.highlightlang:
  187. """Return the current highlightlang setting for the document"""
  188. node = None
  189. doc = self.state.document
  190. if hasattr(doc, "findall"):
  191. # docutils >= 0.18.1
  192. for node in doc.findall(addnodes.highlightlang):
  193. pass
  194. else:
  195. for elem in doc.traverse():
  196. if isinstance(elem, addnodes.highlightlang):
  197. node = elem
  198. if node:
  199. return node
  200. # No explicit directive found, use defaults
  201. node = addnodes.highlightlang(
  202. lang=self.env.config.highlight_language,
  203. force=False,
  204. # Yes, Sphinx uses this value to effectively disable line
  205. # numbers and not 0 or None or -1 or something. ¯\_(ツ)_/¯
  206. linenothreshold=sys.maxsize,
  207. )
  208. return node
  209. def admonition_wrap(self, *content: nodes.Node) -> List[nodes.Node]:
  210. title = "Example:"
  211. if "title" in self.options:
  212. title = f"{title} {self.options['title']}"
  213. admon = nodes.admonition(
  214. "",
  215. nodes.title("", title),
  216. *content,
  217. classes=["admonition", "admonition-example"],
  218. )
  219. return [admon]
  220. def run_annotated(self) -> List[nodes.Node]:
  221. lang_node = self._highlightlang()
  222. content_node: nodes.Element = nodes.section()
  223. # Configure QMP highlighting for "::" blocks, if needed
  224. if lang_node["lang"] != "QMP":
  225. content_node += addnodes.highlightlang(
  226. lang="QMP",
  227. force=False, # "True" ignores lexing errors
  228. linenothreshold=lang_node["linenothreshold"],
  229. )
  230. self.do_parse(self.content, content_node)
  231. # Restore prior language highlighting, if needed
  232. if lang_node["lang"] != "QMP":
  233. content_node += addnodes.highlightlang(**lang_node.attributes)
  234. return content_node.children
  235. def run(self) -> List[nodes.Node]:
  236. annotated = "annotated" in self.options
  237. if annotated:
  238. content_nodes = self.run_annotated()
  239. else:
  240. self.arguments = ["QMP"]
  241. content_nodes = super().run()
  242. return self.admonition_wrap(*content_nodes)
  243. def setup(app: Sphinx) -> ExtensionMetadata:
  244. """Register qapi-doc directive with Sphinx"""
  245. app.add_config_value("qapidoc_srctree", None, "env")
  246. app.add_directive("qapi-doc", QAPIDocDirective)
  247. app.add_directive("qmp-example", QMPExample)
  248. return {
  249. "version": __version__,
  250. "parallel_read_safe": True,
  251. "parallel_write_safe": True,
  252. }