qapidoc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 visit_paragraph(self, section: QAPIDoc.Section) -> None:
  106. # Squelch empty paragraphs.
  107. if not section.text:
  108. return
  109. self.ensure_blank_line()
  110. self.add_lines(section.text, section.info)
  111. self.ensure_blank_line()
  112. def preamble(self, ent: QAPISchemaDefinition) -> None:
  113. """
  114. Generate option lines for QAPI entity directives.
  115. """
  116. if ent.doc and ent.doc.since:
  117. assert ent.doc.since.kind == QAPIDoc.Kind.SINCE
  118. # Generated from the entity's docblock; info location is exact.
  119. self.add_line(f":since: {ent.doc.since.text}", ent.doc.since.info)
  120. if ent.ifcond.is_present():
  121. doc = ent.ifcond.docgen()
  122. assert ent.info
  123. # Generated from entity definition; info location is approximate.
  124. self.add_line(f":ifcond: {doc}", ent.info)
  125. # Hoist special features such as :deprecated: and :unstable:
  126. # into the options block for the entity. If, in the future, new
  127. # special features are added, qapi-domain will chirp about
  128. # unrecognized options and fail until they are handled in
  129. # qapi-domain.
  130. for feat in ent.features:
  131. if feat.is_special():
  132. # FIXME: handle ifcond if present. How to display that
  133. # information is TBD.
  134. # Generated from entity def; info location is approximate.
  135. assert feat.info
  136. self.add_line(f":{feat.name}:", feat.info)
  137. self.ensure_blank_line()
  138. # Transmogrification core methods
  139. def visit_module(self, path: str) -> None:
  140. name = Path(path).stem
  141. # module directives are credited to the first line of a module file.
  142. self.add_line_raw(f".. qapi:module:: {name}", path, 1)
  143. self.ensure_blank_line()
  144. def visit_freeform(self, doc: QAPIDoc) -> None:
  145. # TODO: Once the old qapidoc transformer is deprecated, freeform
  146. # sections can be updated to pure rST, and this transformed removed.
  147. #
  148. # For now, translate our micro-format into rST. Code adapted
  149. # from Peter Maydell's freeform().
  150. assert len(doc.all_sections) == 1, doc.all_sections
  151. body = doc.all_sections[0]
  152. text = body.text
  153. info = doc.info
  154. if re.match(r"=+ ", text):
  155. # Section/subsection heading (if present, will always be the
  156. # first line of the block)
  157. (heading, _, text) = text.partition("\n")
  158. (leader, _, heading) = heading.partition(" ")
  159. # Implicit +1 for heading in the containing .rst doc
  160. level = len(leader) + 1
  161. # https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#sections
  162. markers = ' #*=_^"'
  163. overline = level <= 2
  164. marker = markers[level]
  165. self.ensure_blank_line()
  166. # This credits all 2 or 3 lines to the single source line.
  167. if overline:
  168. self.add_line(marker * len(heading), info)
  169. self.add_line(heading, info)
  170. self.add_line(marker * len(heading), info)
  171. self.ensure_blank_line()
  172. # Eat blank line(s) and advance info
  173. trimmed = text.lstrip("\n")
  174. text = trimmed
  175. info = info.next_line(len(text) - len(trimmed) + 1)
  176. self.add_lines(text, info)
  177. self.ensure_blank_line()
  178. class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
  179. """A QAPI schema visitor which adds Sphinx dependencies each module
  180. This class calls the Sphinx note_dependency() function to tell Sphinx
  181. that the generated documentation output depends on the input
  182. schema file associated with each module in the QAPI input.
  183. """
  184. def __init__(self, env: Any, qapidir: str) -> None:
  185. self._env = env
  186. self._qapidir = qapidir
  187. def visit_module(self, name: str) -> None:
  188. if name != "./builtin":
  189. qapifile = self._qapidir + "/" + name
  190. self._env.note_dependency(os.path.abspath(qapifile))
  191. super().visit_module(name)
  192. class NestedDirective(Directive):
  193. def run(self) -> Sequence[nodes.Node]:
  194. raise NotImplementedError
  195. def do_parse(self, rstlist: StringList, node: nodes.Node) -> None:
  196. """
  197. Parse rST source lines and add them to the specified node
  198. Take the list of rST source lines rstlist, parse them as
  199. rST, and add the resulting docutils nodes as children of node.
  200. The nodes are parsed in a way that allows them to include
  201. subheadings (titles) without confusing the rendering of
  202. anything else.
  203. """
  204. with switch_source_input(self.state, rstlist):
  205. nested_parse_with_titles(self.state, rstlist, node)
  206. class QAPIDocDirective(NestedDirective):
  207. """Extract documentation from the specified QAPI .json file"""
  208. required_argument = 1
  209. optional_arguments = 1
  210. option_spec = {
  211. "qapifile": directives.unchanged_required,
  212. "transmogrify": directives.flag,
  213. }
  214. has_content = False
  215. def new_serialno(self) -> str:
  216. """Return a unique new ID string suitable for use as a node's ID"""
  217. env = self.state.document.settings.env
  218. return "qapidoc-%d" % env.new_serialno("qapidoc")
  219. def transmogrify(self, schema: QAPISchema) -> nodes.Element:
  220. raise NotImplementedError
  221. def legacy(self, schema: QAPISchema) -> nodes.Element:
  222. vis = QAPISchemaGenRSTVisitor(self)
  223. vis.visit_begin(schema)
  224. for doc in schema.docs:
  225. if doc.symbol:
  226. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  227. else:
  228. vis.freeform(doc)
  229. return vis.get_document_node() # type: ignore
  230. def run(self) -> Sequence[nodes.Node]:
  231. env = self.state.document.settings.env
  232. qapifile = env.config.qapidoc_srctree + "/" + self.arguments[0]
  233. qapidir = os.path.dirname(qapifile)
  234. transmogrify = "transmogrify" in self.options
  235. try:
  236. schema = QAPISchema(qapifile)
  237. # First tell Sphinx about all the schema files that the
  238. # output documentation depends on (including 'qapifile' itself)
  239. schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
  240. except QAPIError as err:
  241. # Launder QAPI parse errors into Sphinx extension errors
  242. # so they are displayed nicely to the user
  243. raise ExtensionError(str(err)) from err
  244. if transmogrify:
  245. contentnode = self.transmogrify(schema)
  246. else:
  247. contentnode = self.legacy(schema)
  248. return contentnode.children
  249. class QMPExample(CodeBlock, NestedDirective):
  250. """
  251. Custom admonition for QMP code examples.
  252. When the :annotated: option is present, the body of this directive
  253. is parsed as normal rST, but with any '::' code blocks set to use
  254. the QMP lexer. Code blocks must be explicitly written by the user,
  255. but this allows for intermingling explanatory paragraphs with
  256. arbitrary rST syntax and code blocks for more involved examples.
  257. When :annotated: is absent, the directive body is treated as a
  258. simple standalone QMP code block literal.
  259. """
  260. required_argument = 0
  261. optional_arguments = 0
  262. has_content = True
  263. option_spec = {
  264. "annotated": directives.flag,
  265. "title": directives.unchanged,
  266. }
  267. def _highlightlang(self) -> addnodes.highlightlang:
  268. """Return the current highlightlang setting for the document"""
  269. node = None
  270. doc = self.state.document
  271. if hasattr(doc, "findall"):
  272. # docutils >= 0.18.1
  273. for node in doc.findall(addnodes.highlightlang):
  274. pass
  275. else:
  276. for elem in doc.traverse():
  277. if isinstance(elem, addnodes.highlightlang):
  278. node = elem
  279. if node:
  280. return node
  281. # No explicit directive found, use defaults
  282. node = addnodes.highlightlang(
  283. lang=self.env.config.highlight_language,
  284. force=False,
  285. # Yes, Sphinx uses this value to effectively disable line
  286. # numbers and not 0 or None or -1 or something. ¯\_(ツ)_/¯
  287. linenothreshold=sys.maxsize,
  288. )
  289. return node
  290. def admonition_wrap(self, *content: nodes.Node) -> List[nodes.Node]:
  291. title = "Example:"
  292. if "title" in self.options:
  293. title = f"{title} {self.options['title']}"
  294. admon = nodes.admonition(
  295. "",
  296. nodes.title("", title),
  297. *content,
  298. classes=["admonition", "admonition-example"],
  299. )
  300. return [admon]
  301. def run_annotated(self) -> List[nodes.Node]:
  302. lang_node = self._highlightlang()
  303. content_node: nodes.Element = nodes.section()
  304. # Configure QMP highlighting for "::" blocks, if needed
  305. if lang_node["lang"] != "QMP":
  306. content_node += addnodes.highlightlang(
  307. lang="QMP",
  308. force=False, # "True" ignores lexing errors
  309. linenothreshold=lang_node["linenothreshold"],
  310. )
  311. self.do_parse(self.content, content_node)
  312. # Restore prior language highlighting, if needed
  313. if lang_node["lang"] != "QMP":
  314. content_node += addnodes.highlightlang(**lang_node.attributes)
  315. return content_node.children
  316. def run(self) -> List[nodes.Node]:
  317. annotated = "annotated" in self.options
  318. if annotated:
  319. content_nodes = self.run_annotated()
  320. else:
  321. self.arguments = ["QMP"]
  322. content_nodes = super().run()
  323. return self.admonition_wrap(*content_nodes)
  324. def setup(app: Sphinx) -> ExtensionMetadata:
  325. """Register qapi-doc directive with Sphinx"""
  326. app.add_config_value("qapidoc_srctree", None, "env")
  327. app.add_directive("qapi-doc", QAPIDocDirective)
  328. app.add_directive("qmp-example", QMPExample)
  329. return {
  330. "version": __version__,
  331. "parallel_read_safe": True,
  332. "parallel_write_safe": True,
  333. }