qapidoc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. from pathlib import Path
  25. import re
  26. import sys
  27. from typing import TYPE_CHECKING
  28. from docutils import nodes
  29. from docutils.parsers.rst import Directive, directives
  30. from docutils.statemachine import StringList
  31. from qapi.error import QAPIError
  32. from qapi.parser import QAPIDoc
  33. from qapi.schema import (
  34. QAPISchema,
  35. QAPISchemaDefinition,
  36. QAPISchemaVisitor,
  37. )
  38. from qapi.source import QAPISourceInfo
  39. from qapidoc_legacy import QAPISchemaGenRSTVisitor # type: ignore
  40. from sphinx import addnodes
  41. from sphinx.directives.code import CodeBlock
  42. from sphinx.errors import ExtensionError
  43. from sphinx.util.docutils import switch_source_input
  44. from sphinx.util.nodes import nested_parse_with_titles
  45. if TYPE_CHECKING:
  46. from typing import (
  47. Any,
  48. Generator,
  49. List,
  50. Sequence,
  51. )
  52. from sphinx.application import Sphinx
  53. from sphinx.util.typing import ExtensionMetadata
  54. __version__ = "1.0"
  55. class Transmogrifier:
  56. def __init__(self) -> None:
  57. self._result = StringList()
  58. self.indent = 0
  59. # General-purpose rST generation functions
  60. def get_indent(self) -> str:
  61. return " " * self.indent
  62. @contextmanager
  63. def indented(self) -> Generator[None]:
  64. self.indent += 1
  65. try:
  66. yield
  67. finally:
  68. self.indent -= 1
  69. def add_line_raw(self, line: str, source: str, *lineno: int) -> None:
  70. """Append one line of generated reST to the output."""
  71. # NB: Sphinx uses zero-indexed lines; subtract one.
  72. lineno = tuple((n - 1 for n in lineno))
  73. if line.strip():
  74. # not a blank line
  75. self._result.append(
  76. self.get_indent() + line.rstrip("\n"), source, *lineno
  77. )
  78. else:
  79. self._result.append("", source, *lineno)
  80. def add_line(self, content: str, info: QAPISourceInfo) -> None:
  81. # NB: We *require* an info object; this works out OK because we
  82. # don't document built-in objects that don't have
  83. # one. Everything else should.
  84. self.add_line_raw(content, info.fname, info.line)
  85. def add_lines(
  86. self,
  87. content: str,
  88. info: QAPISourceInfo,
  89. ) -> None:
  90. lines = content.splitlines(True)
  91. for i, line in enumerate(lines):
  92. self.add_line_raw(line, info.fname, info.line + i)
  93. def ensure_blank_line(self) -> None:
  94. # Empty document -- no blank line required.
  95. if not self._result:
  96. return
  97. # Last line isn't blank, add one.
  98. if self._result[-1].strip(): # pylint: disable=no-member
  99. fname, line = self._result.info(-1)
  100. assert isinstance(line, int)
  101. # New blank line is credited to one-after the current last line.
  102. # +2: correct for zero/one index, then increment by one.
  103. self.add_line_raw("", fname, line + 2)
  104. # Transmogrification helpers
  105. def preamble(self, ent: QAPISchemaDefinition) -> None:
  106. """
  107. Generate option lines for QAPI entity directives.
  108. """
  109. if ent.doc and ent.doc.since:
  110. assert ent.doc.since.kind == QAPIDoc.Kind.SINCE
  111. # Generated from the entity's docblock; info location is exact.
  112. self.add_line(f":since: {ent.doc.since.text}", ent.doc.since.info)
  113. if ent.ifcond.is_present():
  114. doc = ent.ifcond.docgen()
  115. assert ent.info
  116. # Generated from entity definition; info location is approximate.
  117. self.add_line(f":ifcond: {doc}", ent.info)
  118. # Hoist special features such as :deprecated: and :unstable:
  119. # into the options block for the entity. If, in the future, new
  120. # special features are added, qapi-domain will chirp about
  121. # unrecognized options and fail until they are handled in
  122. # qapi-domain.
  123. for feat in ent.features:
  124. if feat.is_special():
  125. # FIXME: handle ifcond if present. How to display that
  126. # information is TBD.
  127. # Generated from entity def; info location is approximate.
  128. assert feat.info
  129. self.add_line(f":{feat.name}:", feat.info)
  130. self.ensure_blank_line()
  131. # Transmogrification core methods
  132. def visit_module(self, path: str) -> None:
  133. name = Path(path).stem
  134. # module directives are credited to the first line of a module file.
  135. self.add_line_raw(f".. qapi:module:: {name}", path, 1)
  136. self.ensure_blank_line()
  137. def visit_freeform(self, doc: QAPIDoc) -> None:
  138. # TODO: Once the old qapidoc transformer is deprecated, freeform
  139. # sections can be updated to pure rST, and this transformed removed.
  140. #
  141. # For now, translate our micro-format into rST. Code adapted
  142. # from Peter Maydell's freeform().
  143. assert len(doc.all_sections) == 1, doc.all_sections
  144. body = doc.all_sections[0]
  145. text = body.text
  146. info = doc.info
  147. if re.match(r"=+ ", text):
  148. # Section/subsection heading (if present, will always be the
  149. # first line of the block)
  150. (heading, _, text) = text.partition("\n")
  151. (leader, _, heading) = heading.partition(" ")
  152. # Implicit +1 for heading in the containing .rst doc
  153. level = len(leader) + 1
  154. # https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#sections
  155. markers = ' #*=_^"'
  156. overline = level <= 2
  157. marker = markers[level]
  158. self.ensure_blank_line()
  159. # This credits all 2 or 3 lines to the single source line.
  160. if overline:
  161. self.add_line(marker * len(heading), info)
  162. self.add_line(heading, info)
  163. self.add_line(marker * len(heading), info)
  164. self.ensure_blank_line()
  165. # Eat blank line(s) and advance info
  166. trimmed = text.lstrip("\n")
  167. text = trimmed
  168. info = info.next_line(len(text) - len(trimmed) + 1)
  169. self.add_lines(text, info)
  170. self.ensure_blank_line()
  171. class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
  172. """A QAPI schema visitor which adds Sphinx dependencies each module
  173. This class calls the Sphinx note_dependency() function to tell Sphinx
  174. that the generated documentation output depends on the input
  175. schema file associated with each module in the QAPI input.
  176. """
  177. def __init__(self, env: Any, qapidir: str) -> None:
  178. self._env = env
  179. self._qapidir = qapidir
  180. def visit_module(self, name: str) -> None:
  181. if name != "./builtin":
  182. qapifile = self._qapidir + "/" + name
  183. self._env.note_dependency(os.path.abspath(qapifile))
  184. super().visit_module(name)
  185. class NestedDirective(Directive):
  186. def run(self) -> Sequence[nodes.Node]:
  187. raise NotImplementedError
  188. def do_parse(self, rstlist: StringList, node: nodes.Node) -> None:
  189. """
  190. Parse rST source lines and add them to the specified node
  191. Take the list of rST source lines rstlist, parse them as
  192. rST, and add the resulting docutils nodes as children of node.
  193. The nodes are parsed in a way that allows them to include
  194. subheadings (titles) without confusing the rendering of
  195. anything else.
  196. """
  197. with switch_source_input(self.state, rstlist):
  198. nested_parse_with_titles(self.state, rstlist, node)
  199. class QAPIDocDirective(NestedDirective):
  200. """Extract documentation from the specified QAPI .json file"""
  201. required_argument = 1
  202. optional_arguments = 1
  203. option_spec = {
  204. "qapifile": directives.unchanged_required,
  205. "transmogrify": directives.flag,
  206. }
  207. has_content = False
  208. def new_serialno(self) -> str:
  209. """Return a unique new ID string suitable for use as a node's ID"""
  210. env = self.state.document.settings.env
  211. return "qapidoc-%d" % env.new_serialno("qapidoc")
  212. def transmogrify(self, schema: QAPISchema) -> nodes.Element:
  213. raise NotImplementedError
  214. def legacy(self, schema: QAPISchema) -> nodes.Element:
  215. vis = QAPISchemaGenRSTVisitor(self)
  216. vis.visit_begin(schema)
  217. for doc in schema.docs:
  218. if doc.symbol:
  219. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  220. else:
  221. vis.freeform(doc)
  222. return vis.get_document_node() # type: ignore
  223. def run(self) -> Sequence[nodes.Node]:
  224. env = self.state.document.settings.env
  225. qapifile = env.config.qapidoc_srctree + "/" + self.arguments[0]
  226. qapidir = os.path.dirname(qapifile)
  227. transmogrify = "transmogrify" in self.options
  228. try:
  229. schema = QAPISchema(qapifile)
  230. # First tell Sphinx about all the schema files that the
  231. # output documentation depends on (including 'qapifile' itself)
  232. schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
  233. except QAPIError as err:
  234. # Launder QAPI parse errors into Sphinx extension errors
  235. # so they are displayed nicely to the user
  236. raise ExtensionError(str(err)) from err
  237. if transmogrify:
  238. contentnode = self.transmogrify(schema)
  239. else:
  240. contentnode = self.legacy(schema)
  241. return contentnode.children
  242. class QMPExample(CodeBlock, NestedDirective):
  243. """
  244. Custom admonition for QMP code examples.
  245. When the :annotated: option is present, the body of this directive
  246. is parsed as normal rST, but with any '::' code blocks set to use
  247. the QMP lexer. Code blocks must be explicitly written by the user,
  248. but this allows for intermingling explanatory paragraphs with
  249. arbitrary rST syntax and code blocks for more involved examples.
  250. When :annotated: is absent, the directive body is treated as a
  251. simple standalone QMP code block literal.
  252. """
  253. required_argument = 0
  254. optional_arguments = 0
  255. has_content = True
  256. option_spec = {
  257. "annotated": directives.flag,
  258. "title": directives.unchanged,
  259. }
  260. def _highlightlang(self) -> addnodes.highlightlang:
  261. """Return the current highlightlang setting for the document"""
  262. node = None
  263. doc = self.state.document
  264. if hasattr(doc, "findall"):
  265. # docutils >= 0.18.1
  266. for node in doc.findall(addnodes.highlightlang):
  267. pass
  268. else:
  269. for elem in doc.traverse():
  270. if isinstance(elem, addnodes.highlightlang):
  271. node = elem
  272. if node:
  273. return node
  274. # No explicit directive found, use defaults
  275. node = addnodes.highlightlang(
  276. lang=self.env.config.highlight_language,
  277. force=False,
  278. # Yes, Sphinx uses this value to effectively disable line
  279. # numbers and not 0 or None or -1 or something. ¯\_(ツ)_/¯
  280. linenothreshold=sys.maxsize,
  281. )
  282. return node
  283. def admonition_wrap(self, *content: nodes.Node) -> List[nodes.Node]:
  284. title = "Example:"
  285. if "title" in self.options:
  286. title = f"{title} {self.options['title']}"
  287. admon = nodes.admonition(
  288. "",
  289. nodes.title("", title),
  290. *content,
  291. classes=["admonition", "admonition-example"],
  292. )
  293. return [admon]
  294. def run_annotated(self) -> List[nodes.Node]:
  295. lang_node = self._highlightlang()
  296. content_node: nodes.Element = nodes.section()
  297. # Configure QMP highlighting for "::" blocks, if needed
  298. if lang_node["lang"] != "QMP":
  299. content_node += addnodes.highlightlang(
  300. lang="QMP",
  301. force=False, # "True" ignores lexing errors
  302. linenothreshold=lang_node["linenothreshold"],
  303. )
  304. self.do_parse(self.content, content_node)
  305. # Restore prior language highlighting, if needed
  306. if lang_node["lang"] != "QMP":
  307. content_node += addnodes.highlightlang(**lang_node.attributes)
  308. return content_node.children
  309. def run(self) -> List[nodes.Node]:
  310. annotated = "annotated" in self.options
  311. if annotated:
  312. content_nodes = self.run_annotated()
  313. else:
  314. self.arguments = ["QMP"]
  315. content_nodes = super().run()
  316. return self.admonition_wrap(*content_nodes)
  317. def setup(app: Sphinx) -> ExtensionMetadata:
  318. """Register qapi-doc directive with Sphinx"""
  319. app.add_config_value("qapidoc_srctree", None, "env")
  320. app.add_directive("qapi-doc", QAPIDocDirective)
  321. app.add_directive("qmp-example", QMPExample)
  322. return {
  323. "version": __version__,
  324. "parallel_read_safe": True,
  325. "parallel_write_safe": True,
  326. }