qapidoc.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. import os
  22. import re
  23. import sys
  24. import textwrap
  25. from typing import List
  26. from docutils import nodes
  27. from docutils.parsers.rst import Directive, directives
  28. from docutils.statemachine import ViewList
  29. from qapi.error import QAPIError, QAPISemError
  30. from qapi.gen import QAPISchemaVisitor
  31. from qapi.schema import QAPISchema
  32. from sphinx import addnodes
  33. from sphinx.directives.code import CodeBlock
  34. from sphinx.errors import ExtensionError
  35. from sphinx.util.docutils import switch_source_input
  36. from sphinx.util.nodes import nested_parse_with_titles
  37. __version__ = "1.0"
  38. def dedent(text: str) -> str:
  39. # Adjust indentation to make description text parse as paragraph.
  40. lines = text.splitlines(True)
  41. if re.match(r"\s+", lines[0]):
  42. # First line is indented; description started on the line after
  43. # the name. dedent the whole block.
  44. return textwrap.dedent(text)
  45. # Descr started on same line. Dedent line 2+.
  46. return lines[0] + textwrap.dedent("".join(lines[1:]))
  47. # Disable black auto-formatter until re-enabled:
  48. # fmt: off
  49. class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
  50. """A QAPI schema visitor which generates docutils/Sphinx nodes
  51. This class builds up a tree of docutils/Sphinx nodes corresponding
  52. to documentation for the various QAPI objects. To use it, first
  53. create a QAPISchemaGenRSTVisitor object, and call its
  54. visit_begin() method. Then you can call one of the two methods
  55. 'freeform' (to add documentation for a freeform documentation
  56. chunk) or 'symbol' (to add documentation for a QAPI symbol). These
  57. will cause the visitor to build up the tree of document
  58. nodes. Once you've added all the documentation via 'freeform' and
  59. 'symbol' method calls, you can call 'get_document_nodes' to get
  60. the final list of document nodes (in a form suitable for returning
  61. from a Sphinx directive's 'run' method).
  62. """
  63. def __init__(self, sphinx_directive):
  64. self._cur_doc = None
  65. self._sphinx_directive = sphinx_directive
  66. self._top_node = nodes.section()
  67. self._active_headings = [self._top_node]
  68. def _make_dlitem(self, term, defn):
  69. """Return a dlitem node with the specified term and definition.
  70. term should be a list of Text and literal nodes.
  71. defn should be one of:
  72. - a string, which will be handed to _parse_text_into_node
  73. - a list of Text and literal nodes, which will be put into
  74. a paragraph node
  75. """
  76. dlitem = nodes.definition_list_item()
  77. dlterm = nodes.term('', '', *term)
  78. dlitem += dlterm
  79. if defn:
  80. dldef = nodes.definition()
  81. if isinstance(defn, list):
  82. dldef += nodes.paragraph('', '', *defn)
  83. else:
  84. self._parse_text_into_node(defn, dldef)
  85. dlitem += dldef
  86. return dlitem
  87. def _make_section(self, title):
  88. """Return a section node with optional title"""
  89. section = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  90. if title:
  91. section += nodes.title(title, title)
  92. return section
  93. def _nodes_for_ifcond(self, ifcond, with_if=True):
  94. """Return list of Text, literal nodes for the ifcond
  95. Return a list which gives text like ' (If: condition)'.
  96. If with_if is False, we don't return the "(If: " and ")".
  97. """
  98. doc = ifcond.docgen()
  99. if not doc:
  100. return []
  101. doc = nodes.literal('', doc)
  102. if not with_if:
  103. return [doc]
  104. nodelist = [nodes.Text(' ('), nodes.strong('', 'If: ')]
  105. nodelist.append(doc)
  106. nodelist.append(nodes.Text(')'))
  107. return nodelist
  108. def _nodes_for_one_member(self, member):
  109. """Return list of Text, literal nodes for this member
  110. Return a list of doctree nodes which give text like
  111. 'name: type (optional) (If: ...)' suitable for use as the
  112. 'term' part of a definition list item.
  113. """
  114. term = [nodes.literal('', member.name)]
  115. if member.type.doc_type():
  116. term.append(nodes.Text(': '))
  117. term.append(nodes.literal('', member.type.doc_type()))
  118. if member.optional:
  119. term.append(nodes.Text(' (optional)'))
  120. if member.ifcond.is_present():
  121. term.extend(self._nodes_for_ifcond(member.ifcond))
  122. return term
  123. def _nodes_for_variant_when(self, branches, variant):
  124. """Return list of Text, literal nodes for variant 'when' clause
  125. Return a list of doctree nodes which give text like
  126. 'when tagname is variant (If: ...)' suitable for use in
  127. the 'branches' part of a definition list.
  128. """
  129. term = [nodes.Text(' when '),
  130. nodes.literal('', branches.tag_member.name),
  131. nodes.Text(' is '),
  132. nodes.literal('', '"%s"' % variant.name)]
  133. if variant.ifcond.is_present():
  134. term.extend(self._nodes_for_ifcond(variant.ifcond))
  135. return term
  136. def _nodes_for_members(self, doc, what, base=None, branches=None):
  137. """Return list of doctree nodes for the table of members"""
  138. dlnode = nodes.definition_list()
  139. for section in doc.args.values():
  140. term = self._nodes_for_one_member(section.member)
  141. # TODO drop fallbacks when undocumented members are outlawed
  142. if section.text:
  143. defn = dedent(section.text)
  144. else:
  145. defn = [nodes.Text('Not documented')]
  146. dlnode += self._make_dlitem(term, defn)
  147. if base:
  148. dlnode += self._make_dlitem([nodes.Text('The members of '),
  149. nodes.literal('', base.doc_type())],
  150. None)
  151. if branches:
  152. for v in branches.variants:
  153. if v.type.name == 'q_empty':
  154. continue
  155. assert not v.type.is_implicit()
  156. term = [nodes.Text('The members of '),
  157. nodes.literal('', v.type.doc_type())]
  158. term.extend(self._nodes_for_variant_when(branches, v))
  159. dlnode += self._make_dlitem(term, None)
  160. if not dlnode.children:
  161. return []
  162. section = self._make_section(what)
  163. section += dlnode
  164. return [section]
  165. def _nodes_for_enum_values(self, doc):
  166. """Return list of doctree nodes for the table of enum values"""
  167. seen_item = False
  168. dlnode = nodes.definition_list()
  169. for section in doc.args.values():
  170. termtext = [nodes.literal('', section.member.name)]
  171. if section.member.ifcond.is_present():
  172. termtext.extend(self._nodes_for_ifcond(section.member.ifcond))
  173. # TODO drop fallbacks when undocumented members are outlawed
  174. if section.text:
  175. defn = dedent(section.text)
  176. else:
  177. defn = [nodes.Text('Not documented')]
  178. dlnode += self._make_dlitem(termtext, defn)
  179. seen_item = True
  180. if not seen_item:
  181. return []
  182. section = self._make_section('Values')
  183. section += dlnode
  184. return [section]
  185. def _nodes_for_arguments(self, doc, arg_type):
  186. """Return list of doctree nodes for the arguments section"""
  187. if arg_type and not arg_type.is_implicit():
  188. assert not doc.args
  189. section = self._make_section('Arguments')
  190. dlnode = nodes.definition_list()
  191. dlnode += self._make_dlitem(
  192. [nodes.Text('The members of '),
  193. nodes.literal('', arg_type.name)],
  194. None)
  195. section += dlnode
  196. return [section]
  197. return self._nodes_for_members(doc, 'Arguments')
  198. def _nodes_for_features(self, doc):
  199. """Return list of doctree nodes for the table of features"""
  200. seen_item = False
  201. dlnode = nodes.definition_list()
  202. for section in doc.features.values():
  203. dlnode += self._make_dlitem(
  204. [nodes.literal('', section.member.name)], dedent(section.text))
  205. seen_item = True
  206. if not seen_item:
  207. return []
  208. section = self._make_section('Features')
  209. section += dlnode
  210. return [section]
  211. def _nodes_for_sections(self, doc):
  212. """Return list of doctree nodes for additional sections"""
  213. nodelist = []
  214. for section in doc.sections:
  215. if section.tag and section.tag == 'TODO':
  216. # Hide TODO: sections
  217. continue
  218. if not section.tag:
  219. # Sphinx cannot handle sectionless titles;
  220. # Instead, just append the results to the prior section.
  221. container = nodes.container()
  222. self._parse_text_into_node(section.text, container)
  223. nodelist += container.children
  224. continue
  225. snode = self._make_section(section.tag)
  226. self._parse_text_into_node(dedent(section.text), snode)
  227. nodelist.append(snode)
  228. return nodelist
  229. def _nodes_for_if_section(self, ifcond):
  230. """Return list of doctree nodes for the "If" section"""
  231. nodelist = []
  232. if ifcond.is_present():
  233. snode = self._make_section('If')
  234. snode += nodes.paragraph(
  235. '', '', *self._nodes_for_ifcond(ifcond, with_if=False)
  236. )
  237. nodelist.append(snode)
  238. return nodelist
  239. def _add_doc(self, typ, sections):
  240. """Add documentation for a command/object/enum...
  241. We assume we're documenting the thing defined in self._cur_doc.
  242. typ is the type of thing being added ("Command", "Object", etc)
  243. sections is a list of nodes for sections to add to the definition.
  244. """
  245. doc = self._cur_doc
  246. snode = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  247. snode += nodes.title('', '', *[nodes.literal(doc.symbol, doc.symbol),
  248. nodes.Text(' (' + typ + ')')])
  249. self._parse_text_into_node(doc.body.text, snode)
  250. for s in sections:
  251. if s is not None:
  252. snode += s
  253. self._add_node_to_current_heading(snode)
  254. def visit_enum_type(self, name, info, ifcond, features, members, prefix):
  255. doc = self._cur_doc
  256. self._add_doc('Enum',
  257. self._nodes_for_enum_values(doc)
  258. + self._nodes_for_features(doc)
  259. + self._nodes_for_sections(doc)
  260. + self._nodes_for_if_section(ifcond))
  261. def visit_object_type(self, name, info, ifcond, features,
  262. base, members, branches):
  263. doc = self._cur_doc
  264. if base and base.is_implicit():
  265. base = None
  266. self._add_doc('Object',
  267. self._nodes_for_members(doc, 'Members', base, branches)
  268. + self._nodes_for_features(doc)
  269. + self._nodes_for_sections(doc)
  270. + self._nodes_for_if_section(ifcond))
  271. def visit_alternate_type(self, name, info, ifcond, features,
  272. alternatives):
  273. doc = self._cur_doc
  274. self._add_doc('Alternate',
  275. self._nodes_for_members(doc, 'Members')
  276. + self._nodes_for_features(doc)
  277. + self._nodes_for_sections(doc)
  278. + self._nodes_for_if_section(ifcond))
  279. def visit_command(self, name, info, ifcond, features, arg_type,
  280. ret_type, gen, success_response, boxed, allow_oob,
  281. allow_preconfig, coroutine):
  282. doc = self._cur_doc
  283. self._add_doc('Command',
  284. self._nodes_for_arguments(doc, arg_type)
  285. + self._nodes_for_features(doc)
  286. + self._nodes_for_sections(doc)
  287. + self._nodes_for_if_section(ifcond))
  288. def visit_event(self, name, info, ifcond, features, arg_type, boxed):
  289. doc = self._cur_doc
  290. self._add_doc('Event',
  291. self._nodes_for_arguments(doc, arg_type)
  292. + self._nodes_for_features(doc)
  293. + self._nodes_for_sections(doc)
  294. + self._nodes_for_if_section(ifcond))
  295. def symbol(self, doc, entity):
  296. """Add documentation for one symbol to the document tree
  297. This is the main entry point which causes us to add documentation
  298. nodes for a symbol (which could be a 'command', 'object', 'event',
  299. etc). We do this by calling 'visit' on the schema entity, which
  300. will then call back into one of our visit_* methods, depending
  301. on what kind of thing this symbol is.
  302. """
  303. self._cur_doc = doc
  304. entity.visit(self)
  305. self._cur_doc = None
  306. def _start_new_heading(self, heading, level):
  307. """Start a new heading at the specified heading level
  308. Create a new section whose title is 'heading' and which is placed
  309. in the docutils node tree as a child of the most recent level-1
  310. heading. Subsequent document sections (commands, freeform doc chunks,
  311. etc) will be placed as children of this new heading section.
  312. """
  313. if len(self._active_headings) < level:
  314. raise QAPISemError(self._cur_doc.info,
  315. 'Level %d subheading found outside a '
  316. 'level %d heading'
  317. % (level, level - 1))
  318. snode = self._make_section(heading)
  319. self._active_headings[level - 1] += snode
  320. self._active_headings = self._active_headings[:level]
  321. self._active_headings.append(snode)
  322. return snode
  323. def _add_node_to_current_heading(self, node):
  324. """Add the node to whatever the current active heading is"""
  325. self._active_headings[-1] += node
  326. def freeform(self, doc):
  327. """Add a piece of 'freeform' documentation to the document tree
  328. A 'freeform' document chunk doesn't relate to any particular
  329. symbol (for instance, it could be an introduction).
  330. If the freeform document starts with a line of the form
  331. '= Heading text', this is a section or subsection heading, with
  332. the heading level indicated by the number of '=' signs.
  333. """
  334. # QAPIDoc documentation says free-form documentation blocks
  335. # must have only a body section, nothing else.
  336. assert not doc.sections
  337. assert not doc.args
  338. assert not doc.features
  339. self._cur_doc = doc
  340. text = doc.body.text
  341. if re.match(r'=+ ', text):
  342. # Section/subsection heading (if present, will always be
  343. # the first line of the block)
  344. (heading, _, text) = text.partition('\n')
  345. (leader, _, heading) = heading.partition(' ')
  346. node = self._start_new_heading(heading, len(leader))
  347. if text == '':
  348. return
  349. else:
  350. node = nodes.container()
  351. self._parse_text_into_node(text, node)
  352. self._cur_doc = None
  353. def _parse_text_into_node(self, doctext, node):
  354. """Parse a chunk of QAPI-doc-format text into the node
  355. The doc comment can contain most inline rST markup, including
  356. bulleted and enumerated lists.
  357. As an extra permitted piece of markup, @var will be turned
  358. into ``var``.
  359. """
  360. # Handle the "@var means ``var`` case
  361. doctext = re.sub(r'@([\w-]+)', r'``\1``', doctext)
  362. rstlist = ViewList()
  363. for line in doctext.splitlines():
  364. # The reported line number will always be that of the start line
  365. # of the doc comment, rather than the actual location of the error.
  366. # Being more precise would require overhaul of the QAPIDoc class
  367. # to track lines more exactly within all the sub-parts of the doc
  368. # comment, as well as counting lines here.
  369. rstlist.append(line, self._cur_doc.info.fname,
  370. self._cur_doc.info.line)
  371. # Append a blank line -- in some cases rST syntax errors get
  372. # attributed to the line after one with actual text, and if there
  373. # isn't anything in the ViewList corresponding to that then Sphinx
  374. # 1.6's AutodocReporter will then misidentify the source/line location
  375. # in the error message (usually attributing it to the top-level
  376. # .rst file rather than the offending .json file). The extra blank
  377. # line won't affect the rendered output.
  378. rstlist.append("", self._cur_doc.info.fname, self._cur_doc.info.line)
  379. self._sphinx_directive.do_parse(rstlist, node)
  380. def get_document_nodes(self):
  381. """Return the list of docutils nodes which make up the document"""
  382. return self._top_node.children
  383. # Turn the black formatter on for the rest of the file.
  384. # fmt: on
  385. class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
  386. """A QAPI schema visitor which adds Sphinx dependencies each module
  387. This class calls the Sphinx note_dependency() function to tell Sphinx
  388. that the generated documentation output depends on the input
  389. schema file associated with each module in the QAPI input.
  390. """
  391. def __init__(self, env, qapidir):
  392. self._env = env
  393. self._qapidir = qapidir
  394. def visit_module(self, name):
  395. if name != "./builtin":
  396. qapifile = self._qapidir + "/" + name
  397. self._env.note_dependency(os.path.abspath(qapifile))
  398. super().visit_module(name)
  399. class NestedDirective(Directive):
  400. def run(self):
  401. raise NotImplementedError
  402. def do_parse(self, rstlist, node):
  403. """
  404. Parse rST source lines and add them to the specified node
  405. Take the list of rST source lines rstlist, parse them as
  406. rST, and add the resulting docutils nodes as children of node.
  407. The nodes are parsed in a way that allows them to include
  408. subheadings (titles) without confusing the rendering of
  409. anything else.
  410. """
  411. with switch_source_input(self.state, rstlist):
  412. nested_parse_with_titles(self.state, rstlist, node)
  413. class QAPIDocDirective(NestedDirective):
  414. """Extract documentation from the specified QAPI .json file"""
  415. required_argument = 1
  416. optional_arguments = 1
  417. option_spec = {"qapifile": directives.unchanged_required}
  418. has_content = False
  419. def new_serialno(self):
  420. """Return a unique new ID string suitable for use as a node's ID"""
  421. env = self.state.document.settings.env
  422. return "qapidoc-%d" % env.new_serialno("qapidoc")
  423. def run(self):
  424. env = self.state.document.settings.env
  425. qapifile = env.config.qapidoc_srctree + "/" + self.arguments[0]
  426. qapidir = os.path.dirname(qapifile)
  427. try:
  428. schema = QAPISchema(qapifile)
  429. # First tell Sphinx about all the schema files that the
  430. # output documentation depends on (including 'qapifile' itself)
  431. schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
  432. vis = QAPISchemaGenRSTVisitor(self)
  433. vis.visit_begin(schema)
  434. for doc in schema.docs:
  435. if doc.symbol:
  436. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  437. else:
  438. vis.freeform(doc)
  439. return vis.get_document_nodes()
  440. except QAPIError as err:
  441. # Launder QAPI parse errors into Sphinx extension errors
  442. # so they are displayed nicely to the user
  443. raise ExtensionError(str(err)) from err
  444. class QMPExample(CodeBlock, NestedDirective):
  445. """
  446. Custom admonition for QMP code examples.
  447. When the :annotated: option is present, the body of this directive
  448. is parsed as normal rST, but with any '::' code blocks set to use
  449. the QMP lexer. Code blocks must be explicitly written by the user,
  450. but this allows for intermingling explanatory paragraphs with
  451. arbitrary rST syntax and code blocks for more involved examples.
  452. When :annotated: is absent, the directive body is treated as a
  453. simple standalone QMP code block literal.
  454. """
  455. required_argument = 0
  456. optional_arguments = 0
  457. has_content = True
  458. option_spec = {
  459. "annotated": directives.flag,
  460. "title": directives.unchanged,
  461. }
  462. def _highlightlang(self) -> addnodes.highlightlang:
  463. """Return the current highlightlang setting for the document"""
  464. node = None
  465. doc = self.state.document
  466. if hasattr(doc, "findall"):
  467. # docutils >= 0.18.1
  468. for node in doc.findall(addnodes.highlightlang):
  469. pass
  470. else:
  471. for elem in doc.traverse():
  472. if isinstance(elem, addnodes.highlightlang):
  473. node = elem
  474. if node:
  475. return node
  476. # No explicit directive found, use defaults
  477. node = addnodes.highlightlang(
  478. lang=self.env.config.highlight_language,
  479. force=False,
  480. # Yes, Sphinx uses this value to effectively disable line
  481. # numbers and not 0 or None or -1 or something. ¯\_(ツ)_/¯
  482. linenothreshold=sys.maxsize,
  483. )
  484. return node
  485. def admonition_wrap(self, *content) -> List[nodes.Node]:
  486. title = "Example:"
  487. if "title" in self.options:
  488. title = f"{title} {self.options['title']}"
  489. admon = nodes.admonition(
  490. "",
  491. nodes.title("", title),
  492. *content,
  493. classes=["admonition", "admonition-example"],
  494. )
  495. return [admon]
  496. def run_annotated(self) -> List[nodes.Node]:
  497. lang_node = self._highlightlang()
  498. content_node: nodes.Element = nodes.section()
  499. # Configure QMP highlighting for "::" blocks, if needed
  500. if lang_node["lang"] != "QMP":
  501. content_node += addnodes.highlightlang(
  502. lang="QMP",
  503. force=False, # "True" ignores lexing errors
  504. linenothreshold=lang_node["linenothreshold"],
  505. )
  506. self.do_parse(self.content, content_node)
  507. # Restore prior language highlighting, if needed
  508. if lang_node["lang"] != "QMP":
  509. content_node += addnodes.highlightlang(**lang_node.attributes)
  510. return content_node.children
  511. def run(self) -> List[nodes.Node]:
  512. annotated = "annotated" in self.options
  513. if annotated:
  514. content_nodes = self.run_annotated()
  515. else:
  516. self.arguments = ["QMP"]
  517. content_nodes = super().run()
  518. return self.admonition_wrap(*content_nodes)
  519. def setup(app):
  520. """Register qapi-doc directive with Sphinx"""
  521. app.add_config_value("qapidoc_srctree", None, "env")
  522. app.add_directive("qapi-doc", QAPIDocDirective)
  523. app.add_directive("qmp-example", QMPExample)
  524. return {
  525. "version": __version__,
  526. "parallel_read_safe": True,
  527. "parallel_write_safe": True,
  528. }