qapidoc.py 14 KB

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